Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.12% covered (success)
94.12%
16 / 17
75.00% covered (warning)
75.00%
3 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
Factory
94.12% covered (success)
94.12%
16 / 17
75.00% covered (warning)
75.00%
3 / 4
6.01
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 create
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getEntity
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 getEntityName
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
3.01
1<?php
2
3namespace BO\Zmsentities\Schema;
4
5use BO\Zmsentities\Helper\Property;
6
7/**
8 * @SuppressWarnings(NumberOfChildren)
9 */
10class Factory
11{
12    /**
13     * @var mixed $data unserialized entity
14     */
15    protected $data = null;
16
17    public function __construct(mixed $data)
18    {
19        $this->data = $data;
20    }
21
22    public static function create(mixed $data): self
23    {
24        return new self($data);
25    }
26
27    /**
28     * Detect type of entity and return initialized object
29     *
30     * @return Entity
31     */
32    public function getEntity()
33    {
34        $entityName = $this->getEntityName();
35        /** @var class-string<Entity> $class */
36        $class = "\\BO\\Zmsentities\\$entityName";
37        /** @var Entity $entity */
38        $entity = new $class(new UnflattedArray($this->data));
39        return $entity;
40    }
41
42    /**
43     * Parse schema and return Entity name
44     *
45     * @return string
46     */
47    public function getEntityName()
48    {
49        if (!Property::__keyExists('$schema', $this->data)) {
50            throw new \BO\Zmsentities\Exception\SchemaMissingKey('Missing $schema-key on given data.');
51        }
52        $schema = $this->data['$schema'];
53        $entityName = is_string($schema)
54            ? (preg_replace('#^.*/([^/]+)\.json#', '$1', $schema) ?? '')
55            : '';
56        $entityName = ucfirst($entityName);
57
58        // jsonSerialize() lowercases the class short name (AvailabilityHistory →
59        // availabilityhistory.json). ucfirst then yields Availabilityhistory, which
60        // PSR-4 cannot autoload on Linux.
61        $classAliases = [
62            'Availabilityhistory' => 'AvailabilityHistory',
63        ];
64
65        return $classAliases[$entityName] ?? $entityName;
66    }
67}