-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathSegmentDescriptor.php
More file actions
64 lines (57 loc) · 2.15 KB
/
SegmentDescriptor.php
File metadata and controls
64 lines (57 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
namespace Fhp\Segment;
/**
* Contains meta information about a segment, i.e. anything that can be statically known about a sub-class of
* {@link BaseSegment} through reflection.
*/
class SegmentDescriptor extends BaseDescriptor
{
/** @var SegmentDescriptor[] */
private static array $descriptors = [];
/**
* @param string $class The name of a sub-class of {@link BaseSegment}.
* @return SegmentDescriptor The descriptor for the class.
*/
public static function get(string $class): SegmentDescriptor
{
if (!array_key_exists($class, static::$descriptors)) {
static::$descriptors[$class] = new SegmentDescriptor($class);
}
return static::$descriptors[$class];
}
/** Example: "HITANS" */
public string $kennung;
/**
* Please use the factory above.
* @param string $class The name of a sub-class of {@link BaseSegment}.
*/
protected function __construct(string $class)
{
$this->class = $class;
try {
$clazz = new \ReflectionClass($class);
if (!$clazz->isSubclassOf(BaseSegment::class)) {
throw new \InvalidArgumentException("Must inherit from BaseSegment: $class");
}
parent::__construct($clazz);
// Parse the class name into segment type (Kennung) and version.
if (preg_match('/^([A-Z]+)v([0-9]+)$/', $clazz->getShortName(), $match) !== 1) {
throw new \InvalidArgumentException("Invalid segment class name: $class");
}
$this->kennung = $match[1];
$this->version = (int) $match[2];
} catch (\ReflectionException $e) {
throw new \RuntimeException($e);
}
}
public function validateObject($obj): void // Override
{
parent::validateObject($obj);
if (!$obj instanceof BaseSegment) {
throw new \InvalidArgumentException('Expected sub-class of BaseSegment, got ' . gettype($obj));
}
if ($obj->getName() !== $this->kennung) {
throw new \InvalidArgumentException("Expected $this->kennung, got " . $obj->getName());
}
}
}