Completed
Push — master ( cfd9ba...ce4958 )
by Milos
26:38
created

AttributePath::fromString()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 17
nc 5
nop 1
1
<?php
2
3
/*
4
 * This file is part of the tmilos/scim-filter-parser package.
5
 *
6
 * (c) Milos Tomic <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Tmilos\ScimFilterParser\Ast;
13
14
class AttributePath extends Node
15
{
16
    /** @var string */
17
    public $schema;
18
19
    /** @var string[] */
20
    public $attributeNames = [];
21
22
    /**
23
     * @param string $string
24
     *
25
     * @return AttributePath
26
     */
27
    public static function fromString($string)
28
    {
29
        $string = trim($string);
30
        if (!$string) {
31
            throw new \InvalidArgumentException('Empty attribute path');
32
        }
33
34
        $colonPos = strrpos($string, ':');
35
        if ($colonPos !== false) {
36
            $schema = substr($string, 0, $colonPos);
37
            $path = substr($string, $colonPos + 1);
38
        } else {
39
            $schema = null;
40
            $path = $string;
41
        }
42
43
        $parts = explode('.', $path);
44
        $attributePath = new static();
45
        $attributePath->schema = $schema;
46
        foreach ($parts as $part) {
47
            $attributePath->add($part);
48
        }
49
50
        return $attributePath;
51
    }
52
53
    public function add($attributeName)
54
    {
55
        $firstLetter = strtolower(substr($attributeName, 0, 1));
56
        if ($firstLetter < 'a' || $firstLetter > 'z') {
57
            throw new \InvalidArgumentException(sprintf('Invalid attribute name "%s"', $attributeName));
58
        }
59
60
        $this->attributeNames[] = $attributeName;
61
    }
62
63
    public function __toString()
64
    {
65
        if ($this->schema) {
66
            return $this->schema.' : '.implode('.', $this->attributeNames);
67
        }
68
69
        return implode('.', $this->attributeNames);
70
    }
71
72
    public function dump()
73
    {
74
        return [
75
            'AttributePath' => $this->__toString(),
76
        ];
77
    }
78
}
79