Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
0.00% |
0 / 18 |
|
0.00% |
0 / 3 |
CRAP | |
0.00% |
0 / 1 |
DataCollection | |
0.00% |
0 / 18 |
|
0.00% |
0 / 3 |
182 | |
0.00% |
0 / 1 |
fromFile | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
6 | |||
__construct | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
72 | |||
jsonSerialize | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
12 |
1 | <?php |
2 | /** @noinspection PhpUnhandledExceptionInspection */ |
3 | declare(strict_types=1); |
4 | // TODO unit test |
5 | |
6 | /* |
7 | * data holding class |
8 | * |
9 | * for some data-classes we use this weak-typed class, for those where it seemed to be especially important |
10 | * a typesafe variant with getters/setters |
11 | * TODO with PHP7.4 both can be merged and will be typesafe without getters/setters |
12 | * |
13 | */ |
14 | |
15 | abstract class DataCollection implements JsonSerializable { |
16 | static function fromFile(string $path = null): DataCollection { |
17 | if (!file_exists($path)) { |
18 | throw new Exception("JSON file not found: `$path`"); |
19 | } |
20 | |
21 | $initData = JSON::decode(file_get_contents($path), true); |
22 | |
23 | $class = get_called_class(); |
24 | |
25 | return new $class($initData); |
26 | } |
27 | |
28 | function __construct($initData) { |
29 | $class = get_called_class(); |
30 | |
31 | foreach ($initData as $key => $value) { |
32 | if (property_exists($this, $key)) { |
33 | $isEmptyString = (($value === "") and is_string($this->$key)); |
34 | $this->$key = ($isEmptyString or $value) ? $value : $this->$key; |
35 | } |
36 | } |
37 | |
38 | foreach ($this as $key => $value) { |
39 | if ($value === null) { |
40 | throw new Exception("$class creation error: `$key` shall not be null after creation."); |
41 | } |
42 | } |
43 | } |
44 | |
45 | public function jsonSerialize(): mixed { |
46 | $jsonData = []; |
47 | |
48 | foreach ($this as $key => $value) { |
49 | if (substr($key, 0, 1) != '_') { |
50 | $jsonData[$key] = $value; |
51 | } |
52 | } |
53 | |
54 | return $jsonData; |
55 | } |
56 | } |