Completed
Push — master ( 76dcd2...c75946 )
by Michael
02:21
created

AsinParser   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 12
c 5
b 0
f 0
lcom 1
cbo 2
dl 0
loc 75
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
C processAsin() 0 33 8
A getAsin() 0 4 1
A setAsin() 0 4 1
A getCleanedUrl() 0 3 1
1
<?php
2
namespace Amazon;
3
4
use Amazon\Exceptions\InvalidAsinException;
5
6
7
/**
8
 * Class AsinFetcher
9
 * @see https://de.wikipedia.org/wiki/Amazon_Standard_Identification_Number
10
 * @package Amazon
11
 */
12
class AsinParser extends Parser
13
{
14
15
    const LENGTH_ASIN = 10;
16
17
    /**
18
     * @var string
19
     */
20
    private $asin = null;
21
22
    public function __construct($url)
23
    {
24
        parent::__construct($url);
25
        $urlParameter = parse_url($this->getUrl());
26
27
        $this->processAsin($urlParameter['host'], $urlParameter['path']);
28
    }
29
30
    protected function processAsin($host, $path)
31
    {
32
        $path = str_replace('/product', '', $path);
33
        $pathParts = explode('/', $path);
34
35
        //ShortUrl
36
        if (preg_match('/amzn/', $host)) {
37
            $this->setAsin(end($pathParts));
38
            return;
39
        }
40
41
        if (false === array_key_exists(2, $pathParts)) {
42
            throw new InvalidAsinException(sprintf('Url %s has no ASIN', $this->getUrl()));
43
        }
44
45
        foreach ($pathParts as $index => $part) {
46
            if (strlen($part) === self::LENGTH_ASIN) {
47
                if (array_key_exists($index - 1, $pathParts) && $pathParts[$index - 1] === 'dp') {
48
                    $this->setAsin($part);
49
                    return;
50
                }
51
52
            }
53
        }
54
55
        if (strlen($pathParts[2]) !== self::LENGTH_ASIN) {
56
            throw new InvalidAsinException(sprintf('Url %s has no valid ASIN', $this->getUrl()));
57
58
        }
59
        //@todo length of ASIN!
60
        $this->setAsin($pathParts[2]);
61
        return;
62
    }
63
64
    /**
65
     * @return string
66
     */
67
    public function getAsin()
68
    {
69
        return $this->asin;
70
    }
71
72
    /**
73
     * @param string $asin
74
     */
75
    protected function setAsin($asin)
76
    {
77
        $this->asin = $asin;
78
    }
79
80
    /**
81
     * @return string
82
     */
83
    public function getCleanedUrl() {
84
        return sprintf('http://www.amazon.%s/dp/%s/', $this->getTld(), $this->getAsin());
85
    }
86
}