<?php declare(strict_types=1);


namespace Newland\Toubiz\Poi\Neos\PageFrame;

use Neos\Flow\Annotations as Flow;
use Newland\PageFrameProvider\Service\PageFrameContextService;
use Newland\Toubiz\Sync\Neos\Domain\Model\Article;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ArticleRepository;

class ArticlePageFrameHelper
{

    /**
     * @var PageFrameContextService
     * @Flow\Inject()
     */
    protected $pageFrameContext;

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

    public function getArticle(): ?Article
    {
        $articleUid = $this->pageFrameContext->getPluginArguments()['article'] ?? null;
        $articleUid = $this->resolveFlowEntityEncoding($articleUid);
        if (!$articleUid) {
            return null;
        }

        return $this->articleRepository->findOneBy([ 'Persistence_Object_Identifier' => $articleUid ]);
    }

    /**
     * Flow entity encoding (if passing models as arguments) uses an array with the `__identity` key for the uuid.
     * @see EntityToIdentityConverter
     *
     * @param string|array|null $articleUid
     * @return string|null
     */
    private function resolveFlowEntityEncoding($articleUid): ?string
    {
        if (\is_string($articleUid) || $articleUid === null) {
            return $articleUid;
        }

        if (\is_array($articleUid) && array_key_exists('__identity', $articleUid)) {
            return $articleUid['__identity'];
        }

        return null;
    }
}
