HEX
Server: LiteSpeed
System: Linux houston.panomity.com 6.8.0-100-generic #100-Ubuntu SMP PREEMPT_DYNAMIC Tue Jan 13 16:40:06 UTC 2026 x86_64
User: nudepix (1011)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: //home/timetracker.panomity.com/src/Form/DataTransformer/TagArrayToStringTransformer.php
<?php

/*
 * This file is part of the Kimai time-tracking app.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Form\DataTransformer;

use App\Entity\Tag;
use App\Repository\TagRepository;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;

final class TagArrayToStringTransformer implements DataTransformerInterface
{
    public function __construct(private TagRepository $tagRepository)
    {
    }

    /**
     * Transforms an array of tags to a string.
     *
     * @param Tag[]|null $tags
     * @return string
     */
    public function transform(mixed $tags): mixed
    {
        if (empty($tags)) {
            return '';
        }

        return implode(', ', $tags);
    }

    /**
     * Transforms a string to an array of tags.
     *
     * @see \Symfony\Bridge\Doctrine\Form\DataTransformer\CollectionToArrayTransformer::reverseTransform()
     *
     * @param string|null $stringOfTags
     * @return Tag[]
     * @throws TransformationFailedException
     */
    public function reverseTransform(mixed $stringOfTags): mixed
    {
        // check for empty tag list
        if ('' === $stringOfTags || null === $stringOfTags) {
            return [];
        }

        $names = array_filter(array_unique(array_map('trim', explode(',', $stringOfTags))));

        // get the current tags and find the new ones that should be created
        $tags = $this->tagRepository->findBy(['name' => $names]);
        // works, because of the implicit case: (string) $tag
        $newNames = array_diff($names, $tags);

        foreach ($newNames as $name) {
            $tag = new Tag();
            $tag->setName(mb_substr($name, 0, 100));
            $tags[] = $tag;

            // new tags persist automatically thanks to the cascade={"persist"}
        }

        return $tags;
    }
}