<?php

namespace Internetgalerie\IgDatapoolFe\Property\TypeConverter;

use TYPO3\CMS\Extbase\Persistence\ObjectStorage;

/**
 * This converter transforms arrays or strings to persistent objects. It does the following:
 *
 * - If the input is string, it is assumed to be a UID. Then, the object is fetched from persistence.
 * - If the input is array, we check if it has an identity property.
 *
 * - If the input has an identity property and NO additional properties, we fetch the object from persistence.
 * - If the input has an identity property AND additional properties, we fetch the object from persistence,
 *   and set the sub-properties. We only do this if the configuration option "CONFIGURATION_MODIFICATION_ALLOWED" is TRUE.
 * - If the input has NO identity property, but additional properties, we create a new object and return it.
 *   However, we only do this if the configuration option "CONFIGURATION_CREATION_ALLOWED" is TRUE.
 *
 * @api
 */
class PersistentObjectConverter extends \TYPO3\CMS\Extbase\Property\TypeConverter\PersistentObjectConverter
{

    protected $priority = 20;

    /**
     * Handle the case if $source is an array.
     *
     * @param  array                                                             $source
     * @param  string                                                            $targetType
     * @param  array                                                             &$convertedChildProperties
     * @param  \TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface $configuration
     * @return object
     * @throws \TYPO3\CMS\Extbase\Property\Exception\InvalidPropertyMappingConfigurationException
     */
    public function convertFrom($source, string $targetType, array $convertedChildProperties = array(), \TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface $configuration = null): ObjectStorage
    {
        $object = parent::convertFrom($source, $targetType, $convertedChildProperties, $configuration);
        /**
         * First try session, then Persistence
         */
        $sessObject = $GLOBALS['TSFE'] -> fe_user -> getKey('ses', md5(\Internetgalerie\IgDatapoolFe\Controller\ActionController::$currentObjectClass));

        if ($sessObject != null) {
            foreach ($sessObject->_getProperties() as $name => $value) {
                if ($sessObject -> _isDirty($name) && $sessObject -> {'get'.ucfirst($name)}() != null) {
                    $object -> {'set'.ucfirst($name)}($value);
                }
            }
        }

        return $object;
    }
}
