1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
/** |
3
|
|
|
* Created by Vitaly Iegorov <[email protected]>. |
4
|
|
|
* on 06.04.17 at 07:30 |
5
|
|
|
*/ |
6
|
|
|
namespace samsonframework\stringconditiontree\string; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* This class describes string character group structure(CGS). |
10
|
|
|
* |
11
|
|
|
* @author Vitaly Egorov <[email protected]> |
12
|
|
|
*/ |
13
|
|
|
class Structure |
14
|
|
|
{ |
15
|
|
|
/** array Supported character group types */ |
16
|
|
|
const CG_TYPES = [ |
17
|
|
|
FixedVariableFixedCG::class, |
18
|
|
|
VariableFixedCG::class, |
19
|
|
|
VariableCG::class, |
20
|
|
|
FixedCG::class, |
21
|
|
|
]; |
22
|
|
|
|
23
|
|
|
/** @var AbstractCharacterGroup[] */ |
24
|
|
|
public $groups = []; |
25
|
|
|
|
26
|
|
|
/** @var string Input string */ |
27
|
|
|
public $input; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Create string character group structure from input string. |
31
|
|
|
* |
32
|
|
|
* @param string $input Input string for string character group structure |
33
|
|
|
*/ |
34
|
14 |
|
public function __construct(string $input) |
35
|
|
|
{ |
36
|
14 |
|
$this->input = $input; |
37
|
|
|
|
38
|
|
|
// Iterate until input is cleared |
39
|
14 |
|
while (strlen($input)) { |
40
|
14 |
|
foreach (self::CG_TYPES as $characterGroupType) { |
41
|
|
|
// Try to create character group |
42
|
14 |
|
if (($group = $characterGroupType::fromString($input)) !== null) { |
43
|
14 |
|
$this->groups[] = $group; |
44
|
|
|
// Reset CG type iterator to preserve order |
45
|
14 |
|
break; |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
} |
49
|
14 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Compare structure character groups. |
53
|
|
|
* |
54
|
|
|
* @param Structure $structure Compared string structure group |
55
|
|
|
* |
56
|
|
|
* @return int Comparison result |
57
|
|
|
*/ |
58
|
13 |
|
public function compare(Structure $structure): int |
59
|
|
|
{ |
60
|
13 |
|
$initialStructureSize = count($this->groups); |
61
|
13 |
|
$comparedStructureSize = count($structure->groups); |
62
|
13 |
|
$maxSize = max($initialStructureSize, $comparedStructureSize); |
63
|
|
|
|
64
|
|
|
// Iterate maximum sized structure |
65
|
13 |
|
for ($index = 0; $index < $maxSize; $index++) { |
66
|
|
|
// Get compared/initial group or last compared character group is size mismatches |
67
|
13 |
|
$comparedGroup = $structure->groups[$index] ?? $structure->groups[$comparedStructureSize - 1]; |
68
|
13 |
|
$initialGroup = $this->groups[$index] ?? $this->groups[$initialStructureSize - 1]; |
69
|
|
|
|
70
|
|
|
// Define if initial character group has higher priority |
71
|
13 |
|
$return = $initialGroup->compare($comparedGroup); |
72
|
|
|
|
73
|
13 |
|
if ($return !== 0) { |
74
|
12 |
|
return $return; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
2 |
|
return 0; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|