<commit_before><?php
/**
 * translate fields during serialization
 */

namespace Graviton\I18nBundle\Listener;

use Graviton\ExceptionBundle\Exception\DeserializationException;
use Graviton\I18NBundle\Service\I18nUtils;
use JMS\Serializer\EventDispatcher\PreDeserializeEvent;
use Graviton\I18nBundle\Document\TranslatableDocumentInterface;
use Symfony\Component\HttpKernel\Event\KernelEvent;

/**
 * translate fields during serialization
 *
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link     http://swisscom.ch
 */
class I18nDeserializationListener
{
    /**
     * @var mixed[]
     */
    protected $translatableStore = [];

    /**
     * @var \Graviton\I18nBundle\Service\I18nUtils
     */
    protected $utils;

    /**
     * @var string
     */
    protected $defaultLanguage = null;

    /**
     * set utils (i18nutils)
     *
     * @param \Graviton\I18NBundle\Service\I18NUtils $utils utils
     *
     * @return void
     */
    public function setUtils(I18nUtils $utils)
    {
        $this->utils = $utils;
        $this->defaultLanguage = $utils->getDefaultLanguage();
    }

    /**
     * remove translateable strings from object
     *
     * @param PreDeserializeEvent $event event
     *
     * @return void
     */
    public function onPreDeserialize(PreDeserializeEvent $event)
    {
        $eventClass = $event->getType()['name'];

        if (!class_exists($eventClass)) {
            throw new DeserializationException(sprintf('Can\' find class %s to deserialize', $eventClass));
        }

        $object = new $eventClass;

        if ($object instanceof TranslatableDocumentInterface) {
            $data = $event->getData();

            foreach ($object->getTranslatableFields() as $field) {
                $isArray = substr($field, -2, 2) === '[]';
                if ($isArray) {
                    $field = substr($field, 0, -2);
                }

                if (!isset($data[$field])) {
                    continue;
                }

                if ($isArray) {
                    $this->queueTranslatable($data[$field], true);
                    $data[$field] = array_map([$this, 'getDefaultTranslation'], array_values($data[$field]));
                } else {
                    $this->queueTranslatable($data[$field]);
                    $data[$field] = $this->getDefaultTranslation($data[$field]);
                }
            }
            $event->setData($data);
        }
    }

    /**
     * Function will be executed on kernel finish_request event; persists all translatables at once (uniquefied)
     *
     * @throws \Exception
     *
     * @return void
     */
    public function onKernelFinishRequest()
    {
        foreach ($this->translatableStore as $translatable) {
            $this->utils->insertTranslatable($translatable, false);
        }
        $this->utils->flushTranslatables();
    }

    /**
     * Queues a translatable to be inserted at a later time
     *
     * @param array $translatable the translatable
     * @param bool  $isArray      if is many or not
     *
     * @return void
     */
    private function queueTranslatable(array $translatable, $isArray = false)
    {
        if (!$isArray) {
            $translatable = [$translatable];
        }

        foreach ($translatable as $singleItem) {
            $this->translatableStore[$singleItem[$this->defaultLanguage]] = $singleItem;
        }
    }

    /**
     * Get default translation<commit_msg>don't call persist if we haven't written anything<commit_after><?php
/**
 * translate fields during serialization
 */

namespace Graviton\I18nBundle\Listener;

use Graviton\ExceptionBundle\Exception\DeserializationException;
use Graviton\I18NBundle\Service\I18nUtils;
use JMS\Serializer\EventDispatcher\PreDeserializeEvent;
use Graviton\I18nBundle\Document\TranslatableDocumentInterface;
use Symfony\Component\HttpKernel\Event\KernelEvent;

/**
 * translate fields during serialization
 *
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link     http://swisscom.ch
 */
class I18nDeserializationListener
{
    /**
     * @var mixed[]
     */
    protected $translatableStore = [];

    /**
     * @var \Graviton\I18nBundle\Service\I18nUtils
     */
    protected $utils;

    /**
     * @var string
     */
    protected $defaultLanguage = null;

    /**
     * set utils (i18nutils)
     *
     * @param \Graviton\I18NBundle\Service\I18NUtils $utils utils
     *
     * @return void
     */
    public function setUtils(I18nUtils $utils)
    {
        $this->utils = $utils;
        $this->defaultLanguage = $utils->getDefaultLanguage();
    }

    /**
     * remove translateable strings from object
     *
     * @param PreDeserializeEvent $event event
     *
     * @return void
     */
    public function onPreDeserialize(PreDeserializeEvent $event)
    {
        $eventClass = $event->getType()['name'];

        if (!class_exists($eventClass)) {
            throw new DeserializationException(sprintf('Can\' find class %s to deserialize', $eventClass));
        }

        $object = new $eventClass;

        if ($object instanceof TranslatableDocumentInterface) {
            $data = $event->getData();

            foreach ($object->getTranslatableFields() as $field) {
                $isArray = substr($field, -2, 2) === '[]';
                if ($isArray) {
                    $field = substr($field, 0, -2);
                }

                if (!isset($data[$field])) {
                    continue;
                }

                if ($isArray) {
                    $this->queueTranslatable($data[$field], true);
                    $data[$field] = array_map([$this, 'getDefaultTranslation'], array_values($data[$field]));
                } else {
                    $this->queueTranslatable($data[$field]);
                    $data[$field] = $this->getDefaultTranslation($data[$field]);
                }
            }
            $event->setData($data);
        }
    }

    /**
     * Function will be executed on kernel finish_request event; persists all translatables at once (uniquefied)
     *
     * @throws \Exception
     *
     * @return void
     */
    public function onKernelFinishRequest()
    {
        if (empty($this->translatableStore)) {
            return;
        }

        foreach ($this->translatableStore as $translatable) {
            $this->utils->insertTranslatable($translatable, false);
        }
        $this->utils->flushTranslatables();
    }

    /**
     * Queues a translatable to be inserted at a later time
     *
     * @param array $translatable the translatable
     * @param bool  $isArray      if is many or not
     *
     * @return void
     */
    private function queueTranslatable(array $translatable, $isArray = false)
    {
        if (!$isArray) {
            $translatable = [$translatable];
        }

        foreach ($translatable as $singleItem) {
            $this->translatableStore[$singleItem[$this->defaultLanguage]] = $singleItem;
        }
    }

    /**
     * Get default translation
{'fraction_non_alphanumeric': 0.12332145793368046, 'fraction_numerical': 0.00712523979172376, 'mean_word_length': 2.1529157667386607, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 40, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1791928', 'n_tokens_mistral': 2113, 'n_tokens_neox': 2020, 'n_words': 417}