Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <fabien@symfony.com>
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 Symfony\Component\HttpKernel\Controller;
13
 
14
use Psr\Log\LoggerInterface;
15
use Symfony\Component\HttpFoundation\Request;
16
 
17
/**
18
 * This implementation uses the '_controller' request attribute to determine
19
 * the controller to execute.
20
 *
21
 * @author Fabien Potencier <fabien@symfony.com>
22
 * @author Tobias Schultze <http://tobion.de>
23
 */
24
class ControllerResolver implements ControllerResolverInterface
25
{
26
    private ?LoggerInterface $logger;
27
 
28
    public function __construct(LoggerInterface $logger = null)
29
    {
30
        $this->logger = $logger;
31
    }
32
 
33
    public function getController(Request $request): callable|false
34
    {
35
        if (!$controller = $request->attributes->get('_controller')) {
36
            $this->logger?->warning('Unable to look for the controller as the "_controller" parameter is missing.');
37
 
38
            return false;
39
        }
40
 
41
        if (\is_array($controller)) {
42
            if (isset($controller[0]) && \is_string($controller[0]) && isset($controller[1])) {
43
                try {
44
                    $controller[0] = $this->instantiateController($controller[0]);
45
                } catch (\Error|\LogicException $e) {
46
                    if (\is_callable($controller)) {
47
                        return $controller;
48
                    }
49
 
50
                    throw $e;
51
                }
52
            }
53
 
54
            if (!\is_callable($controller)) {
55
                throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller));
56
            }
57
 
58
            return $controller;
59
        }
60
 
61
        if (\is_object($controller)) {
62
            if (!\is_callable($controller)) {
63
                throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($controller));
64
            }
65
 
66
            return $controller;
67
        }
68
 
69
        if (\function_exists($controller)) {
70
            return $controller;
71
        }
72
 
73
        try {
74
            $callable = $this->createController($controller);
75
        } catch (\InvalidArgumentException $e) {
76
            throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$e->getMessage(), 0, $e);
77
        }
78
 
79
        if (!\is_callable($callable)) {
80
            throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable: ', $request->getPathInfo()).$this->getControllerError($callable));
81
        }
82
 
83
        return $callable;
84
    }
85
 
86
    /**
87
     * Returns a callable for the given controller.
88
     *
89
     * @throws \InvalidArgumentException When the controller cannot be created
90
     */
91
    protected function createController(string $controller): callable
92
    {
93
        if (!str_contains($controller, '::')) {
94
            $controller = $this->instantiateController($controller);
95
 
96
            if (!\is_callable($controller)) {
97
                throw new \InvalidArgumentException($this->getControllerError($controller));
98
            }
99
 
100
            return $controller;
101
        }
102
 
103
        [$class, $method] = explode('::', $controller, 2);
104
 
105
        try {
106
            $controller = [$this->instantiateController($class), $method];
107
        } catch (\Error|\LogicException $e) {
108
            try {
109
                if ((new \ReflectionMethod($class, $method))->isStatic()) {
110
                    return $class.'::'.$method;
111
                }
112
            } catch (\ReflectionException) {
113
                throw $e;
114
            }
115
 
116
            throw $e;
117
        }
118
 
119
        if (!\is_callable($controller)) {
120
            throw new \InvalidArgumentException($this->getControllerError($controller));
121
        }
122
 
123
        return $controller;
124
    }
125
 
126
    /**
127
     * Returns an instantiated controller.
128
     */
129
    protected function instantiateController(string $class): object
130
    {
131
        return new $class();
132
    }
133
 
134
    private function getControllerError(mixed $callable): string
135
    {
136
        if (\is_string($callable)) {
137
            if (str_contains($callable, '::')) {
138
                $callable = explode('::', $callable, 2);
139
            } else {
140
                return sprintf('Function "%s" does not exist.', $callable);
141
            }
142
        }
143
 
144
        if (\is_object($callable)) {
145
            $availableMethods = $this->getClassMethodsWithoutMagicMethods($callable);
146
            $alternativeMsg = $availableMethods ? sprintf(' or use one of the available methods: "%s"', implode('", "', $availableMethods)) : '';
147
 
148
            return sprintf('Controller class "%s" cannot be called without a method name. You need to implement "__invoke"%s.', get_debug_type($callable), $alternativeMsg);
149
        }
150
 
151
        if (!\is_array($callable)) {
152
            return sprintf('Invalid type for controller given, expected string, array or object, got "%s".', get_debug_type($callable));
153
        }
154
 
155
        if (!isset($callable[0]) || !isset($callable[1]) || 2 !== \count($callable)) {
156
            return 'Invalid array callable, expected [controller, method].';
157
        }
158
 
159
        [$controller, $method] = $callable;
160
 
161
        if (\is_string($controller) && !class_exists($controller)) {
162
            return sprintf('Class "%s" does not exist.', $controller);
163
        }
164
 
165
        $className = \is_object($controller) ? get_debug_type($controller) : $controller;
166
 
167
        if (method_exists($controller, $method)) {
168
            return sprintf('Method "%s" on class "%s" should be public and non-abstract.', $method, $className);
169
        }
170
 
171
        $collection = $this->getClassMethodsWithoutMagicMethods($controller);
172
 
173
        $alternatives = [];
174
 
175
        foreach ($collection as $item) {
176
            $lev = levenshtein($method, $item);
177
 
178
            if ($lev <= \strlen($method) / 3 || str_contains($item, $method)) {
179
                $alternatives[] = $item;
180
            }
181
        }
182
 
183
        asort($alternatives);
184
 
185
        $message = sprintf('Expected method "%s" on class "%s"', $method, $className);
186
 
187
        if (\count($alternatives) > 0) {
188
            $message .= sprintf(', did you mean "%s"?', implode('", "', $alternatives));
189
        } else {
190
            $message .= sprintf('. Available methods: "%s".', implode('", "', $collection));
191
        }
192
 
193
        return $message;
194
    }
195
 
196
    private function getClassMethodsWithoutMagicMethods($classOrObject): array
197
    {
198
        $methods = get_class_methods($classOrObject);
199
 
200
        return array_filter($methods, function (string $method) {
201
            return 0 !== strncmp($method, '__', 2);
202
        });
203
    }
204
}