|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Kiboko\Component\Flow\Magento2; |
| 6 | + |
| 7 | +use Kiboko\Component\Bucket\AcceptanceResultBucket; |
| 8 | +use Kiboko\Component\Bucket\RejectionResultBucket; |
| 9 | +use Kiboko\Contract\Mapping\CompiledMapperInterface; |
| 10 | +use Kiboko\Contract\Pipeline\TransformerInterface; |
| 11 | +use Psr\SimpleCache\CacheInterface; |
| 12 | +use Symfony\Component\Serializer\Encoder\JsonEncoder; |
| 13 | +use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; |
| 14 | +use Symfony\Component\Serializer\Serializer; |
| 15 | +use Symfony\Component\Serializer\SerializerInterface; |
| 16 | + |
| 17 | +final class CategoryLookup implements TransformerInterface |
| 18 | +{ |
| 19 | + private SerializerInterface $serializer; |
| 20 | + |
| 21 | + public function __construct( |
| 22 | + private \Psr\Log\LoggerInterface $logger, |
| 23 | + private \Kiboko\Magento\V2_1\Client|\Kiboko\Magento\V2_2\Client|\Kiboko\Magento\V2_3\Client|\Kiboko\Magento\V2_4\Client $client, |
| 24 | + private CacheInterface $cache, |
| 25 | + private string $cacheKey, |
| 26 | + private CompiledMapperInterface $mapper, |
| 27 | + private string $mappingField, |
| 28 | + ) { |
| 29 | + $this->serializer = new Serializer( |
| 30 | + normalizers: [ |
| 31 | + new ObjectNormalizer() |
| 32 | + ], |
| 33 | + encoders: [ |
| 34 | + new JsonEncoder() |
| 35 | + ] |
| 36 | + ); |
| 37 | + } |
| 38 | + |
| 39 | + public function transform(): \Generator |
| 40 | + { |
| 41 | + $line = yield; |
| 42 | + while (true) { |
| 43 | + try { |
| 44 | + $lookup = $this->cache->get(sprintf($this->cacheKey, $line[$this->mappingField])); |
| 45 | + |
| 46 | + if ($lookup === null) { |
| 47 | + $lookup = $this->client->catalogCategoryRepositoryV1GetGet( |
| 48 | + categoryId: $line[$this->mappingField], |
| 49 | + ); |
| 50 | + |
| 51 | + if (!$lookup instanceof \Kiboko\Magento\V2_1\Model\CatalogDataCategoryInterface |
| 52 | + && !$lookup instanceof \Kiboko\Magento\V2_2\Model\CatalogDataCategoryInterface |
| 53 | + && !$lookup instanceof \Kiboko\Magento\V2_3\Model\CatalogDataCategoryInterface |
| 54 | + && !$lookup instanceof \Kiboko\Magento\V2_4\Model\CatalogDataCategoryInterface |
| 55 | + ) { |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + $this->cache->set( |
| 60 | + sprintf($this->cacheKey, $line[$this->mappingField]), |
| 61 | + $this->serializer->serialize($lookup, null), |
| 62 | + ); |
| 63 | + } |
| 64 | + } catch (\RuntimeException $exception) { |
| 65 | + $this->logger->warning($exception->getMessage(), ['exception' => $exception, 'item' => $line]); |
| 66 | + $line = yield new RejectionResultBucket($line); |
| 67 | + continue; |
| 68 | + } |
| 69 | + |
| 70 | + $output = ($this->mapper)($lookup, $line); |
| 71 | + |
| 72 | + $line = yield new AcceptanceResultBucket($output); |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments