Passed
Push — master ( 89d9c2...d06d8f )
by Sebastian
02:25
created

Mailcode_Variables::addPathed()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 9
rs 10
1
<?php
2
/**
3
 * File containing the {@see Mailcode_Variables} class.
4
 *
5
 * @package Mailcode
6
 * @subpackage Variables
7
 * @see Mailcode_Variables
8
 */
9
10
declare(strict_types=1);
11
12
namespace Mailcode;
13
14
/**
15
 * Handler for all variable-related tasks.
16
 *
17
 * @package Mailcode
18
 * @subpackage Variables
19
 * @author Sebastian Mordziol <[email protected]>
20
 */
21
class Mailcode_Variables
22
{
23
    const REGEX_VARIABLE_NAME = '/\$\s*([A-Z0-9_]+)\s*\.\s*([A-Z0-9_]+)|\$\s*([A-Z0-9_]+)/six';
24
    
25
   /**
26
    * @var Mailcode_Variables_Collection_Regular
27
    */
28
    protected $collection;
29
    
30
   /**
31
    * Parses the specified string to find all variable names contained within, if any.
32
    * 
33
    * @param string $subject
34
    * @return Mailcode_Variables_Collection_Regular
35
    */
36
    public function parseString(string $subject) : Mailcode_Variables_Collection_Regular
37
    {
38
        $this->collection = new Mailcode_Variables_Collection_Regular();
39
        
40
        $matches = array();
41
        preg_match_all(self::REGEX_VARIABLE_NAME, $subject, $matches, PREG_PATTERN_ORDER);
42
        
43
        if(!isset($matches[0]) || empty($matches[0]))
44
        {
45
            return $this->collection;
46
        }
47
        
48
        foreach($matches[0] as $idx => $matchedText)
49
        {
50
            if(!empty($matches[3][$idx]))
51
            {
52
                $this->addSingle($matches[3][$idx], $matchedText);
53
            }
54
            else 
55
            {
56
                $this->addPathed($matches[1][$idx], $matches[2][$idx], $matchedText);
57
            }
58
        }
59
        
60
        return $this->collection;
61
    }
62
    
63
    protected function addSingle(string $name, string $matchedText) : void
64
    {
65
        // ignore US style numbers like $451
66
        if(is_numeric($name))
67
        {
68
            return;
69
        }
70
        
71
        $this->collection->add(new Mailcode_Variables_Variable('', $name, $matchedText));
72
    }
73
    
74
    protected function addPathed(string $path, string $name, string $matchedText) : void
75
    {
76
        // ignore US style numbers like $45.12
77
        if(is_numeric($path.'.'.$name))
78
        {
79
            return;
80
        }
81
        
82
        $this->collection->add(new Mailcode_Variables_Variable($path, $name, $matchedText));
83
    }
84
}
85