Server IP : 213.176.29.180 / Your IP : 18.119.139.90 Web Server : Apache System : Linux 213.176.29.180.hostiran.name 4.18.0-553.22.1.el8_10.x86_64 #1 SMP Tue Sep 24 05:16:59 EDT 2024 x86_64 User : webtaragh ( 1001) PHP Version : 7.4.33 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON Directory (0750) : /home/webtaragh/public_html/../www/../www/ |
[ Home ] | [ C0mmand ] | [ Upload File ] |
---|
readable/src/readable.php 0000644 00000020234 14736103267 0011354 0 ustar 00 <?php namespace mindplay; use Closure; use Error; use ErrorException; use Exception; use ReflectionFunction; use Throwable; /** * Pseudo-namespace for functions that generate human-readable string representations * of most types of PHP values. */ abstract class readable { /** * @var int strings longer than this number of characters will be truncated when formatting string-values */ public static $max_string_length = 120; /** * @var string[] map where PHP error severity code => constant name */ public static $severity_names = [ E_ERROR => "E_ERROR", E_USER_ERROR => "E_USER_ERROR", E_CORE_ERROR => "E_CORE_ERROR", E_COMPILE_ERROR => "E_COMPILE_ERROR", E_PARSE => "E_PARSE", E_WARNING => "E_WARNING", E_USER_WARNING => "E_USER_WARNING", E_CORE_WARNING => "E_CORE_WARNING", E_COMPILE_WARNING => "E_COMPILE_WARNING", E_NOTICE => "E_NOTICE", E_USER_NOTICE => "E_USER_NOTICE", E_STRICT => "E_STRICT", E_RECOVERABLE_ERROR => "E_RECOVERABLE_ERROR", E_DEPRECATED => "E_DEPRECATED", E_USER_DEPRECATED => "E_USER_DEPRECATED", ]; /** * @param mixed $value any type of PHP value * * @return string readable representation of the given value */ public static function value($value) { $type = is_array($value) && is_callable($value) ? "callable" : strtolower(gettype($value)); switch ($type) { case "boolean": return $value ? "true" : "false"; case "integer": return number_format($value, 0, "", ""); case "double": // (for historical reasons "double" is returned in case of a float, and not simply "float") $formatted = sprintf("%.6g", $value); return $value == $formatted ? "{$formatted}" : "~{$formatted}"; case "string": $string = strlen($value) > self::$max_string_length ? substr($value, 0, self::$max_string_length) . "...[" . strlen($value) . "]" : $value; return '"' . addslashes($string) . '"'; case "array": return "[" . self::values($value) . "]"; case "object": if ($value instanceof Closure) { $reflection = new ReflectionFunction($value); return "{Closure in " . $reflection->getFileName() . "({$reflection->getStartLine()})}"; } return "{" . ($value instanceof \stdClass ? "object" : get_class($value)) . "}"; case "resource": return "{" . get_resource_type($value) . "}"; case "callable": return is_object($value[0]) ? '{' . get_class($value[0]) . "}->{$value[1]}()" : "{$value[0]}::{$value[1]}()"; case "null": return "null"; } return "{{$type}}"; // "unknown type" and possibly unsupported (future) types } /** * @param array $array array containing any type of PHP values * * @return string comma-separated human-readable representation of the given values */ public static function values(array $array) { $formatted = array_map(['mindplay\\readable', 'value'], $array); if (array_keys($array) !== range(0, count($array) - 1)) { foreach ($formatted as $name => $value) { $formatted[$name] = self::value($name) . " => {$value}"; } } return implode(", ", $formatted); } /** * @param mixed $value any type of PHP value * * @return string human-readable type-name */ public static function typeof($value) { $type = ! is_string($value) && ! is_object($value) && is_callable($value) ? "callable" : strtolower(gettype($value)); switch ($type) { case "boolean": return "bool"; case "integer": return "int"; case "double": return "float"; case "object": return $value instanceof \stdClass ? "object" : get_class($value); case "string": case "array": case "resource": case "callable": case "null": return $type; } return "unknown"; } /** * @param mixed $callable * * @return string human-readable description of callback */ public static function callback($callable) { if (is_string($callable) && is_callable($callable)) { return "{$callable}()"; } elseif (is_object($callable) && method_exists($callable, "__invoke")) { return $callable instanceof Closure ? self::value($callable) : "{" . get_class($callable) . "}->__invoke()"; } return self::value($callable); } /** * @param Exception|Error|Throwable|int $error an Exception, Error (or one of the E_* error severity constants) * * @return string */ public static function error($error) { if (is_int($error)) { return static::severity($error); } $type = get_class($error); if ($error instanceof ErrorException) { $severity = static::severity($error->getSeverity()); $type = "{$type}: {$severity}"; } if ($error instanceof Exception || $error instanceof Error) { $message = $error->getMessage() ?: '{none}'; $file = $error->getFile() ? $error->getFile() . "(" . $error->getLine() . ")" : "{no file}"; return "{$type} with message: {$message} in {$file}"; } return $type; } /** * @param int $severity one of the E_* error severity constants * * @return string */ public static function severity($severity) { return isset(self::$severity_names[$severity]) ? self::$severity_names[$severity] : "{unknown error-code}"; } /** * @param array|Exception|Error|Throwable $source Exception, Error or stack-trace data as provided * by Exception::getTrace() or by debug_backtrace() * @param bool $with_params if TRUE, calls will be formatted with parameters * * @return string */ public static function trace($source, $with_params = true) { if ($source instanceof Exception || $source instanceof Error) { $trace = $source->getTrace(); } elseif (is_array($source)) { $trace = $source; } else { return "{stack-trace unavailable}"; } $formatted = []; foreach ($trace as $index => $entry) { $line = array_key_exists("line", $entry) ? ":" . $entry["line"] : ""; $file = isset($entry["file"]) ? $entry["file"] : "{no file}"; $function = isset($entry["class"]) ? $entry["class"] . @$entry["type"] . @$entry["function"] : @$entry["function"]; if ($function === "require" || $function === "include") { // bypass argument formatting for include and require statements $args = isset($entry["args"]) && is_array($entry["args"]) ? reset($entry["args"]) : ""; } else { $args = $with_params && isset($entry["args"]) && is_array($entry["args"]) ? static::values($entry["args"]) : ""; } $call = $function ? "{$function}({$args})" : ""; $depth = $index + 1; $formatted[] = sprintf("%6s", "{$depth}.") . " {$file}{$line} {$call}"; } return implode("\n", $formatted); } } readable/README.md 0000644 00000004043 14736103267 0007574 0 ustar 00 mindplay/readable ================= A few simple functions to format any kind of PHP value or type as human-readable. [![PHP Version](https://img.shields.io/badge/php-5.4%2B-blue.svg)](https://packagist.org/packages/mindplay/middleman) [![Build Status](https://travis-ci.org/mindplay-dk/readable.svg)](https://travis-ci.org/mindplay-dk/readable) [![Code Coverage](https://scrutinizer-ci.com/g/mindplay-dk/readable/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/mindplay-dk/readable/?branch=master) Mainly, this is intended to help you produce better error-messages: ```php if (!is_int($value)) { throw new UnexpectedValueException("expected integer, got: " . readable::typeof($value)); } else if ($value > 100) { throw new RangeException("expected value up to 100, got: " . readable::value($value)); } ``` Note that this library is not "better var_dump" - it won't color-code things or dump deep object graphs. There are plenty of other libraries for that sort of thing. Presently, this library consists of these simple functions: * `readable::value($value)` formats any single PHP value as human-readable. * `readable::values($array)` formats an array of (mixed) values as human-readable. * `readable::typeof($value)` returns the type of value (or class name) for any given value. * `readable::callback($callable)` formats any `callable` as human-readable. * `readable::severity($int)` returns for example `E_WARNING` as human-readable `"Warning"`. * `readable::error($exception)` returns a human-readable `Exception`/`Error` summary. * `readable::trace($trace)` formats a stack-trace with file-names, line-numbers, function-names and (optionally) arguments. The latter function `callback()` will fall back to regular `value()` formatting if the given value is not a callable - this function is preferable when a given value was expected to be `callable`, e.g. recognizes function-names as strings and objects implementing `__invoke()`. See the [source code](src/readable.php) and [test suite](test/test.php) for all formatting features. middleman/UPGRADING.md 0000644 00000010250 14736103267 0010347 0 ustar 00 Upgrading ========= ### From 2.x to 3.x PSR-15 (as of `0.4`) no longer defines an interface for client-middleware. As a consequence, this release only supports server-middleware and `ServerRequestInterface`. We hope to see support for client-middleware emerge in the form of a new PSR in the future, but at this point, supporting PSR-15 while directly supporting client-middleware is impossible. ### From 1.x to 2.x #### Name Change `InteropResolver` was renamed to `ContainerResolver` - the method-signature has not changed, so you only need to update your imports to reference the new name. #### MiddlewareInterface Removed The built-in `MiddlewareInterface` has been removed, and you need to select one of the two PSR-15 interfaces, as described below. If you used `callable` middleware, you should expect errors/exceptions, as middleman retains support for `callable`, but now requires a PSR-15 compatible method-signature, as described below. #### PSR-15 Middleware `mindplay/middleman^2` adopts the [PSR-15](https://github.com/http-interop/http-middleware) `0.2` interfaces. This changes the middleware signature substantially, from the legacy signature: function (RequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface To the PSR-15 signature: function (RequestInterface|ServerRequestInterface $request, DelegateInterface $delegate): ResponseInterface PSR-15 introduces two distinct interfaces: `MiddlewareInterface` for processing `RequestInterface`, and `ServerMiddlewareInterface` for processing `ServerRequestInterface`. Because the Response object no longer passes down through the middleware stack, you will need to port your middleware components from the old signature to one of the new signatures. For example, if you had something like the following: ```php use mindplay\middleman\MiddlewareInterface; class MyMiddleware implements MiddlewareInterface { public function __invoke(RequestInterface $request, ResponseInterface $response, $next) { if ($request instanceof ServerRequestInterface) { if ($request->getUri()->getPath() === "/test") { return $response->withBody(...); } } return $next($request, $response->withHeader("X-Foo", "bar")); } } ``` You would need to change several things: ```php use Interop\Http\Middleware\ServerMiddlewareInterface; class MyMiddleware implements ServerMiddlewareInterface { public function process(ServerRequestInterface $request, DelegateInterface $next) { if ($request->getUri()->getPath() === "/test") { return new Response()->withBody(...); } $response = $next->process($request); if (! $response->hasHeader("X-Foo")) { $response = $response->withHeader("X-Foo", "bar"); } return $response; } } ``` That is: 1. The implemented interface (if any) changed from one provided by `middleman` to one provided by PSR-15 - which means the method-name changed from `__invoke()` to `process()`. 2. In the case of server-middleware, the interface specifically type-hints the request as `ServerRequestInterface`, removing the need to type-check within the implementation. 3. The delegate to the next middleware on the stack is type-hinted as `DelegateInterface`, and must now be invoked by calling it's `process()` method. 4. The response argument no longer exists - this has two significant consequences: 1. If we're not going to delegate to the next middleware, the middleware component needs to construct the response object by itself. (at the moment, this means that middleware that constructs a response needs to depend on a PSR-7 implementation - this is the situation until [PSR-17](https://github.com/php-fig/fig-standards/tree/master/proposed/http-factory) becomes available.) 2. In this example, we were decorating the response with a default header `X-Foo: bar`, which might have been overwritten by the next middleware on the stack - instead, we now need to delegate to the next middleware *first*, and then *conditionally* decorate with a default header-value, if one is not already present. middleman/src/ContainerResolver.php 0000644 00000002715 14736103267 0013460 0 ustar 00 <?php namespace mindplay\middleman; use Interop\Container\ContainerInterface; use RuntimeException; /** * Optionally, pass this as `$resolver` to {@see Dispatcher::__construct()} to provide * integration with a dependency injection container - for example: * * $dispatcher = new Dispatcher( * [ * RouterMiddleware::class, * ErrorMiddleware::class, * ], * new InteropResolver($container) * ); * * Note that this resolver will ignore any middleware component that is not a string - so you * can mix component names with regular middleware closures, callable objects, and so on. * * You can use class-names or other component names, depending on what your container supports. * * @link https://github.com/container-interop/container-interop */ class ContainerResolver { /** * @var ContainerInterface */ private $container; /** * @param ContainerInterface $container */ public function __construct(ContainerInterface $container) { $this->container = $container; } public function __invoke($name) { if (! is_string($name)) { return $name; // nothing to resolve (may be a closure or other callable middleware object) } if ($this->container->has($name)) { return $this->container->get($name); } throw new RuntimeException("unable to resolve middleware component name: {$name}"); } } middleman/src/Delegate.php 0000644 00000002476 14736103267 0011532 0 ustar 00 <?php namespace mindplay\middleman; use Interop\Http\ServerMiddleware\DelegateInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; /** * PSR-15 delegate wrapper for internal callbacks generated by {@see Dispatcher} during dispatch. * * @internal */ class Delegate implements DelegateInterface { /** * @var callable */ private $callback; /** * @param callable $callback function (RequestInterface $request) : ResponseInterface */ public function __construct(callable $callback) { $this->callback = $callback; } /** * Dispatch the next available middleware and return the response. * * @param ServerRequestInterface $request * @return ResponseInterface */ public function process(ServerRequestInterface $request) { return call_user_func($this->callback, $request); } /** * Dispatch the next available middleware and return the response. * * This method duplicates `next()` to provide backwards compatibility with non-PSR 15 middleware. * * @param ServerRequestInterface $request * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request) { return call_user_func($this->callback, $request); } } middleman/src/Dispatcher.php 0000644 00000007062 14736103267 0012102 0 ustar 00 <?php namespace mindplay\middleman; use Interop\Http\ServerMiddleware\DelegateInterface; use Interop\Http\ServerMiddleware\MiddlewareInterface; use InvalidArgumentException; use LogicException; use mindplay\readable; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; /** * PSR-7 / PSR-15 middleware dispatcher */ class Dispatcher implements MiddlewareInterface { /** * @var callable middleware resolver */ private $resolver; /** * @var mixed[] unresolved middleware stack */ private $stack; /** * @param (callable|MiddlewareInterface|mixed)[] $stack middleware stack (with at least one middleware component) * @param callable|null $resolver optional middleware resolver: * function (string $name): MiddlewareInterface * * @throws InvalidArgumentException if an empty middleware stack was given */ public function __construct($stack, callable $resolver = null) { if (count($stack) === 0) { throw new InvalidArgumentException("an empty middleware stack was given"); } $this->stack = $stack; $this->resolver = $resolver; } /** * Dispatches the middleware stack and returns the resulting `ResponseInterface`. * * @param ServerRequestInterface $request * * @return ResponseInterface * * @throws LogicException on unexpected result from any middleware on the stack */ public function dispatch(ServerRequestInterface $request) { $resolved = $this->resolve(0); return $resolved($request); } /** * @inheritdoc */ public function process(ServerRequestInterface $request, DelegateInterface $delegate) { $this->stack[] = function (ServerRequestInterface $request) use ($delegate) { return $delegate->process($request); }; $response = $this->dispatch($request); array_pop($this->stack); return $response; } /** * @param int $index middleware stack index * * @return Delegate */ private function resolve($index) { if (isset($this->stack[$index])) { return new Delegate(function (ServerRequestInterface $request) use ($index) { $middleware = $this->resolver ? call_user_func($this->resolver, $this->stack[$index]) : $this->stack[$index]; // as-is switch (true) { case $middleware instanceof MiddlewareInterface: $result = $middleware->process($request, $this->resolve($index + 1)); break; case is_callable($middleware): $result = $middleware($request, $this->resolve($index + 1)); break; default: $given = readable::callback($middleware); throw new LogicException("unsupported middleware type: {$given}"); } if (! $result instanceof ResponseInterface) { $given = readable::value($result); $source = readable::callback($middleware); throw new LogicException("unexpected middleware result: {$given} returned by: {$source}"); } return $result; }); } return new Delegate(function () { throw new LogicException("unresolved request: middleware stack exhausted with no result"); }); } } middleman/README.md 0000644 00000013043 14736103267 0007767 0 ustar 00 mindplay/middleman ================== Dead simple PSR-15 / PSR-7 [middleware](#middleware) dispatcher. Provides (optional) integration with a [variety](https://github.com/container-interop/container-interop#compatible-projects) of dependency injection containers compliant with [container-interop](https://github.com/container-interop/container-interop). To upgrade between major releases, please see [UPGRADING.md](UPGRADING.md). [![PHP Version](https://img.shields.io/badge/php-5.4%2B-blue.svg)](https://packagist.org/packages/mindplay/middleman) [![Build Status](https://travis-ci.org/mindplay-dk/middleman.svg?branch=master)](https://travis-ci.org/mindplay-dk/middleman) [![Code Coverage](https://scrutinizer-ci.com/g/mindplay-dk/middleman/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/mindplay-dk/middleman/?branch=master) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/mindplay-dk/middleman/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/mindplay-dk/middleman/?branch=master) A growing catalog of PSR-15 middleware-components is available from [github.com/middlewares](https://github.com/middlewares). You can implement simple middleware "in place" by using anonymous functions in a middleware-stack: ```php use Psr\Http\Message\ServerRequestInterface; use Zend\Diactoros\Response; $dispatcher = new Dispatcher([ function (ServerRequestInterface $request, callable $next) { return $next($request); // delegate control to next middleware }, function (ServerRequestInterface $request) { return (new Response())->withBody(...); // abort middleware stack and return the response }, // ... ]); $response = $dispatcher->dispatch($request); ``` For simplicity, the middleware-stack in a `Dispatcher` is immutable - if you need a stack you can manipulate, `array`, `ArrayObject`, `SplStack` etc. are all fine choices. To implement reusable middleware components, you should implement the PSR-15 [MiddlewareInterface](https://github.com/http-interop/http-middleware/blob/master/src/MiddlewareInterface.php). ```php use Psr\Http\Message\ServerRequestInterface; use Interop\Http\ServerMiddleware\MiddlewareInterface; class MyMiddleware implements MiddlewareInteface { public function process(ServerRequestInterface $request, DelegateInterface $delegate) { // ... } } ``` If you want to integrate with a [DI container](https://github.com/container-interop/container-interop#compatible-projects) you can use the `ContainerResolver` - a "resolver" is a callable which gets applied to every element in your middleware stack, with a signature like: function (string $name) : MiddlewareInterface The following example obtains middleware components on-the-fly from a DI container: ```php $dispatcher = new Dispatcher( [ RouterMiddleware::class, ErrorMiddleware::class, ], new ContainerResolver($container) ); ``` If you want the `Dispatcher` to integrate deeply with your framework of choice, you can implement this as a class implementing the magic `__invoke()` function (as `ContainerResolver` does) - or "in place", as an anonymous function with a matching signature. If you want to understand precisely how this component works, the whole thing is [just one class with a few lines of code](src/Dispatcher.php) - if you're going to base your next project on middleware, you can (and should) understand the whole mechanism. ----- <a name="middleware"></a> ### Middleware? Middleware is a powerful, yet simple control facility. If you're new to the concept of middleware, the following section will provide a basic overview. In a nutshell, a middleware component is a function (or [MiddlewareInterface](src/MiddlewareInterface.php) instance) that takes an incoming (PSR-7) `RequestInterface` object, and returns a `ResponseInterface` object. It does this in one of three ways: by *assuming*, *delegating*, or *sharing* responsibility for the creation of a response object. ##### 1. Assuming Responsibility A middleware component *assumes* responsibility by creating and returning a response object, rather than delegating to the next middleware on the stack: ```php use Zend\Diactoros\Response; function ($request, $next) { return (new Response())->withBody(...); // next middleware won't be run } ``` Middleware near the top of the stack has the power to completely bypass middleware further down the stack. ##### 2. Delegating Responsibility By calling `$next`, middleware near the top of the stack may choose to fully delegate the responsibility for the creation of a response to other middleware components further down the stack: ```php function ($request, $next) { if ($request->getMethod() !== 'POST') { return $next($request); // run the next middleware } else { // ... } } ``` Note that exhausting the middleware stack will result in an exception - it's assumed that the last middleware component on the stack always produces a response of some sort, typically a "404 not found" error page. ##### 3. Sharing Responsibility Middleware near the top of the stack may choose to delegate responsibility for the creation of the response to middleware further down the stack, and then make additional changes to the returned response before returning it: ```php function ($request, $next) { $result = $next($request); // run the next middleware return $result->withHeader(...); // then modify it's response } ``` The middleware component at the top of the stack ultimately has the most control, as it may override any properties of the response object before returning.