GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#159)
by Roman
01:55
created

AbstractResource::getAliases()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
crap 2
1
<?php declare(strict_types=1);
2
3
namespace OpenStack\Common\Resource;
4
5
use OpenStack\Common\Transport\Serializable;
6
use OpenStack\Common\Transport\Utils;
7
use Psr\Http\Message\ResponseInterface;
8
9
/**
10
 * Represents a top-level abstraction of a remote API resource. Usually a resource represents a discrete
11
 * entity such as a Server, Container, Load Balancer. Apart from a representation of state, a resource can
12
 * also execute RESTFul operations on itself (updating, deleting, listing) or on other models.
13
 *
14
 * @package OpenStack\Common\Resource
15
 */
16
abstract class AbstractResource implements ResourceInterface, Serializable
17
{
18
    /**
19
     * The JSON key that indicates how the API nests singular resources. For example, when
20
     * performing a GET, it could respond with ``{"server": {"id": "12345"}}``. In this case,
21
     * "server" is the resource key, since the essential state of the server is nested inside.
22
     *
23
     * @var string
24
     */
25
    protected $resourceKey;
26
27
    /**
28
     * An array of aliases that will be checked when the resource is being populated. For example,
29
     *
30
     * 'FOO_BAR' => 'fooBar'
31
     *
32
     * will extract FOO_BAR from the response, and save it as 'fooBar' in the resource.
33
     *
34
     * do the same as above plus indicates that target property is a list
35
     *
36
     * @var array
37
     */
38
    protected $aliases = [];
39
40
    /**
41
     * @var array
42
     */
43
    static private $_aliasesCache = [];
44
45
    /**
46
     * Populates the current resource from a response object.
47
     *
48
     * @param ResponseInterface $response
49
     *
50
     * @return AbstractResource
51
     */
52
    public function populateFromResponse(ResponseInterface $response): self
53
    {
54
        if (strpos($response->getHeaderLine('Content-Type'), 'application/json') === 0) {
55
            $json = Utils::jsonDecode($response);
56
            if (!empty($json)) {
57
                $this->populateFromArray(Utils::flattenJson($json, $this->resourceKey));
58
            }
59
        }
60
61
        return $this;
62
    }
63 74
64
    /**
65 74
     * Populates the current resource from a data array.
66 61
     *
67 61
     * @param array $array
68 61
     *
69 61
     * @return mixed|void
70 61
     */
71
    public function populateFromArray(array $array): self
72 74
    {
73
        $className = get_class($this);
74
75
        if (!isset(self::$_aliasesCache[$className])) {
76
            self::$_aliasesCache[$className] = $this->getAliases();
77
        }
78
79
        $aliases = self::$_aliasesCache[$className];
80
81
        foreach ($array as $key => $val) {
82 133
            $alias = $aliases[$key] ?? false;
83
84 133
            if ($alias instanceof Alias) {
85
                $alias = $aliases[$key];
86 133
87 133
                $key = $alias->getName();
88
                $val = $alias->getValue($this, $val);
89 133
            }
90 131
91 128
            if (property_exists($this, $key)) {
92 128
                $this->{$key} = $val;
93
            }
94 131
        }
95 131
96 133
        return $this;
97 133
    }
98
99 128
    /**
100 2
     * Constructs alias objects
101 128
     *
102 6
     * @return Alias[]
103 6
     */
104 6
    protected function getAliases()
105 6
    {
106 6
        $aliases = [];
107 128
108 28
        foreach ((array)$this->aliases as $alias => $property) {
109 127
            $aliases[$alias] = new Alias($property);
110 11
        }
111 11
112
        return $aliases;
113 128
    }
114
115
    /**
116 124
     * Internal method which retrieves the values of provided keys.
117
     *
118 124
     * @param array $keys
119 124
     *
120 124
     * @return array
121
     */
122
    protected function getAttrs(array $keys)
123 12
    {
124
        $output = [];
125 12
126 12
        foreach ($keys as $key) {
127 12
            if (property_exists($this, $key) && $this->$key !== null) {
128 12
                $output[$key] = $this->$key;
129
            }
130 12
        }
131
132
        return $output;
133 131
    }
134
135 131 View Code Duplication
    public function model(string $class, $data = null): ResourceInterface
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
136
    {
137 131
        $model = new $class();
138 3
139
        // @codeCoverageIgnoreStart
140
        if (!$model instanceof ResourceInterface) {
141 128
            throw new \RuntimeException(sprintf('%s does not implement %s', $class, ResourceInterface::class));
142 128
        }
143 128
        // @codeCoverageIgnoreEnd
144
145
        if ($data instanceof ResponseInterface) {
146
            $model->populateFromResponse($data);
147
        } elseif (is_array($data)) {
148
            $model->populateFromArray($data);
149
        }
150
151
        return $model;
152
    }
153 65
154
    public function serialize(): \stdClass
155 65
    {
156
        $output = new \stdClass();
157 65
158 65
        foreach ((new \ReflectionClass($this))->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
159 65
            $name = $property->getName();
160 65
            $val = $this->{$name};
161 65
162
            $fn = function ($val) {
163 65
                return ($val instanceof Serializable) ? $val->serialize() : $val;
164
            };
165
166
            if (is_array($val)) {
167
                foreach ($val as $sk => $sv) {
168
                    $val[$sk] = $fn($sv);
169
                }
170
            }
171 60
172
            $output->{$name} = $fn($val);
173 60
        }
174
175
        return $output;
176 38
    }
177
}
178