Completed
Push — master ( b67af4...08e6a3 )
by John
02:45
created

BasicURLParser   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 3
dl 0
loc 45
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B parse() 0 29 4
1
<?php
2
namespace LunixRESTBasics\APIRequest\URLParser;
3
4
use LunixREST\APIRequest\URLParser\Exceptions\InvalidRequestURLException;
5
use LunixREST\APIRequest\URLParser\ParsedURL;
6
use LunixREST\APIRequest\URLParser\URLParser;
7
use Psr\Http\Message\UriInterface;
8
9
/**
10
 * A basic URL parser. Expects URLS in the format:
11
 * /VERSION/APIKEY/ENDPOINT_NAME[/INSTANCE_ID].EXTENSION[?QUERY_STRING]
12
 * Class BasicURLParser
13
 * @package LunixRESTBasics\APIRequest\URLParser
14
 */
15
class BasicURLParser implements URLParser
16
{
17
    /**
18
     * BasicURLParser constructor.
19
     */
20 4
    public function __construct()
21
    {
22 4
    }
23
24
    /**
25
     * Parses API request data out of a url
26
     * @param UriInterface $uri
27
     * @return ParsedURL
28
     * @throws InvalidRequestURLException
29
     */
30 3
    public function parse(UriInterface $uri): ParsedURL
31
    {
32 3
        $url = $uri->getPath();
33 3
        $splitURL = explode('/', trim($url, '/'));
34 3
        if (count($splitURL) < 3) {
35 1
            throw new InvalidRequestURLException();
36
        }
37
        //Find endpoint
38 2
        $version = $splitURL[0];
39 2
        $apiKey = $splitURL[1];
40 2
        $endpoint = $splitURL[2];
41
42 2
        $splitExtension = explode('.', $splitURL[count($splitURL) - 1]);
43 2
        $extension = array_pop($splitExtension);
44
45 2
        $element = null;
46
47 2
        if (count($splitURL) == 4) {
48 1
            $element = implode('.', $splitExtension);
49
        } else {
50 1
            $endpoint = implode('.', $splitExtension);
51
        }
52
53 2
        $queryString = $uri->getQuery();
54
55 2
        $mime = \GuzzleHttp\Psr7\mimetype_from_extension($extension);
56
57 2
        return new ParsedURL($endpoint, $element, $version, $apiKey, $mime ? [$mime] : [], $queryString);
58
    }
59
}
60