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\ErrorHandler\ErrorEnhancer;
13
 
14
use Composer\Autoload\ClassLoader;
15
use Symfony\Component\ErrorHandler\DebugClassLoader;
16
use Symfony\Component\ErrorHandler\Error\ClassNotFoundError;
17
use Symfony\Component\ErrorHandler\Error\FatalError;
18
 
19
/**
20
 * @author Fabien Potencier <fabien@symfony.com>
21
 */
22
class ClassNotFoundErrorEnhancer implements ErrorEnhancerInterface
23
{
24
    public function enhance(\Throwable $error): ?\Throwable
25
    {
26
        // Some specific versions of PHP produce a fatal error when extending a not found class.
27
        $message = !$error instanceof FatalError ? $error->getMessage() : $error->getError()['message'];
28
        if (!preg_match('/^(Class|Interface|Trait) [\'"]([^\'"]+)[\'"] not found$/', $message, $matches)) {
29
            return null;
30
        }
31
        $typeName = strtolower($matches[1]);
32
        $fullyQualifiedClassName = $matches[2];
33
 
34
        if (false !== $namespaceSeparatorIndex = strrpos($fullyQualifiedClassName, '\\')) {
35
            $className = substr($fullyQualifiedClassName, $namespaceSeparatorIndex + 1);
36
            $namespacePrefix = substr($fullyQualifiedClassName, 0, $namespaceSeparatorIndex);
37
            $message = sprintf('Attempted to load %s "%s" from namespace "%s".', $typeName, $className, $namespacePrefix);
38
            $tail = ' for another namespace?';
39
        } else {
40
            $className = $fullyQualifiedClassName;
41
            $message = sprintf('Attempted to load %s "%s" from the global namespace.', $typeName, $className);
42
            $tail = '?';
43
        }
44
 
45
        if ($candidates = $this->getClassCandidates($className)) {
46
            $tail = array_pop($candidates).'"?';
47
            if ($candidates) {
48
                $tail = ' for e.g. "'.implode('", "', $candidates).'" or "'.$tail;
49
            } else {
50
                $tail = ' for "'.$tail;
51
            }
52
        }
53
        $message .= "\nDid you forget a \"use\" statement".$tail;
54
 
55
        return new ClassNotFoundError($message, $error);
56
    }
57
 
58
    /**
59
     * Tries to guess the full namespace for a given class name.
60
     *
61
     * By default, it looks for PSR-0 and PSR-4 classes registered via a Symfony or a Composer
62
     * autoloader (that should cover all common cases).
63
     *
64
     * @param string $class A class name (without its namespace)
65
     *
66
     * Returns an array of possible fully qualified class names
67
     */
68
    private function getClassCandidates(string $class): array
69
    {
70
        if (!\is_array($functions = spl_autoload_functions())) {
71
            return [];
72
        }
73
 
74
        // find Symfony and Composer autoloaders
75
        $classes = [];
76
 
77
        foreach ($functions as $function) {
78
            if (!\is_array($function)) {
79
                continue;
80
            }
81
            // get class loaders wrapped by DebugClassLoader
82
            if ($function[0] instanceof DebugClassLoader) {
83
                $function = $function[0]->getClassLoader();
84
 
85
                if (!\is_array($function)) {
86
                    continue;
87
                }
88
            }
89
 
90
            if ($function[0] instanceof ClassLoader) {
91
                foreach ($function[0]->getPrefixes() as $prefix => $paths) {
92
                    foreach ($paths as $path) {
93
                        $classes[] = $this->findClassInPath($path, $class, $prefix);
94
                    }
95
                }
96
 
97
                foreach ($function[0]->getPrefixesPsr4() as $prefix => $paths) {
98
                    foreach ($paths as $path) {
99
                        $classes[] = $this->findClassInPath($path, $class, $prefix);
100
                    }
101
                }
102
            }
103
        }
104
 
105
        return array_unique(array_merge([], ...$classes));
106
    }
107
 
108
    private function findClassInPath(string $path, string $class, string $prefix): array
109
    {
110
        if (!$path = realpath($path.'/'.strtr($prefix, '\\_', '//')) ?: realpath($path.'/'.\dirname(strtr($prefix, '\\_', '//'))) ?: realpath($path)) {
111
            return [];
112
        }
113
 
114
        $classes = [];
115
        $filename = $class.'.php';
116
        foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
117
            if ($filename == $file->getFileName() && $class = $this->convertFileToClass($path, $file->getPathName(), $prefix)) {
118
                $classes[] = $class;
119
            }
120
        }
121
 
122
        return $classes;
123
    }
124
 
125
    private function convertFileToClass(string $path, string $file, string $prefix): ?string
126
    {
127
        $candidates = [
128
            // namespaced class
129
            $namespacedClass = str_replace([$path.\DIRECTORY_SEPARATOR, '.php', '/'], ['', '', '\\'], $file),
130
            // namespaced class (with target dir)
131
            $prefix.$namespacedClass,
132
            // namespaced class (with target dir and separator)
133
            $prefix.'\\'.$namespacedClass,
134
            // PEAR class
135
            str_replace('\\', '_', $namespacedClass),
136
            // PEAR class (with target dir)
137
            str_replace('\\', '_', $prefix.$namespacedClass),
138
            // PEAR class (with target dir and separator)
139
            str_replace('\\', '_', $prefix.'\\'.$namespacedClass),
140
        ];
141
 
142
        if ($prefix) {
143
            $candidates = array_filter($candidates, function ($candidate) use ($prefix) { return str_starts_with($candidate, $prefix); });
144
        }
145
 
146
        // We cannot use the autoloader here as most of them use require; but if the class
147
        // is not found, the new autoloader call will require the file again leading to a
148
        // "cannot redeclare class" error.
149
        foreach ($candidates as $candidate) {
150
            if ($this->classExists($candidate)) {
151
                return $candidate;
152
            }
153
        }
154
 
155
        try {
156
            require_once $file;
157
        } catch (\Throwable) {
158
            return null;
159
        }
160
 
161
        foreach ($candidates as $candidate) {
162
            if ($this->classExists($candidate)) {
163
                return $candidate;
164
            }
165
        }
166
 
167
        return null;
168
    }
169
 
170
    private function classExists(string $class): bool
171
    {
172
        return class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false);
173
    }
174
}