Completed
Push — master ( f9ded0...b13d5b )
by John
02:58 queued 01:00
created

BasicURLParser::parse()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 17
cts 17
cp 1
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 18
nc 3
nop 1
crap 4
1
<?php
2
namespace LunixREST\APIRequest\URLParser;
3
4
use LunixREST\APIRequest\MIMEProvider;
5
use LunixREST\APIRequest\RequestData\URLEncodedQueryStringRequestData;
6
use LunixREST\APIRequest\URLParser\Exceptions\InvalidRequestURLException;
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 LunixREST\Request\URLParser
14
 */
15
class BasicURLParser implements URLParser
16
{
17
18
    /**
19
     * @var MIMEProvider
20
     */
21
    private $MIMEProvider;
22
23
    /**
24
     * BasicURLParser constructor.
25
     * @param MIMEProvider $MIMEProvider
26
     */
27 4
    public function __construct(MIMEProvider $MIMEProvider)
28
    {
29 4
        $this->MIMEProvider = $MIMEProvider;
30 4
    }
31
32
    /**
33
     * Parses API request data out of a url
34
     * @param UriInterface $uri
35
     * @return ParsedURL
36
     * @throws InvalidRequestURLException
37
     */
38 3
    public function parse(UriInterface $uri): ParsedURL
39
    {
40 3
        $url = $uri->getPath();
41 3
        $splitURL = explode('/', trim($url, '/'));
42 3
        if (count($splitURL) < 3) {
43 1
            throw new InvalidRequestURLException();
44
        }
45
        //Find endpoint
46 2
        $version = $splitURL[0];
47 2
        $apiKey = $splitURL[1];
48 2
        $endpoint = $splitURL[2];
49
50 2
        $splitExtension = explode('.', $splitURL[count($splitURL) - 1]);
51 2
        $extension = array_pop($splitExtension);
52
53 2
        $element = null;
54
55 2
        if (count($splitURL) == 4) {
56 1
            $element = implode('.', $splitExtension);
57
        } else {
58 1
            $endpoint = implode('.', $splitExtension);
59
        }
60
61 2
        $queryString = $uri->getQuery();
62
63 2
        $mime = $this->MIMEProvider->getByFileExtension($extension);
64
65 2
        return new ParsedURL($endpoint, $element, $version, $apiKey, $mime ? [$mime] : [], $queryString);
66
    }
67
}
68