Debian Codegraph @

vendor/doctrine/deprecations/src/Deprecation.php

raw
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Doctrine\Deprecations;
6
7 use Psr\Log\LoggerInterface;
8
9 use function array_key_exists;
10 use function array_reduce;
11 use function assert;
12 use function debug_backtrace;
13 use function sprintf;
14 use function str_replace;
15 use function strpos;
16 use function strrpos;
17 use function substr;
18 use function trigger_error;
19
20 use const DEBUG_BACKTRACE_IGNORE_ARGS;
21 use const DIRECTORY_SEPARATOR;
22 use const E_USER_DEPRECATED;
23
24 /**
25 * Manages Deprecation logging in different ways.
26 *
27 * By default triggered exceptions are not logged.
28 *
29 * To enable different deprecation logging mechanisms you can call the
30 * following methods:
31 *
32 * - Minimal collection of deprecations via getTriggeredDeprecations()
33 * \Doctrine\Deprecations\Deprecation::enableTrackingDeprecations();
34 *
35 * - Uses @trigger_error with E_USER_DEPRECATED
36 * \Doctrine\Deprecations\Deprecation::enableWithTriggerError();
37 *
38 * - Sends deprecation messages via a PSR-3 logger
39 * \Doctrine\Deprecations\Deprecation::enableWithPsrLogger($logger);
40 *
41 * Packages that trigger deprecations should use the `trigger()` or
42 * `triggerIfCalledFromOutside()` methods.
43 */
44 class Deprecation
45 {
46 private const TYPE_NONE = 0;
47 private const TYPE_TRACK_DEPRECATIONS = 1;
48 private const TYPE_TRIGGER_ERROR = 2;
49 private const TYPE_PSR_LOGGER = 4;
50
51 /** @var int-mask-of<self::TYPE_*>|null */
52 private static $type;
53
54 /** @var LoggerInterface|null */
55 private static $logger;
56
57 /** @var array<string,bool> */
58 private static $ignoredPackages = [];
59
60 /** @var array<string,int> */
61 private static $triggeredDeprecations = [];
62
63 /** @var array<string,bool> */
64 private static $ignoredLinks = [];
65
66 /** @var bool */
67 private static $deduplication = true;
68
69 /**
70 * Trigger a deprecation for the given package and identfier.
71 *
72 * The link should point to a Github issue or Wiki entry detailing the
73 * deprecation. It is additionally used to de-duplicate the trigger of the
74 * same deprecation during a request.
75 *
76 * @param float|int|string $args
77 */
78 public static function trigger(string $package, string $link, string $message, ...$args): void
79 {
80 $type = self::$type ?? self::getTypeFromEnv();
81
82 if ($type === self::TYPE_NONE) {
83 return;
84 }
85
86 if (isset(self::$ignoredLinks[$link])) {
87 return;
88 }
89
90 if (array_key_exists($link, self::$triggeredDeprecations)) {
91 self::$triggeredDeprecations[$link]++;
92 } else {
93 self::$triggeredDeprecations[$link] = 1;
94 }
95
96 if (self::$deduplication === true && self::$triggeredDeprecations[$link] > 1) {
97 return;
98 }
99
100 if (isset(self::$ignoredPackages[$package])) {
101 return;
102 }
103
104 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
105
106 $message = sprintf($message, ...$args);
107
108 self::delegateTriggerToBackend($message, $backtrace, $link, $package);
109 }
110
111 /**
112 * Trigger a deprecation for the given package and identifier when called from outside.
113 *
114 * "Outside" means we assume that $package is currently installed as a
115 * dependency and the caller is not a file in that package. When $package
116 * is installed as a root package then deprecations triggered from the
117 * tests folder are also considered "outside".
118 *
119 * This deprecation method assumes that you are using Composer to install
120 * the dependency and are using the default /vendor/ folder and not a
121 * Composer plugin to change the install location. The assumption is also
122 * that $package is the exact composer packge name.
123 *
124 * Compared to {@link trigger()} this method causes some overhead when
125 * deprecation tracking is enabled even during deduplication, because it
126 * needs to call {@link debug_backtrace()}
127 *
128 * @param float|int|string $args
129 */
130 public static function triggerIfCalledFromOutside(string $package, string $link, string $message, ...$args): void
131 {
132 $type = self::$type ?? self::getTypeFromEnv();
133
134 if ($type === self::TYPE_NONE) {
135 return;
136 }
137
138 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
139
140 // first check that the caller is not from a tests folder, in which case we always let deprecations pass
141 if (isset($backtrace[1]['file'], $backtrace[0]['file']) && strpos($backtrace[1]['file'], DIRECTORY_SEPARATOR . 'tests' . DIRECTORY_SEPARATOR) === false) {
142 $path = DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $package) . DIRECTORY_SEPARATOR;
143
144 if (strpos($backtrace[0]['file'], $path) === false) {
145 return;
146 }
147
148 if (strpos($backtrace[1]['file'], $path) !== false) {
149 return;
150 }
151 }
152
153 if (isset(self::$ignoredLinks[$link])) {
154 return;
155 }
156
157 if (array_key_exists($link, self::$triggeredDeprecations)) {
158 self::$triggeredDeprecations[$link]++;
159 } else {
160 self::$triggeredDeprecations[$link] = 1;
161 }
162
163 if (self::$deduplication === true && self::$triggeredDeprecations[$link] > 1) {
164 return;
165 }
166
167 if (isset(self::$ignoredPackages[$package])) {
168 return;
169 }
170
171 $message = sprintf($message, ...$args);
172
173 self::delegateTriggerToBackend($message, $backtrace, $link, $package);
174 }
175
176 /** @param list<array{function: string, line?: int, file?: string, class?: class-string, type?: string, args?: mixed[], object?: object}> $backtrace */
177 private static function delegateTriggerToBackend(string $message, array $backtrace, string $link, string $package): void
178 {
179 $type = self::$type ?? self::getTypeFromEnv();
180
181 if (($type & self::TYPE_PSR_LOGGER) > 0) {
182 $context = [
183 'file' => $backtrace[0]['file'] ?? null,
184 'line' => $backtrace[0]['line'] ?? null,
185 'package' => $package,
186 'link' => $link,
187 ];
188
189 assert(self::$logger !== null);
190
191 self::$logger->notice($message, $context);
192 }
193
194 if (! (($type & self::TYPE_TRIGGER_ERROR) > 0)) {
195 return;
196 }
197
198 $message .= sprintf(
199 ' (%s:%d called by %s:%d, %s, package %s)',
200 self::basename($backtrace[0]['file'] ?? 'native code'),
201 $backtrace[0]['line'] ?? 0,
202 self::basename($backtrace[1]['file'] ?? 'native code'),
203 $backtrace[1]['line'] ?? 0,
204 $link,
205 $package
206 );
207
208 @trigger_error($message, E_USER_DEPRECATED);
209 }
210
211 /**
212 * A non-local-aware version of PHPs basename function.
213 */
214 private static function basename(string $filename): string
215 {
216 $pos = strrpos($filename, DIRECTORY_SEPARATOR);
217
218 if ($pos === false) {
219 return $filename;
220 }
221
222 return substr($filename, $pos + 1);
223 }
224
225 public static function enableTrackingDeprecations(): void
226 {
227 self::$type = self::$type ?? self::getTypeFromEnv();
228 self::$type |= self::TYPE_TRACK_DEPRECATIONS;
229 }
230
231 public static function enableWithTriggerError(): void
232 {
233 self::$type = self::$type ?? self::getTypeFromEnv();
234 self::$type |= self::TYPE_TRIGGER_ERROR;
235 }
236
237 public static function enableWithPsrLogger(LoggerInterface $logger): void
238 {
239 self::$type = self::$type ?? self::getTypeFromEnv();
240 self::$type |= self::TYPE_PSR_LOGGER;
241 self::$logger = $logger;
242 }
243
244 public static function withoutDeduplication(): void
245 {
246 self::$deduplication = false;
247 }
248
249 public static function disable(): void
250 {
251 self::$type = self::TYPE_NONE;
252 self::$logger = null;
253 self::$deduplication = true;
254 self::$ignoredLinks = [];
255
256 foreach (self::$triggeredDeprecations as $link => $count) {
257 self::$triggeredDeprecations[$link] = 0;
258 }
259 }
260
261 public static function ignorePackage(string $packageName): void
262 {
263 self::$ignoredPackages[$packageName] = true;
264 }
265
266 public static function ignoreDeprecations(string ...$links): void
267 {
268 foreach ($links as $link) {
269 self::$ignoredLinks[$link] = true;
270 }
271 }
272
273 public static function getUniqueTriggeredDeprecationsCount(): int
274 {
275 return array_reduce(self::$triggeredDeprecations, static function (int $carry, int $count) {
276 return $carry + $count;
277 }, 0);
278 }
279
280 /**
281 * Returns each triggered deprecation link identifier and the amount of occurrences.
282 *
283 * @return array<string,int>
284 */
285 public static function getTriggeredDeprecations(): array
286 {
287 return self::$triggeredDeprecations;
288 }
289
290 /** @return int-mask-of<self::TYPE_*> */
291 private static function getTypeFromEnv(): int
292 {
293 switch ($_SERVER['DOCTRINE_DEPRECATIONS'] ?? $_ENV['DOCTRINE_DEPRECATIONS'] ?? null) {
294 case 'trigger':
295 self::$type = self::TYPE_TRIGGER_ERROR;
296 break;
297
298 case 'track':
299 self::$type = self::TYPE_TRACK_DEPRECATIONS;
300 break;
301
302 default:
303 self::$type = self::TYPE_NONE;
304 break;
305 }
306
307 return self::$type;
308 }
309 }