ikucheriavenko
3/4/2017 - 6:08 PM

Some operations with Crawler class

Some operations with Crawler class

<?php

namespace AppBundle\Service\Template;

use AppBundle\Entity\Template\TemplateParameter;
use Symfony\Component\DomCrawler\Crawler;

//todo: templateParameter
class TemplateDomCrawler
{
    public function __construct(Crawler $crawler)
    {
        $this->domCrawler = $crawler;
    }

    public function filterParametersOnValidity(array $changes, array $templateParams)
    {
        foreach ($changes as $name => &$change) {
            $this->loadContent($change);

            $addedParametersValues = $this->domCrawler
                ->filterXPath('//span[@class="drag-parameter-inside"]')
                ->each(function (Crawler $crawler, $i) {
                    return trim($crawler->text());
                });

            $existedValues = array_map(function($templateParam) {
                /** @var TemplateParameter $templateParam */
                return $templateParam->getValue();
            }, $templateParams);

            $nonExistedValues = array_diff($addedParametersValues, $existedValues);

            $this->domCrawler
                ->filterXPath('//span[@class="drag-parameter-inside"]')
                ->each(function (Crawler $crawler, $i) use ($nonExistedValues) {
                    if (in_array(trim($crawler->text()), $nonExistedValues)) {
                        $crawler->parents()->first()->getNode(0)->removeChild($crawler->getNode(0));
                    }
                });
        }
    }

    public function removeParameterizationStyles(array $changes)
    {
        foreach ($changes as $name => &$change) {

            $this->loadContent($change);

            $this->domCrawler->filterXPath('//span[@class="drag-parameter-inside"]')
                ->each(function (Crawler $crawler, $i) {
                    $crawler->getNode(0)->setAttribute('style', '');
                });

            $change = $this->domCrawler->html();
        }

        return $changes;
    }

    public function addTwigSyntax(array $changes)
    {
        foreach ($changes as $name => &$change) {
            $this->loadContent($change);

            $this->domCrawler
                ->filterXPath('//span[@class="drag-parameter-inside"]')
                ->each(function (Crawler $crawler, $i) {
                    $crawler->getNode(0)->textContent = "{{ {$crawler->getNode(0)->textContent} }}";
                });

            $change = $this->domCrawler->html();
        }

        return $changes;
    }

    protected function loadContent($content)
    {
        $this->domCrawler->clear();
        $this->domCrawler->addHtmlContent($content);
    }
}