Upgrade the minimum php version to 8.0 for utils.

This commit is contained in:
李铭昕 2022-01-25 11:47:46 +08:00 committed by GitHub
parent 33f707bb8d
commit 11406a9d61
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
51 changed files with 166 additions and 403 deletions

View File

@ -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",

View File

@ -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());

View File

@ -15,10 +15,7 @@ use Psr\Container\ContainerInterface;
class ApplicationContext
{
/**
* @var null|ContainerInterface
*/
private static $container;
private static ?ContainerInterface $container = null;
/**
* @throws \TypeError

View File

@ -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;
}

View File

@ -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;
}

View File

@ -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());
}

View File

@ -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

View File

@ -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
{

View File

@ -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
{

View File

@ -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

View File

@ -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
{

View File

@ -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()
{

View File

@ -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;
}
}

View File

@ -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);

View File

@ -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.');

View File

@ -65,14 +65,14 @@ class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate
*
* @var array<TKey, TValue>
*/
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;
}
/**

View File

@ -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.

View File

@ -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)
{

View File

@ -80,7 +80,7 @@ class Coroutine
try {
return $coroutine->getId();
} catch (\Throwable $exception) {
} catch (\Throwable) {
return -1;
}
}

View File

@ -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

View File

@ -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

View File

@ -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;
}

View File

@ -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;
}
/**

View File

@ -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
*/

View File

@ -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;
}
}

View File

@ -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;
}
/**

View File

@ -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;
}
/**

View File

@ -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();

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -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;
}
/**

View File

@ -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

View File

@ -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);

View File

@ -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.

View File

@ -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);
}

View File

@ -1,37 +0,0 @@
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Utils;
/**
* @deprecated v2.3, please use ResourceGenerator instead.
*/
class Resource
{
/**
* TODO: Swoole file hook does not support `php://temp` and `php://memory`.
*/
public static function from(string $body, string $filename = 'php://temp')
{
$resource = fopen($filename, 'r+');
if ($body !== '') {
fwrite($resource, $body);
fseek($resource, 0);
}
return $resource;
}
public static function fromMemory(string $body)
{
return static::from($body, 'php://memory');
}
}

View File

@ -19,12 +19,9 @@ use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class ExceptionNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface
{
/**
* @var null|Instantiator
*/
protected $instantiator;
protected ?Instantiator $instantiator = null;
public function denormalize($data, string $class, string $format = null, array $context = [])
public function denormalize($data, string $type, string $format = null, array $context = [])
{
if (is_string($data)) {
$ex = unserialize($data);
@ -37,22 +34,22 @@ class ExceptionNormalizer implements NormalizerInterface, DenormalizerInterface,
}
if (is_array($data) && isset($data['message'], $data['code'])) {
try {
$exception = $this->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'],

View File

@ -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)

View File

@ -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))));
}
/**

View File

@ -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()

View File

@ -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,
};
}
}

View File

@ -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)

View File

@ -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;
}
/**

View File

@ -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)

View File

@ -1,20 +0,0 @@
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Utils\Traits;
/**
* @deprecated please use `Hyperf\Macroable\Macroable` instead
*/
trait Macroable
{
use \Hyperf\Macroable\Macroable;
}

View File

@ -16,10 +16,9 @@ trait Tappable
/**
* Call the given Closure with this instance then return the instance.
*
* @param null|callable $callback
* @return mixed
*/
public function tap($callback = null)
public function tap(?callable $callback = null)
{
return tap($this, $callback);
}

View File

@ -19,15 +19,9 @@ use Throwable;
class Waiter
{
/**
* @var float
*/
protected $pushTimeout = 10.0;
protected float $pushTimeout = 10.0;
/**
* @var float
*/
protected $popTimeout = 10.0;
protected float $popTimeout = 10.0;
public function __construct(float $timeout = 10.0)
{

View File

@ -75,4 +75,12 @@ class JsonTest extends TestCase
});
$this->assertSame([1, 2, 3], $result);
}
public function testJsonEncodeNull()
{
$res = Json::encode(null);
$this->assertSame('null', $res);
$this->assertSame(null, Json::decode('null'));
}
}

View File

@ -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;

View File

@ -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());
}
}

View File

@ -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));
}
}