Completed
Push — master ( 876aec...44d674 )
by John
03:09
created

BasicURLParser   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 3
dl 0
loc 45
ccs 0
cts 25
cp 0
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
    public function __construct()
21
    {
22
    }
23
24
    /**
25
     * Parses API request data out of a url
26
     * @param UriInterface $uri
27
     * @return ParsedURL
28
     * @throws InvalidRequestURLException
29
     */
30
    public function parse(UriInterface $uri): ParsedURL
31
    {
32
        $url = $uri->getPath();
33
        $splitURL = explode('/', trim($url, '/'));
34
        if (count($splitURL) < 3) {
35
            throw new InvalidRequestURLException();
36
        }
37
        //Find endpoint
38
        $version = $splitURL[0];
39
        $apiKey = $splitURL[1];
40
        $endpoint = $splitURL[2];
41
42
        $splitExtension = explode('.', $splitURL[count($splitURL) - 1]);
43
        $extension = array_pop($splitExtension);
44
45
        $element = null;
46
47
        if (count($splitURL) == 4) {
48
            $element = implode('.', $splitExtension);
49
        } else {
50
            $endpoint = implode('.', $splitExtension);
51
        }
52
53
        $queryString = $uri->getQuery();
54
55
        $mime = \GuzzleHttp\Psr7\mimetype_from_extension($extension);
56
57
        return new ParsedURL($endpoint, $element, $version, $apiKey, $mime ? [$mime] : [], $queryString);
58
    }
59
}
60