MenuExtension::checkUrl()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 29
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 15
nc 4
nop 2
dl 0
loc 29
ccs 0
cts 15
cp 0
crap 20
rs 9.7666
c 0
b 0
f 0
1
<?php
2
3
namespace Cdf\BiCoreBundle\Twig\Extension;
4
5
use Cdf\BiCoreBundle\Service\Permessi\PermessiManager;
6
use Doctrine\ORM\EntityManagerInterface;
7
use Doctrine\ORM\QueryBuilder;
8
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
9
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
10
use Twig\Extension\AbstractExtension;
11
use Twig\Environment as TwigEnvironment;
12
use Twig\TwigFunction;
13
use function count;
14
15
class MenuExtension extends AbstractExtension
16
{
17
18
    protected EntityManagerInterface $em;
19
    protected UrlGeneratorInterface $urlgenerator;
20
    protected TokenStorageInterface $user;
21
    protected string $rootpath;
22
23 25
    public function __construct(EntityManagerInterface $em, UrlGeneratorInterface $urlgenerator, TokenStorageInterface $user, string $rootpath)
24
    {
25 25
        $this->em = $em;
26 25
        $this->urlgenerator = $urlgenerator;
27 25
        $this->user = $user;
28 25
        $this->rootpath = $rootpath;
29
    }
30
31 1
    public function getFunctions(): array
32
    {
33 1
        return [
34 1
            new TwigFunction('generamenu', [$this, 'generamenu'], [
35 1
                'needs_environment' => true,
36 1
                'is_safe' => ['html'],
37 1
                    ]),
38 1
        ];
39
    }
40
41 11
    public function generamenu(TwigEnvironment $environment): string
42
    {
43
        /** @phpstan-ignore-next-line */
44 11
        $router = $this->urlgenerator->match('/')['_route'];
0 ignored issues
show
Bug introduced by
The method match() does not exist on Symfony\Component\Routin...r\UrlGeneratorInterface. It seems like you code against a sub-type of Symfony\Component\Routin...r\UrlGeneratorInterface such as Symfony\Component\Routing\RouterInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

44
        $router = $this->urlgenerator->/** @scrutinizer ignore-call */ match('/')['_route'];
Loading history...
45 11
        $rispostahome = array();
46 11
        $rispostahome[] = array('percorso' => $this->getUrlObject('', $router, ''),
47 11
            'nome' => 'Home',
48 11
            'target' => '_self',
49 11
        );
50
51 11
        $em = $this->em;
52
        /* @var $qb QueryBuilder */
53 11
        $qb = $em->createQueryBuilder();
54 11
        $qb->select(array('a'));
55 11
        $qb->from('BiCoreBundle:Menuapplicazione', 'a');
56 11
        $qb->where('a.attivo = :attivo and (a.padre is null or a.padre = 0)');
57 11
        $qb->setParameter('attivo', true);
58 11
        $qb->orderBy('a.padre', 'ASC');
59 11
        $qb->orderBy('a.ordine', 'ASC');
60 11
        $menu = $qb->getQuery()->getResult();
61
62 11
        $risposta = array_merge($rispostahome, $this->getMenu($menu));
0 ignored issues
show
Bug introduced by
It seems like $menu can also be of type integer; however, parameter $menu of Cdf\BiCoreBundle\Twig\Ex...enuExtension::getMenu() does only seem to accept Cdf\BiCoreBundle\Entity\Menuapplicazione[], maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

62
        $risposta = array_merge($rispostahome, $this->getMenu(/** @scrutinizer ignore-type */ $menu));
Loading history...
63
64 11
        $username = '';
65 11
        $urlLogout = '';
66
67 11
        $this->generaManualeMkdocMenu($risposta);
68
69 11
        $this->generaManualePdfMenu($risposta);
70
71
        /** @phpstan-ignore-next-line */
72 11
        if ('ssocdf' === $this->user->getToken()->getFirewallName()) {
0 ignored issues
show
Bug introduced by
The method getFirewallName() does not exist on Symfony\Component\Securi...on\Token\TokenInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Symfony\Component\Securi...ication\Token\NullToken or Symfony\Component\Securi...ken\GuardTokenInterface or Symfony\Component\Securi...ion\Token\AbstractToken or Symfony\Component\Securi...uthenticationGuardToken or Symfony\Component\Securi...uthenticationGuardToken or Symfony\Component\Securi...on\Token\AnonymousToken. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

72
        if ('ssocdf' === $this->user->getToken()->/** @scrutinizer ignore-call */ getFirewallName()) {
Loading history...
73
            $username = $this->user->getToken()->getUser()->getUsername();
0 ignored issues
show
Deprecated Code introduced by
The function Symfony\Component\Securi...nterface::getUsername() has been deprecated: since Symfony 5.3, use getUserIdentifier() instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

73
            $username = /** @scrutinizer ignore-deprecated */ $this->user->getToken()->getUser()->getUsername();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
74
            $urlLogout = $this->urlgenerator->generate('fi_autenticazione_signout');
75
        }
76
77
        /** @phpstan-ignore-next-line */
78 11
        if ('ssolineacomune' === $this->user->getToken()->getFirewallName()) {
79
            $username = $this->user->getToken()->getUser()->getUsername();
0 ignored issues
show
Deprecated Code introduced by
The function Symfony\Component\Securi...nterface::getUsername() has been deprecated: since Symfony 5.3, use getUserIdentifier() instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

79
            $username = /** @scrutinizer ignore-deprecated */ $this->user->getToken()->getUser()->getUsername();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
80
            $urlLogout = $this->urlgenerator->generate('fi_Lineacomuneauth_signout');
81
        }
82
83
        /** @phpstan-ignore-next-line */
84 11
        if ('main' === $this->user->getToken()->getFirewallName()) {
85 11
            $username = $this->user->getToken()->getUser()->getUsername();
0 ignored issues
show
Deprecated Code introduced by
The function Symfony\Component\Securi...nterface::getUsername() has been deprecated: since Symfony 5.3, use getUserIdentifier() instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

85
            $username = /** @scrutinizer ignore-deprecated */ $this->user->getToken()->getUser()->getUsername();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
86 11
            $urlLogout = $this->urlgenerator->generate('fos_user_security_logout');
87
        }
88
89 11
        $risposta[] = array('percorso' => $this->getUrlObject($username, '', ''), 'nome' => $username, 'target' => '',
90 11
            'sottolivello' => array(
91 11
                array('percorso' => $urlLogout, 'nome' => 'Logout', 'target' => '_self'),
92 11
            ),
93 11
        );
94 11
        return $environment->render('@BiCore/Menu/menu.html.twig', array('risposta' => $risposta));
95
    }
96
97
    /**
98
     *
99
     * @param string[][] $risposta
100
     * @return void
101
     */
102 11
    protected function generaManualePdfMenu(array &$risposta): void
103
    {
104 11
        $pathmanuale = $this->rootpath . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'manuale.pdf';
105 11
        if (file_exists($pathmanuale)) {
106
            $risposta[] = array(
107
                'percorso' => $this->getUrlObject('Manuale', $pathmanuale, '_blank'),
108
                'nome' => 'Manuale (Pdf)', 'target' => '_blank',);
109
        }
110
    }
111
112
    /**
113
     *
114
     * @param string[][] $risposta
115
     * @return void
116
     */
117 11
    protected function generaManualeMkdocMenu(&$risposta)
118
    {
119 11
        $mkdocsfile = 'manuale' . DIRECTORY_SEPARATOR . 'index.html';
120 11
        $pathmanualemkdocs = $this->rootpath . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . $mkdocsfile;
121 11
        if (file_exists($pathmanualemkdocs)) {
122
            $risposta[] = array(
123
                'percorso' => array("percorso" => $this->urlgenerator->generate("homepage") . $mkdocsfile),
124
                'nome' => 'Manuale', 'target' => '_blank',);
125
        }
126
    }
127
128
    /**
129
     *
130
     * @param \Cdf\BiCoreBundle\Entity\Menuapplicazione[] $menu
131
     * @return array<mixed>
132
     */
133 11
    protected function getMenu($menu)
134
    {
135 11
        $risposta = array();
136 11
        $em = $this->em;
137
138 11
        foreach ($menu as $item) {
139 11
            $visualizzare = true;
140
141 11
            if ($item->isAutorizzazionerichiesta()) {
142 11
                $permessi = new PermessiManager($this->em, $this->user);
143 11
                $visualizzare = $permessi->canRead($item->getTag());
144
            }
145
146 11
            if ($visualizzare) {
147 11
                $qb = $em->createQueryBuilder();
148 11
                $qb->select(array('a'));
149 11
                $qb->from('BiCoreBundle:Menuapplicazione', 'a');
150 11
                $qb->where('a.padre = :padre_id');
151 11
                $qb->andWhere('a.attivo = :attivo');
152 11
                $qb->orderBy('a.padre', 'ASC');
153 11
                $qb->orderBy('a.ordine', 'ASC');
154 11
                $qb->setParameter('padre_id', $item->getId());
155 11
                $qb->setParameter('attivo', true);
156 11
                $submenu = $qb->getQuery()->getResult();
157
158 11
                $sottomenutabelle = $this->getSubMenu($submenu);
0 ignored issues
show
Bug introduced by
It seems like $submenu can also be of type integer; however, parameter $submenu of Cdf\BiCoreBundle\Twig\Ex...Extension::getSubMenu() does only seem to accept Cdf\BiCoreBundle\Entity\Menuapplicazione[], maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

158
                $sottomenutabelle = $this->getSubMenu(/** @scrutinizer ignore-type */ $submenu);
Loading history...
159
160 11
                $percorso = $this->getUrlObject($item->getNome(), $item->getPercorso(), $item->getTarget());
161 11
                $risposta[] = array(
162 11
                    'percorso' => $percorso,
163 11
                    'nome' => $item->getNome(),
164 11
                    'sottolivello' => $sottomenutabelle,
165 11
                    'target' => $item->getTarget(),
166 11
                    'notifiche' => $item->hasNotifiche(),
167 11
                    'tag' => $item->getTag(),
168 11
                    'percorsonotifiche' => $this->getUrlObject($item->getNome(), $item->getPercorsonotifiche(), ''),
169 11
                );
170 11
                unset($submenu);
171 11
                unset($sottomenutabelle);
172
            }
173
        }
174
175 11
        return $risposta;
176
    }
177
178
    /**
179
     *
180
     * @param \Cdf\BiCoreBundle\Entity\Menuapplicazione[] $submenu
181
     * @return array<mixed>
182
     */
183 11
    protected function getSubMenu($submenu)
184
    {
185 11
        $sottomenutabelle = array();
186 11
        foreach ($submenu as $subitem) {
187 11
            $visualizzare = true;
188 11
            if ($subitem->isAutorizzazionerichiesta()) {
189
                $permessi = new PermessiManager($this->em, $this->user);
190
                $visualizzare = $permessi->canRead($subitem->getTag());
191
            }
192
193 11
            if ($visualizzare) {
194 11
                $vettoresottomenu = $this->getMenu(array($subitem));
195 11
                $sottomenu = $vettoresottomenu[0];
196
197 11
                if (isset($sottomenu['sottolivello']) && count($sottomenu['sottolivello']) > 0) {
198 10
                    $sottolivellomenu = array('sottolivello' => $sottomenu['sottolivello']);
199 10
                    $menuobj = $this->getUrlObject($subitem->getNome(), $subitem->getPercorso(), $subitem->getTarget());
200 10
                    $sottomenutabelle[] = array_merge($menuobj, $sottolivellomenu);
201
                } else {
202 11
                    $sottomenutabelle[] = $this->getUrlObject($subitem->getNome(), $subitem->getPercorso(), $subitem->getTarget());
203
                }
204
            }
205
        }
206
207 11
        return $sottomenutabelle;
208
    }
209
210
    /**
211
     *
212
     * @param string $nome
213
     * @param string $percorso
214
     * @param string $target
215
     * @return array<mixed>
216
     */
217 11
    protected function getUrlObject(string $nome, ?string $percorso, ?string $target)
218
    {
219 11
        if ($this->routeExists($percorso)) {
220 11
            $percorso = $this->urlgenerator->generate($percorso);
0 ignored issues
show
Bug introduced by
It seems like $percorso can also be of type null; however, parameter $name of Symfony\Component\Routin...orInterface::generate() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

220
            $percorso = $this->urlgenerator->generate(/** @scrutinizer ignore-type */ $percorso);
Loading history...
221
        } else {
222 11
            $percorso = '#';
223
        }
224 11
        if (!$target) {
225 11
            $target = '_self';
226
        }
227
228 11
        return array('percorso' => $percorso, 'nome' => $nome, 'target' => $target);
229
    }
230
231 11
    protected function routeExists(?string $name): bool
232
    {
233 11
        if ($name === null) {
234 11
            return false;
235
        }
236 11
        $router = $this->urlgenerator;
237
238
        /** @phpstan-ignore-next-line */
239 11
        if ((null === $router->getRouteCollection()->get($name)) ? false : true) {
0 ignored issues
show
Bug introduced by
The method getRouteCollection() does not exist on Symfony\Component\Routin...r\UrlGeneratorInterface. It seems like you code against a sub-type of Symfony\Component\Routin...r\UrlGeneratorInterface such as Symfony\Component\Routing\RouterInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

239
        if ((null === $router->/** @scrutinizer ignore-call */ getRouteCollection()->get($name)) ? false : true) {
Loading history...
240 11
            return true;
241
        } else {
242 11
            return false;
243
        }
244
    }
245
246
    protected function urlExists(string $name): bool
247
    {
248
        if ($this->checkUrl($name, false)) {
249
            return true;
250
        } else {
251
            if ($this->checkUrl($name, true)) {
252
                return true;
253
            } else {
254
                return false;
255
            }
256
        }
257
    }
258
259
    protected function checkUrl(string $name, bool $useProxy): bool
260
    {
261
        $ch = curl_init($name);
262
263
        /** @phpstan-ignore-next-line */
264
        curl_setopt($ch, CURLOPT_URL, $name);
265
        if (!$useProxy) {
266
            /** @phpstan-ignore-next-line */
267
            curl_setopt($ch, CURLOPT_PROXY, null);
268
        }
269
        /** @phpstan-ignore-next-line */
270
        curl_setopt($ch, CURLOPT_NOBODY, true);
271
        /** @phpstan-ignore-next-line */
272
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
273
        /** @phpstan-ignore-next-line */
274
        curl_setopt($ch, CURLOPT_TIMEOUT, 1); //timeout in seconds
275
        /** @phpstan-ignore-next-line */
276
        curl_exec($ch);
277
        /** @phpstan-ignore-next-line */
278
        $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
279
        if (200 === $retcode || 401 === $retcode) {
280
            $exist = true;
281
        } else {
282
            $exist = false;
283
        }
284
        /** @phpstan-ignore-next-line */
285
        curl_close($ch);
286
287
        return $exist;
288
    }
289
}
290