Completed
Pull Request — master (#8)
by Ricardo
01:45
created

VideoServiceMatcher::parse()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 0
cts 11
cp 0
rs 9.2248
c 0
b 0
f 0
cc 5
nc 5
nop 1
crap 30
1
<?php declare(strict_types=1);
2
3
namespace RicardoFiorani\Matcher;
4
5
use RicardoFiorani\Adapter\VideoAdapterInterface;
6
use RicardoFiorani\Container\Factory\ServicesContainerFactory;
7
use RicardoFiorani\Container\ServicesContainer;
8
use RicardoFiorani\Matcher\Exception\VideoServiceNotCompatibleException;
9
10
class VideoServiceMatcher
11
{
12
    private $serviceContainer;
13
    private $parsedUrls = array();
14
15
    public function __construct()
16
    {
17
        $this->serviceContainer = ServicesContainerFactory::createNewServiceMatcher();
18
    }
19
20
    /**
21
     * @throws VideoServiceNotCompatibleException
22
     */
23
    public function parse($url): VideoAdapterInterface
24
    {
25
        if (isset($this->parsedUrls[$url])) {
26
            return $this->parsedUrls[$url];
27
        }
28
29
        /** @var array $patterns */
30
        /** @var string $serviceName */
31
        foreach ($this->getServiceContainer()->getPatterns() as $serviceName => $patterns) {
32
            /** @var string $pattern */
33
            foreach ($patterns as $pattern) {
34
                if (false != preg_match($pattern, $url)) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match($pattern, $url) of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
35
                    $factory = $this->getServiceContainer()->getFactory($serviceName);
36
37
                    return $this->parsedUrls[$url] = $factory($url, $pattern,
38
                        $this->getServiceContainer()->getRenderer());
39
                }
40
            }
41
        }
42
43
        throw new VideoServiceNotCompatibleException(
44
            sprintf('The url "%s" could not be parsed by any of the services available.', $url)
45
        );
46
    }
47
48
    public function getServiceContainer(): ServicesContainer
49
    {
50
        return $this->serviceContainer;
51
    }
52
53
    public function setServiceContainer(ServicesContainer $serviceContainer)
54
    {
55
        $this->serviceContainer = $serviceContainer;
56
    }
57
}
58