Completed
Push — checkout-optimisation ( 4a6bfb...756f29 )
by Kamil
18:24
created

FlashHelper::addSuccessFlash()   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 3
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
namespace Sylius\Bundle\ResourceBundle\Controller;
13
14
use Sylius\Bundle\ResourceBundle\Event\ResourceControllerEvent;
15
use Sylius\Component\Resource\Model\ResourceInterface;
16
use Symfony\Component\HttpFoundation\Session\SessionInterface;
17
use Symfony\Component\Translation\TranslatorBagInterface;
18
use Symfony\Component\Translation\TranslatorInterface;
19
20
/**
21
 * @author Paweł Jędrzejewski <[email protected]>
22
 * @author Jan Góralski <[email protected]>
23
 */
24
final class FlashHelper implements FlashHelperInterface
25
{
26
    /**
27
     * @var SessionInterface
28
     */
29
    private $session;
30
31
    /**
32
     * @var TranslatorInterface
33
     */
34
    private $translator;
35
36
    /**
37
     * @var string
38
     */
39
    private $defaultLocale;
40
41
    /**
42
     * @param SessionInterface $session
43
     * @param TranslatorInterface $translator
44
     * @param string $defaultLocale
45
     */
46
    public function __construct(SessionInterface $session, TranslatorInterface $translator, $defaultLocale)
47
    {
48
        $this->session = $session;
49
        $this->translator = $translator;
50
        $this->defaultLocale = $defaultLocale;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function addSuccessFlash(RequestConfiguration $requestConfiguration, $actionName, ResourceInterface $resource = null)
57
    {
58
        $this->addFlashWithType($requestConfiguration, $actionName, 'success');
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    public function addErrorFlash(RequestConfiguration $requestConfiguration, $actionName)
65
    {
66
        $this->addFlashWithType($requestConfiguration, $actionName, 'error');
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function addFlashFromEvent(RequestConfiguration $requestConfiguration, ResourceControllerEvent $event)
73
    {
74
        $this->addFlash($event->getMessageType(), $event->getMessage(), $event->getMessageParameters());
75
    }
76
77
    /**
78
     * @param RequestConfiguration $requestConfiguration
79
     * @param string $actionName
80
     * @param string $type
81
     */
82
    private function addFlashWithType(RequestConfiguration $requestConfiguration, $actionName, $type)
83
    {
84
        $metadata = $requestConfiguration->getMetadata();
85
        $metadataName = ucfirst($metadata->getHumanizedName());
86
        $parameters = ['%resource%' => $metadataName];
87
88
        $message = $requestConfiguration->getFlashMessage($actionName);
89
        if (false === $message) {
90
            return;
91
        }
92
93
        if ($this->isTranslationDefined($message, $this->defaultLocale, $parameters)) {
94
            if (!$this->translator instanceof TranslatorBagInterface) {
95
                $this->addFlash($type, $message, $parameters);
96
97
                return;
98
            }
99
100
            $this->addFlash($type, $message);
101
102
            return;
103
        }
104
105
        $this->addFlash(
106
            $type,
107
            $this->getResourceMessage($actionName),
108
            $parameters
109
        );
110
    }
111
112
    /**
113
     * @param string $type
114
     * @param string $message
115
     * @param array $parameters
116
     */
117
    private function addFlash($type, $message, array $parameters = [])
118
    {
119
        if (!empty($parameters)) {
120
            $message = $this->prepareMessage($message, $parameters);
121
        }
122
123
        $this->session->getBag('flashes')->add($type, $message);
0 ignored issues
show
Bug introduced by
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...
124
    }
125
126
    /**
127
     * @param string $message
128
     * @param array $parameters
129
     *
130
     * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,string|array>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
131
     */
132
    private function prepareMessage($message, array $parameters)
133
    {
134
        return [
135
            'message' => $message,
136
            'parameters' => $parameters,
137
        ];
138
    }
139
140
    /**
141
     * @param string $actionName
142
     *
143
     * @return string
144
     */
145
    private function getResourceMessage($actionName)
146
    {
147
        return sprintf('sylius.resource.%s', $actionName);
148
    }
149
150
    /**
151
     * @param string $message
152
     * @param string $locale
153
     * @param array $parameters
154
     *
155
     * @return bool
156
     */
157
    private function isTranslationDefined($message, $locale, array $parameters)
158
    {
159
        if ($this->translator instanceof TranslatorBagInterface) {
160
            $defaultCatalogue = $this->translator->getCatalogue($locale);
161
162
            return $defaultCatalogue->has($message, 'flashes');
163
        }
164
165
        return $message !== $this->translator->trans($message, $parameters,'flashes');
166
    }
167
}
168