Completed
Branch master (c75946)
by Michael
02:13
created

AsinParser::getCleanedUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 0
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
}