<?php

/***************************************************************
 *  Copyright notice
 *
 *  (c) sgalinski Internet Services (https://www.sgalinski.de)
 *
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/

namespace SGalinski\SgJobs\ViewHelpers;

use TYPO3\CMS\Extbase\Reflection\ObjectAccess;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

/**
 * Class SetViewHelper
 **/
class SetViewHelper extends AbstractViewHelper {
	/**
	 * Register the ViewHelper arguments
	 */
	public function initializeArguments() {
		parent::initializeArguments();
		$this->registerArgument('name', 'string', 'The name of the new variable', TRUE);
		$this->registerArgument('value', 'mixed', 'The value of the variable', FALSE, NULL);
	}

	/**
	 * Set (override) the variable in $name.
	 *
	 * @return NULL
	 * @throws \TYPO3Fluid\Fluid\Core\Exception
	 */
	public function render() {
		$value = $this->arguments['value'];
		$name = $this->arguments['name'];
		if (NULL === $value) {
			$value = $this->renderChildren();
		}

		if (!str_contains($name, '.')) {
			if (TRUE === $this->templateVariableContainer->exists($name)) {
				$this->templateVariableContainer->remove($name);
			}

			$this->templateVariableContainer->add($name, $value);
		} elseif (1 === \substr_count($name, '.')) {
			$parts = \explode('.', $name);
			$objectName = \array_shift($parts);
			$path = \implode('.', $parts);
			if (FALSE === $this->templateVariableContainer->exists($objectName)) {
				return NULL;
			}
			$object = $this->templateVariableContainer->get($objectName);
			try {
				ObjectAccess::setProperty($object, $path, $value);
				// Note: re-insert the variable to ensure unreferenced values like arrays also get updated
				$this->templateVariableContainer->remove($objectName);
				$this->templateVariableContainer->add($objectName, $object);
			} catch (\Exception $error) {
				return NULL;
			}
		}

		return NULL;
	}
}