<commit_before><?php

namespace AppBundle\Twig;

use AppBundle\Controller\CatalogController;
use AppBundle\Document\OrderContent;
use AppBundle\Document\Setting;
use AppBundle\Service\SettingsService;
use AppBundle\Service\ShopCartService;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Cache\Simple\FilesystemCache;

class AppRuntime
{
    /** @var ContainerInterface */
    protected $container;
    /** @var  RequestStack */
    protected $requestStack;

    public function __construct(ContainerInterface $container, RequestStack $requestStack)
    {
        $this->container = $container;
        $this->requestStack = $requestStack;
    }

    /**
     * @param \Twig_Environment $environment
     * @param string $chunkName
     * @param string $emptyChunkName
     * @return string
     */
    public function shopCartFunction(\Twig_Environment $environment, $chunkName = 'shop_cart', $emptyChunkName = '')
    {
        if (empty($this->container->getParameter('mongodb_database'))
            || empty($this->container->getParameter('mongodb_user'))) {
                return '';
        }
        $data = [
            'countTotal' => 0,
            'priceTotal' => 0,
            'items' => []
        ];

        $request = $this->requestStack->getCurrentRequest();
        $mongoCache = $this->container->get('mongodb_cache');

        $shopCartData = $mongoCache->fetch(ShopCartService::getCartId());
        if (empty($shopCartData)) {
            if ($emptyChunkName) {
                $templateName = $this->getTemplateName($environment, 'catalog/', $emptyChunkName);
                return $environment->render($templateName, $data);
            } else {
                return '';
            }
        }

        $data['currency'] = $shopCartData['currency'];

        $templateName = $this->getTemplateName($environment, 'catalog/', $chunkName);

        foreach ($shopCartData['data'] as $cName => $products) {
            if (!isset($data['items'][$cName])) {
                $data['items'][$cName] = [];
            }
            foreach ($products as $product) {
                $product['priceTotal'] = $this->getCartContentPriceTotal($product);
                $product['parametersString'] = $this->getCartContentParametersString($product);
                $data['items'][$cName][] = $product;
                $data['countTotal'] += $product['count'];
                $data['priceTotal'] += $product['price'] * $product['count'];
                if (!empty($product['parameters'])) {
                    foreach ($product['parameters'] as $parameters) {
                        if (!empty($parameters['price'])) {
                            $data['priceTotal'] += $parameters['price'] * $product['count'];
                        }
                    }
                }
            }
        }

        return $environment->render($templateName, $data);
    }

    /**
     * @param \Twig_Environment $environment
     * @return string
     */
    public function currencyListFunction(\Twig_Environment $environment)
    {
        if (empty($this->container->getParameter('mongodb_database'))
            || empty($this->container->getParameter('mongodb_user'))) {
                return '';
        }
        $cacheKey = 'currency.list';
        /** @var SettingsService $settingsService */
        $settingsService = $this->container->get('app.settings');
        /** @var FilesystemCache $cache */
        $cache = $this->container->get('app.filecache');

        if ($cache->has($cacheKey)) {
            return $environment->createTemplate($cache->get($cacheKey))->render([]);
        }

        $templateName = 'catalog/currency_list.html.twig';
        $properties = [
            'data' => $settingsService->getSettingsGroup(Setting::GROUP_CURRENCY)
        ];

        $output = $environment->render($templateName, $properties);
        $cache->set($cacheKey, $output, 60*60*24);

        return $output;
    }

    /**
     * @param \Twig_Environment $environment
     * @param string $chunkName
     * @param $collectionName
     * @param array $criteria
     * @param $orderBy
     * @param int $limit
     * @param int $groupSize
     * @param string $cacheKey
     * @return string
     */
    public function contentListFunction(
        \Twig_Environment $environment,
        $chunkName = 'content_list',
        $collectionName,
        $criteria,
        $orderBy = ['_id' => 'asc'],
        $limit = 20,
        $groupSize = 1,
        $cacheKey = ''
    )
    {
        if (!$collectionName) {
            return '';
        }
        /** @var FilesystemCache $cache */
        $cache = $this->container->get('app.filecache');
        if (!empty($cacheKey) && $cache->has($cacheKey)) {
            return $cache->get($cacheKey);
        }

        $templateName = sprintf('catalog/%s.html.twig', $chunkName);

        $catalogController = new CatalogController();
        $catalogController->setContainer($this->container);
        $collection = $catalogController->getCollection($collectionName);

        $items = $collection
            ->find($criteria)
            ->sort($orderBy)
            ->limit($limit);

        $output = $environment->render($templateName, [
            'items' => $items,
            'total' => count($items),
            'groupSize' => $groupSize,
            'groupCount' => ceil(count($items) / $groupSize)
        ]);
        if (!empty($cacheKey)) {
            $cache->set($cacheKey, $output, 60*60*24);
        }
        return $output;
    }

    /**
     * @param $productData
     * @return float
     */
    public function getCartContentPriceTotal($productData)
    {
        $priceTotal = $productData['price'] * $productData['count'];
        if (!empty($productData['parameters'])) {
            foreach ($productData['parameters'] as $parameters) {
                if (!empty($parameters['price'])) {
                    $priceTotal += $parameters['price'] * $productData['count'];
                }
            }
        }
        return $priceTotal;
    }

    /**
     * @param $productData
     * @return string
     */
    public function getCartContentParametersString($productData)
    {
        $parameters = isset($productData['parameters']) && is_array($productData['parameters'])
            ? $productData['parameters']<commit_msg>Cache key option for function "contentList"<commit_after><?php

namespace AppBundle\Twig;

use AppBundle\Controller\CatalogController;
use AppBundle\Document\OrderContent;
use AppBundle\Document\Setting;
use AppBundle\Service\SettingsService;
use AppBundle\Service\ShopCartService;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Cache\Simple\FilesystemCache;

class AppRuntime
{
    /** @var ContainerInterface */
    protected $container;
    /** @var  RequestStack */
    protected $requestStack;

    public function __construct(ContainerInterface $container, RequestStack $requestStack)
    {
        $this->container = $container;
        $this->requestStack = $requestStack;
    }

    /**
     * @param \Twig_Environment $environment
     * @param string $chunkName
     * @param string $emptyChunkName
     * @return string
     */
    public function shopCartFunction(\Twig_Environment $environment, $chunkName = 'shop_cart', $emptyChunkName = '')
    {
        if (empty($this->container->getParameter('mongodb_database'))
            || empty($this->container->getParameter('mongodb_user'))) {
                return '';
        }
        $data = [
            'countTotal' => 0,
            'priceTotal' => 0,
            'items' => []
        ];

        $request = $this->requestStack->getCurrentRequest();
        $mongoCache = $this->container->get('mongodb_cache');

        $shopCartData = $mongoCache->fetch(ShopCartService::getCartId());
        if (empty($shopCartData)) {
            if ($emptyChunkName) {
                $templateName = $this->getTemplateName($environment, 'catalog/', $emptyChunkName);
                return $environment->render($templateName, $data);
            } else {
                return '';
            }
        }

        $data['currency'] = $shopCartData['currency'];

        $templateName = $this->getTemplateName($environment, 'catalog/', $chunkName);

        foreach ($shopCartData['data'] as $cName => $products) {
            if (!isset($data['items'][$cName])) {
                $data['items'][$cName] = [];
            }
            foreach ($products as $product) {
                $product['priceTotal'] = $this->getCartContentPriceTotal($product);
                $product['parametersString'] = $this->getCartContentParametersString($product);
                $data['items'][$cName][] = $product;
                $data['countTotal'] += $product['count'];
                $data['priceTotal'] += $product['price'] * $product['count'];
                if (!empty($product['parameters'])) {
                    foreach ($product['parameters'] as $parameters) {
                        if (!empty($parameters['price'])) {
                            $data['priceTotal'] += $parameters['price'] * $product['count'];
                        }
                    }
                }
            }
        }

        return $environment->render($templateName, $data);
    }

    /**
     * @param \Twig_Environment $environment
     * @return string
     */
    public function currencyListFunction(\Twig_Environment $environment)
    {
        if (empty($this->container->getParameter('mongodb_database'))
            || empty($this->container->getParameter('mongodb_user'))) {
                return '';
        }
        $cacheKey = 'currency.list';
        /** @var SettingsService $settingsService */
        $settingsService = $this->container->get('app.settings');
        /** @var FilesystemCache $cache */
        $cache = $this->container->get('app.filecache');

        if ($cache->has($cacheKey)) {
            return $environment->createTemplate($cache->get($cacheKey))->render([]);
        }

        $templateName = 'catalog/currency_list.html.twig';
        $properties = [
            'data' => $settingsService->getSettingsGroup(Setting::GROUP_CURRENCY)
        ];

        $output = $environment->render($templateName, $properties);
        $cache->set($cacheKey, $output, 60*60*24);

        return $output;
    }

    /**
     * @param \Twig_Environment $environment
     * @param string $chunkName
     * @param $collectionName
     * @param array $criteria
     * @param $orderBy
     * @param int $limit
     * @param int $groupSize
     * @param string $cacheKey
     * @return string
     */
    public function contentListFunction(
        \Twig_Environment $environment,
        $chunkName = 'content_list',
        $collectionName,
        $criteria,
        $orderBy = ['_id' => 'asc'],
        $limit = 20,
        $groupSize = 1,
        $cacheKey = ''
    )
    {
        if (!$collectionName) {
            return '';
        }
        /** @var FilesystemCache $cache */
        $cache = $this->container->get('app.filecache');
        if (!empty($cacheKey) && $cache->has("content.{$cacheKey}")) {
            return $cache->get("content.{$cacheKey}");
        }

        $templateName = sprintf('catalog/%s.html.twig', $chunkName);

        $catalogController = new CatalogController();
        $catalogController->setContainer($this->container);
        $collection = $catalogController->getCollection($collectionName);

        $items = $collection
            ->find($criteria)
            ->sort($orderBy)
            ->limit($limit);

        $output = $environment->render($templateName, [
            'items' => $items,
            'total' => count($items),
            'groupSize' => $groupSize,
            'groupCount' => ceil(count($items) / $groupSize)
        ]);
        if (!empty($cacheKey)) {
            $cache->set("content.{$cacheKey}", $output, 60*60*24);
        }
        return $output;
    }

    /**
     * @param $productData
     * @return float
     */
    public function getCartContentPriceTotal($productData)
    {
        $priceTotal = $productData['price'] * $productData['count'];
        if (!empty($productData['parameters'])) {
            foreach ($productData['parameters'] as $parameters) {
                if (!empty($parameters['price'])) {
                    $priceTotal += $parameters['price'] * $productData['count'];
                }
            }
        }
        return $priceTotal;
    }

    /**
     * @param $productData
     * @return string
     */
    public function getCartContentParametersString($productData)
    {
        $parameters = isset($productData['parameters']) && is_array($productData['parameters'])
            ? $productData['parameters']
{'fraction_non_alphanumeric': 0.15091274752475248, 'fraction_numerical': 0.002629950495049505, 'mean_word_length': 2.247676463200201, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 111, 'https://': 0, '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': '3202551', 'n_tokens_mistral': 3476, 'n_tokens_neox': 3367, 'n_words': 586}