Completed
Push — master ( 018837...6cfa28 )
by Benjamin
02:32
created

MenuBuilder::isValidMachineName()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 8
rs 9.4285
cc 3
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace Alpixel\Bundle\MenuBundle\Builder;
4
5
use Alpixel\Bundle\MenuBundle\Exception\LocaleException;
6
use Alpixel\Bundle\MenuBundle\Model\ItemInterface;
7
use Doctrine\ORM\EntityManager;
8
use Knp\Menu\FactoryInterface;
9
use Knp\Menu\MenuItem as KnpMenuItem;
10
use Symfony\Component\HttpFoundation\RequestStack;
11
use UnexpectedValueException;
12
13
class MenuBuilder
14
{
15
    protected $currentUri;
16
    protected $entityManager;
17
    protected $factory;
18
    protected $knpMenu;
19
    protected $defaultLocale;
20
    protected $request;
21
22
    /**
23
     * MenuBuilder constructor.
24
     *
25
     * @param EntityManager    $entityManager
26
     * @param FactoryInterface $factory
27
     */
28
    public function __construct(RequestStack $requestStack, EntityManager $entityManager, FactoryInterface $factory)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $entityManager. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
29
    {
30
        $this->entityManager = $entityManager;
31
        $this->factory = $factory;
32
33
        $request = $requestStack->getCurrentRequest();
34
        $this->request = $request;
35
        $this->currentUri = $request->getRequestUri();
36
    }
37
38
    /**
39
     * Check if locale is valid.
40
     *
41
     * @param $locale
42
     *
43
     * @return bool
44
     */
45
    public static function isValidLocale($locale)
46
    {
47
        if (is_string($locale) && !empty($locale)) {
48
            return true;
49
        }
50
51
        return false;
52
    }
53
54
    /**
55
     * The parameter $locale must be defined in your
56
     * symfony configuration file under parameters.
57
     *
58
     * @param $locale String
59
     *
60
     * @return $this
61
     */
62
    public function setDefaultLocale($locale)
63
    {
64
        if (self::isValidLocale($locale)) {
65
            $this->defaultLocale = $locale;
66
67
            return $this;
68
        }
69
70
        throw new LocaleException('
71
            The $locale parameter must be a non empty string or the locale is not defined
72
            under the Symfony parameters configuration.
73
        ');
74
    }
75
76
    /**
77
     * Return default locale.
78
     *
79
     * @return string
80
     */
81
    public function getDefaultLocale()
82
    {
83
        return $this->defaultLocale;
84
    }
85
86
    /**
87
     * Check if the machineName is valid.
88
     *
89
     * @param $machineName
90
     *
91
     * @return bool
92
     */
93
    public static function isValidMachineName($machineName)
94
    {
95
        if (is_string($machineName) && !empty($machineName)) {
96
            return true;
97
        }
98
99
        return false;
100
    }
101
102
    /**
103
     * Retrun null or a KnpMenuItem instance.
104
     *
105
     * @return null|KnpMenuItem
106
     */
107
    public function getKnpMenu()
108
    {
109
        return $this->knpMenu;
110
    }
111
112
    /**
113
     * Set the KnpMenuItem instance.
114
     *
115
     * @param KnpMenuItem $knpMenu
116
     *
117
     * @return $this
118
     */
119
    public function setKnpMenu(KnpMenuItem $knpMenu)
120
    {
121
        $this->knpMenu = $knpMenu;
122
123
        return $this;
124
    }
125
126
    /**
127
     * Create KnpMenuItem.
128
     *
129
     * @param string $machineName The name of menu
130
     * @param string $locale      Language code (Recommanded ISO-639)
131
     *
132
     * @return KnpMenuItem Get formatted menu
133
     */
134
    public function createKnpMenu($machineName, $locale = null)
135
    {
136
        if (!self::isValidMachineName($machineName)) {
137
            throw new UnexpectedValueException('The parameter $machineName must be a non empty string');
138
        }
139
140
        if ($locale === null) {
141
            $locale = $this->getDefaultLocale();
142
        } elseif (!self::isValidLocale($locale)) {
143
            throw new LocaleException();
144
        }
145
146
        $this->setKnpMenu($this->factory->createItem('root'));
0 ignored issues
show
Compatibility introduced by
$this->factory->createItem('root') of type object<Knp\Menu\ItemInterface> is not a sub-type of object<Knp\Menu\MenuItem>. It seems like you assume a concrete implementation of the interface Knp\Menu\ItemInterface 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...
147
148
        $menu = $this->entityManager
149
                     ->getRepository('AlpixelMenuBundle:Menu')
150
                     ->findOneMenuByMachineNameAndLocale($machineName, $locale);
151
152
        $items = $menu->getItems()->toArray();
153
154
        foreach ($items as $item) {
155
            if ($item->getParent() === null) {
156
                $this->getTree($this->knpMenu, $item);
157
            }
158
        }
159
160
        return $this->getKnpMenu();
161
    }
162
163
    /**
164
     * Create tree un KnpMenuItem.
165
     *
166
     * @param KnpMenuItem      $knpMenu
167
     * @param ItemInterface    $item
168
     * @param KnpMenuItem|null $parent
169
     *
170
     * @return KnpMenuItem A formatted KnpMenu
171
     */
172
    protected function getTree(KnpMenuItem $knpMenu, ItemInterface $item, KnpMenuItem $parent = null)
173
    {
174
        $menuItem = ($parent === null) ? $knpMenu->addChild($item) : $parent->addChild($item);
175
176
        if (($uri = $item->getUri()) !== null) {
177
            if ($uri[0] == '/') {
178
                $baseUri = $this->request->getBasePath().
179
                           $this->request->getBaseURL().
180
                           $uri;
181
                $uri = $this->request->getSchemeAndHttpHost().$baseUri;
182
183
                if ($baseUri === $this->currentUri) {
184
                    $menuItem->setCurrent(true);
185
                }
186
            }
187
            $menuItem->setUri($uri);
188
        }
189
190
        $menuItem->setAttributes([
191
            'position' => $item->getPosition(),
192
            'slug'     => $item->getSlug(),
193
        ]);
194
195
        foreach ($item->getChildren() as $child) {
196
            $this->getTree($knpMenu, $child, $menuItem);
0 ignored issues
show
Documentation introduced by
$menuItem is of type object<Knp\Menu\ItemInterface>, but the function expects a null|object<Knp\Menu\MenuItem>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
197
        }
198
199
        return $menuItem;
200
    }
201
}
202