Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
ModelOptions
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
3 / 3
13
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 __call
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
7
 getPayloadParams
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2
3declare(strict_types=1);
4
5namespace Vultr\VultrPhp\Util;
6
7use ReflectionClass;
8use RuntimeException;
9
10abstract class ModelOptions
11{
12    private array $prop_map;
13
14    public function __construct()
15    {
16        $reflection = new ReflectionClass($this::class);
17
18        foreach ($reflection->getProperties() as $property)
19        {
20            $this->prop_map[$property->getName()] = (string)$property->getType();
21        }
22    }
23
24    public function __call($name, $args) : mixed
25    {
26        if (!preg_match('/^([a-z]{3,4})(.*)$/', $name, $match))
27        {
28            throw new RuntimeException('Call to undefined method '.$this::class.'::'.$name);
29        }
30
31        $prop = VultrUtil::convertCamelCaseToUnderscore($match[2]);
32        $action = $match[1];
33        if (!isset($this->prop_map[$prop]))
34        {
35            throw new RuntimeException('Call to undefined method prop '.$this::class.'::'.$name);
36        }
37
38        switch ($action)
39        {
40            case 'get':
41            return $this->$prop;
42
43            case 'set':
44                $this->$prop = $args[0];
45            return null;
46
47            case 'with':
48                $object = clone $this;
49                $object->$prop = $args[0];
50            return $object;
51
52            default:
53            throw new RuntimeException('Call to undefined action `'.$action.'` in '.$this::class.'::'.$name);
54        }
55    }
56
57    public function getPayloadParams() : array
58    {
59        $output = [];
60        foreach (array_keys($this->prop_map) as $key)
61        {
62            if ($this->$key === null) continue;
63
64            $value = $this->$key;
65            if ($value instanceof Model)
66            {
67                $value = $value->toArray();
68            }
69
70            $output[$key] = $value;
71        }
72
73        return $output;
74    }
75}