Completed
Pull Request — 2.1 (#1090)
by Paweł
09:07
created

PublishArticleToAppleNewsRuleApplicator::apply()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 19

Duplication

Lines 19
Ratio 100 %

Importance

Changes 0
Metric Value
dl 19
loc 19
rs 9.6333
c 0
b 0
f 0
cc 4
nc 3
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher Core Bundle.
7
 *
8
 * Copyright 2017 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2017 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\CoreBundle\Rule\Applicator;
18
19
use SWP\Bundle\ContentBundle\ArticleEvents;
20
use SWP\Bundle\ContentBundle\Event\ArticleEvent;
21
use SWP\Bundle\ContentBundle\Model\ArticleInterface;
22
use SWP\Component\Rule\Applicator\AbstractRuleApplicator;
23
use SWP\Component\Rule\Model\RuleSubjectInterface;
24
use SWP\Component\Rule\Model\RuleInterface;
25
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
26
use Symfony\Component\OptionsResolver\OptionsResolver;
27
28 View Code Duplication
final class PublishArticleToAppleNewsRuleApplicator extends AbstractRuleApplicator
29
{
30
    /**
31
     * @var EventDispatcherInterface
32
     */
33
    private $eventDispatcher;
34
35
    /**
36
     * @var array
37
     */
38
    private $supportedKeys = ['isPublishedToAppleNews'];
39
40
    public function __construct(EventDispatcherInterface $eventDispatcher)
41
    {
42
        $this->eventDispatcher = $eventDispatcher;
43
    }
44
45
    public function apply(RuleInterface $rule, RuleSubjectInterface $subject)
46
    {
47
        $configuration = $this->validateRuleConfiguration($rule->getConfiguration());
48
49
        if (empty($configuration) || !$this->isAllowedType($subject)) {
50
            return;
51
        }
52
53
        if ($isPublishedToAppleNews = (bool) $configuration[$this->supportedKeys[0]]) {
54
            $subject->setPublishedToAppleNews($isPublishedToAppleNews);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface SWP\Component\Rule\Model\RuleSubjectInterface as the method setPublishedToAppleNews() does only exist in the following implementations of said interface: SWP\Bundle\CoreBundle\Model\Article.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
55
            $this->eventDispatcher->dispatch(ArticleEvents::PUBLISH, new ArticleEvent($subject, null, ArticleEvents::PUBLISH));
0 ignored issues
show
Compatibility introduced by
$subject of type object<SWP\Component\Rul...l\RuleSubjectInterface> is not a sub-type of object<SWP\Bundle\Conten...Model\ArticleInterface>. It seems like you assume a child interface of the interface SWP\Component\Rule\Model\RuleSubjectInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
56
57
            $this->logger->info(sprintf(
58
                'Configuration: "%s" for "%s" rule has been applied!',
59
                json_encode($configuration, JSON_THROW_ON_ERROR, 512),
60
                $rule->getExpression()
61
            ));
62
        }
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function isSupported(RuleSubjectInterface $subject)
69
    {
70
        return $subject instanceof ArticleInterface && 'article' === $subject->getSubjectType();
71
    }
72
73
    private function validateRuleConfiguration(array $configuration)
74
    {
75
        $resolver = new OptionsResolver();
76
        $this->configureOptions($resolver, $configuration);
77
78
        return $this->resolveConfig($resolver, $configuration);
79
    }
80
81
    private function configureOptions(OptionsResolver $resolver, array $configuration)
82
    {
83
        $resolver->setDefaults([
84
            $this->supportedKeys[0] => false,
85
        ]);
86
        $resolver->setDefined(array_keys($configuration));
87
    }
88
89
    private function isAllowedType(RuleSubjectInterface $subject)
90
    {
91
        if (!$subject instanceof ArticleInterface) {
92
            $this->logger->warning(sprintf(
93
                '"%s" is not supported by "%s" rule applicator!',
94
                is_object($subject) ? get_class($subject) : gettype($subject),
95
                get_class($this)
96
            ));
97
98
            return false;
99
        }
100
101
        return true;
102
    }
103
}
104