<?php

namespace KupShop\GTMBundle\Tests;

use KupShop\GTMBundle\Utils\GTMLoader;
use Symfony\Component\DependencyInjection\ContainerInterface;

trait GTMTestHelper
{
    protected $serviceCache;

    /**
     *  Ve chvíli, kdy se volá např. /kosik/ se vyrenderuji spravne data z gtm checkout class.
     *  Jenze se v defaultnich sablonach zavola taky addToCart a removeFromCart a naloadujou se tam i data z tehlech class.
     *  Proto si je pripadne v testu namockuju aby nic nedelaly.
     *
     * @return void
     */
    protected function mockUnusedClasses(array $allowClasses, ?ContainerInterface $container = null)
    {
        $gtmLoader = $this->get(GTMLoader::class);
        $classes = $gtmLoader->getPageTypes() + $gtmLoader->getEcommerceTypes();

        if (is_null($this->serviceCache)) {
            foreach ($classes as $eventName => $className) {
                $this->serviceCache[$className] = $this->get($className);
            }
        }

        foreach ($classes as $eventName => $className) {
            if (!in_array($className, $allowClasses)) {
                $mockClass = $this->getMockBuilder($className)
                    ->setMethods(['getPageData'])
                    ->setMethods(['getData'])
                    ->getMock();
                $this->set($className, $mockClass, $container);
            } else {
                $this->set($className, $this->serviceCache[$className], $container);
            }
        }
    }

    public function recursivelyChangeType($data)
    {
        if ($data instanceof \stdClass) {
            $data = (array) $data;
        }

        if (!is_array($data)) {
            return $data;
        }

        $result = [];

        foreach ($data as $key => $value) {
            $result[$key] = $this->recursivelyChangeType($value);
        }

        return $result;
    }
}
