Passed
Pull Request — master (#111)
by Adam
02:02
created

GenericResponse   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 7
c 2
b 0
f 0
dl 0
loc 24
rs 10
wmc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A getLink() 0 15 3
1
<?php
2
3
namespace AcquiaCloudApi\Response;
4
5
use AcquiaCloudApi\Exception\NoLinkedResourceException;
6
use AcquiaCloudApi\Exception\LinkedResourceNotFoundException;
7
8
abstract class GenericResponse
9
{
10
11
    /**
12
     * @param string $name
13
     * @return array{type:string, path:string}
14
     * @throws NoLinkedResourceException
15
     * @throws LinkedResourceNotFoundException
16
     */
17
    public function getLink(string $name)
18
    {
19
        if (!property_exists($this, 'links')) {
20
            throw new NoLinkedResourceException('No linked resources for ' . get_called_class());
21
        } elseif (!property_exists($this->links, $name)) {
22
            throw new LinkedResourceNotFoundException('No property exists for ' . $name . '. Available links are ' . implode(' ', array_keys((array) $this->links)));
23
        }
24
25
        /**
26
         * Because the name of the property within the $links->property->$name object may change, we must avoid accessing it directly.
27
         * The below converts the object into an array, obtains the values directly (bypassing the need to know the key),
28
         * and retrieves the first (and only) item from the resultant array which will be our linked resource path.
29
         */
30
        $path = current(array_values((array) $this->links->$name));
31
        return ['type' => $name, 'path' => $path];
32
    }
33
}
34