Transform CSS expression to XPath

@param string $path_src

@return string
178865
protected function _transform($path_src)
    {
        $path = (string)$path_src;

        if (strpos($path, ',') !== false) {
            $paths = explode(',', $path);
            $expressions = [];
            foreach ($paths as $path) {
                $xpath = $this->transform(trim($path));
                if (is_string($xpath)) {
                    $expressions[] = $xpath;
                } elseif (is_array($xpath)) {
                    /** @noinspection SlowArrayOperationsInLoopInspection */
                    $expressions = array_merge($expressions, $xpath);
                }
            }
            return implode('|', $expressions);
        }

        $paths = ['//'];
        $path = preg_replace('|\s+>\s+|', '>', $path);
        $segments = preg_split('/\s+/', $path);
        foreach ($segments as $key => $segment) {
            $pathSegment = static::_tokenize($segment);
            if (0 === $key) {
                if (0 === strpos($pathSegment, '[contains(')) {
                    $paths[0] .= '*' . ltrim($pathSegment, '*');
                } else {
                    $paths[0] .= $pathSegment;
                }
                continue;
            }
            if (0 === strpos($pathSegment, '[contains(')) {
                foreach ($paths as $pathKey => $xpath) {
                    $paths[$pathKey] .= '//*' . ltrim($pathSegment, '*');
                    $paths[] = $xpath . $pathSegment;
                }
            } else {
                foreach ($paths as $pathKey => $xpath) {
                    $paths[$pathKey] .= '//' . $pathSegment;
                }
            }
        }

        if (1 === count($paths)) {
            return $paths[0];
        }
        return implode('|', $paths);
    }
414260
private function extractWebspaceFromPath($path)
    {
        $match = preg_match(
            sprintf(
                '/^\/%s\/([\w\.-]*?)\/.*$/',
                $this->pathSegmentRegistry->getPathSegment('base')
            ),
            $path,
            $matches
        );

        if ($match) {
            return $matches[1];
        }

        return;
    }
276359
protected static function readCss( $path, $class_prefix = 'fa-' ) {
		//if path is incorrect or file does not exist, stop.
		if ( ! file_exists( $path ) ) {
			throw new \Exception( 'Can\'t read the CSS. File does not exists.' );
		}

		$css     = file_get_contents( $path );
		$pattern = '/\.(' . $class_prefix . '(?:\w+(?:-)?)+):before\s+{\s*content:\s*"(.+)";\s+}/';

		preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER );

		$icons = array();
		foreach ( $matches as $match ) {
			$icons[ $match[1] ] = $match[2];
		}

		return $icons;
	}
565191
def selector_to_xpath(cls, selector, xmlns=None):
        
        selector = selector.replace(' .', ' *.')
        if selector[0] == '.':
            selector = '*' + selector
            log.debug(selector)
        
        if '#' in selector:
            selector = selector.replace('#', '*#')
            log.debug(selector)

        if xmlns is not None:
            prefix = list(xmlns.keys())[0]
            href = xmlns[prefix]
            selector = ' '.join([
                (n.strip() != '>' and prefix + '|' + n.strip() or n.strip())
                for n in selector.split(' ')
                ])
            log.debug(selector)
        
        path = cssselect.GenericTranslator().css_to_xpath(selector)
        path = path.replace("descendant-or-self::", "")
        path = path.replace("/descendant::", "//")
        path = path.replace('/*/', '//')
        
        log.debug(' ==> %s' % path)
        
        return path
148247
public static function img($src, $attr = array())
	{
		if ( ! preg_match('#^(\w+://)# i', $src))
		{
			$src = \Uri::base(false).$src;
		}
		$attr['src'] = $src;
		$attr['alt'] = (isset($attr['alt'])) ? $attr['alt'] : pathinfo($src, PATHINFO_FILENAME);
		return html_tag('img', $attr);
	}
1046921
public function html($path=null, $pos=0) {
		if($this->xpath === null)
			return null;
		if(!$path)
			return trim(static::getInnerHTML($this->domnode));
		else {
			$item = $this->item($path, $pos);
			if($item === null)
				return null;
			return $item->html();
		}
	}
209705
public function link(String $path) : String
    {
        if( ! IS::url($path) )
        {
            $path = Request::getBaseURL(Base::suffix($path, '.css'));
        }

        $attributes['href'] = $path;
        $attributes['rel']  = 'stylesheet';
        $attributes['type'] = 'text/css';

        return $this->_singleElement('link', $attributes);
    }
232436
public static function toXPath($selector)
    {
        if (isset(self::$compiled[$selector])){
            return self::$compiled[$selector];
        }

        // Select DOMText
        if ($selector === 'text') {
            return '//text()';
        }

        // Select DOMComment
        if ($selector === 'comment') {
            return '//comment()';
        }

        if (!class_exists('Symfony\\Component\\CssSelector\\CssSelectorConverter')) {
            throw new \RuntimeException('Unable to filter with a CSS selector as the Symfony CssSelector 2.8+ is not installed (you can use filterXPath instead).');
        }

        $converter = new CssSelectorConverter(true);

        $xPathQuery = $converter->toXPath($selector);
        self::$compiled[$selector] = $xPathQuery;

        return $xPathQuery;
    }
712620
public function getElement($path)
    {
        $found = null;

        foreach ($this->getElements() as $element) {
            if ($element instanceof ElementsInterface) {
                if (! is_null($found = $element->getElement($path))) {
                    return $found;
                }
            }

            if ($element instanceof NamedFormElement && $element->getPath() == $path) {
                return $element;
            }
        }
    }
1191515
public function extractPathInfo($pathInfo)
    {
        if ($this->getRegex() === null) {
            return $pathInfo;
        }

        preg_match($this->getRegex(), $pathInfo, $matches);

        if (isset($matches[1])) {
            return $matches[1];
        } else {
            // Empty     then root node ("/" or "/edit)
            return "/";
        }
    }
623008
public function xpath() {
    if (!isset($this->xpath)) {
      $this->xpath = new \DOMXPath($this);
    }

    return $this->xpath;
  }
80535
public function query($path)
    {
        $this->initializeXPath();

        if ($path) {
            return $this->xpath->query($path);
        }
        return false;
    }
105656
public static function transform(string $path)
    {
        if (isset(self::$xpath_cache[$path])) {
            return self::$xpath_cache[$path];
        }

        $tmp_path = self::replaceCharInsideEnclosure($path, ',');
        if (strpos($tmp_path, ',') !== false) {
            $paths = explode(',', $tmp_path);
            $expressions = array();

            foreach ($paths as $single_path) {
                $single_path = str_replace("\0", ',', $single_path); // restore commas
                $xpath = self::transform(trim($single_path));
                $expressions[] = $xpath;
            }

            return implode('|', $expressions);
        }

        // replace spaces inside (), to correctly create tokens (restore later)

        $path_escaped = self::replaceCharInsideEnclosure($path, ' ');

        // create tokens and analyze to create segments

        $tokens = preg_split('/\s+/', $path_escaped);

        $segments = array();

        foreach ($tokens as $key => $token) {
            $token = str_replace("\0", ' ', $token); // restore spaces

            if ($segment = self::getSegmentFromToken($token, $key, $tokens)) {
                $segments[] = $segment;
            }
        }

        // use segments to create array with transformed tokens

        $new_path_tokens = self::transformCssSegments($segments);

        // result tokens to xpath

        $xpath_result = implode('', $new_path_tokens);

        self::$xpath_cache[$path] = $xpath_result;

        return $xpath_result;
    }
710118
public function render(Path $path)
    {
        $html = null;
        $t = new TemplateLocator($path);
        foreach ($t->next() as $template) {
            $context = $this->buildContext($path, $template);

            // Skip template if no valid context could be created.
            if ($context === null) continue;

            // If abort() wasn't called in template, and it returned some HTML, we'll break and return this.
            $html = $this->renderOrAbort($template, $context);
            if ($html !== null) break;
        }
        if ($html === null) {
            // If no match is found, it might be that we're looking for an "index" model, so append "/index" adn try
            // again.
            $pathWithoutExt = explode('/', $path->getWithoutExtension());
            $fileWithoutExt = end($pathWithoutExt);
            if ($fileWithoutExt !== 'index') {
                return $this->render(new Path($path . '/index'));
            }

            // Nope, this really is a 404.
            return null;
        }

        // What ContentLoaders / Models were accessed during render?
        foreach ($this->resources as $modelName => $resource) {
            if ($resource->wasAccessed()) {
                $this->dispatcher->dispatch(
                    RenderDependencyEvent::NAME, new RenderDependencyEvent($modelName, $path)
                );
            }
        }

        $this->dispatcher
            ->dispatch(RenderEvent::NAME, new RenderEvent($path, $html));

        return $html;
    }
417999
public function selector2xpath($selector)
    {
        $parts = preg_split('/\\s+/', $selector);
        $xpath = "";
        foreach ($parts as $part) {
            if (preg_match('/^([A-Za-z][A-Za-z0-9]*)/', $part, $matches)) {
                $xpath .= "//$matches[1]";
            } else {
                $xpath .= "//*";
            }
            $xfilters = array();
            if (preg_match('/#([^#.\[]+)/', $part, $matches)) {
                $xfilters[] = "@id='$matches[1]'";
            }
            if (preg_match('/\.([^#.\[]+)/', $part, $matches)) {
                $xfilters[] = "contains(@class,'$matches[1]')";
            }
            if ($xfilters) {
                $xpath .= '[' . implode(',', $xfilters) . ']';
            }
        }
        return $xpath;
    }
400836
public function xpath($path)
    {
        if ($path === '') {
            return clone $this;
        }
        $query = $this->_document->getQuery();

        $nodes = [];
        foreach ($this->_nodes as $node) {
            /**
             * @var \DOMNode $node2
             */
            foreach ($query->xpath($path, $node) as $node2) {
                $nodes[$node2->getNodePath()] = $node2;
            }
        }

        return new SelectorList($this, array_values($nodes));
    }
341299
public function findClass($path)
    {
        $namespace = null;
        $tokens = token_get_all(file_get_contents($path));
        foreach ($tokens as $key => $token) {
            if ($this->tokenIsNamespace($token)) {
                $namespace = $this->getNamespace($key + 2, $tokens);
            } elseif ($this->tokenIsClassOrInterface($token)) {
                return ltrim($namespace.'\\'.$this->getClass($key + 2, $tokens), '\\');
            }
        }
    }