1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the MiddlewareBundle |
7
|
|
|
* |
8
|
|
|
* (c) Indra Gunawan <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Indragunawan\MiddlewareBundle\DependencyInjection\Compiler; |
15
|
|
|
|
16
|
|
|
use Indragunawan\MiddlewareBundle\Middleware\MiddlewareInterface; |
17
|
|
|
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; |
18
|
|
|
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; |
19
|
|
|
use Symfony\Component\DependencyInjection\ContainerBuilder; |
20
|
|
|
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; |
21
|
|
|
use Symfony\Component\DependencyInjection\Reference; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @author Indra Gunawan <[email protected]> |
25
|
|
|
*/ |
26
|
|
|
final class AddMiddlewarePass implements CompilerPassInterface |
27
|
|
|
{ |
28
|
|
|
/** |
29
|
|
|
* {@inheritdoc} |
30
|
|
|
*/ |
31
|
|
|
public function process(ContainerBuilder $container) |
32
|
|
|
{ |
33
|
|
|
if (!$container->hasDefinition('indragunawan_middleware.middleware')) { |
34
|
|
|
return; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$definition = $container->findDefinition('indragunawan_middleware.middleware'); |
38
|
|
|
foreach ($container->findTaggedServiceIds('indragunawan.middleware') as $id => $attrs) { |
39
|
|
|
foreach ($attrs as $attr) { |
40
|
|
|
$class = $container->getDefinition($id)->getClass(); |
41
|
|
|
if (!$r = $container->getReflectionClass($class)) { |
42
|
|
|
throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id)); |
43
|
|
|
} elseif (!$r->isSubclassOf(MiddlewareInterface::class)) { |
44
|
|
|
throw new InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, MiddlewareInterface::class)); |
45
|
|
|
} elseif (empty($attr['event'])) { |
46
|
|
|
throw new InvalidArgumentException('"event" tag attribute must be set'); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$priority = 0; |
50
|
|
|
$name = null; |
51
|
|
|
$supports = forward_static_call([$class, 'supports']); |
52
|
|
|
if (\is_string($supports)) { |
53
|
|
|
$name = $supports; |
54
|
|
|
} elseif (\is_string($supports[0])) { |
55
|
|
|
$name = $supports[0]; |
56
|
|
|
$priority = isset($supports[1]) ? $supports[1] : 0; |
57
|
|
|
} else { |
58
|
|
|
throw new InvalidArgumentException(sprintf('Invalid return format "supports" of class "%s".', $class)); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
$definition->addMethodCall('addMiddleware', [$attr['event'], $name, new ServiceClosureArgument(new Reference($id)), $priority]); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|