<?php
namespace Newland\Toubiz\Sync\Neos\Domain\Repository;

/*
 * This file is part of the "toubiz-sync-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Persistence\Repository;
use Newland\Toubiz\Sync\Neos\Domain\Model\KeyValue;

/**
 * KeyValue repository.
 *
 * @Flow\Scope("singleton")
 *
 * @method KeyValue|null findOneByIdentifier(string $identifier);
 */
class KeyValueRepository extends Repository
{

    /**
     * @param string $identifier
     * @param string $data
     */
    public function store(string $identifier, string $data): void
    {
        $keyValue = $this->findOneByIdentifier($identifier);
        $persisted = (bool) $keyValue;

        if (!$keyValue) {
            $keyValue = new KeyValue;
        }

        $keyValue->setIdentifier($identifier);
        $keyValue->setValue($data);

        if ($persisted) {
            $this->update($keyValue);
        } else {
            $this->add($keyValue);
        }
    }

    /**
     * @param string $identifier
     * @return mixed|null
     */
    public function retrieve(string $identifier)
    {
        $keyValue = $this->findOneByIdentifier($identifier);

        if ($keyValue) {
            return $keyValue->getValue();
        }

        return null;
    }
}
