<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Domain\TypeConverter;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Property\Exception\TargetNotFoundException;
use Neos\Flow\Property\PropertyMappingConfigurationInterface;
use Neos\Flow\Property\TypeConverter\AbstractTypeConverter;
use Newland\Toubiz\Sync\Neos\Domain\Model\Article;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ArticleRepository;

class ArticleTypeConverter extends AbstractTypeConverter
{
    protected $sourceTypes = [ 'string' ];
    protected $targetType = Article::class;
    protected $priority = 99;

    /**
     * @Flow\Inject
     * @var ArticleRepository
     */
    protected $articleRepository;

    public function convertFrom(
        $source,
        $targetType,
        array $convertedChildProperties = [],
        PropertyMappingConfigurationInterface $configuration = null
    ) {
        /** @var Article|null $article */
        $article = $this->articleRepository->findByIdentifier((string) $source);

        if ($article === null) {
            throw new TargetNotFoundException('No record with identifier ' . $source . ' found.');
        }

        return $article;
    }
}
