Completed
Push — 1.5 ( 293f07...bc7cd6 )
by Rafał
13:04
created

ArticleResolver::resolve()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 8.9297
c 0
b 0
f 0
cc 6
nc 5
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Superdesk Web Publisher Core Bundle.
5
 *
6
 * Copyright 2018 Sourcefabric z.u. and contributors.
7
 *
8
 * For the full copyright and license information, please see the
9
 * AUTHORS and LICENSE files distributed with this source code.
10
 *
11
 * @copyright 2018 Sourcefabric z.ú
12
 * @license http://www.superdesk.org/license
13
 */
14
15
namespace SWP\Bundle\CoreBundle\Resolver;
16
17
use Doctrine\Common\Cache\CacheProvider;
18
use SWP\Bundle\CoreBundle\Model\ArticleInterface;
19
use SWP\Component\TemplatesSystem\Gimme\Meta\Meta;
20
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
21
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
22
23
class ArticleResolver implements ArticleResolverInterface
24
{
25
    /**
26
     * @var UrlMatcherInterface
27
     */
28
    private $matcher;
29
30
    /**
31
     * @var CacheProvider
32
     */
33
    private $cacheProvider;
34
35
    public function __construct(UrlMatcherInterface $matcher, CacheProvider $cacheProvider)
36
    {
37
        $this->matcher = $matcher;
38
        $this->cacheProvider = $cacheProvider;
39
    }
40
41
    public function resolve(string $url): ?ArticleInterface
42
    {
43
        $collectionRouteCacheKey = md5('route_'.$url);
44
45
        $result = null;
46
47
        if ($this->cacheProvider->contains($collectionRouteCacheKey)) {
48
            return $result;
49
        }
50
51
        try {
52
            $route = $this->matcher->match($this->getFragmentFromUrl($url, 'path'));
53
54
            if (isset($route['_article_meta']) && $route['_article_meta'] instanceof Meta && ($article = $route['_article_meta']->getValues()) instanceof ArticleInterface) {
55
                return $article;
56
            }
57
        } catch (ResourceNotFoundException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
58
        }
59
60
        $this->cacheProvider->save($collectionRouteCacheKey, $result);
61
62
        return $result;
63
    }
64
65
    private function getFragmentFromUrl(string $url, string $fragment): ?string
66
    {
67
        $fragments = \parse_url($url);
68
        if (!\array_key_exists($fragment, $fragments)) {
69
            return null;
70
        }
71
72
        return str_replace('/app_dev.php', '', $fragments[$fragment]);
73
    }
74
}
75