1<?php
2namespace Crossjoin\Css\Format\Rule\AtPage;
3
4use Crossjoin\Css\Format\Rule\DeclarationAbstract;
5use Crossjoin\Css\Format\Rule\TraitDeclarations;
6use Crossjoin\Css\Format\Rule\AtRuleAbstract;
7use Crossjoin\Css\Format\StyleSheet\StyleSheet;
8use Crossjoin\Css\Helper\Placeholder;
9
10class PageRule
11extends AtRuleAbstract
12{
13    use TraitDeclarations;
14
15    protected $selector;
16
17    /**
18     * @param string|null $ruleString
19     * @param StyleSheet|null $styleSheet
20     */
21    public function __construct($ruleString = null, StyleSheet $styleSheet = null)
22    {
23        if ($styleSheet !== null) {
24            $this->setStyleSheet($styleSheet);
25        }
26        if ($ruleString !== null) {
27            $ruleString = Placeholder::replaceStringsAndComments($ruleString);
28            $ruleString = Placeholder::removeCommentPlaceholders($ruleString, true);
29            $this->parseRuleString($ruleString);
30        }
31    }
32
33    /**
34     * @param PageSelector $selector
35     * @return $this
36     */
37    public function setSelector(PageSelector $selector)
38    {
39        $this->selector = $selector;
40
41        return $this;
42    }
43
44    /**
45     * @return PageSelector
46     */
47    public function getSelector()
48    {
49        return $this->selector;
50    }
51
52    /**
53     * Adds a declaration to the rule.
54     *
55     * @param PageDeclaration $declaration
56     * @return $this
57     */
58    public function addDeclaration(DeclarationAbstract $declaration)
59    {
60        if ($declaration instanceof PageDeclaration) {
61            $this->declarations[] = $declaration;
62        } else {
63            throw new \InvalidArgumentException(
64                "Invalid declaration instance. Instance of 'PageDeclaration' expected."
65            );
66        }
67
68        return $this;
69    }
70
71    /**
72     * Parses the page rule.
73     *
74     * @param string $ruleString
75     */
76    protected function parseRuleString($ruleString)
77    {
78        // Remove at-rule name and unnecessary white-spaces
79        $ruleString = preg_replace('/^[ \r\n\t\f]*@page[ \r\n\t\f]*/i', '', $ruleString);
80        $ruleString = trim($ruleString, " \r\n\t\f");
81
82        // Extract query list and create a rule from it
83        $pageSelector = new PageSelector($ruleString, $this->getStyleSheet());
84        $this->setSelector($pageSelector);
85    }
86}