Skip to content

Commit ba6ba2f

Browse files
committed
Сервис проверки контроллеров роутов на существование.
1 parent 5b40f0f commit ba6ba2f

File tree

6 files changed

+115
-1
lines changed

6 files changed

+115
-1
lines changed

DependencyInjection/Configuration.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ public function getConfigTreeBuilder(): TreeBuilder
2929
->scalarNode('router_request_context_base_url')->defaultValue('')->end()
3030
->scalarNode('router_cache_path')->defaultValue('%kernel.cache_dir%/routes')->end()
3131
->scalarNode('router_config_file')->defaultValue('app/routes.yaml')->end()
32+
->booleanNode('router_check_exists_controller')->defaultValue(false)->end()
3233
->arrayNode('controller_annotations_path')
3334
->useAttributeAsKey('name')
3435
->prototype('scalar')->end()

DependencyInjection/WpSymfonyRouterExtension.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,10 @@ private function registerRouterConfiguration(
8383
): void {
8484
$annotationsConfigEnabled = $container->getParameter('enable_annotations');
8585

86+
if ($config['router_check_exists_controller'] === false) {
87+
$container->removeDefinition('router.checker.exists.autoload');
88+
}
89+
8690
if ($config['default_uri'] === null) {
8791
$host = (string)$container->getParameter('kernel.http.host');
8892
$schema = (string)$container->getParameter('kernel.schema');
@@ -100,7 +104,8 @@ private function registerRouterConfiguration(
100104
'symfony/framework-bundle',
101105
'5.2',
102106
'Not setting the "framework.router.utf8" configuration option is deprecated,
103-
it will default to "true" in version 6.0.');
107+
it will default to "true" in version 6.0.'
108+
);
104109
}
105110

106111
$container->setParameter('router.request.context.host', $config['router_request_context_host']);

Resources/config/services.yaml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,17 @@ services:
9494
class: Prokl\WpSymfonyRouterBundle\Services\Annotations\SearchAnnotatedClasses
9595
arguments: ['%kernel.project_dir%', '%controller.annotations.path%']
9696

97+
# Проверка роутов на существование контроллеров.
98+
router.checker.exists:
99+
class: Prokl\WpSymfonyRouterBundle\Services\Utils\RouteCheckerExist
100+
arguments: ['@routes.collection']
101+
102+
# Проверка роутов на существование контроллеров.
103+
router.checker.exists.autoload:
104+
class: Prokl\WpSymfonyRouterBundle\Services\Utils\RouteCheckerExist
105+
factory: ['@router.checker.exists', 'check']
106+
tags: ['service.bootstrap']
107+
97108
# Диспетчер запуска контроллеров.
98109
dispatcher.controller:
99110
class: Prokl\WpSymfonyRouterBundle\Services\Utils\DispatchController
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php
2+
3+
namespace Prokl\WpSymfonyRouterBundle\Services\Utils;
4+
5+
use LogicException;
6+
use Symfony\Component\Routing\RouteCollection;
7+
8+
/**
9+
* Class RouteCheckerExist
10+
* @package Prokl\WpSymfonyRouterBundle\Services\Utils
11+
*/
12+
class RouteCheckerExist
13+
{
14+
/**
15+
* @var RouteCollection $routeCollection Коллекция роутов.
16+
*/
17+
private $routeCollection;
18+
19+
/**
20+
* RouteCheckerExist constructor.
21+
*
22+
* @param RouteCollection $routeCollection Коллекция роутов.
23+
*/
24+
public function __construct(RouteCollection $routeCollection)
25+
{
26+
$this->routeCollection = $routeCollection;
27+
}
28+
29+
/**
30+
* Проверка роутов на существование контроллеров.
31+
*
32+
* @return void
33+
* @throws LogicException Когда контроллер не существует.
34+
*/
35+
public function check() : void
36+
{
37+
$allRoutes = $this->routeCollection->all();
38+
foreach ($allRoutes as $nameRoute => $route) {
39+
$controller = $route->getDefault('_controller');
40+
if (is_string($controller)) {
41+
if (strpos($controller, '::') !== false) {
42+
$callback = explode('::', $controller, 2);
43+
$class = $callback[0];
44+
} else {
45+
// _invoke_
46+
$class = $controller;
47+
}
48+
49+
if (!class_exists($class)) {
50+
throw new LogicException(
51+
sprintf(
52+
'Class %s declaring as controller for route %s not exists.',
53+
$class,
54+
$nameRoute
55+
)
56+
);
57+
}
58+
}
59+
}
60+
}
61+
}

readme.MD

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,4 @@
1919
- `controller_annotations_path` - массив с путями к контроллерам, использующим аннотации.
2020
- `router_cache_path` - путь к кэшу аннотаций. По умолчанию `%kernel.cache_dir%/routes`.
2121
- `router_config_file` - путь к файлу с конфигурацией роутов. По умолчанию `app/routes.yaml`. Файл может быть в любом поддерживаемом Symfony формате - Yaml, PHP, XML и т.д.
22+
- `router_check_exists_controller` - проверять на существование классы-контроллеры. По умолчанию `false`.

ruleset.xml

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?xml version="1.0"?>
2+
<ruleset name="RegioStandard">
3+
<description>RegioMedia PHP Coding Standard</description>
4+
5+
<!-- Основа: https://www.php-fig.org/psr/psr-2/ -->
6+
<rule ref="PSR2" />
7+
8+
<!-- Включают обязательность док-блоков для классов и функций -->
9+
<rule ref="Squiz.Commenting.FunctionComment" />
10+
<rule ref="Squiz.Commenting.FunctionCommentThrowTag" />
11+
<rule ref="Squiz.Commenting.ClassComment">
12+
<exclude name="Squiz.Commenting.ClassComment.TagNotAllowed"/>.
13+
</rule>
14+
<rule ref="Squiz.Commenting.VariableComment" />
15+
16+
<!-- увеличивает лимит на длину строки по сравнению с PSR-2 -->
17+
<rule ref="Generic.Files.LineLength">
18+
<properties>
19+
<property name="lineLimit" value="140"/>
20+
<property name="absoluteLineLimit" value="200"/>
21+
</properties>
22+
</rule>
23+
24+
<!-- предупреждает об использовании нежелательных функций (устаревшие и отладочные) -->
25+
<rule ref="Generic.PHP.ForbiddenFunctions">
26+
<properties>
27+
<property name="error" value="false" />
28+
<property name="forbiddenFunctions" type="array"
29+
value="sizeof=>count,delete=>unset,d=>null,var_dump=>null" />
30+
</properties>
31+
</rule>
32+
33+
<!-- запрещает использование двойных кавычек там, где они не нужны -->
34+
<rule ref="Squiz.Strings.DoubleQuoteUsage.NotRequired" />
35+
</ruleset>

0 commit comments

Comments
 (0)