Completed
Push — master ( 1ce981...0b7883 )
by Tom
02:21
created

Nth::odd()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/* @description     Transformation Style Sheets - Revolutionising PHP templating    *
3
 * @author          Tom Butler [email protected]                                             *
4
 * @copyright       2015 Tom Butler <[email protected]> | https://r.je/                      *
5
 * @license         http://www.opensource.org/licenses/bsd-license.php  BSD License *
6
 * @version         1.0                                                             */
7
namespace Transphporm\Pseudo;
8
use \Transphporm\Parser\Tokenizer;
9
class Nth implements \Transphporm\Pseudo {
10
	private $count = 0;
11
	private $lastParentNode;
12
13
	public function match($name, $args, \DomElement $element) {
14
		if ($element->parentNode !== $this->lastParentNode) $this->count = 0;
15
16
		$this->lastParentNode = $element->parentNode;
17
18
19
20
		if ($name !== 'nth-child') return true;
21
22
		$this->count++;
23
		$criteria = $args[0];
24
25
		if (is_callable([$this, $criteria])) return $this->$criteria($this->count);
26
		$this->assert(is_numeric($criteria), "Argument passed to 'nth-child' must be 'odd', 'even', or of type int");
27
		return $this->count == $criteria;
28
	}
29
30
	//TODO: Abstract assertions throughout
31
	private function assert($condition, $error) {
32
		if (!$condition) throw new \Exception($error);
33
	}
34
35
	private function odd($num) {
36
		return $num % 2 === 1;
37
	}
38
39
	private function even($num) {
40
		return $num % 2 === 0;
41
	}
42
}
43