ModelResolver   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 7
Bugs 0 Features 0
Metric Value
wmc 4
eloc 17
c 7
b 0
f 0
dl 0
loc 60
ccs 17
cts 17
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A find() 0 25 2
A loadVersionIfNeeded() 0 7 2
1
<?php
2
3
namespace Spinen\ConnectWise\Support;
4
5
/**
6
 * Class ModelResolver
7
 *
8
 * @package Spinen\ConnectWise\Support
9
 */
10
class ModelResolver
11
{
12
    /**
13
     * List of Models for each resource endpoint for each used version
14
     *
15
     * @var array
16
     */
17
    protected $maps = [];
18
19
    /**
20
     * Find the model to fill with the results from the request
21
     *
22
     * This is a little more complicated than you would think that it needs to be, but we have to map the response to
23
     * a model by looking at the URI.  If the URI is for a specific id, then the id has to be converted to the wildcard
24
     * in the map. If it is a single resource & not a collection then the id has to be removed from the end.
25
     *
26
     * @param string $uri
27
     * @param string $version
28
     *
29
     * @return string|null
30
     */
31 2
    public function find($uri, $version)
32
    {
33 2
        $this->loadVersionIfNeeded($version);
34
35
        // Pull leading slash off
36 2
        $uri = ltrim($uri, '/');
37
38
        // Bust the resource into the parts
39 2
        $uri_parts = parse_url($uri);
40
41
        // Trim "/" off the end
42 2
        $pattern = rtrim($uri_parts['path'], '/');
43
44
        // Replace /(/)d+(/?)/ with /$1{id}$2/
45 2
        $pattern = preg_replace('|(/)\\d+(/?)|u', '$1{id}$2', $pattern);
46
47
        // Make regex
48 2
        $pattern = '|^/' . $pattern . '$|ui';
49
50
        // Search the map for the uri that matches
51 2
        return ($uri = $this->maps[$version]->search(
52
            function ($model, $uri) use ($pattern) {
53 2
                return preg_match($pattern, $uri);
54 2
            }
55 2
        )) ? $this->maps[$version][$uri] : null;
56
    }
57
58
    /**
59
     * If not already loaded, load in the uri to class for the version
60
     *
61
     * @param string $version
62
     */
63 2
    protected function loadVersionIfNeeded($version)
64
    {
65 2
        if (!array_key_exists($version, $this->maps)) {
66 2
            $this->maps[$version] = collect(
67 2
                json_decode(
68 2
                    @file_get_contents(__DIR__ . '/../Models/v' . str_replace('.', '_', $version) . '/map.json'),
69 2
                    true
70
                )
71
            );
72
        }
73 2
    }
74
}
75