Completed
Pull Request — master (#152)
by
unknown
45:53
created

PageUrlProvider::localeInLocaleCodes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace BitBag\SyliusCmsPlugin\Sitemap\Provider;
4
5
use BitBag\SyliusCmsPlugin\Entity\PageInterface;
6
use BitBag\SyliusCmsPlugin\Entity\PageTranslationInterface;
7
use BitBag\SyliusCmsPlugin\Repository\PageRepositoryInterface;
8
use Doctrine\Common\Collections\Collection;
9
use SitemapPlugin\Factory\SitemapUrlFactoryInterface;
10
use SitemapPlugin\Model\ChangeFrequency;
11
use SitemapPlugin\Model\SitemapUrlInterface;
12
use SitemapPlugin\Provider\UrlProviderInterface;
13
use Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository;
14
use Sylius\Component\Channel\Context\ChannelContextInterface;
15
use Sylius\Component\Core\Model\ChannelInterface;
16
use Sylius\Component\Locale\Context\LocaleContextInterface;
17
use Sylius\Component\Locale\Model\LocaleInterface;
18
use Sylius\Component\Resource\Model\TranslationInterface;
19
use Symfony\Component\Routing\RouterInterface;
20
21
class PageUrlProvider implements UrlProviderInterface
22
{
23
24
    /**
25
     * @var PageRepositoryInterface|EntityRepository
26
     */
27
    private $pageRepository;
28
29
    /**
30
     * @var RouterInterface
31
     */
32
    private $router;
33
34
    /**
35
     * @var SitemapUrlFactoryInterface
36
     */
37
    private $sitemapUrlFactory;
38
39
    /**
40
     * @var LocaleContextInterface
41
     */
42
    private $localeContext;
43
44
    /**
45
     * @var ChannelContextInterface
46
     */
47
    private $channelContext;
48
49
    /**
50
     * @var array
51
     */
52
    private $urls = [];
53
54
    /**
55
     * @var array
56
     */
57
    private $channelLocaleCodes;
58
59
    /**
60
     * @param PageRepositoryInterface $pageRepository
61
     * @param RouterInterface $router
62
     * @param SitemapUrlFactoryInterface $sitemapUrlFactory
63
     * @param LocaleContextInterface $localeContext
64
     * @param ChannelContextInterface $channelContext
65
     */
66
    public function __construct(
67
        PageRepositoryInterface $pageRepository,
68
        RouterInterface $router,
69
        SitemapUrlFactoryInterface $sitemapUrlFactory,
70
        LocaleContextInterface $localeContext,
71
        ChannelContextInterface $channelContext
72
    ) {
73
        $this->pageRepository = $pageRepository;
74
        $this->router = $router;
75
        $this->sitemapUrlFactory = $sitemapUrlFactory;
76
        $this->localeContext = $localeContext;
77
        $this->channelContext = $channelContext;
78
    }
79
    /**
80
     * @return string
81
     */
82
    public function getName(): string
83
    {
84
        return 'cms_pages';
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    public function generate(): iterable
91
    {
92
        foreach ($this->getPages() as $product) {
93
            $this->urls[] = $this->createProductUrl($product);
94
        }
95
        return $this->urls;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->urls; (array) is incompatible with the return type declared by the interface SitemapPlugin\Provider\U...iderInterface::generate of type SitemapPlugin\Provider\iterable.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
96
    }
97
98
    /**
99
     * @param PageInterface $page
100
     *
101
     * @return Collection|PageTranslationInterface[]
102
     */
103
    private function getTranslations(PageInterface $page): Collection
104
    {
105
        return $page->getTranslations()->filter(function (TranslationInterface $translation) {
106
            return $this->localeInLocaleCodes($translation);
107
        });
108
    }
109
110
    /**
111
     * @param TranslationInterface $translation
112
     *
113
     * @return bool
114
     */
115
    private function localeInLocaleCodes(TranslationInterface $translation): bool
116
    {
117
        return in_array($translation->getLocale(), $this->getLocaleCodes());
118
    }
119
120
    /**
121
     * @return array|Collection|PageInterface[]
122
     */
123
    private function getPages(): iterable
124
    {
125
        return $this->pageRepository->createQueryBuilder('o')
0 ignored issues
show
Bug introduced by
The method createQueryBuilder does only exist in Sylius\Bundle\ResourceBu...ne\ORM\EntityRepository, but not in BitBag\SyliusCmsPlugin\R...PageRepositoryInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
126
            ->addSelect('translation')
127
            ->innerJoin('o.translations', 'translation')
128
            ->andWhere('o.enabled = :enabled')
129
            ->setParameter('enabled', true)
130
            ->getQuery()
131
            ->getResult();
132
    }
133
134
    /**
135
     * @return array
136
     */
137
    private function getLocaleCodes(): array
138
    {
139
        if ($this->channelLocaleCodes === null) {
140
            /** @var ChannelInterface $channel */
141
            $channel = $this->channelContext->getChannel();
142
            $this->channelLocaleCodes = $channel->getLocales()->map(function (LocaleInterface $locale) {
143
                return $locale->getCode();
144
            })->toArray();
145
        }
146
        return $this->channelLocaleCodes;
147
    }
148
149
    /**
150
     * @param PageInterface $page
151
     *
152
     * @return SitemapUrlInterface
153
     */
154
    private function createProductUrl(PageInterface $page): SitemapUrlInterface
155
    {
156
        $pageUrl = $this->sitemapUrlFactory->createNew();
157
        $pageUrl->setChangeFrequency(ChangeFrequency::daily());
158
        $pageUrl->setPriority(0.7);
159
        if ($page->getUpdatedAt()) {
160
            $pageUrl->setLastModification($page->getUpdatedAt());
161
        }
162
        /** @var PageTranslationInterface $translation */
163
        foreach ($this->getTranslations($page) as $translation) {
164
            if (!$translation->getLocale()) {
165
                continue;
166
            }
167
            if (!$this->localeInLocaleCodes($translation)) {
168
                continue;
169
            }
170
            $location = $this->router->generate('bitbag_sylius_cms_plugin_shop_page_show', [
171
                'slug' => $translation->getSlug(),
172
                '_locale' => $translation->getLocale(),
173
            ]);
174
            if ($translation->getLocale() === $this->localeContext->getLocaleCode()) {
175
                $pageUrl->setLocalization($location);
176
                continue;
177
            }
178
            $pageUrl->addAlternative($location, $translation->getLocale());
179
        }
180
        return $pageUrl;
181
    }
182
183
}
184