Completed
Push — master ( 2b639a...0dc5a4 )
by Auke
64:43
created

Value::__construct()   A

Complexity

Conditions 4
Paths 1

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 1
nop 1
dl 0
loc 21
rs 9.584
c 0
b 0
f 0
1
<?php
2
/*
3
 * This file is part of the Ariadne Component Library.
4
 *
5
 * (c) Muze <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace arc\path;
12
13
/**
14
 * This class is a value object for a collapsed path. It behaves as close as possible like a string.
15
 * But you can't change it. Serializing it to json or php will return a string. You can access characters
16
 * by position, like a string. You can count() it.
17
 * \arc\path::collapse() will return an instance of this class. If the collapsed path is identical to
18
 * another path Value, \arc\path::collapse will return that value. This means that you can use a ===
19
 * to compare path Value objects, as long as you only use \arc\path::collapse() to create them.
20
 */
21
final class Value implements \JsonSerializable, \Serializable, \ArrayAccess, \Countable {
22
23
    private $path = '';
24
25
	public function __construct($path)
26
	{
27
        $path = str_replace('\\', '/', (string) $path);
28
        $this->path = \arc\path::reduce(
29
            $path,
30
            function ($result, $entry) {
31
                if ($entry == '..' ) {
32
                    $result = dirname( $result );
33
                    if (isset($result[1])) { // fast check to see if there is a dirname
34
                        $result .= '/';
35
                    } else {
36
                        $result = '/';
37
                    }
38
                } else if ($entry !== '.') {
39
                    $result .= $entry .'/';
40
                }
41
                return $result;
42
            },
43
            '/' // initial value, always start paths with a '/'
44
        );
45
	}
46
47
48
	public function __toString()
49
	{
50
		return $this->path;
51
	}
52
53
	public function jsonSerialize()
54
	{
55
		return $this->path;
56
	}
57
58
	public function serialize()
59
	{
60
		return serialize($this->path);
61
	}
62
63
	public function unserialize($data)
64
	{
65
		$this->path = unserialize($data);
66
	}
67
68
	public function count()
69
	{
70
		return count($this->path);
71
	}
72
73
	public function offsetGet($offset)
74
	{
75
		return $this->path[$offset];
76
	}
77
78
	public function offsetSet($offset, $char)
79
	{
80
		throw new \LogicException('\arc\path\Value is immutable, cast it to a string to change it');
81
	}
82
83
	public function offsetUnset($offset)
84
	{
85
		throw new \LogicException('\arc\path\Value is immutable, cast it to a string to change it');
86
	}
87
88
	public function offsetExists($offset)
89
	{
90
		return isset($this->path[$offset]);
91
	}
92
}