<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonCommon\Classes;

/**
 * Helper class to create an object from a given array, that provides magic getter and setter function. This type of
 * object is useful when you need to transform an associative array with array syntax into an object with get and set
 * functions (e.g. when handling document template variables).
 *
 * transforms:
 *   $array['someProperty'] === 123;
 * into:
 *   $arrayObject->getSomeProperty() === 123;
 */
class ArrayAccessorWrapper
{
    /**
     * @var array
     */
    private $properties = [];

    /**
     * ArrayObject constructor.
     *
     * @param array $array
     */
    public function __construct(array $array = [])
    {
        $this->set($array);
    }

    private function set($data)
    {
        foreach ($data as $key => $value) {
            // Lower all variables names and remove shopware _ prefix
            $key = mb_strtolower(str_replace('_', '', $key));
            if (is_array($value)) {
                $sub = new ArrayAccessorWrapper($value);
                $value = $sub;
            }
            $this->properties[$key] = $value;
        }
    }

    public function __call($method, $params)
    {
        $var = mb_strtolower(mb_substr($method, 3));

        if (mb_strpos($method, 'get') === 0) {
            if (array_key_exists($var, $this->properties)) {
                return $this->properties[$var];
            }

            throw new \RuntimeException(sprintf('Calling getter of property "%s" failed, because it was not set.', $var));
        }
        if (mb_strpos($method, 'set') === 0) {
            $this->properties[$var] = $params[0];
        }

        throw new \RuntimeException(sprintf('Method call "%s" is not allowed since it is not a getter/setter call.', $method));
    }
}
