<?php declare(strict_types=1);

namespace Newland\Toubiz\Poi\Neos\Migration\Transformations;

use Neos\ContentRepository\Domain\Model\NodeData;
use Neos\ContentRepository\Migration\Transformations\AbstractTransformation;

class TopicToIdentifiers extends AbstractTransformation
{
    public function execute(NodeData $node): NodeData
    {
        $this->replacePrefixes($node, 'preselectedCategories');
        $this->replacePrefixes($node, 'preselectedProperties');
        $this->replacePrefixes($node, 'preselectedTopics');
        return $node;
    }

    private function replacePrefixes(NodeData $node, string $property): void
    {
        if (!$node->hasProperty($property)) {
            return;
        }

        $values = $node->getProperty($property);
        if (!\is_array($values)) {
            return;
        }

        foreach ($values as $index => $value) {
            $values[$index] = preg_replace('/^(category|attribute):/', '', $value);
        }
        $node->setProperty($property, $values);
    }
}
