4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\CssSelector\XPath\Extension;
14 use Symfony\Component\CssSelector\Exception\ExpressionErrorException;
15 use Symfony\Component\CssSelector\XPath\XPathExpr;
18 * XPath expression translator pseudo-class extension.
20 * This component is a port of the Python cssselect library,
21 * which is copyright Ian Bicking, @see https://github.com/SimonSapin/cssselect.
23 * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
27 class PseudoClassExtension extends AbstractExtension
32 public function getPseudoClassTranslators()
35 'root' => array($this, 'translateRoot'),
36 'first-child' => array($this, 'translateFirstChild'),
37 'last-child' => array($this, 'translateLastChild'),
38 'first-of-type' => array($this, 'translateFirstOfType'),
39 'last-of-type' => array($this, 'translateLastOfType'),
40 'only-child' => array($this, 'translateOnlyChild'),
41 'only-of-type' => array($this, 'translateOnlyOfType'),
42 'empty' => array($this, 'translateEmpty'),
47 * @param XPathExpr $xpath
51 public function translateRoot(XPathExpr $xpath)
53 return $xpath->addCondition('not(parent::*)');
57 * @param XPathExpr $xpath
61 public function translateFirstChild(XPathExpr $xpath)
66 ->addCondition('position() = 1');
70 * @param XPathExpr $xpath
74 public function translateLastChild(XPathExpr $xpath)
79 ->addCondition('position() = last()');
83 * @param XPathExpr $xpath
87 * @throws ExpressionErrorException
89 public function translateFirstOfType(XPathExpr $xpath)
91 if ('*' === $xpath->getElement()) {
92 throw new ExpressionErrorException('"*:first-of-type" is not implemented.');
97 ->addCondition('position() = 1');
101 * @param XPathExpr $xpath
105 * @throws ExpressionErrorException
107 public function translateLastOfType(XPathExpr $xpath)
109 if ('*' === $xpath->getElement()) {
110 throw new ExpressionErrorException('"*:last-of-type" is not implemented.');
115 ->addCondition('position() = last()');
119 * @param XPathExpr $xpath
123 public function translateOnlyChild(XPathExpr $xpath)
128 ->addCondition('last() = 1');
132 * @param XPathExpr $xpath
136 * @throws ExpressionErrorException
138 public function translateOnlyOfType(XPathExpr $xpath)
140 if ('*' === $xpath->getElement()) {
141 throw new ExpressionErrorException('"*:only-of-type" is not implemented.');
144 return $xpath->addCondition('last() = 1');
148 * @param XPathExpr $xpath
152 public function translateEmpty(XPathExpr $xpath)
154 return $xpath->addCondition('not(*) and not(string-length())');
160 public function getName()
162 return 'pseudo-class';