Route   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 9
c 2
b 0
f 0
lcom 1
cbo 0
dl 0
loc 71
ccs 29
cts 29
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A __toString() 0 8 2
B processRoute() 0 25 5
A isRouteProcesed() 0 4 1
1
<?php
2
namespace Wonnova\SDK\Http;
3
4
/**
5
 * This class represents an immutable route, based on a route pattern, a list of params to be replaced on that pattern
6
 * and a list of query params
7
 *
8
 * @author Wonnova
9
 * @link http://www.wonnova.com
10
 */
11
class Route
12
{
13
    /**
14
     * @var string
15
     */
16
    private $processedRoute;
17
    /**
18
     * @var string
19
     */
20
    private $routePattern;
21
    /**
22
     * @var array
23
     */
24
    private $routeParams;
25
    /**
26
     * @var array
27
     */
28
    private $queryParams;
29
30
    /**
31
     * @param string $routePattern
32
     * @param array $routeParams
33
     * @param array $queryParams
34
     */
35 24
    public function __construct($routePattern, array $routeParams = [], $queryParams = [])
36
    {
37 24
        $this->routePattern = $routePattern;
38 24
        $this->routeParams  = $routeParams;
39 24
        $this->queryParams  = $queryParams;
40 24
    }
41
42 24
    public function __toString()
43
    {
44 24
        if (! $this->isRouteProcesed()) {
45 24
            $this->processRoute();
46 24
        }
47
48 24
        return $this->processedRoute;
49
    }
50
51 24
    private function processRoute()
52
    {
53
        // Replace route params from route pattern
54 24
        $uri = $this->routePattern;
55 24
        foreach ($this->routeParams as $key => $value) {
56 15
            $key = '%' . $key . '%';
57 15
            $uri = str_replace($key, $value, $uri);
58 24
        }
59
60
        // If there are query params, process them
61 24
        if (! empty($this->queryParams)) {
62 11
            $uri = $uri . '?';
63 11
            foreach ($this->queryParams as $key => $value) {
64 11
                if (empty($value)) {
65 4
                    continue;
66
                }
67
68 9
                $uri .= sprintf('%s=%s&', $key, $value);
69 11
            }
70
            // Remove the last ampersand
71 11
            $uri = substr($uri, 0, strlen($uri) - 1);
72 11
        }
73
74 24
        $this->processedRoute = $uri;
75 24
    }
76
77 24
    private function isRouteProcesed()
78
    {
79 24
        return isset($this->processedRoute);
80
    }
81
}
82