Completed
Push — master ( e6719d...13ae3c )
by John
01:53
created

BasicURLParser::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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