Skip to content

Commit 72e8ce8

Browse files
authored
Merge pull request #285 from clue-labs/backslashes
Improve performance by using global namespace prefix for all functions
2 parents e2e461d + ca7eae9 commit 72e8ce8

File tree

9 files changed

+50
-50
lines changed

9 files changed

+50
-50
lines changed

src/AccessLogHandler.php

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -94,14 +94,14 @@ private function logWhenClosed(ServerRequestInterface $request, ResponseInterfac
9494
if ($body instanceof ReadableStreamInterface && $body->isReadable()) {
9595
$size = 0;
9696
$body->on('data', function (string $chunk) use (&$size) {
97-
$size += strlen($chunk);
97+
$size += \strlen($chunk);
9898
});
9999

100100
$body->on('close', function () use (&$size, $request, $response, $start) {
101101
$this->log($request, $response, $size, $this->now() - $start);
102102
});
103103
} else {
104-
$this->log($request, $response, $body->getSize() ?? strlen((string) $body), $this->now() - $start);
104+
$this->log($request, $response, $body->getSize() ?? \strlen((string) $body), $this->now() - $start);
105105
}
106106
}
107107

@@ -122,19 +122,19 @@ private function log(ServerRequestInterface $request, ResponseInterface $respons
122122
$this->logger->log(
123123
($request->getAttribute('remote_addr') ?? $request->getServerParams()['REMOTE_ADDR'] ?? '-') . ' ' .
124124
'"' . $this->escape($method) . ' ' . $this->escape($request->getRequestTarget()) . ' HTTP/' . $request->getProtocolVersion() . '" ' .
125-
$status . ' ' . $responseSize . ' ' . sprintf('%.3F', $time < 0 ? 0 : $time)
125+
$status . ' ' . $responseSize . ' ' . \sprintf('%.3F', $time < 0 ? 0 : $time)
126126
);
127127
}
128128

129129
private function escape(string $s): string
130130
{
131-
return (string) preg_replace_callback('/[\x00-\x1F\x7F-\xFF"\\\\]+/', function (array $m) {
132-
return str_replace('%', '\x', rawurlencode($m[0]));
131+
return (string) \preg_replace_callback('/[\x00-\x1F\x7F-\xFF"\\\\]+/', function (array $m) {
132+
return \str_replace('%', '\x', \rawurlencode($m[0]));
133133
}, $s);
134134
}
135135

136136
private function now(): float
137137
{
138-
return $this->hasHighResolution ? hrtime(true) * 1e-9 : microtime(true);
138+
return $this->hasHighResolution ? \hrtime(true) * 1e-9 : \microtime(true);
139139
}
140140
}

src/App.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ public function __invoke(ServerRequestInterface $request): ResponseInterface
290290
if ($response instanceof PromiseInterface) {
291291
/** @throws void */
292292
$response = await($response);
293-
assert($response instanceof ResponseInterface);
293+
\assert($response instanceof ResponseInterface);
294294
}
295295

296296
return $response;
@@ -308,14 +308,14 @@ public function __invoke(ServerRequestInterface $request): ResponseInterface
308308
private function handleRequest(ServerRequestInterface $request)
309309
{
310310
$response = ($this->handler)($request);
311-
assert($response instanceof ResponseInterface || $response instanceof PromiseInterface || $response instanceof \Generator);
311+
\assert($response instanceof ResponseInterface || $response instanceof PromiseInterface || $response instanceof \Generator);
312312

313313
if ($response instanceof \Generator) {
314314
if ($response->valid()) {
315315
$response = $this->coroutine($response);
316316
} else {
317317
$response = $response->getReturn();
318-
assert($response instanceof ResponseInterface);
318+
\assert($response instanceof ResponseInterface);
319319
}
320320
}
321321

@@ -336,7 +336,7 @@ private function coroutine(\Generator $generator): PromiseInterface
336336
}
337337

338338
$promise = $generator->current();
339-
assert($promise instanceof PromiseInterface);
339+
\assert($promise instanceof PromiseInterface);
340340

341341
$promise->then(function ($value) use ($generator, $next) {
342342
$generator->send($value);

src/Container.php

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ public function callable(string $class): callable
9494
// Check `$handler` references a class name that is callable, i.e. has an `__invoke()` method.
9595
// This initial version is intentionally limited to checking the method name only.
9696
// A follow-up version will likely use reflection to check request handler argument types.
97-
if (!is_callable($handler)) {
97+
if (!\is_callable($handler)) {
9898
throw new \Error(
9999
'Request handler ' . \explode("\0", $class)[0] . ' has no public __invoke() method'
100100
);
@@ -115,7 +115,7 @@ public function callable(string $class): callable
115115
*/
116116
public function getEnv(string $name): ?string
117117
{
118-
assert(\preg_match('/^[A-Z][A-Z0-9_]+$/', $name) === 1);
118+
\assert(\preg_match('/^[A-Z][A-Z0-9_]+$/', $name) === 1);
119119

120120
if ($this->container instanceof ContainerInterface && $this->container->has($name)) {
121121
$value = $this->container->get($name);
@@ -180,7 +180,7 @@ public function getErrorHandler(): ErrorHandler
180180
*/
181181
private function loadObject(string $name, int $depth = 64) /*: object (PHP 7.2+) */
182182
{
183-
assert(\is_array($this->container));
183+
\assert(\is_array($this->container));
184184

185185
if (\array_key_exists($name, $this->container)) {
186186
if (\is_string($this->container[$name])) {
@@ -226,13 +226,13 @@ private function loadObject(string $name, int $depth = 64) /*: object (PHP 7.2+)
226226
);
227227
}
228228

229-
assert($this->container[$name] instanceof $name);
229+
\assert($this->container[$name] instanceof $name);
230230

231231
return $this->container[$name];
232232
}
233233

234234
// Check `$name` references a valid class name that can be autoloaded
235-
if (!\class_exists($name, true) && !interface_exists($name, false) && !trait_exists($name, false)) {
235+
if (!\class_exists($name, true) && !\interface_exists($name, false) && !\trait_exists($name, false)) {
236236
throw new \Error('Class ' . $name . ' not found');
237237
}
238238

@@ -287,7 +287,7 @@ private function loadParameter(\ReflectionParameter $parameter, int $depth, bool
287287
throw new \Error(self::parameterError($parameter, $for) . ' is recursive');
288288
}
289289

290-
assert(\is_array($this->container));
290+
\assert(\is_array($this->container));
291291
$type = $parameter->getType();
292292

293293
// abort for union types (PHP 8.0+) and intersection types (PHP 8.1+)
@@ -306,7 +306,7 @@ private function loadParameter(\ReflectionParameter $parameter, int $depth, bool
306306
} // @codeCoverageIgnoreEnd
307307

308308
// load container variables if parameter name is known
309-
assert($type === null || $type instanceof \ReflectionNamedType);
309+
\assert($type === null || $type instanceof \ReflectionNamedType);
310310
if ($allowVariables && $this->hasVariable($parameter->getName())) {
311311
$value = $this->loadVariable($parameter->getName(), $depth);
312312

@@ -355,13 +355,13 @@ private function hasVariable(string $name): bool
355355
*/
356356
private function loadVariable(string $name, int $depth = 64) /*: object|string|int|float|bool|null (PHP 8.0+) */
357357
{
358-
assert($this->hasVariable($name));
359-
assert(\is_array($this->container) || !$this->container->has($name));
358+
\assert($this->hasVariable($name));
359+
\assert(\is_array($this->container) || !$this->container->has($name));
360360

361361
if (\is_array($this->container) && ($this->container[$name] ?? null) instanceof \Closure) {
362362
// build list of factory parameters based on parameter types
363363
$factory = $this->container[$name];
364-
assert($factory instanceof \Closure);
364+
\assert($factory instanceof \Closure);
365365
$closure = new \ReflectionFunction($factory);
366366
$params = $this->loadFunctionParams($closure, $depth - 1, true, '$' . $name);
367367

@@ -378,17 +378,17 @@ private function loadVariable(string $name, int $depth = 64) /*: object|string|i
378378
} elseif (\is_array($this->container) && \array_key_exists($name, $this->container)) {
379379
$value = $this->container[$name];
380380
} elseif (isset($_ENV[$name])) {
381-
assert(\is_string($_ENV[$name]));
381+
\assert(\is_string($_ENV[$name]));
382382
$value = $_ENV[$name];
383383
} elseif (isset($_SERVER[$name])) {
384-
assert(\is_string($_SERVER[$name]));
384+
\assert(\is_string($_SERVER[$name]));
385385
$value = $_SERVER[$name];
386386
} else {
387387
$value = \getenv($name);
388-
assert($this->useProcessEnv && $value !== false);
388+
\assert($this->useProcessEnv && $value !== false);
389389
}
390390

391-
assert(\is_object($value) || \is_scalar($value) || $value === null);
391+
\assert(\is_object($value) || \is_scalar($value) || $value === null);
392392
return $value;
393393
}
394394

src/FilesystemHandler.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ public function __construct(string $root)
6464
public function __invoke(ServerRequestInterface $request): ResponseInterface
6565
{
6666
$local = $request->getAttribute('path', '');
67-
assert(\is_string($local));
67+
\assert(\is_string($local));
6868
$path = \rtrim($this->root . '/' . $local, '/');
6969

7070
// local path should not contain "./", "../", "//" or null bytes or start with slash

src/Io/FiberHandler.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,13 +40,13 @@ public function __invoke(ServerRequestInterface $request, callable $next)
4040
$deferred = null;
4141
$fiber = new \Fiber(function () use ($request, $next, &$deferred) {
4242
$response = $next($request);
43-
assert($response instanceof ResponseInterface || $response instanceof PromiseInterface || $response instanceof \Generator);
43+
\assert($response instanceof ResponseInterface || $response instanceof PromiseInterface || $response instanceof \Generator);
4444

4545
// if the next request handler returns immediately, the fiber can terminate immediately without using a Deferred
4646
// if the next request handler suspends the fiber, we only reach this point after resuming the fiber, so the code below will have assigned a Deferred
4747
/** @var ?Deferred<ResponseInterface> $deferred */
4848
if ($deferred !== null) {
49-
assert($response instanceof ResponseInterface);
49+
\assert($response instanceof ResponseInterface);
5050
$deferred->resolve($response);
5151
}
5252

src/Io/LogStreamHandler.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ public function log(string $message): void
8585
$prefix = \date('Y-m-d H:i:s', (int) $time) . \sprintf('.%03d ', (int) (($time - (int) $time) * 1e3));
8686

8787
$ret = \fwrite($this->stream, $prefix . $message . \PHP_EOL);
88-
assert(\is_int($ret));
88+
\assert(\is_int($ret));
8989
}
9090

9191
private function isAbsolutePath(string $path): bool

src/Io/MiddlewareHandler.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ class MiddlewareHandler
1515
/** @param list<callable> $handlers */
1616
public function __construct(array $handlers)
1717
{
18-
assert(count($handlers) >= 2);
18+
\assert(\count($handlers) >= 2);
1919

2020
$this->handlers = $handlers;
2121
}

src/Io/RouteHandler.php

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ public function map(array $methods, string $route, $handler, ...$handlers): void
5252
$handlers = [$handler];
5353
}
5454

55-
$last = key($handlers);
55+
$last = \key($handlers);
5656
$container = $this->container;
5757
foreach ($handlers as $i => $handler) {
5858
if ($handler instanceof Container && $i !== $last) {
@@ -66,7 +66,7 @@ public function map(array $methods, string $route, $handler, ...$handlers): void
6666
}
6767

6868
/** @var non-empty-array<callable> $handlers */
69-
$handler = \count($handlers) > 1 ? new MiddlewareHandler(array_values($handlers)) : \reset($handlers);
69+
$handler = \count($handlers) > 1 ? new MiddlewareHandler(\array_values($handlers)) : \reset($handlers);
7070
$this->routeDispatcher = null;
7171
$this->routeCollector->addRoute($methods, $route, $handler);
7272
}
@@ -88,15 +88,15 @@ public function __invoke(ServerRequestInterface $request)
8888
}
8989

9090
$routeInfo = $this->routeDispatcher->dispatch($request->getMethod(), $target);
91-
assert(\is_array($routeInfo) && isset($routeInfo[0]));
91+
\assert(\is_array($routeInfo) && isset($routeInfo[0]));
9292

9393
// happy path: matching route found, assign route attributes and invoke request handler
9494
if ($routeInfo[0] === \FastRoute\Dispatcher::FOUND) {
9595
$handler = $routeInfo[1];
9696
$vars = $routeInfo[2];
9797

9898
foreach ($vars as $key => $value) {
99-
$request = $request->withAttribute($key, rawurldecode($value));
99+
$request = $request->withAttribute($key, \rawurldecode($value));
100100
}
101101

102102
return $handler($request);
@@ -108,8 +108,8 @@ public function __invoke(ServerRequestInterface $request)
108108
}
109109

110110
// unexpected request method for route: report error `405 Method Not Allowed`
111-
assert($routeInfo[0] === \FastRoute\Dispatcher::METHOD_NOT_ALLOWED);
112-
assert(\is_array($routeInfo[1]) && \count($routeInfo[1]) > 0);
111+
\assert($routeInfo[0] === \FastRoute\Dispatcher::METHOD_NOT_ALLOWED);
112+
\assert(\is_array($routeInfo[1]) && \count($routeInfo[1]) > 0);
113113

114114
return $this->errorHandler->requestMethodNotAllowed($routeInfo[1]);
115115
}

src/Io/SapiHandler.php

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ public function requestFromGlobals(): ServerRequestInterface
5454
} else {
5555
foreach ($_SERVER as $key => $value) {
5656
if (\strpos($key, 'HTTP_') === 0) {
57-
$key = str_replace(' ', '-', \ucwords(\strtolower(\str_replace('_', ' ', \substr($key, 5)))));
57+
$key = \str_replace(' ', '-', \ucwords(\strtolower(\str_replace('_', ' ', \substr($key, 5)))));
5858
$headers[$key] = $value;
5959

6060
if ($host === null && $key === 'Host') {
@@ -73,15 +73,15 @@ public function requestFromGlobals(): ServerRequestInterface
7373
$url = (($_SERVER['HTTPS'] ?? null) === 'on' ? 'https://' : 'http://') . $target;
7474
}
7575

76-
$body = file_get_contents('php://input');
77-
assert(\is_string($body));
76+
$body = \file_get_contents('php://input');
77+
\assert(\is_string($body));
7878

7979
$request = new ServerRequest(
8080
$_SERVER['REQUEST_METHOD'] ?? 'GET',
8181
$url,
8282
$headers,
8383
$body,
84-
substr($_SERVER['SERVER_PROTOCOL'] ?? 'http/1.1', 5),
84+
\substr($_SERVER['SERVER_PROTOCOL'] ?? 'http/1.1', 5),
8585
$_SERVER
8686
);
8787
if ($host === null) {
@@ -121,22 +121,22 @@ public function sendResponse(ResponseInterface $response): void
121121

122122
// remove default "Content-Type" header set by PHP (default_mimetype)
123123
if (!$response->hasHeader('Content-Type')) {
124-
header('Content-Type:');
125-
header_remove('Content-Type');
124+
\header('Content-Type:');
125+
\header_remove('Content-Type');
126126
}
127127

128128
// send all headers without applying default "; charset=utf-8" set by PHP (default_charset)
129-
$old = ini_get('default_charset');
130-
assert(\is_string($old));
131-
ini_set('default_charset', '');
129+
$old = \ini_get('default_charset');
130+
\assert(\is_string($old));
131+
\ini_set('default_charset', '');
132132
foreach ($response->getHeaders() as $name => $values) {
133133
foreach ($values as $value) {
134-
header($name . ': ' . $value, false);
134+
\header($name . ': ' . $value, false);
135135
}
136136
}
137-
ini_set('default_charset', $old);
137+
\ini_set('default_charset', $old);
138138

139-
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status . ' ' . $response->getReasonPhrase());
139+
\header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status . ' ' . $response->getReasonPhrase());
140140

141141
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'HEAD' || $status === Response::STATUS_NO_CONTENT || $status === Response::STATUS_NOT_MODIFIED) {
142142
$body->close();
@@ -145,8 +145,8 @@ public function sendResponse(ResponseInterface $response): void
145145

146146
if ($body instanceof ReadableStreamInterface) {
147147
// try to disable nginx buffering (http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering)
148-
if (isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'nginx') === 0) {
149-
header('X-Accel-Buffering: no');
148+
if (isset($_SERVER['SERVER_SOFTWARE']) && \strpos($_SERVER['SERVER_SOFTWARE'], 'nginx') === 0) {
149+
\header('X-Accel-Buffering: no');
150150
}
151151

152152
// clear output buffer to show streaming output (default in cli-server)
@@ -157,7 +157,7 @@ public function sendResponse(ResponseInterface $response): void
157157
// flush data whenever stream reports one data chunk
158158
$body->on('data', function ($chunk) {
159159
echo $chunk;
160-
flush();
160+
\flush();
161161
});
162162
} else {
163163
echo $body;

0 commit comments

Comments
 (0)