From 11406a9d616e62cf9ebfa23cff1ec9b8b8c74bda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E9=93=AD=E6=98=95?= Date: Tue, 25 Jan 2022 11:47:46 +0800 Subject: [PATCH] Upgrade the minimum php version to 8.0 for utils. --- composer.json | 2 +- .../src/Server/Request/XmlParser.php | 2 +- src/utils/src/ApplicationContext.php | 5 +-- src/utils/src/Arr.php | 10 ++--- src/utils/src/Backoff.php | 11 +----- src/utils/src/Channel/Caller.php | 24 ++---------- src/utils/src/Channel/ChannelManager.php | 10 +---- src/utils/src/ChannelPool.php | 5 +-- src/utils/src/ClearStatCache.php | 10 ++--- src/utils/src/CodeGen/PhpDocReader.php | 14 ++----- src/utils/src/CodeGen/PhpDocReaderManager.php | 5 +-- src/utils/src/CodeGen/PhpParser.php | 10 +---- src/utils/src/CodeGen/Project.php | 4 +- src/utils/src/Codec/Json.php | 5 +-- src/utils/src/Codec/Xml.php | 16 ++------ src/utils/src/Collection.php | 5 ++- src/utils/src/Composer.php | 30 +++------------ src/utils/src/Context.php | 2 +- src/utils/src/Coroutine.php | 2 +- src/utils/src/Coroutine/Concurrent.php | 16 +++----- src/utils/src/Exception/ExceptionThrower.php | 8 +--- .../Exception/ParallelExecutionException.php | 14 ++----- src/utils/src/Filesystem/Filesystem.php | 9 ++--- src/utils/src/Fluent.php | 2 +- src/utils/src/Functions.php | 5 ++- src/utils/src/HigherOrderCollectionProxy.php | 20 ++-------- src/utils/src/HigherOrderTapProxy.php | 13 +------ src/utils/src/MessageBag.php | 22 +++++------ src/utils/src/MimeTypeExtensionGuesser.php | 6 +-- src/utils/src/Network.php | 11 +++--- src/utils/src/Optional.php | 15 +++----- src/utils/src/Parallel.php | 7 +--- src/utils/src/Pipeline.php | 27 +++----------- src/utils/src/Pluralizer.php | 9 +---- src/utils/src/Reflection/ClassInvoker.php | 13 +------ src/utils/src/Resource.php | 37 ------------------- .../src/Serializer/ExceptionNormalizer.php | 15 +++----- src/utils/src/Serializer/ScalarNormalizer.php | 21 ++++------- src/utils/src/Serializer/Serializer.php | 24 ++++++------ .../src/Serializer/SerializerFactory.php | 8 +--- src/utils/src/Serializer/SimpleNormalizer.php | 22 ++++------- .../src/Serializer/SymfonyNormalizer.php | 8 +--- src/utils/src/Stringable.php | 6 +-- src/utils/src/Traits/Container.php | 2 +- src/utils/src/Traits/Macroable.php | 20 ---------- src/utils/src/Traits/Tappable.php | 3 +- src/utils/src/Waiter.php | 10 +---- src/utils/tests/Codec/JsonTest.php | 8 ++++ src/utils/tests/{ => Codec}/XmlTest.php | 2 +- src/utils/tests/CollectionTest.php | 6 +++ src/utils/tests/FunctionTest.php | 8 ++++ 51 files changed, 166 insertions(+), 403 deletions(-) delete mode 100644 src/utils/src/Resource.php delete mode 100644 src/utils/src/Traits/Macroable.php rename src/utils/tests/{ => Codec}/XmlTest.php (98%) diff --git a/composer.json b/composer.json index e843b8f2f..7ef1848d0 100644 --- a/composer.json +++ b/composer.json @@ -42,7 +42,7 @@ "google/protobuf": "^3.6.1", "grpc/grpc": "^1.15", "guzzlehttp/guzzle": "^6.3|^7.0", - "hyperf/engine": "dev-master", + "hyperf/engine": "^1.2|^2.0", "influxdb/influxdb-php": "^1.15.0", "ircmaxell/random-lib": "^1.2", "jcchavezs/zipkin-opentracing": "^2.0", diff --git a/src/http-message/src/Server/Request/XmlParser.php b/src/http-message/src/Server/Request/XmlParser.php index bf6615ae7..035792c18 100644 --- a/src/http-message/src/Server/Request/XmlParser.php +++ b/src/http-message/src/Server/Request/XmlParser.php @@ -23,7 +23,7 @@ class XmlParser implements RequestParserInterface public function parse(string $rawBody, string $contentType): array { try { - return Xml::toArray($rawBody) ?? []; + return Xml::toArray($rawBody); } catch (InvalidArgumentException $e) { if ($this->throwException) { throw new BadRequestHttpException('Invalid XML data in request body: ' . $e->getMessage()); diff --git a/src/utils/src/ApplicationContext.php b/src/utils/src/ApplicationContext.php index dc16b7b62..8bf64c7d0 100644 --- a/src/utils/src/ApplicationContext.php +++ b/src/utils/src/ApplicationContext.php @@ -15,10 +15,7 @@ use Psr\Container\ContainerInterface; class ApplicationContext { - /** - * @var null|ContainerInterface - */ - private static $container; + private static ?ContainerInterface $container = null; /** * @throws \TypeError diff --git a/src/utils/src/Arr.php b/src/utils/src/Arr.php index 94bcf026c..7c2a3d7b2 100644 --- a/src/utils/src/Arr.php +++ b/src/utils/src/Arr.php @@ -110,7 +110,7 @@ class Arr } /** - * Get all of the given array except for a specified array of keys. + * Get all the given array except for a specified array of keys. * * @param array|string $keys */ @@ -241,7 +241,7 @@ class Arr if (static::exists($array, $key)) { return $array[$key]; } - if (! is_string($key) || strpos($key, '.') === false) { + if (! is_string($key) || ! str_contains($key, '.')) { return $array[$key] ?? value($default); } foreach (explode('.', $key) as $segment) { @@ -321,7 +321,7 @@ class Arr foreach ($array as $item) { $itemValue = data_get($item, $value); // If the key is "null", we will just append the value to the array and keep - // looping. Otherwise we will key the array using the value of the key we + // looping. Otherwise, we will key the array using the value of the key we // received from the developer. Then we'll return the final array form. if (is_null($key)) { $results[] = $itemValue; @@ -384,7 +384,7 @@ class Arr if (is_null($number)) { return $array[array_rand($array)]; } - if ((int) $number === 0) { + if ($number === 0) { return []; } $keys = array_rand($array, $number); @@ -531,7 +531,7 @@ class Arr } } } else { - foreach ($array2 as $key => $value) { + foreach ($array2 as $value) { if ($unique && in_array($value, $array1, true)) { continue; } diff --git a/src/utils/src/Backoff.php b/src/utils/src/Backoff.php index 6e486b78a..4e38ddb7b 100644 --- a/src/utils/src/Backoff.php +++ b/src/utils/src/Backoff.php @@ -18,21 +18,15 @@ class Backoff */ private const CAP = 60 * 1000; // 1 minute - /** - * @var int - */ - private $firstMs; - /** * Backoff interval. - * @var int */ - private $currentMs; + private int $currentMs; /** * @param int the first backoff in milliseconds */ - public function __construct(int $firstMs = 0) + public function __construct(private int $firstMs = 0) { if ($firstMs < 0) { throw new \InvalidArgumentException( @@ -49,7 +43,6 @@ class Backoff ); } - $this->firstMs = $firstMs; $this->currentMs = $firstMs; } diff --git a/src/utils/src/Channel/Caller.php b/src/utils/src/Channel/Caller.php index 634135e93..ea5b1e766 100644 --- a/src/utils/src/Channel/Caller.php +++ b/src/utils/src/Channel/Caller.php @@ -18,25 +18,10 @@ use Hyperf\Utils\Exception\WaitTimeoutException; class Caller { - /** - * @var null|Channel - */ - protected $channel; + protected ?Channel $channel = null; - /** - * @var float wait seconds - */ - protected $waitTimeout; - - /** - * @var null|Closure - */ - protected $closure; - - public function __construct(Closure $closure, float $waitTimeout = 10) + public function __construct(protected Closure $closure, protected float $waitTimeout = 10) { - $this->closure = $closure; - $this->waitTimeout = $waitTimeout; $this->initInstance(); } @@ -69,10 +54,7 @@ class Caller public function initInstance(): void { - if ($this->channel) { - $this->channel->close(); - } - + $this->channel?->close(); $this->channel = new Channel(1); $this->channel->push($this->closure->__invoke()); } diff --git a/src/utils/src/Channel/ChannelManager.php b/src/utils/src/Channel/ChannelManager.php index db86cf4d9..9efffa687 100644 --- a/src/utils/src/Channel/ChannelManager.php +++ b/src/utils/src/Channel/ChannelManager.php @@ -18,16 +18,10 @@ class ChannelManager /** * @var Channel[] */ - protected $channels = []; + protected array $channels = []; - /** - * @var int - */ - protected $size = 1; - - public function __construct(int $size = 1) + public function __construct(protected int $size = 1) { - $this->size = $size; } public function get(int $id, bool $initialize = false): ?Channel diff --git a/src/utils/src/ChannelPool.php b/src/utils/src/ChannelPool.php index 48e2463bc..d484e5082 100644 --- a/src/utils/src/ChannelPool.php +++ b/src/utils/src/ChannelPool.php @@ -15,10 +15,7 @@ use Swoole\Coroutine\Channel; class ChannelPool extends \SplQueue { - /** - * @var null|ChannelPool - */ - private static $instance; + private static ?ChannelPool $instance = null; public static function getInstance(): self { diff --git a/src/utils/src/ClearStatCache.php b/src/utils/src/ClearStatCache.php index ca970230b..d90e4bd6c 100644 --- a/src/utils/src/ClearStatCache.php +++ b/src/utils/src/ClearStatCache.php @@ -14,20 +14,16 @@ namespace Hyperf\Utils; class ClearStatCache { /** - * Interval at which to clear fileystem stat cache. Values below 1 indicate + * Interval at which to clear filesystem stat cache. Values below 1 indicate * the stat cache should ALWAYS be cleared. Otherwise, the value is the number * of seconds between clear operations. - * - * @var int */ - private static $interval = 1; + private static int $interval = 1; /** * When the filesystem stat cache was last cleared. - * - * @var int */ - private static $lastCleared; + private static int $lastCleared = 0; public static function clear(?string $filename = null): void { diff --git a/src/utils/src/CodeGen/PhpDocReader.php b/src/utils/src/CodeGen/PhpDocReader.php index 3b3006879..8c00283e8 100644 --- a/src/utils/src/CodeGen/PhpDocReader.php +++ b/src/utils/src/CodeGen/PhpDocReader.php @@ -40,24 +40,16 @@ class PhpDocReader 'iterable' => 'iterable', ]; - /** - * @var null|PhpDocReader - */ - protected static $instance; + protected static ?PhpDocReader $instance = null; - /** @var UseStatementParser */ - private $parser; - - /** @var bool */ - private $ignorePhpDocErrors; + private UseStatementParser $parser; /** * @param bool $ignorePhpDocErrors enable or disable throwing errors when PhpDoc errors occur (when parsing annotations) */ - public function __construct(bool $ignorePhpDocErrors = false) + public function __construct(private bool $ignorePhpDocErrors = false) { $this->parser = new UseStatementParser(); - $this->ignorePhpDocErrors = $ignorePhpDocErrors; } public static function getInstance(): PhpDocReader diff --git a/src/utils/src/CodeGen/PhpDocReaderManager.php b/src/utils/src/CodeGen/PhpDocReaderManager.php index 3b6971f96..ed1317d99 100644 --- a/src/utils/src/CodeGen/PhpDocReaderManager.php +++ b/src/utils/src/CodeGen/PhpDocReaderManager.php @@ -15,10 +15,7 @@ use PhpDocReader\PhpDocReader; class PhpDocReaderManager { - /** - * @var null|PhpDocReader - */ - protected static $instance; + protected static ?PhpDocReader $instance = null; public static function getInstance(): PhpDocReader { diff --git a/src/utils/src/CodeGen/PhpParser.php b/src/utils/src/CodeGen/PhpParser.php index 08aa33b9a..7a69bbb1f 100644 --- a/src/utils/src/CodeGen/PhpParser.php +++ b/src/utils/src/CodeGen/PhpParser.php @@ -33,15 +33,9 @@ class PhpParser 'null', ]; - /** - * @var null|PhpParser - */ - protected static $instance; + protected static ?PhpParser $instance = null; - /** - * @var Parser - */ - protected $parser; + protected Parser $parser; public function __construct() { diff --git a/src/utils/src/CodeGen/Project.php b/src/utils/src/CodeGen/Project.php index 4aa5937b0..8aa186357 100644 --- a/src/utils/src/CodeGen/Project.php +++ b/src/utils/src/CodeGen/Project.php @@ -30,7 +30,7 @@ class Project } foreach ($this->getAutoloadRules() as $prefix => $prefixPath) { - if ($this->isRootNamespace($prefix) || strpos($path, $prefixPath) === 0) { + if ($this->isRootNamespace($prefix) || str_starts_with($path, $prefixPath)) { return $prefix . str_replace('/', '\\', substr($path, strlen($prefixPath))); } } @@ -49,7 +49,7 @@ class Project } foreach ($this->getAutoloadRules() as $prefix => $prefixPath) { - if ($this->isRootNamespace($prefix) || strpos($name, $prefix) === 0) { + if ($this->isRootNamespace($prefix) || str_starts_with($name, $prefix)) { return $prefixPath . str_replace('\\', '/', substr($name, strlen($prefix))) . $extension; } } diff --git a/src/utils/src/Codec/Json.php b/src/utils/src/Codec/Json.php index 6d786a458..343ed28c8 100644 --- a/src/utils/src/Codec/Json.php +++ b/src/utils/src/Codec/Json.php @@ -18,10 +18,9 @@ use Hyperf\Utils\Exception\InvalidArgumentException; class Json { /** - * @param mixed $data * @throws InvalidArgumentException */ - public static function encode($data, int $flags = JSON_UNESCAPED_UNICODE, int $depth = 512): string + public static function encode(mixed $data, int $flags = JSON_UNESCAPED_UNICODE, int $depth = 512): string { if ($data instanceof Jsonable) { return (string) $data; @@ -43,7 +42,7 @@ class Json /** * @throws InvalidArgumentException */ - public static function decode(string $json, bool $assoc = true, int $depth = 512, int $flags = 0) + public static function decode(string $json, bool $assoc = true, int $depth = 512, int $flags = 0): mixed { try { $decode = json_decode($json, $assoc, $depth, $flags | JSON_THROW_ON_ERROR); diff --git a/src/utils/src/Codec/Xml.php b/src/utils/src/Codec/Xml.php index 89f0a19b5..da3d8b534 100644 --- a/src/utils/src/Codec/Xml.php +++ b/src/utils/src/Codec/Xml.php @@ -18,7 +18,7 @@ use SimpleXMLElement; class Xml { - public static function toXml($data, $parentNode = null, $root = 'root') + public static function toXml(mixed $data, ?SimpleXMLElement $parentNode = null, string $root = 'root') { if ($data instanceof Xmlable) { return (string) $data; @@ -47,19 +47,9 @@ class Xml return trim($xml->asXML()); } - public static function toArray($xml) + public static function toArray($xml): array { - // For PHP 8.0, libxml_disable_entity_loader() has been deprecated. - // As libxml 2.9.0 is now required, external entity loading is guaranteed to be disabled by default. - // And this function is no longer needed to protect against XXE attacks, unless the (still vulnerable). LIBXML_NOENT is used. - // In that case, it is recommended to refactor the code using libxml_set_external_entity_loader() to suppress loading of external entities. - if (\PHP_VERSION_ID < 80000) { - $disableLibxmlEntityLoader = libxml_disable_entity_loader(true); - $respObject = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOERROR); - libxml_disable_entity_loader($disableLibxmlEntityLoader); - } else { - $respObject = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOERROR); - } + $respObject = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOERROR); if ($respObject === false) { throw new InvalidArgumentException('Syntax error.'); diff --git a/src/utils/src/Collection.php b/src/utils/src/Collection.php index 6ccab72fc..e57b9910b 100644 --- a/src/utils/src/Collection.php +++ b/src/utils/src/Collection.php @@ -65,14 +65,14 @@ class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate * * @var array */ - protected $items = []; + protected array $items = []; /** * The methods that can be proxied. * * @var string[] */ - protected static $proxies + protected static array $proxies = [ 'average', 'avg', @@ -222,6 +222,7 @@ class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate if ($count = $items->count()) { return $items->sum() / $count; } + return null; } /** diff --git a/src/utils/src/Composer.php b/src/utils/src/Composer.php index 6a7bdd378..54fb8b2ff 100644 --- a/src/utils/src/Composer.php +++ b/src/utils/src/Composer.php @@ -15,35 +15,17 @@ use Composer\Autoload\ClassLoader; class Composer { - /** - * @var null|Collection - */ - private static $content; + private static ?Collection $content = null; - /** - * @var null|Collection - */ - private static $json; + private static ?Collection $json = null; - /** - * @var array - */ - private static $extra = []; + private static array $extra = []; - /** - * @var array - */ - private static $scripts = []; + private static array $scripts = []; - /** - * @var array - */ - private static $versions = []; + private static array $versions = []; - /** - * @var null|ClassLoader - */ - private static $classLoader; + private static ?ClassLoader $classLoader = null; /** * @throws \RuntimeException When `composer.lock` does not exist. diff --git a/src/utils/src/Context.php b/src/utils/src/Context.php index 308409528..65f4b65e5 100644 --- a/src/utils/src/Context.php +++ b/src/utils/src/Context.php @@ -15,7 +15,7 @@ use Hyperf\Engine\Coroutine as Co; class Context { - protected static $nonCoContext = []; + protected static array $nonCoContext = []; public static function set(string $id, $value) { diff --git a/src/utils/src/Coroutine.php b/src/utils/src/Coroutine.php index ce59202bb..a22616125 100644 --- a/src/utils/src/Coroutine.php +++ b/src/utils/src/Coroutine.php @@ -80,7 +80,7 @@ class Coroutine try { return $coroutine->getId(); - } catch (\Throwable $exception) { + } catch (\Throwable) { return -1; } } diff --git a/src/utils/src/Coroutine/Concurrent.php b/src/utils/src/Coroutine/Concurrent.php index 064914463..efef8e10a 100644 --- a/src/utils/src/Coroutine/Concurrent.php +++ b/src/utils/src/Coroutine/Concurrent.php @@ -16,6 +16,7 @@ use Hyperf\Engine\Channel; use Hyperf\ExceptionHandler\Formatter\FormatterInterface; use Hyperf\Utils\ApplicationContext; use Hyperf\Utils\Coroutine; +use Hyperf\Utils\Exception\InvalidArgumentException; /** * @method bool isFull() @@ -23,19 +24,10 @@ use Hyperf\Utils\Coroutine; */ class Concurrent { - /** - * @var Channel - */ - protected $channel; + protected Channel $channel; - /** - * @var int - */ - protected $limit; - - public function __construct(int $limit) + public function __construct(protected int $limit) { - $this->limit = $limit; $this->channel = new Channel($limit); } @@ -44,6 +36,8 @@ class Concurrent if (in_array($name, ['isFull', 'isEmpty'])) { return $this->channel->{$name}(...$arguments); } + + throw new InvalidArgumentException(sprintf('The method %s is not supported.', $name)); } public function getLimit(): int diff --git a/src/utils/src/Exception/ExceptionThrower.php b/src/utils/src/Exception/ExceptionThrower.php index e6fec266f..c7426ae74 100644 --- a/src/utils/src/Exception/ExceptionThrower.php +++ b/src/utils/src/Exception/ExceptionThrower.php @@ -15,14 +15,8 @@ use Throwable; final class ExceptionThrower { - /** - * @var Throwable - */ - private $throwable; - - public function __construct(Throwable $throwable) + public function __construct(private Throwable $throwable) { - $this->throwable = $throwable; } public function getThrowable(): Throwable diff --git a/src/utils/src/Exception/ParallelExecutionException.php b/src/utils/src/Exception/ParallelExecutionException.php index 1b4954e9a..721c0304d 100644 --- a/src/utils/src/Exception/ParallelExecutionException.php +++ b/src/utils/src/Exception/ParallelExecutionException.php @@ -13,17 +13,11 @@ namespace Hyperf\Utils\Exception; class ParallelExecutionException extends \RuntimeException { - /** - * @var array - */ - private $results; + private array $results = []; - /** - * @var array - */ - private $throwables; + private array $throwables = []; - public function getResults() + public function getResults(): array { return $this->results; } @@ -33,7 +27,7 @@ class ParallelExecutionException extends \RuntimeException $this->results = $results; } - public function getThrowables() + public function getThrowables(): array { return $this->throwables; } diff --git a/src/utils/src/Filesystem/Filesystem.php b/src/utils/src/Filesystem/Filesystem.php index 0a5a43642..c0809d9ea 100644 --- a/src/utils/src/Filesystem/Filesystem.php +++ b/src/utils/src/Filesystem/Filesystem.php @@ -90,10 +90,8 @@ class Filesystem /** * Require the given file once. - * - * @return mixed */ - public function requireOnce(string $file) + public function requireOnce(string $file): void { require_once $file; } @@ -204,7 +202,7 @@ class Filesystem if (! @unlink($path)) { $success = false; } - } catch (ErrorException $e) { + } catch (ErrorException) { $success = false; } } @@ -231,7 +229,7 @@ class Filesystem /** * Create a hard link to the target file or directory. */ - public function link(string $target, string $link) + public function link(string $target, string $link): bool { if (! $this->windowsOs()) { return symlink($target, $link); @@ -240,6 +238,7 @@ class Filesystem $mode = $this->isDirectory($target) ? 'J' : 'H'; exec("mklink /{$mode} \"{$link}\" \"{$target}\""); + return true; } /** diff --git a/src/utils/src/Fluent.php b/src/utils/src/Fluent.php index 49108e369..bffaf505c 100755 --- a/src/utils/src/Fluent.php +++ b/src/utils/src/Fluent.php @@ -23,7 +23,7 @@ use JsonSerializable; class Fluent implements ArrayAccess, Arrayable, Jsonable, JsonSerializable { /** - * All of the attributes set on the fluent instance. + * All the attributes set on the fluent instance. * * @var array */ diff --git a/src/utils/src/Functions.php b/src/utils/src/Functions.php index 02b20f027..5eefc7afc 100644 --- a/src/utils/src/Functions.php +++ b/src/utils/src/Functions.php @@ -56,7 +56,7 @@ if (! function_exists('env')) { return ''; case 'null': case '(null)': - return; + return null; } if (($valueLength = strlen($value)) > 1 && $value[0] === '"' && $value[$valueLength - 1] === '"') { return substr($value, 1, -1); @@ -394,7 +394,7 @@ if (! function_exists('getter')) { if (! function_exists('parallel')) { /** * @param callable[] $callables - * @param int $concurrent if $concurrent is equal to 0, that means unlimit + * @param int $concurrent if $concurrent is equal to 0, that means unlimited */ function parallel(array $callables, int $concurrent = 0) { @@ -471,6 +471,7 @@ if (! function_exists('optional')) { if (! is_null($value)) { return $callback($value); } + return null; } } diff --git a/src/utils/src/HigherOrderCollectionProxy.php b/src/utils/src/HigherOrderCollectionProxy.php index 21d9b043d..ee1455ce9 100644 --- a/src/utils/src/HigherOrderCollectionProxy.php +++ b/src/utils/src/HigherOrderCollectionProxy.php @@ -18,27 +18,13 @@ namespace Hyperf\Utils; */ class HigherOrderCollectionProxy { - /** - * The collection being operated on. - * - * @var Collection - */ - protected $collection; - - /** - * The method being proxied. - * - * @var string - */ - protected $method; - /** * Create a new proxy instance. + * @param Collection $collection the collection being operated on + * @param string $method the method being proxied */ - public function __construct(Collection $collection, string $method) + public function __construct(protected Collection $collection, protected string $method) { - $this->method = $method; - $this->collection = $collection; } /** diff --git a/src/utils/src/HigherOrderTapProxy.php b/src/utils/src/HigherOrderTapProxy.php index ae07961be..8174c79b6 100644 --- a/src/utils/src/HigherOrderTapProxy.php +++ b/src/utils/src/HigherOrderTapProxy.php @@ -13,21 +13,12 @@ namespace Hyperf\Utils; class HigherOrderTapProxy { - /** - * The target being tapped. - * - * @var mixed - */ - public $target; - /** * Create a new tap proxy instance. - * - * @param mixed $target + * @param mixed $target the target being tapped */ - public function __construct($target) + public function __construct(public mixed $target) { - $this->target = $target; } /** diff --git a/src/utils/src/MessageBag.php b/src/utils/src/MessageBag.php index 69f2598b9..ae52a75b2 100644 --- a/src/utils/src/MessageBag.php +++ b/src/utils/src/MessageBag.php @@ -21,18 +21,14 @@ use JsonSerializable; class MessageBag implements Arrayable, Countable, Jsonable, JsonSerializable, MessageBagContract, MessageProvider { /** - * All of the registered messages. - * - * @var array + * All the registered messages. */ - protected $messages = []; + protected array $messages = []; /** * Default format for message output. - * - * @var string */ - protected $format = ':message'; + protected string $format = ':message'; /** * Create a new message bag instance. @@ -92,7 +88,7 @@ class MessageBag implements Arrayable, Countable, Jsonable, JsonSerializable, Me } /** - * Determine if messages exist for all of the given keys. + * Determine if messages exist for all the given keys. * * @param null|array|string $key */ @@ -155,7 +151,7 @@ class MessageBag implements Arrayable, Countable, Jsonable, JsonSerializable, Me } /** - * Get all of the messages from the message bag for a given key. + * Get all the messages from the message bag for a given key. */ public function get(string $key, ?string $format = null): array { @@ -178,7 +174,7 @@ class MessageBag implements Arrayable, Countable, Jsonable, JsonSerializable, Me } /** - * Get all of the messages for every key in the message bag. + * Get all the messages for every key in the message bag. */ public function all(?string $format = null): array { @@ -194,7 +190,7 @@ class MessageBag implements Arrayable, Countable, Jsonable, JsonSerializable, Me } /** - * Get all of the unique messages for every key in the message bag. + * Get all the unique messages for every key in the message bag. */ public function unique(?string $format = null): array { @@ -304,7 +300,7 @@ class MessageBag implements Arrayable, Countable, Jsonable, JsonSerializable, Me */ protected function isUnique(string $key, string $message): bool { - $messages = (array) $this->messages; + $messages = $this->messages; return ! isset($messages[$key]) || ! in_array($message, $messages[$key]); } @@ -335,7 +331,7 @@ class MessageBag implements Arrayable, Countable, Jsonable, JsonSerializable, Me return collect($messages) ->map(function ($message) use ($format, $messageKey) { // We will simply spin through the given messages and transform each one - // replacing the :message place holder with the real message allowing + // replacing the :message placeholder with the real message allowing // the messages to be easily formatted to each developer's desires. return str_replace([':message', ':key'], [$message, $messageKey], $format); })->all(); diff --git a/src/utils/src/MimeTypeExtensionGuesser.php b/src/utils/src/MimeTypeExtensionGuesser.php index 978c48edc..4cc43db10 100644 --- a/src/utils/src/MimeTypeExtensionGuesser.php +++ b/src/utils/src/MimeTypeExtensionGuesser.php @@ -18,7 +18,7 @@ class MimeTypeExtensionGuesser * * @see http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types */ - protected $defaultExtensions = [ + protected array $defaultExtensions = [ 'application/andrew-inset' => 'ez', 'application/applixware' => 'aw', 'application/atom+xml' => 'atom', @@ -804,11 +804,11 @@ class MimeTypeExtensionGuesser public function guessExtension(string $mimeType): ?string { - return isset($this->defaultExtensions[$mimeType]) ? $this->defaultExtensions[$mimeType] : null; + return $this->defaultExtensions[$mimeType] ?? null; } public function guessMimeType(string $extension): ?string { - return isset($this->defaultMineTypes[$extension]) ? $this->defaultMineTypes[$extension] : null; + return $this->defaultMineTypes[$extension] ?? null; } } diff --git a/src/utils/src/Network.php b/src/utils/src/Network.php index 16ed0d8e9..a9b8f395b 100644 --- a/src/utils/src/Network.php +++ b/src/utils/src/Network.php @@ -36,11 +36,12 @@ class Network if (is_array($ips) && ! empty($ips)) { return current($ips); } - /** @var mixed|string $ip */ - $ip = gethostbyname(gethostname()); - if (is_string($ip)) { - return $ip; + + $name = gethostname(); + if ($name === false) { + throw new RuntimeException('Can not get the internal IP.'); } - throw new RuntimeException('Can not get the internal IP.'); + + return gethostbyname($name); } } diff --git a/src/utils/src/Optional.php b/src/utils/src/Optional.php index 76250e415..d52a0aa53 100644 --- a/src/utils/src/Optional.php +++ b/src/utils/src/Optional.php @@ -13,6 +13,7 @@ namespace Hyperf\Utils; use ArrayAccess; use Hyperf\Macroable\Macroable; +use Hyperf\Utils\Exception\InvalidArgumentException; class Optional implements ArrayAccess { @@ -20,21 +21,13 @@ class Optional implements ArrayAccess __call as macroCall; } - /** - * The underlying object. - * - * @var mixed - */ - protected $value; - /** * Create a new optional instance. * - * @param mixed $value + * @param mixed $value the underlying object */ - public function __construct($value) + public function __construct(protected $value) { - $this->value = $value; } /** @@ -83,6 +76,8 @@ class Optional implements ArrayAccess if (is_object($this->value)) { return $this->value->{$method}(...$parameters); } + + return null; } /** diff --git a/src/utils/src/Parallel.php b/src/utils/src/Parallel.php index 2e31bbe62..48f6d4c46 100644 --- a/src/utils/src/Parallel.php +++ b/src/utils/src/Parallel.php @@ -19,12 +19,9 @@ class Parallel /** * @var callable[] */ - private $callbacks = []; + private array $callbacks = []; - /** - * @var null|Channel - */ - private $concurrentChannel; + private ?Channel $concurrentChannel = null; /** * @param int $concurrent if $concurrent is equal to 0, that means unlimit diff --git a/src/utils/src/Pipeline.php b/src/utils/src/Pipeline.php index 217c19d76..321ffc4de 100644 --- a/src/utils/src/Pipeline.php +++ b/src/utils/src/Pipeline.php @@ -20,44 +20,29 @@ use Psr\Container\ContainerInterface; */ class Pipeline { - /** - * The container implementation. - * - * @var ContainerInterface - */ - protected $container; - /** * The object being passed through the pipeline. - * - * @var mixed */ - protected $passable; + protected mixed $passable = null; /** * The array of class pipes. - * - * @var array */ - protected $pipes = []; + protected array $pipes = []; /** * The method to call on each pipe. - * - * @var string */ - protected $method = 'handle'; + protected string $method = 'handle'; - public function __construct(ContainerInterface $container) + public function __construct(protected ContainerInterface $container) { - $this->container = $container; } /** * Set the object being sent through the pipeline. - * @param mixed $passable */ - public function send($passable): self + public function send(mixed $passable): self { $this->passable = $passable; @@ -113,7 +98,7 @@ class Pipeline return function ($stack, $pipe) { return function ($passable) use ($stack, $pipe) { if (is_callable($pipe)) { - // If the pipe is an instance of a Closure, we will just call it directly but + // If the pipe is an instance of a Closure, we will just call it directly, but // otherwise we'll resolve the pipes out of the container and call it with // the appropriate method and arguments, returning the results back out. return $pipe($passable, $stack); diff --git a/src/utils/src/Pluralizer.php b/src/utils/src/Pluralizer.php index 543291cdc..9e943c5af 100644 --- a/src/utils/src/Pluralizer.php +++ b/src/utils/src/Pluralizer.php @@ -20,10 +20,8 @@ class Pluralizer { /** * Uncountable word forms. - * - * @var array */ - public static $uncountable + public static array $uncountable = [ 'audio', 'bison', @@ -68,10 +66,7 @@ class Pluralizer 'wheat', ]; - /** - * @var null|Inflector - */ - protected static $inflector; + protected static ?Inflector $inflector = null; /** * Get the plural form of an English word. diff --git a/src/utils/src/Reflection/ClassInvoker.php b/src/utils/src/Reflection/ClassInvoker.php index 4b413f8da..816a27291 100644 --- a/src/utils/src/Reflection/ClassInvoker.php +++ b/src/utils/src/Reflection/ClassInvoker.php @@ -15,19 +15,10 @@ use ReflectionClass; class ClassInvoker { - /** - * @var object - */ - protected $instance; + protected ReflectionClass $reflection; - /** - * @var ReflectionClass - */ - protected $reflection; - - public function __construct(object $instance) + public function __construct(protected object $instance) { - $this->instance = $instance; $this->reflection = new ReflectionClass($instance); } diff --git a/src/utils/src/Resource.php b/src/utils/src/Resource.php deleted file mode 100644 index 92aa8223b..000000000 --- a/src/utils/src/Resource.php +++ /dev/null @@ -1,37 +0,0 @@ -getInstantiator()->instantiate($class); + $exception = $this->getInstantiator()->instantiate($type); foreach (['code', 'message', 'file', 'line'] as $attribute) { if (isset($data[$attribute])) { - $property = ReflectionManager::reflectProperty($class, $attribute); + $property = ReflectionManager::reflectProperty($type, $attribute); $property->setAccessible(true); $property->setValue($exception, $data[$attribute]); } } return $exception; - } catch (\ReflectionException $e) { + } catch (\ReflectionException) { return new \RuntimeException(sprintf( 'Bad data %s: %s', $data['class'], $data['message'] ), $data['code']); - } catch (\TypeError $e) { + } catch (\TypeError) { return new \RuntimeException(sprintf( 'Uncaught data %s: %s', $data['class'], diff --git a/src/utils/src/Serializer/ScalarNormalizer.php b/src/utils/src/Serializer/ScalarNormalizer.php index 5966cc9cc..208d4b56a 100644 --- a/src/utils/src/Serializer/ScalarNormalizer.php +++ b/src/utils/src/Serializer/ScalarNormalizer.php @@ -24,20 +24,15 @@ class ScalarNormalizer implements NormalizerInterface, DenormalizerInterface, Ca return get_class($this) === __CLASS__; } - public function denormalize($data, string $class, string $format = null, array $context = []) + public function denormalize($data, string $type, string $format = null, array $context = []) { - switch ($class) { - case 'int': - return (int) $data; - case 'string': - return (string) $data; - case 'float': - return (float) $data; - case 'bool': - return (bool) $data; - default: - return $data; - } + return match ($type) { + 'int' => (int) $data, + 'string' => (string) $data, + 'float' => (float) $data, + 'bool' => (bool) $data, + default => $data, + }; } public function supportsDenormalization($data, $type, string $format = null) diff --git a/src/utils/src/Serializer/Serializer.php b/src/utils/src/Serializer/Serializer.php index 633404bd1..ea66b7b7b 100644 --- a/src/utils/src/Serializer/Serializer.php +++ b/src/utils/src/Serializer/Serializer.php @@ -138,39 +138,39 @@ class Serializer implements Normalizer, SerializerInterface, ContextAwareNormali return $this->denormalize($data, $type, $format, $context); } - public function normalize($data, string $format = null, array $context = []) + public function normalize($object, string $format = null, array $context = []) { // If a normalizer supports the given data, use it - if ($normalizer = $this->getNormalizer($data, $format, $context)) { - return $normalizer->normalize($data, $format, $context); + if ($normalizer = $this->getNormalizer($object, $format, $context)) { + return $normalizer->normalize($object, $format, $context); } - if ($data === null || is_scalar($data)) { - return $data; + if ($object === null || is_scalar($object)) { + return $object; } - if (\is_array($data) || $data instanceof \Traversable) { - if ($data instanceof \Countable && $data->count() === 0) { - return $data; + if (\is_array($object) || $object instanceof \Traversable) { + if ($object instanceof \Countable && $object->count() === 0) { + return $object; } $normalized = []; - foreach ($data as $key => $val) { + foreach ($object as $key => $val) { $normalized[$key] = $this->normalize($val, $format, $context); } return $normalized; } - if (\is_object($data)) { + if (\is_object($object)) { if (! $this->normalizers) { throw new LogicException('You must register at least one normalizer to be able to normalize objects.'); } - throw new NotNormalizableValueException(sprintf('Could not normalize object of type "%s", no supporting normalizer found.', get_debug_type($data))); + throw new NotNormalizableValueException(sprintf('Could not normalize object of type "%s", no supporting normalizer found.', get_debug_type($object))); } - throw new NotNormalizableValueException('An unexpected value could not be normalized: ' . (! \is_resource($data) ? var_export($data, true) : sprintf('%s resource', get_resource_type($data)))); + throw new NotNormalizableValueException('An unexpected value could not be normalized: ' . (! \is_resource($object) ? var_export($object, true) : sprintf('%s resource', get_resource_type($object)))); } /** diff --git a/src/utils/src/Serializer/SerializerFactory.php b/src/utils/src/Serializer/SerializerFactory.php index 0ec9709ab..c1c2ad435 100644 --- a/src/utils/src/Serializer/SerializerFactory.php +++ b/src/utils/src/Serializer/SerializerFactory.php @@ -17,14 +17,8 @@ use Symfony\Component\Serializer\Serializer; class SerializerFactory { - /** - * @var string - */ - protected $serializer; - - public function __construct(string $serializer = Serializer::class) + public function __construct(protected string $serializer = Serializer::class) { - $this->serializer = $serializer; } public function __invoke() diff --git a/src/utils/src/Serializer/SimpleNormalizer.php b/src/utils/src/Serializer/SimpleNormalizer.php index 6b31266d8..0b45b530d 100644 --- a/src/utils/src/Serializer/SimpleNormalizer.php +++ b/src/utils/src/Serializer/SimpleNormalizer.php @@ -22,19 +22,13 @@ class SimpleNormalizer implements NormalizerInterface public function denormalize($data, string $class) { - switch ($class) { - case 'int': - return (int) $data; - case 'string': - return (string) $data; - case 'float': - return (float) $data; - case 'array': - return (array) $data; - case 'bool': - return (bool) $data; - default: - return $data; - } + return match ($class) { + 'int' => (int) $data, + 'string' => (string) $data, + 'float' => (float) $data, + 'array' => (array) $data, + 'bool' => (bool) $data, + default => $data, + }; } } diff --git a/src/utils/src/Serializer/SymfonyNormalizer.php b/src/utils/src/Serializer/SymfonyNormalizer.php index 026428ac7..73a8b7b64 100644 --- a/src/utils/src/Serializer/SymfonyNormalizer.php +++ b/src/utils/src/Serializer/SymfonyNormalizer.php @@ -16,14 +16,8 @@ use Symfony\Component\Serializer\Serializer; class SymfonyNormalizer implements NormalizerInterface { - /** - * @var Serializer - */ - protected $serializer; - - public function __construct(Serializer $serializer) + public function __construct(protected Serializer $serializer) { - $this->serializer = $serializer; } public function normalize($object) diff --git a/src/utils/src/Stringable.php b/src/utils/src/Stringable.php index 6a9a7c49b..c5d70c7a1 100644 --- a/src/utils/src/Stringable.php +++ b/src/utils/src/Stringable.php @@ -23,10 +23,8 @@ class Stringable implements JsonSerializable /** * The underlying string value. - * - * @var string */ - protected $value; + protected string $value; /** * Create a new instance of the class. @@ -56,7 +54,7 @@ class Stringable implements JsonSerializable */ public function __toString() { - return (string) $this->value; + return $this->value; } /** diff --git a/src/utils/src/Traits/Container.php b/src/utils/src/Traits/Container.php index b96122673..d0108e115 100644 --- a/src/utils/src/Traits/Container.php +++ b/src/utils/src/Traits/Container.php @@ -26,7 +26,7 @@ trait Container /** * Finds an entry of the container by its identifier and returns it, - * Retunrs $default when does not exists in the container. + * Returns $default when does not exist in the container. * @param null|mixed $default */ public static function get(string $id, $default = null) diff --git a/src/utils/src/Traits/Macroable.php b/src/utils/src/Traits/Macroable.php deleted file mode 100644 index 815e027be..000000000 --- a/src/utils/src/Traits/Macroable.php +++ /dev/null @@ -1,20 +0,0 @@ -assertSame([1, 2, 3], $result); } + + public function testJsonEncodeNull() + { + $res = Json::encode(null); + $this->assertSame('null', $res); + + $this->assertSame(null, Json::decode('null')); + } } diff --git a/src/utils/tests/XmlTest.php b/src/utils/tests/Codec/XmlTest.php similarity index 98% rename from src/utils/tests/XmlTest.php rename to src/utils/tests/Codec/XmlTest.php index 38054222e..2502ce075 100644 --- a/src/utils/tests/XmlTest.php +++ b/src/utils/tests/Codec/XmlTest.php @@ -9,7 +9,7 @@ declare(strict_types=1); * @contact group@hyperf.io * @license https://github.com/hyperf/hyperf/blob/master/LICENSE */ -namespace HyperfTest\Utils; +namespace HyperfTest\Utils\Codec; use Hyperf\Utils\Codec\Xml; use Hyperf\Utils\Exception\InvalidArgumentException; diff --git a/src/utils/tests/CollectionTest.php b/src/utils/tests/CollectionTest.php index 2bb23e96f..1392adad9 100644 --- a/src/utils/tests/CollectionTest.php +++ b/src/utils/tests/CollectionTest.php @@ -57,4 +57,10 @@ class CollectionTest extends TestCase $this->assertSame(['Hyperf', $uuid], $collection->flatten()->toArray()); } + + public function testCollectionAverage() + { + $col = new Collection([]); + $this->assertNull($col->avg()); + } } diff --git a/src/utils/tests/FunctionTest.php b/src/utils/tests/FunctionTest.php index 22e43f9ee..6b3a12c2b 100644 --- a/src/utils/tests/FunctionTest.php +++ b/src/utils/tests/FunctionTest.php @@ -201,4 +201,12 @@ class FunctionTest extends TestCase $assert = value($foo = new FooClosure(), $id); $this->assertSame($assert, $foo); } + + public function testEnv() + { + $id = 'NULL_' . uniqid(); + putenv("{$id}=(null)"); + + $this->assertNull(env($id)); + } }