Completed
Push — master ( d87b58...45003b )
by Kamil
125:34 queued 104:29
created

Bundle/ResourceBundle/Controller/FlashHelper.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Sylius\Bundle\ResourceBundle\Controller;
15
16
use Doctrine\Common\Inflector\Inflector;
17
use Sylius\Bundle\ResourceBundle\Event\ResourceControllerEvent;
18
use Sylius\Component\Resource\Model\ResourceInterface;
19
use Symfony\Component\HttpFoundation\Session\SessionInterface;
20
use Symfony\Component\Translation\TranslatorBagInterface;
21
use Symfony\Component\Translation\TranslatorInterface;
22
23
final class FlashHelper implements FlashHelperInterface
24
{
25
    /**
26
     * @var SessionInterface
27
     */
28
    private $session;
29
30
    /**
31
     * @var TranslatorInterface
32
     */
33
    private $translator;
34
35
    /**
36
     * @var string
37
     */
38
    private $defaultLocale;
39
40
    /**
41
     * @param SessionInterface $session
42
     * @param TranslatorInterface $translator
43
     * @param string $defaultLocale
44
     */
45
    public function __construct(SessionInterface $session, TranslatorInterface $translator, string $defaultLocale)
46
    {
47
        $this->session = $session;
48
        $this->translator = $translator;
49
        $this->defaultLocale = $defaultLocale;
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function addSuccessFlash(
56
        RequestConfiguration $requestConfiguration,
57
        string $actionName,
58
        ?ResourceInterface $resource = null
59
    ): void {
60
        $this->addFlashWithType($requestConfiguration, $actionName, 'success');
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    public function addErrorFlash(RequestConfiguration $requestConfiguration, string $actionName): void
67
    {
68
        $this->addFlashWithType($requestConfiguration, $actionName, 'error');
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function addFlashFromEvent(RequestConfiguration $requestConfiguration, ResourceControllerEvent $event): void
75
    {
76
        $this->addFlash($event->getMessageType(), $event->getMessage(), $event->getMessageParameters());
77
    }
78
79
    /**
80
     * @param RequestConfiguration $requestConfiguration
81
     * @param string $actionName
82
     * @param string $type
83
     */
84
    private function addFlashWithType(RequestConfiguration $requestConfiguration, string $actionName, string $type): void
85
    {
86
        $metadata = $requestConfiguration->getMetadata();
87
        $metadataName = ucfirst($metadata->getHumanizedName());
88
        $parameters = $this->getParametersWithName($metadataName, $actionName);
89
90
        $message = (string) $requestConfiguration->getFlashMessage($actionName);
91
        if (empty($message)) {
92
            return;
93
        }
94
95
        if ($this->isTranslationDefined($message, $this->defaultLocale, $parameters)) {
96
            if (!$this->translator instanceof TranslatorBagInterface) {
97
                $this->addFlash($type, $message, $parameters);
98
99
                return;
100
            }
101
102
            $this->addFlash($type, $message);
103
104
            return;
105
        }
106
107
        $this->addFlash(
108
            $type,
109
            $this->getResourceMessage($actionName),
110
            $parameters
111
        );
112
    }
113
114
    /**
115
     * @param string $type
116
     * @param string $message
117
     * @param array $parameters
118
     */
119
    private function addFlash(string $type, string $message, array $parameters = []): void
120
    {
121
        if (!empty($parameters)) {
122
            $message = $this->prepareMessage($message, $parameters);
123
        }
124
125
        $this->session->getBag('flashes')->add($type, $message);
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface Symfony\Component\HttpFo...ion\SessionBagInterface as the method add() does only exist in the following implementations of said interface: Symfony\Component\HttpFo...lash\AutoExpireFlashBag, Symfony\Component\HttpFo...\Session\Flash\FlashBag.

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...
126
    }
127
128
    /**
129
     * @param string $message
130
     * @param array $parameters
131
     *
132
     * @return array
133
     */
134
    private function prepareMessage(string $message, array $parameters): array
135
    {
136
        return [
137
            'message' => $message,
138
            'parameters' => $parameters,
139
        ];
140
    }
141
142
    /**
143
     * @param string $actionName
144
     *
145
     * @return string
146
     */
147
    private function getResourceMessage(string $actionName): string
148
    {
149
        return sprintf('sylius.resource.%s', $actionName);
150
    }
151
152
    /**
153
     * @param string $message
154
     * @param string $locale
155
     * @param array $parameters
156
     *
157
     * @return bool
158
     */
159
    private function isTranslationDefined(string $message, string $locale, array $parameters): bool
160
    {
161
        if ($this->translator instanceof TranslatorBagInterface) {
162
            $defaultCatalogue = $this->translator->getCatalogue($locale);
163
164
            return $defaultCatalogue->has($message, 'flashes');
165
        }
166
167
        return $message !== $this->translator->trans($message, $parameters, 'flashes');
168
    }
169
170
    /**
171
     * @param string $metadataName
172
     * @param string $actionName
173
     *
174
     * @return array
175
     */
176
    private function getParametersWithName(string $metadataName, string $actionName): array
177
    {
178
        if (stripos($actionName, 'bulk') !== false) {
179
            return ['%resources%' => ucfirst(Inflector::pluralize($metadataName))];
180
        }
181
182
        return ['%resource%' => ucfirst($metadataName)];
183
    }
184
}
185