Updated Rector to commit 3c9a2453294bed3e258935aad37d355c8251db4f

3c9a245329 Make SimplifyRegexPatternRector work without parent nodes + deprecate BetterNodeFinder and findParent* methods (#4105)
This commit is contained in:
Tomas Votruba 2023-06-07 12:49:26 +00:00
parent 6f867b1fcb
commit 1fdcfc8e63
36 changed files with 149 additions and 1372 deletions

View File

@ -5,9 +5,7 @@ namespace Rector\CodeQuality\Rector\FuncCall;
use RectorPrefix202306\Nette\Utils\Strings;
use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\StaticCall;
use Rector\Core\Php\Regex\RegexPatternArgumentManipulator;
use PhpParser\Node\Scalar\String_;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
@ -22,15 +20,6 @@ final class SimplifyRegexPatternRector extends AbstractRector
* @var array<string, string>
*/
private const COMPLEX_PATTERN_TO_SIMPLE = ['[0-9]' => '\\d', '[a-zA-Z0-9_]' => '\\w', '[A-Za-z0-9_]' => '\\w', '[0-9a-zA-Z_]' => '\\w', '[0-9A-Za-z_]' => '\\w', '[\\r\\n\\t\\f\\v ]' => '\\s'];
/**
* @readonly
* @var \Rector\Core\Php\Regex\RegexPatternArgumentManipulator
*/
private $regexPatternArgumentManipulator;
public function __construct(RegexPatternArgumentManipulator $regexPatternArgumentManipulator)
{
$this->regexPatternArgumentManipulator = $regexPatternArgumentManipulator;
}
public function getRuleDefinition() : RuleDefinition
{
return new RuleDefinition('Simplify regex pattern to known ranges', [new CodeSample(<<<'CODE_SAMPLE'
@ -58,30 +47,20 @@ CODE_SAMPLE
*/
public function getNodeTypes() : array
{
return [FuncCall::class, StaticCall::class];
return [String_::class];
}
/**
* @param FuncCall|StaticCall $node
* @param String_ $node
*/
public function refactor(Node $node) : ?Node
{
$patterns = $this->regexPatternArgumentManipulator->matchCallArgumentWithRegexPattern($node);
if ($patterns === []) {
return null;
}
$hasChanged = \false;
foreach ($patterns as $pattern) {
foreach (self::COMPLEX_PATTERN_TO_SIMPLE as $complexPattern => $simple) {
$originalValue = $pattern->value;
$simplifiedValue = Strings::replace($pattern->value, '#' . \preg_quote($complexPattern, '#') . '#', $simple);
if ($originalValue === $simplifiedValue) {
continue;
}
$pattern->value = $simplifiedValue;
$hasChanged = \true;
foreach (self::COMPLEX_PATTERN_TO_SIMPLE as $complexPattern => $simple) {
$originalValue = $node->value;
$simplifiedValue = Strings::replace($node->value, '#' . \preg_quote($complexPattern, '#') . '#', $simple);
if ($originalValue === $simplifiedValue) {
continue;
}
}
if ($hasChanged) {
$node->value = $simplifiedValue;
return $node;
}
return null;

View File

@ -5,10 +5,7 @@ namespace Rector\Php73\Rector\FuncCall;
use RectorPrefix202306\Nette\Utils\Strings;
use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Scalar\String_;
use Rector\Core\Php\Regex\RegexPatternArgumentManipulator;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\Util\StringUtils;
use Rector\Core\ValueObject\PhpVersionFeature;
@ -39,19 +36,6 @@ final class RegexDashEscapeRector extends AbstractRector implements MinPhpVersio
* @see https://regex101.com/r/TBVme9/9
*/
private const RIGHT_HAND_UNESCAPED_DASH_REGEX = '#(?<!\\[)(?<!\\\\)-(\\\\(w|s|d)[.*]?)\\]#i';
/**
* @var bool
*/
private $hasChanged = \false;
/**
* @readonly
* @var \Rector\Core\Php\Regex\RegexPatternArgumentManipulator
*/
private $regexPatternArgumentManipulator;
public function __construct(RegexPatternArgumentManipulator $regexPatternArgumentManipulator)
{
$this->regexPatternArgumentManipulator = $regexPatternArgumentManipulator;
}
public function provideMinPhpVersion() : int
{
return PhpVersionFeature::ESCAPE_DASH_IN_REGEX;
@ -71,43 +55,33 @@ CODE_SAMPLE
*/
public function getNodeTypes() : array
{
return [FuncCall::class, StaticCall::class];
return [String_::class];
}
/**
* @param FuncCall|StaticCall $node
* @param String_ $node
*/
public function refactor(Node $node) : ?Node
{
$regexArguments = $this->regexPatternArgumentManipulator->matchCallArgumentWithRegexPattern($node);
if ($regexArguments === []) {
$stringKind = $node->getAttribute(AttributeKey::KIND);
if (\in_array($stringKind, [String_::KIND_HEREDOC, String_::KIND_NOWDOC], \true)) {
return null;
}
foreach ($regexArguments as $regexArgument) {
if (StringUtils::isMatch($regexArgument->value, self::THREE_BACKSLASH_FOR_ESCAPE_NEXT_REGEX)) {
continue;
}
$this->escapeStringNode($regexArgument);
}
if (!$this->hasChanged) {
if (StringUtils::isMatch($node->value, self::THREE_BACKSLASH_FOR_ESCAPE_NEXT_REGEX)) {
return null;
}
return $node;
}
private function escapeStringNode(String_ $string) : void
{
$stringValue = $string->value;
$stringValue = $node->value;
if (StringUtils::isMatch($stringValue, self::LEFT_HAND_UNESCAPED_DASH_REGEX)) {
$string->value = Strings::replace($stringValue, self::LEFT_HAND_UNESCAPED_DASH_REGEX, '$1\\-');
$node->value = Strings::replace($stringValue, self::LEFT_HAND_UNESCAPED_DASH_REGEX, '$1\\-');
// helped needed to skip re-escaping regular expression
$string->setAttribute(AttributeKey::IS_REGULAR_PATTERN, \true);
$this->hasChanged = \true;
return;
$node->setAttribute(AttributeKey::IS_REGULAR_PATTERN, \true);
return $node;
}
if (StringUtils::isMatch($stringValue, self::RIGHT_HAND_UNESCAPED_DASH_REGEX)) {
$string->value = Strings::replace($stringValue, self::RIGHT_HAND_UNESCAPED_DASH_REGEX, '\\-$1]');
$node->value = Strings::replace($stringValue, self::RIGHT_HAND_UNESCAPED_DASH_REGEX, '\\-$1]');
// helped needed to skip re-escaping regular expression
$string->setAttribute(AttributeKey::IS_REGULAR_PATTERN, \true);
$this->hasChanged = \true;
$node->setAttribute(AttributeKey::IS_REGULAR_PATTERN, \true);
return $node;
}
return null;
}
}

View File

@ -19,12 +19,12 @@ final class VersionResolver
* @api
* @var string
*/
public const PACKAGE_VERSION = 'ae64ccd4e8ac4d3fbd956e8a60de1d27c598cb8f';
public const PACKAGE_VERSION = '3c9a2453294bed3e258935aad37d355c8251db4f';
/**
* @api
* @var string
*/
public const RELEASE_DATE = '2023-06-07 15:49:38';
public const RELEASE_DATE = '2023-06-07 13:45:36';
/**
* @var int
*/

View File

@ -15,7 +15,7 @@ final class RectorKernel
/**
* @var string
*/
private const CACHE_KEY = 'v67';
private const CACHE_KEY = 'v68';
/**
* @var \Symfony\Component\DependencyInjection\ContainerInterface|null
*/

View File

@ -1,174 +0,0 @@
<?php
declare (strict_types=1);
namespace Rector\Core\Php\Regex;
use RectorPrefix202306\Nette\Utils\Strings;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Const_;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\ClassConstFetch;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\ClassMethod;
use PHPStan\Type\ObjectType;
use Rector\Core\PhpParser\Comparing\NodeComparator;
use Rector\Core\PhpParser\Node\BetterNodeFinder;
use Rector\Core\PhpParser\NodeFinder\LocalConstantFinder;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\NodeTypeResolver\NodeTypeResolver;
final class RegexPatternArgumentManipulator
{
/**
* @var array<string, int>
*/
private const FUNCTIONS_WITH_PATTERNS_TO_ARGUMENT_POSITION = ['preg_match' => 0, 'preg_replace_callback_array' => 0, 'preg_replace_callback' => 0, 'preg_replace' => 0, 'preg_match_all' => 0, 'preg_split' => 0, 'preg_grep' => 0];
/**
* @var array<string, array<string, int>>
*/
private const STATIC_METHODS_WITH_PATTERNS_TO_ARGUMENT_POSITION = [Strings::class => ['match' => 1, 'matchAll' => 1, 'replace' => 1, 'split' => 1]];
/**
* @readonly
* @var \Rector\Core\PhpParser\Node\BetterNodeFinder
*/
private $betterNodeFinder;
/**
* @readonly
* @var \Rector\NodeNameResolver\NodeNameResolver
*/
private $nodeNameResolver;
/**
* @readonly
* @var \Rector\NodeTypeResolver\NodeTypeResolver
*/
private $nodeTypeResolver;
/**
* @readonly
* @var \Rector\Core\PhpParser\NodeFinder\LocalConstantFinder
*/
private $localConstantFinder;
/**
* @readonly
* @var \Rector\Core\PhpParser\Comparing\NodeComparator
*/
private $nodeComparator;
public function __construct(BetterNodeFinder $betterNodeFinder, NodeNameResolver $nodeNameResolver, NodeTypeResolver $nodeTypeResolver, LocalConstantFinder $localConstantFinder, NodeComparator $nodeComparator)
{
$this->betterNodeFinder = $betterNodeFinder;
$this->nodeNameResolver = $nodeNameResolver;
$this->nodeTypeResolver = $nodeTypeResolver;
$this->localConstantFinder = $localConstantFinder;
$this->nodeComparator = $nodeComparator;
}
/**
* @return String_[]
* @param \PhpParser\Node\Expr\FuncCall|\PhpParser\Node\Expr\StaticCall $call
*/
public function matchCallArgumentWithRegexPattern($call) : array
{
if ($call instanceof FuncCall) {
return $this->processFuncCall($call);
}
return $this->processStaticCall($call);
}
/**
* @return String_[]
*/
private function processFuncCall(FuncCall $funcCall) : array
{
foreach (self::FUNCTIONS_WITH_PATTERNS_TO_ARGUMENT_POSITION as $functionName => $argumentPosition) {
if (!$this->nodeNameResolver->isName($funcCall, $functionName)) {
continue;
}
if (!isset($funcCall->args[$argumentPosition])) {
return [];
}
if (!$funcCall->args[$argumentPosition] instanceof Arg) {
return [];
}
return $this->resolveArgumentValues($funcCall->args[$argumentPosition]->value);
}
return [];
}
/**
* @return String_[]
*/
private function processStaticCall(StaticCall $staticCall) : array
{
foreach (self::STATIC_METHODS_WITH_PATTERNS_TO_ARGUMENT_POSITION as $type => $methodNamesToArgumentPosition) {
if (!$this->nodeTypeResolver->isObjectType($staticCall->class, new ObjectType($type))) {
continue;
}
foreach ($methodNamesToArgumentPosition as $methodName => $argumentPosition) {
if (!$this->nodeNameResolver->isName($staticCall->name, $methodName)) {
continue;
}
if (!isset($staticCall->args[$argumentPosition])) {
return [];
}
if (!$staticCall->args[$argumentPosition] instanceof Arg) {
return [];
}
return $this->resolveArgumentValues($staticCall->args[$argumentPosition]->value);
}
}
return [];
}
/**
* @return String_[]
*/
private function resolveArgumentValues(Expr $expr) : array
{
if ($expr instanceof String_) {
return [$expr];
}
if ($expr instanceof Variable) {
$strings = [];
$assignNodes = $this->findAssignerForVariable($expr);
foreach ($assignNodes as $assignNode) {
if ($assignNode->expr instanceof String_) {
$strings[] = $assignNode->expr;
}
}
return $strings;
}
if ($expr instanceof ClassConstFetch) {
return $this->matchClassConstFetchStringValue($expr);
}
return [];
}
/**
* @return Assign[]
*/
private function findAssignerForVariable(Variable $variable) : array
{
$classMethod = $this->betterNodeFinder->findParentType($variable, ClassMethod::class);
if (!$classMethod instanceof ClassMethod) {
return [];
}
return $this->betterNodeFinder->find([$classMethod], function (Node $node) use($variable) : bool {
if (!$node instanceof Assign) {
return \false;
}
return $this->nodeComparator->areNodesEqual($node->var, $variable);
});
}
/**
* @return String_[]
*/
private function matchClassConstFetchStringValue(ClassConstFetch $classConstFetch) : array
{
$classConst = $this->localConstantFinder->match($classConstFetch);
if (!$classConst instanceof Const_) {
return [];
}
if ($classConst->value instanceof String_) {
return [$classConst->value];
}
return [];
}
}

View File

@ -82,6 +82,8 @@ final class BetterNodeFinder
$this->currentFileProvider = $currentFileProvider;
}
/**
* @deprecated Make use of child nodes instead
*
* @template TNode of \PhpParser\Node
* @param array<class-string<TNode>> $types
* @return TNode|null
@ -101,8 +103,9 @@ final class BetterNodeFinder
return null;
}
/**
* @template T of Node
* @deprecated Make use of child nodes instead
* @param class-string<T> $type
* @template T of Node
* @return T|null
*/
public function findParentType(Node $node, string $type) : ?Node

View File

@ -1,67 +0,0 @@
<?php
declare (strict_types=1);
namespace Rector\Core\PhpParser\NodeFinder;
use PhpParser\Node\Const_;
use PhpParser\Node\Expr\ClassConstFetch;
use PhpParser\Node\Stmt\Class_;
use PHPStan\Type\TypeWithClassName;
use Rector\Core\PhpParser\Node\BetterNodeFinder;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\NodeTypeResolver\NodeTypeResolver;
final class LocalConstantFinder
{
/**
* @readonly
* @var \Rector\NodeTypeResolver\NodeTypeResolver
*/
private $nodeTypeResolver;
/**
* @readonly
* @var \Rector\NodeNameResolver\NodeNameResolver
*/
private $nodeNameResolver;
/**
* @readonly
* @var \Rector\Core\PhpParser\Node\BetterNodeFinder
*/
private $betterNodeFinder;
public function __construct(NodeTypeResolver $nodeTypeResolver, NodeNameResolver $nodeNameResolver, BetterNodeFinder $betterNodeFinder)
{
$this->nodeTypeResolver = $nodeTypeResolver;
$this->nodeNameResolver = $nodeNameResolver;
$this->betterNodeFinder = $betterNodeFinder;
}
public function match(ClassConstFetch $classConstFetch) : ?Const_
{
$class = $this->betterNodeFinder->findParentType($classConstFetch, Class_::class);
if (!$class instanceof Class_) {
return null;
}
$constantName = $this->nodeNameResolver->getName($classConstFetch->name);
if ($constantName === null) {
return null;
}
$constantClassType = $this->nodeTypeResolver->getType($classConstFetch->class);
if (!$constantClassType instanceof TypeWithClassName) {
return null;
}
if (!$this->nodeNameResolver->isName($class, $constantClassType->getClassName())) {
return null;
}
return $this->findConstantByName($class, $constantName);
}
private function findConstantByName(Class_ $class, string $constantName) : ?Const_
{
foreach ($class->getConstants() as $classConsts) {
foreach ($classConsts->consts as $const) {
if (!$this->nodeNameResolver->isName($const->name, $constantName)) {
continue;
}
return $const;
}
}
return null;
}
}

2
vendor/autoload.php vendored
View File

@ -22,4 +22,4 @@ if (PHP_VERSION_ID < 50600) {
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit7c4d2c8edb8f8b085b66dc49e6d0a50a::getLoader();
return ComposerAutoloaderInit602763358f418ecf9eade927db0f6c3b::getLoader();

View File

@ -590,7 +590,6 @@ return array(
'RectorPrefix202306\\React\\Promise\\PromiseInterface' => $vendorDir . '/react/promise/src/PromiseInterface.php',
'RectorPrefix202306\\React\\Promise\\PromisorInterface' => $vendorDir . '/react/promise/src/PromisorInterface.php',
'RectorPrefix202306\\React\\Promise\\RejectedPromise' => $vendorDir . '/react/promise/src/RejectedPromise.php',
'RectorPrefix202306\\React\\Promise\\Timer\\TimeoutException' => $vendorDir . '/react/promise-timer/src/TimeoutException.php',
'RectorPrefix202306\\React\\Promise\\UnhandledRejectionException' => $vendorDir . '/react/promise/src/UnhandledRejectionException.php',
'RectorPrefix202306\\React\\Socket\\Connection' => $vendorDir . '/react/socket/src/Connection.php',
'RectorPrefix202306\\React\\Socket\\ConnectionInterface' => $vendorDir . '/react/socket/src/ConnectionInterface.php',
@ -1494,7 +1493,6 @@ return array(
'Rector\\Core\\PhpParser\\AstResolver' => $baseDir . '/src/PhpParser/AstResolver.php',
'Rector\\Core\\PhpParser\\ClassLikeAstResolver' => $baseDir . '/src/PhpParser/ClassLikeAstResolver.php',
'Rector\\Core\\PhpParser\\Comparing\\NodeComparator' => $baseDir . '/src/PhpParser/Comparing/NodeComparator.php',
'Rector\\Core\\PhpParser\\NodeFinder\\LocalConstantFinder' => $baseDir . '/src/PhpParser/NodeFinder/LocalConstantFinder.php',
'Rector\\Core\\PhpParser\\NodeFinder\\LocalMethodCallFinder' => $baseDir . '/src/PhpParser/NodeFinder/LocalMethodCallFinder.php',
'Rector\\Core\\PhpParser\\NodeFinder\\PropertyFetchFinder' => $baseDir . '/src/PhpParser/NodeFinder/PropertyFetchFinder.php',
'Rector\\Core\\PhpParser\\NodeTransformer' => $baseDir . '/src/PhpParser/NodeTransformer.php',
@ -1516,7 +1514,6 @@ return array(
'Rector\\Core\\PhpParser\\ValueObject\\StmtsAndTokens' => $baseDir . '/src/PhpParser/ValueObject/StmtsAndTokens.php',
'Rector\\Core\\Php\\PhpVersionProvider' => $baseDir . '/src/Php/PhpVersionProvider.php',
'Rector\\Core\\Php\\PhpVersionResolver\\ProjectComposerJsonPhpVersionResolver' => $baseDir . '/src/Php/PhpVersionResolver/ProjectComposerJsonPhpVersionResolver.php',
'Rector\\Core\\Php\\Regex\\RegexPatternArgumentManipulator' => $baseDir . '/src/Php/Regex/RegexPatternArgumentManipulator.php',
'Rector\\Core\\Php\\ReservedKeywordAnalyzer' => $baseDir . '/src/Php/ReservedKeywordAnalyzer.php',
'Rector\\Core\\ProcessAnalyzer\\RectifiedAnalyzer' => $baseDir . '/src/ProcessAnalyzer/RectifiedAnalyzer.php',
'Rector\\Core\\Provider\\CurrentFileProvider' => $baseDir . '/src/Provider/CurrentFileProvider.php',

View File

@ -10,7 +10,6 @@ return array(
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'e69f7f6ee287b969198c3c9d6777bd38' => $vendorDir . '/symfony/polyfill-intl-normalizer/bootstrap.php',
'b6b991a57620e2fb6b2f66f03fe9ddc2' => $vendorDir . '/symfony/string/Resources/functions.php',
'972fda704d680a3a53c68e34e193cb22' => $vendorDir . '/react/promise-timer/src/functions_include.php',
'9b38cf48e83f5d8f60375221cd213eee' => $vendorDir . '/phpstan/phpstan/bootstrap.php',
'2324d0e5cadd603331d27de142371f0b' => $vendorDir . '/symfony/contracts/Deprecation/function.php',
'd507e002f7fce7f0c6dbf1f22edcb902' => $vendorDir . '/tracy/tracy/src/Tracy/functions.php',

View File

@ -28,7 +28,6 @@ return array(
'RectorPrefix202306\\Symfony\\Component\\Config\\' => array($vendorDir . '/symfony/config'),
'RectorPrefix202306\\React\\Stream\\' => array($vendorDir . '/react/stream/src'),
'RectorPrefix202306\\React\\Socket\\' => array($vendorDir . '/react/socket/src'),
'RectorPrefix202306\\React\\Promise\\Timer\\' => array($vendorDir . '/react/promise-timer/src'),
'RectorPrefix202306\\React\\Promise\\' => array($vendorDir . '/react/promise/src'),
'RectorPrefix202306\\React\\EventLoop\\' => array($vendorDir . '/react/event-loop/src'),
'RectorPrefix202306\\React\\Dns\\' => array($vendorDir . '/react/dns/src'),

View File

@ -2,7 +2,7 @@
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit7c4d2c8edb8f8b085b66dc49e6d0a50a
class ComposerAutoloaderInit602763358f418ecf9eade927db0f6c3b
{
private static $loader;
@ -22,17 +22,17 @@ class ComposerAutoloaderInit7c4d2c8edb8f8b085b66dc49e6d0a50a
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit7c4d2c8edb8f8b085b66dc49e6d0a50a', 'loadClassLoader'), true, true);
spl_autoload_register(array('ComposerAutoloaderInit602763358f418ecf9eade927db0f6c3b', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInit7c4d2c8edb8f8b085b66dc49e6d0a50a', 'loadClassLoader'));
spl_autoload_unregister(array('ComposerAutoloaderInit602763358f418ecf9eade927db0f6c3b', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit7c4d2c8edb8f8b085b66dc49e6d0a50a::getInitializer($loader));
call_user_func(\Composer\Autoload\ComposerStaticInit602763358f418ecf9eade927db0f6c3b::getInitializer($loader));
$loader->setClassMapAuthoritative(true);
$loader->register(true);
$filesToLoad = \Composer\Autoload\ComposerStaticInit7c4d2c8edb8f8b085b66dc49e6d0a50a::$files;
$filesToLoad = \Composer\Autoload\ComposerStaticInit602763358f418ecf9eade927db0f6c3b::$files;
$requireFile = \Closure::bind(static function ($fileIdentifier, $file) {
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;

View File

@ -4,14 +4,13 @@
namespace Composer\Autoload;
class ComposerStaticInit7c4d2c8edb8f8b085b66dc49e6d0a50a
class ComposerStaticInit602763358f418ecf9eade927db0f6c3b
{
public static $files = array (
'ad155f8f1cf0d418fe49e248db8c661b' => __DIR__ . '/..' . '/react/promise/src/functions_include.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
'e69f7f6ee287b969198c3c9d6777bd38' => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer/bootstrap.php',
'b6b991a57620e2fb6b2f66f03fe9ddc2' => __DIR__ . '/..' . '/symfony/string/Resources/functions.php',
'972fda704d680a3a53c68e34e193cb22' => __DIR__ . '/..' . '/react/promise-timer/src/functions_include.php',
'9b38cf48e83f5d8f60375221cd213eee' => __DIR__ . '/..' . '/phpstan/phpstan/bootstrap.php',
'2324d0e5cadd603331d27de142371f0b' => __DIR__ . '/..' . '/symfony/contracts/Deprecation/function.php',
'd507e002f7fce7f0c6dbf1f22edcb902' => __DIR__ . '/..' . '/tracy/tracy/src/Tracy/functions.php',
@ -47,7 +46,6 @@ class ComposerStaticInit7c4d2c8edb8f8b085b66dc49e6d0a50a
'RectorPrefix202306\\Symfony\\Component\\Config\\' => 44,
'RectorPrefix202306\\React\\Stream\\' => 32,
'RectorPrefix202306\\React\\Socket\\' => 32,
'RectorPrefix202306\\React\\Promise\\Timer\\' => 39,
'RectorPrefix202306\\React\\Promise\\' => 33,
'RectorPrefix202306\\React\\EventLoop\\' => 35,
'RectorPrefix202306\\React\\Dns\\' => 29,
@ -165,10 +163,6 @@ class ComposerStaticInit7c4d2c8edb8f8b085b66dc49e6d0a50a
array (
0 => __DIR__ . '/..' . '/react/socket/src',
),
'RectorPrefix202306\\React\\Promise\\Timer\\' =>
array (
0 => __DIR__ . '/..' . '/react/promise-timer/src',
),
'RectorPrefix202306\\React\\Promise\\' =>
array (
0 => __DIR__ . '/..' . '/react/promise/src',
@ -832,7 +826,6 @@ class ComposerStaticInit7c4d2c8edb8f8b085b66dc49e6d0a50a
'RectorPrefix202306\\React\\Promise\\PromiseInterface' => __DIR__ . '/..' . '/react/promise/src/PromiseInterface.php',
'RectorPrefix202306\\React\\Promise\\PromisorInterface' => __DIR__ . '/..' . '/react/promise/src/PromisorInterface.php',
'RectorPrefix202306\\React\\Promise\\RejectedPromise' => __DIR__ . '/..' . '/react/promise/src/RejectedPromise.php',
'RectorPrefix202306\\React\\Promise\\Timer\\TimeoutException' => __DIR__ . '/..' . '/react/promise-timer/src/TimeoutException.php',
'RectorPrefix202306\\React\\Promise\\UnhandledRejectionException' => __DIR__ . '/..' . '/react/promise/src/UnhandledRejectionException.php',
'RectorPrefix202306\\React\\Socket\\Connection' => __DIR__ . '/..' . '/react/socket/src/Connection.php',
'RectorPrefix202306\\React\\Socket\\ConnectionInterface' => __DIR__ . '/..' . '/react/socket/src/ConnectionInterface.php',
@ -1736,7 +1729,6 @@ class ComposerStaticInit7c4d2c8edb8f8b085b66dc49e6d0a50a
'Rector\\Core\\PhpParser\\AstResolver' => __DIR__ . '/../..' . '/src/PhpParser/AstResolver.php',
'Rector\\Core\\PhpParser\\ClassLikeAstResolver' => __DIR__ . '/../..' . '/src/PhpParser/ClassLikeAstResolver.php',
'Rector\\Core\\PhpParser\\Comparing\\NodeComparator' => __DIR__ . '/../..' . '/src/PhpParser/Comparing/NodeComparator.php',
'Rector\\Core\\PhpParser\\NodeFinder\\LocalConstantFinder' => __DIR__ . '/../..' . '/src/PhpParser/NodeFinder/LocalConstantFinder.php',
'Rector\\Core\\PhpParser\\NodeFinder\\LocalMethodCallFinder' => __DIR__ . '/../..' . '/src/PhpParser/NodeFinder/LocalMethodCallFinder.php',
'Rector\\Core\\PhpParser\\NodeFinder\\PropertyFetchFinder' => __DIR__ . '/../..' . '/src/PhpParser/NodeFinder/PropertyFetchFinder.php',
'Rector\\Core\\PhpParser\\NodeTransformer' => __DIR__ . '/../..' . '/src/PhpParser/NodeTransformer.php',
@ -1758,7 +1750,6 @@ class ComposerStaticInit7c4d2c8edb8f8b085b66dc49e6d0a50a
'Rector\\Core\\PhpParser\\ValueObject\\StmtsAndTokens' => __DIR__ . '/../..' . '/src/PhpParser/ValueObject/StmtsAndTokens.php',
'Rector\\Core\\Php\\PhpVersionProvider' => __DIR__ . '/../..' . '/src/Php/PhpVersionProvider.php',
'Rector\\Core\\Php\\PhpVersionResolver\\ProjectComposerJsonPhpVersionResolver' => __DIR__ . '/../..' . '/src/Php/PhpVersionResolver/ProjectComposerJsonPhpVersionResolver.php',
'Rector\\Core\\Php\\Regex\\RegexPatternArgumentManipulator' => __DIR__ . '/../..' . '/src/Php/Regex/RegexPatternArgumentManipulator.php',
'Rector\\Core\\Php\\ReservedKeywordAnalyzer' => __DIR__ . '/../..' . '/src/Php/ReservedKeywordAnalyzer.php',
'Rector\\Core\\ProcessAnalyzer\\RectifiedAnalyzer' => __DIR__ . '/../..' . '/src/ProcessAnalyzer/RectifiedAnalyzer.php',
'Rector\\Core\\Provider\\CurrentFileProvider' => __DIR__ . '/../..' . '/src/Provider/CurrentFileProvider.php',
@ -3040,9 +3031,9 @@ class ComposerStaticInit7c4d2c8edb8f8b085b66dc49e6d0a50a
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit7c4d2c8edb8f8b085b66dc49e6d0a50a::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit7c4d2c8edb8f8b085b66dc49e6d0a50a::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInit7c4d2c8edb8f8b085b66dc49e6d0a50a::$classMap;
$loader->prefixLengthsPsr4 = ComposerStaticInit602763358f418ecf9eade927db0f6c3b::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit602763358f418ecf9eade927db0f6c3b::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInit602763358f418ecf9eade927db0f6c3b::$classMap;
}, null, ClassLoader::class);
}

View File

@ -1534,122 +1534,36 @@
],
"install-path": "..\/react\/promise"
},
{
"name": "react\/promise-timer",
"version": "v1.9.0",
"version_normalized": "1.9.0.0",
"source": {
"type": "git",
"url": "https:\/\/github.com\/reactphp\/promise-timer.git",
"reference": "aa7a73c74b8d8c0f622f5982ff7b0351bc29e495"
},
"dist": {
"type": "zip",
"url": "https:\/\/api.github.com\/repos\/reactphp\/promise-timer\/zipball\/aa7a73c74b8d8c0f622f5982ff7b0351bc29e495",
"reference": "aa7a73c74b8d8c0f622f5982ff7b0351bc29e495",
"shasum": ""
},
"require": {
"php": ">=5.3",
"react\/event-loop": "^1.2",
"react\/promise": "^3.0 || ^2.7.0 || ^1.2.1"
},
"require-dev": {
"phpunit\/phpunit": "^9.3 || ^5.7 || ^4.8.35"
},
"time": "2022-06-13T13:41:03+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"files": [
"src\/functions_include.php"
],
"psr-4": {
"RectorPrefix202306\\React\\Promise\\Timer\\": "src\/"
}
},
"notification-url": "https:\/\/packagist.org\/downloads\/",
"license": [
"MIT"
],
"authors": [
{
"name": "Christian L\u00fcck",
"email": "christian@clue.engineering",
"homepage": "https:\/\/clue.engineering\/"
},
{
"name": "Cees-Jan Kiewiet",
"email": "reactphp@ceesjankiewiet.nl",
"homepage": "https:\/\/wyrihaximus.net\/"
},
{
"name": "Jan Sorgalla",
"email": "jsorgalla@gmail.com",
"homepage": "https:\/\/sorgalla.com\/"
},
{
"name": "Chris Boden",
"email": "cboden@gmail.com",
"homepage": "https:\/\/cboden.dev\/"
}
],
"description": "A trivial implementation of timeouts for Promises, built on top of ReactPHP.",
"homepage": "https:\/\/github.com\/reactphp\/promise-timer",
"keywords": [
"async",
"event-loop",
"promise",
"reactphp",
"timeout",
"timer"
],
"support": {
"issues": "https:\/\/github.com\/reactphp\/promise-timer\/issues",
"source": "https:\/\/github.com\/reactphp\/promise-timer\/tree\/v1.9.0"
},
"funding": [
{
"url": "https:\/\/github.com\/WyriHaximus",
"type": "github"
},
{
"url": "https:\/\/github.com\/clue",
"type": "github"
}
],
"install-path": "..\/react\/promise-timer"
},
{
"name": "react\/socket",
"version": "v1.12.0",
"version_normalized": "1.12.0.0",
"version": "v1.13.0",
"version_normalized": "1.13.0.0",
"source": {
"type": "git",
"url": "https:\/\/github.com\/reactphp\/socket.git",
"reference": "81e1b4d7f5450ebd8d2e9a95bb008bb15ca95a7b"
"reference": "cff482bbad5848ecbe8b57da57e4e213b03619aa"
},
"dist": {
"type": "zip",
"url": "https:\/\/api.github.com\/repos\/reactphp\/socket\/zipball\/81e1b4d7f5450ebd8d2e9a95bb008bb15ca95a7b",
"reference": "81e1b4d7f5450ebd8d2e9a95bb008bb15ca95a7b",
"url": "https:\/\/api.github.com\/repos\/reactphp\/socket\/zipball\/cff482bbad5848ecbe8b57da57e4e213b03619aa",
"reference": "cff482bbad5848ecbe8b57da57e4e213b03619aa",
"shasum": ""
},
"require": {
"evenement\/evenement": "^3.0 || ^2.0 || ^1.0",
"php": ">=5.3.0",
"react\/dns": "^1.8",
"react\/dns": "^1.11",
"react\/event-loop": "^1.2",
"react\/promise": "^3 || ^2.6 || ^1.2.1",
"react\/promise-timer": "^1.9",
"react\/stream": "^1.2"
},
"require-dev": {
"phpunit\/phpunit": "^9.3 || ^5.7 || ^4.8.35",
"phpunit\/phpunit": "^9.5 || ^5.7 || ^4.8.35",
"react\/async": "^4 || ^3 || ^2",
"react\/promise-stream": "^1.4"
"react\/promise-stream": "^1.4",
"react\/promise-timer": "^1.9"
},
"time": "2022-08-25T12:32:25+00:00",
"time": "2023-06-07T10:28:34+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
@ -1693,16 +1607,12 @@
],
"support": {
"issues": "https:\/\/github.com\/reactphp\/socket\/issues",
"source": "https:\/\/github.com\/reactphp\/socket\/tree\/v1.12.0"
"source": "https:\/\/github.com\/reactphp\/socket\/tree\/v1.13.0"
},
"funding": [
{
"url": "https:\/\/github.com\/WyriHaximus",
"type": "github"
},
{
"url": "https:\/\/github.com\/clue",
"type": "github"
"url": "https:\/\/opencollective.com\/reactphp",
"type": "open_collective"
}
],
"install-path": "..\/react\/socket"

File diff suppressed because one or more lines are too long

View File

@ -1,126 +0,0 @@
# Changelog
## 1.9.0 (2022-06-13)
* Feature: Improve forward compatibility with upcoming Promise v3 API.
(#54 and #55 by @clue)
* Minor documentation improvements for upcoming Promise v3.
(#58 by @clue and #56 by @SimonFrings)
* Improve test suite, fix legacy HHVM build by downgrading Composer.
(#57 by @SimonFrings)
## 1.8.0 (2021-12-06)
* Feature: Add new `sleep()` function and deprecate `resolve()` and `reject()` functions.
(#51 by @clue)
```php
// deprecated
React\Promise\Timer\resolve($time);
React\Promise\Timer\reject($time);
// new
React\Promise\Timer\sleep($time);
```
* Feature: Support PHP 8.1 release.
(#50 by @Thomas-Gelf, #52 by @clue and #48 by @SimonFrings)
* Improve API documentation and add parameter types and return types.
(#49 by @clue and #47 by @SimonFrings)
## 1.7.0 (2021-07-11)
A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop).
* Feature: Simplify usage by supporting new [default loop](https://reactphp.org/event-loop/#loop).
(#46 by @clue)
```php
// old (still supported)
$promise = timeout($promise, $time, $loop);
$promise = resolve($time, $loop);
$promise = reject($time, $loop);
// new (using default loop)
$promise = timeout($promise, $time);
$promise = resolve($time);
$promise = reject($time);
```
* Improve test suite, use GitHub actions for continuous integration (CI),
update PHPUnit config, run tests on PHP 8 and add full core team to the license.
(#43 by @WyriHaximus, #44 and #45 by @SimonFrings)
## 1.6.0 (2020-07-10)
* Feature: Forward compatibility with react/promise v3.
(#37 by @WyriHaximus)
* Improve test suite and add `.gitattributes` to exclude dev files from exports.
Run tests on PHPUnit 9 and PHP 7.4 and clean up test suite.
(#38 by @WyriHaximus, #39 by @reedy, #41 by @clue and #42 by @SimonFrings)
## 1.5.1 (2019-03-27)
* Fix: Typo in readme
(#35 by @aak74)
* Improvement: Only include functions file when functions aren't defined
(#36 by @Niko9911)
## 1.5.0 (2018-06-13)
* Feature: Improve memory consumption by cleaning up garbage references to pending promise without canceller.
(#34 by @clue)
## 1.4.0 (2018-06-11)
* Feature: Improve memory consumption by cleaning up garbage references.
(#33 by @clue)
## 1.3.0 (2018-04-24)
* Feature: Improve memory consumption by cleaning up unneeded references.
(#32 by @clue)
## 1.2.1 (2017-12-22)
* README improvements
(#28 by @jsor)
* Improve test suite by adding forward compatiblity with PHPUnit 6 and
fix test suite forward compatibility with upcoming EventLoop releases
(#30 and #31 by @clue)
## 1.2.0 (2017-08-08)
* Feature: Only start timers if input Promise is still pending and
return a settled output promise if the input is already settled.
(#25 by @clue)
* Feature: Cap minimum timer interval at 1µs across all versions
(#23 by @clue)
* Feature: Forward compatibility with EventLoop v1.0 and v0.5
(#27 by @clue)
* Improve test suite by adding PHPUnit to require-dev and
lock Travis distro so new defaults will not break the build
(#24 and #26 by @clue)
## 1.1.1 (2016-12-27)
* Improve test suite to use PSR-4 autoloader and proper namespaces.
(#21 by @clue)
## 1.1.0 (2016-02-29)
* Feature: Support promise cancellation for all timer primitives
(#18 by @clue)
## 1.0.0 (2015-09-29)
* First tagged release

View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,318 +0,0 @@
# PromiseTimer
[![CI status](https://github.com/reactphp/promise-timer/actions/workflows/ci.yml/badge.svg)](https://github.com/reactphp/promise-timer/actions)
[![installs on Packagist](https://img.shields.io/packagist/dt/react/promise-timer?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/promise-timer)
A trivial implementation of timeouts for `Promise`s, built on top of [ReactPHP](https://reactphp.org/).
**Table of contents**
* [Usage](#usage)
* [timeout()](#timeout)
* [sleep()](#sleep)
* [~~resolve()~~](#resolve)
* [~~reject()~~](#reject)
* [TimeoutException](#timeoutexception)
* [getTimeout()](#gettimeout)
* [Install](#install)
* [Tests](#tests)
* [License](#license)
## Usage
This lightweight library consists only of a few simple functions.
All functions reside under the `React\Promise\Timer` namespace.
The below examples refer to all functions with their fully-qualified names like this:
```php
React\Promise\Timer\timeout(…);
```
As of PHP 5.6+ you can also import each required function into your code like this:
```php
use function React\Promise\Timer\timeout;
timeout(…);
```
Alternatively, you can also use an import statement similar to this:
```php
use React\Promise\Timer;
Timer\timeout(…);
```
### timeout()
The `timeout(PromiseInterface<mixed, Throwable|mixed> $promise, float $time, ?LoopInterface $loop = null): PromiseInterface<mixed, TimeoutException|Throwable|mixed>` function can be used to
cancel operations that take *too long*.
You need to pass in an input `$promise` that represents a pending operation
and timeout parameters. It returns a new promise with the following
resolution behavior:
- If the input `$promise` resolves before `$time` seconds, resolve the
resulting promise with its fulfillment value.
- If the input `$promise` rejects before `$time` seconds, reject the
resulting promise with its rejection value.
- If the input `$promise` does not settle before `$time` seconds, *cancel*
the operation and reject the resulting promise with a [`TimeoutException`](#timeoutexception).
Internally, the given `$time` value will be used to start a timer that will
*cancel* the pending operation once it triggers. This implies that if you
pass a really small (or negative) value, it will still start a timer and will
thus trigger at the earliest possible time in the future.
If the input `$promise` is already settled, then the resulting promise will
resolve or reject immediately without starting a timer at all.
This function takes an optional `LoopInterface|null $loop` parameter that can be used to
pass the event loop instance to use. You can use a `null` value here in order to
use the [default loop](https://github.com/reactphp/event-loop#loop). This value
SHOULD NOT be given unless you're sure you want to explicitly use a given event
loop instance.
A common use case for handling only resolved values looks like this:
```php
$promise = accessSomeRemoteResource();
React\Promise\Timer\timeout($promise, 10.0)->then(function ($value) {
// the operation finished within 10.0 seconds
});
```
A more complete example could look like this:
```php
$promise = accessSomeRemoteResource();
React\Promise\Timer\timeout($promise, 10.0)->then(
function ($value) {
// the operation finished within 10.0 seconds
},
function ($error) {
if ($error instanceof React\Promise\Timer\TimeoutException) {
// the operation has failed due to a timeout
} else {
// the input operation has failed due to some other error
}
}
);
```
Or if you're using [react/promise v3](https://github.com/reactphp/promise):
```php
React\Promise\Timer\timeout($promise, 10.0)->then(function ($value) {
// the operation finished within 10.0 seconds
})->catch(function (React\Promise\Timer\TimeoutException $error) {
// the operation has failed due to a timeout
})->catch(function (Throwable $error) {
// the input operation has failed due to some other error
});
```
As discussed above, the [`timeout()`](#timeout) function will take care of
the underlying operation if it takes *too long*. In this case, you can be
sure the resulting promise will always be rejected with a
[`TimeoutException`](#timeoutexception). On top of this, the function will
try to *cancel* the underlying operation. Responsibility for this
cancellation logic is left up to the underlying operation.
- A common use case involves cleaning up any resources like open network
sockets or file handles or terminating external processes or timers.
- If the given input `$promise` does not support cancellation, then this is a
NO-OP. This means that while the resulting promise will still be rejected,
the underlying input `$promise` may still be pending and can hence continue
consuming resources
On top of this, the returned promise is implemented in such a way that it can
be cancelled when it is still pending. Cancelling a pending promise will
cancel the underlying operation. As discussed above, responsibility for this
cancellation logic is left up to the underlying operation.
```php
$promise = accessSomeRemoteResource();
$timeout = React\Promise\Timer\timeout($promise, 10.0);
$timeout->cancel();
```
For more details on the promise cancellation, please refer to the
[Promise documentation](https://github.com/reactphp/promise#cancellablepromiseinterface).
If you want to wait for multiple promises to resolve, you can use the normal
promise primitives like this:
```php
$promises = array(
accessSomeRemoteResource(),
accessSomeRemoteResource(),
accessSomeRemoteResource()
);
$promise = React\Promise\all($promises);
React\Promise\Timer\timeout($promise, 10)->then(function ($values) {
// *all* promises resolved
});
```
The applies to all promise collection primitives alike, i.e. `all()`,
`race()`, `any()`, `some()` etc.
For more details on the promise primitives, please refer to the
[Promise documentation](https://github.com/reactphp/promise#functions).
### sleep()
The `sleep(float $time, ?LoopInterface $loop = null): PromiseInterface<void, RuntimeException>` function can be used to
create a new promise that resolves in `$time` seconds.
```php
React\Promise\Timer\sleep(1.5)->then(function () {
echo 'Thanks for waiting!' . PHP_EOL;
});
```
Internally, the given `$time` value will be used to start a timer that will
resolve the promise once it triggers. This implies that if you pass a really
small (or negative) value, it will still start a timer and will thus trigger
at the earliest possible time in the future.
This function takes an optional `LoopInterface|null $loop` parameter that can be used to
pass the event loop instance to use. You can use a `null` value here in order to
use the [default loop](https://github.com/reactphp/event-loop#loop). This value
SHOULD NOT be given unless you're sure you want to explicitly use a given event
loop instance.
The returned promise is implemented in such a way that it can be cancelled
when it is still pending. Cancelling a pending promise will reject its value
with a `RuntimeException` and clean up any pending timers.
```php
$timer = React\Promise\Timer\sleep(2.0);
$timer->cancel();
```
### ~~resolve()~~
> Deprecated since v1.8.0, see [`sleep()`](#sleep) instead.
The `resolve(float $time, ?LoopInterface $loop = null): PromiseInterface<float, RuntimeException>` function can be used to
create a new promise that resolves in `$time` seconds with the `$time` as the fulfillment value.
```php
React\Promise\Timer\resolve(1.5)->then(function ($time) {
echo 'Thanks for waiting ' . $time . ' seconds' . PHP_EOL;
});
```
Internally, the given `$time` value will be used to start a timer that will
resolve the promise once it triggers. This implies that if you pass a really
small (or negative) value, it will still start a timer and will thus trigger
at the earliest possible time in the future.
This function takes an optional `LoopInterface|null $loop` parameter that can be used to
pass the event loop instance to use. You can use a `null` value here in order to
use the [default loop](https://github.com/reactphp/event-loop#loop). This value
SHOULD NOT be given unless you're sure you want to explicitly use a given event
loop instance.
The returned promise is implemented in such a way that it can be cancelled
when it is still pending. Cancelling a pending promise will reject its value
with a `RuntimeException` and clean up any pending timers.
```php
$timer = React\Promise\Timer\resolve(2.0);
$timer->cancel();
```
### ~~reject()~~
> Deprecated since v1.8.0, see [`sleep()`](#sleep) instead.
The `reject(float $time, ?LoopInterface $loop = null): PromiseInterface<void, TimeoutException|RuntimeException>` function can be used to
create a new promise which rejects in `$time` seconds with a `TimeoutException`.
```php
React\Promise\Timer\reject(2.0)->then(null, function (React\Promise\Timer\TimeoutException $e) {
echo 'Rejected after ' . $e->getTimeout() . ' seconds ' . PHP_EOL;
});
```
Internally, the given `$time` value will be used to start a timer that will
reject the promise once it triggers. This implies that if you pass a really
small (or negative) value, it will still start a timer and will thus trigger
at the earliest possible time in the future.
This function takes an optional `LoopInterface|null $loop` parameter that can be used to
pass the event loop instance to use. You can use a `null` value here in order to
use the [default loop](https://github.com/reactphp/event-loop#loop). This value
SHOULD NOT be given unless you're sure you want to explicitly use a given event
loop instance.
The returned promise is implemented in such a way that it can be cancelled
when it is still pending. Cancelling a pending promise will reject its value
with a `RuntimeException` and clean up any pending timers.
```php
$timer = React\Promise\Timer\reject(2.0);
$timer->cancel();
```
### TimeoutException
The `TimeoutException` extends PHP's built-in `RuntimeException`.
#### getTimeout()
The `getTimeout(): float` method can be used to
get the timeout value in seconds.
## Install
The recommended way to install this library is [through Composer](https://getcomposer.org/).
[New to Composer?](https://getcomposer.org/doc/00-intro.md)
This project follows [SemVer](https://semver.org/).
This will install the latest supported version:
```bash
$ composer require react/promise-timer:^1.9
```
See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades.
This project aims to run on any platform and thus does not require any PHP
extensions and supports running on legacy PHP 5.3 through current PHP 8+ and
HHVM.
It's *highly recommended to use the latest supported PHP version* for this project.
## Tests
To run the test suite, you first need to clone this repo and then install all
dependencies [through Composer](https://getcomposer.org/):
```bash
$ composer install
```
To run the test suite, go to the project root and run:
```bash
$ vendor/bin/phpunit
```
## License
MIT, see [LICENSE file](LICENSE).

View File

@ -1,57 +0,0 @@
{
"name": "react\/promise-timer",
"description": "A trivial implementation of timeouts for Promises, built on top of ReactPHP.",
"keywords": [
"Promise",
"timeout",
"timer",
"event-loop",
"ReactPHP",
"async"
],
"homepage": "https:\/\/github.com\/reactphp\/promise-timer",
"license": "MIT",
"authors": [
{
"name": "Christian L\u00fcck",
"homepage": "https:\/\/clue.engineering\/",
"email": "christian@clue.engineering"
},
{
"name": "Cees-Jan Kiewiet",
"homepage": "https:\/\/wyrihaximus.net\/",
"email": "reactphp@ceesjankiewiet.nl"
},
{
"name": "Jan Sorgalla",
"homepage": "https:\/\/sorgalla.com\/",
"email": "jsorgalla@gmail.com"
},
{
"name": "Chris Boden",
"homepage": "https:\/\/cboden.dev\/",
"email": "cboden@gmail.com"
}
],
"autoload": {
"psr-4": {
"RectorPrefix202306\\React\\Promise\\Timer\\": "src\/"
},
"files": [
"src\/functions_include.php"
]
},
"autoload-dev": {
"psr-4": {
"RectorPrefix202306\\React\\Tests\\Promise\\Timer\\": "tests\/"
}
},
"require": {
"php": ">=5.3",
"react\/event-loop": "^1.2",
"react\/promise": "^3.0 || ^2.7.0 || ^1.2.1"
},
"require-dev": {
"phpunit\/phpunit": "^9.3 || ^5.7 || ^4.8.35"
}
}

View File

@ -1,31 +0,0 @@
<?php
namespace RectorPrefix202306\React\Promise\Timer;
use RuntimeException;
class TimeoutException extends RuntimeException
{
/** @var float */
private $timeout;
/**
* @param float $timeout
* @param string|null $message
* @param int|null $code
* @param null|\Exception|\Throwable $previous
*/
public function __construct($timeout, $message = '', $code = 0, $previous = null)
{
// Preserve compatibility with our former nullable signature, but avoid invalid arguments for the parent constructor:
parent::__construct((string) $message, (int) $code, $previous);
$this->timeout = (float) $timeout;
}
/**
* Get the timeout value in seconds.
*
* @return float
*/
public function getTimeout()
{
return $this->timeout;
}
}

View File

@ -1,319 +0,0 @@
<?php
namespace RectorPrefix202306\React\Promise\Timer;
use RectorPrefix202306\React\EventLoop\Loop;
use RectorPrefix202306\React\EventLoop\LoopInterface;
use RectorPrefix202306\React\Promise\Promise;
use RectorPrefix202306\React\Promise\PromiseInterface;
/**
* Cancel operations that take *too long*.
*
* You need to pass in an input `$promise` that represents a pending operation
* and timeout parameters. It returns a new promise with the following
* resolution behavior:
*
* - If the input `$promise` resolves before `$time` seconds, resolve the
* resulting promise with its fulfillment value.
*
* - If the input `$promise` rejects before `$time` seconds, reject the
* resulting promise with its rejection value.
*
* - If the input `$promise` does not settle before `$time` seconds, *cancel*
* the operation and reject the resulting promise with a [`TimeoutException`](#timeoutexception).
*
* Internally, the given `$time` value will be used to start a timer that will
* *cancel* the pending operation once it triggers. This implies that if you
* pass a really small (or negative) value, it will still start a timer and will
* thus trigger at the earliest possible time in the future.
*
* If the input `$promise` is already settled, then the resulting promise will
* resolve or reject immediately without starting a timer at all.
*
* This function takes an optional `LoopInterface|null $loop` parameter that can be used to
* pass the event loop instance to use. You can use a `null` value here in order to
* use the [default loop](https://github.com/reactphp/event-loop#loop). This value
* SHOULD NOT be given unless you're sure you want to explicitly use a given event
* loop instance.
*
* A common use case for handling only resolved values looks like this:
*
* ```php
* $promise = accessSomeRemoteResource();
* React\Promise\Timer\timeout($promise, 10.0)->then(function ($value) {
* // the operation finished within 10.0 seconds
* });
* ```
*
* A more complete example could look like this:
*
* ```php
* $promise = accessSomeRemoteResource();
* React\Promise\Timer\timeout($promise, 10.0)->then(
* function ($value) {
* // the operation finished within 10.0 seconds
* },
* function ($error) {
* if ($error instanceof React\Promise\Timer\TimeoutException) {
* // the operation has failed due to a timeout
* } else {
* // the input operation has failed due to some other error
* }
* }
* );
* ```
*
* Or if you're using [react/promise v3](https://github.com/reactphp/promise):
*
* ```php
* React\Promise\Timer\timeout($promise, 10.0)->then(function ($value) {
* // the operation finished within 10.0 seconds
* })->catch(function (React\Promise\Timer\TimeoutException $error) {
* // the operation has failed due to a timeout
* })->catch(function (Throwable $error) {
* // the input operation has failed due to some other error
* });
* ```
*
* As discussed above, the [`timeout()`](#timeout) function will take care of
* the underlying operation if it takes *too long*. In this case, you can be
* sure the resulting promise will always be rejected with a
* [`TimeoutException`](#timeoutexception). On top of this, the function will
* try to *cancel* the underlying operation. Responsibility for this
* cancellation logic is left up to the underlying operation.
*
* - A common use case involves cleaning up any resources like open network
* sockets or file handles or terminating external processes or timers.
*
* - If the given input `$promise` does not support cancellation, then this is a
* NO-OP. This means that while the resulting promise will still be rejected,
* the underlying input `$promise` may still be pending and can hence continue
* consuming resources
*
* On top of this, the returned promise is implemented in such a way that it can
* be cancelled when it is still pending. Cancelling a pending promise will
* cancel the underlying operation. As discussed above, responsibility for this
* cancellation logic is left up to the underlying operation.
*
* ```php
* $promise = accessSomeRemoteResource();
* $timeout = React\Promise\Timer\timeout($promise, 10.0);
*
* $timeout->cancel();
* ```
*
* For more details on the promise cancellation, please refer to the
* [Promise documentation](https://github.com/reactphp/promise#cancellablepromiseinterface).
*
* If you want to wait for multiple promises to resolve, you can use the normal
* promise primitives like this:
*
* ```php
* $promises = array(
* accessSomeRemoteResource(),
* accessSomeRemoteResource(),
* accessSomeRemoteResource()
* );
*
* $promise = React\Promise\all($promises);
*
* React\Promise\Timer\timeout($promise, 10)->then(function ($values) {
* // *all* promises resolved
* });
* ```
*
* The applies to all promise collection primitives alike, i.e. `all()`,
* `race()`, `any()`, `some()` etc.
*
* For more details on the promise primitives, please refer to the
* [Promise documentation](https://github.com/reactphp/promise#functions).
*
* @param PromiseInterface<mixed, \Throwable|mixed> $promise
* @param float $time
* @param ?LoopInterface $loop
* @return PromiseInterface<mixed, TimeoutException|\Throwable|mixed>
*/
function timeout(PromiseInterface $promise, $time, LoopInterface $loop = null)
{
// cancelling this promise will only try to cancel the input promise,
// thus leaving responsibility to the input promise.
$canceller = null;
if (\method_exists($promise, 'cancel')) {
// pass promise by reference to clean reference after cancellation handler
// has been invoked once in order to avoid garbage references in call stack.
$canceller = function () use(&$promise) {
$promise->cancel();
$promise = null;
};
}
if ($loop === null) {
$loop = Loop::get();
}
return new Promise(function ($resolve, $reject) use($loop, $time, $promise) {
$timer = null;
$promise = $promise->then(function ($v) use(&$timer, $loop, $resolve) {
if ($timer) {
$loop->cancelTimer($timer);
}
$timer = \false;
$resolve($v);
}, function ($v) use(&$timer, $loop, $reject) {
if ($timer) {
$loop->cancelTimer($timer);
}
$timer = \false;
$reject($v);
});
// promise already resolved => no need to start timer
if ($timer === \false) {
return;
}
// start timeout timer which will cancel the input promise
$timer = $loop->addTimer($time, function () use($time, &$promise, $reject) {
$reject(new TimeoutException($time, 'Timed out after ' . $time . ' seconds'));
// try to invoke cancellation handler of input promise and then clean
// reference in order to avoid garbage references in call stack.
if (\method_exists($promise, 'cancel')) {
$promise->cancel();
}
$promise = null;
});
}, $canceller);
}
/**
* Create a new promise that resolves in `$time` seconds.
*
* ```php
* React\Promise\Timer\sleep(1.5)->then(function () {
* echo 'Thanks for waiting!' . PHP_EOL;
* });
* ```
*
* Internally, the given `$time` value will be used to start a timer that will
* resolve the promise once it triggers. This implies that if you pass a really
* small (or negative) value, it will still start a timer and will thus trigger
* at the earliest possible time in the future.
*
* This function takes an optional `LoopInterface|null $loop` parameter that can be used to
* pass the event loop instance to use. You can use a `null` value here in order to
* use the [default loop](https://github.com/reactphp/event-loop#loop). This value
* SHOULD NOT be given unless you're sure you want to explicitly use a given event
* loop instance.
*
* The returned promise is implemented in such a way that it can be cancelled
* when it is still pending. Cancelling a pending promise will reject its value
* with a `RuntimeException` and clean up any pending timers.
*
* ```php
* $timer = React\Promise\Timer\sleep(2.0);
*
* $timer->cancel();
* ```
*
* @param float $time
* @param ?LoopInterface $loop
* @return PromiseInterface<void, \RuntimeException>
*/
function sleep($time, LoopInterface $loop = null)
{
if ($loop === null) {
$loop = Loop::get();
}
$timer = null;
return new Promise(function ($resolve) use($loop, $time, &$timer) {
// resolve the promise when the timer fires in $time seconds
$timer = $loop->addTimer($time, function () use($resolve) {
$resolve(null);
});
}, function () use(&$timer, $loop) {
// cancelling this promise will cancel the timer, clean the reference
// in order to avoid garbage references in call stack and then reject.
$loop->cancelTimer($timer);
$timer = null;
throw new \RuntimeException('Timer cancelled');
});
}
/**
* [Deprecated] Create a new promise that resolves in `$time` seconds with the `$time` as the fulfillment value.
*
* ```php
* React\Promise\Timer\resolve(1.5)->then(function ($time) {
* echo 'Thanks for waiting ' . $time . ' seconds' . PHP_EOL;
* });
* ```
*
* Internally, the given `$time` value will be used to start a timer that will
* resolve the promise once it triggers. This implies that if you pass a really
* small (or negative) value, it will still start a timer and will thus trigger
* at the earliest possible time in the future.
*
* This function takes an optional `LoopInterface|null $loop` parameter that can be used to
* pass the event loop instance to use. You can use a `null` value here in order to
* use the [default loop](https://github.com/reactphp/event-loop#loop). This value
* SHOULD NOT be given unless you're sure you want to explicitly use a given event
* loop instance.
*
* The returned promise is implemented in such a way that it can be cancelled
* when it is still pending. Cancelling a pending promise will reject its value
* with a `RuntimeException` and clean up any pending timers.
*
* ```php
* $timer = React\Promise\Timer\resolve(2.0);
*
* $timer->cancel();
* ```
*
* @param float $time
* @param ?LoopInterface $loop
* @return PromiseInterface<float, \RuntimeException>
* @deprecated 1.8.0 See `sleep()` instead
* @see sleep()
*/
function resolve($time, LoopInterface $loop = null)
{
return \sleep($time, $loop)->then(function () use($time) {
return $time;
});
}
/**
* [Deprecated] Create a new promise which rejects in `$time` seconds with a `TimeoutException`.
*
* ```php
* React\Promise\Timer\reject(2.0)->then(null, function (React\Promise\Timer\TimeoutException $e) {
* echo 'Rejected after ' . $e->getTimeout() . ' seconds ' . PHP_EOL;
* });
* ```
*
* Internally, the given `$time` value will be used to start a timer that will
* reject the promise once it triggers. This implies that if you pass a really
* small (or negative) value, it will still start a timer and will thus trigger
* at the earliest possible time in the future.
*
* This function takes an optional `LoopInterface|null $loop` parameter that can be used to
* pass the event loop instance to use. You can use a `null` value here in order to
* use the [default loop](https://github.com/reactphp/event-loop#loop). This value
* SHOULD NOT be given unless you're sure you want to explicitly use a given event
* loop instance.
*
* The returned promise is implemented in such a way that it can be cancelled
* when it is still pending. Cancelling a pending promise will reject its value
* with a `RuntimeException` and clean up any pending timers.
*
* ```php
* $timer = React\Promise\Timer\reject(2.0);
*
* $timer->cancel();
* ```
*
* @param float $time
* @param LoopInterface $loop
* @return PromiseInterface<void, TimeoutException|\RuntimeException>
* @deprecated 1.8.0 See `sleep()` instead
* @see sleep()
*/
function reject($time, LoopInterface $loop = null)
{
return \sleep($time, $loop)->then(function () use($time) {
throw new TimeoutException($time, 'Timer expired after ' . $time . ' seconds');
});
}

View File

@ -1,7 +0,0 @@
<?php
namespace RectorPrefix202306\React\Promise\Timer;
if (!\function_exists('RectorPrefix202306\\React\\Promise\\Timer\\timeout')) {
require __DIR__ . '/functions.php';
}

View File

@ -1,5 +1,16 @@
# Changelog
## 1.13.0 (2023-06-07)
* Feature: Include timeout logic to avoid dependency on reactphp/promise-timer.
(#305 by @clue)
* Feature: Improve errno detection for failed connections without `ext-sockets`.
(#304 by @clue)
* Improve test suite, clean up leftover `.sock` files and report failed assertions.
(#299, #300, #301 and #306 by @clue)
## 1.12.0 (2022-08-25)
* Feature: Forward compatibility with react/promise 3.

View File

@ -1494,7 +1494,7 @@ This project follows [SemVer](https://semver.org/).
This will install the latest supported version:
```bash
composer require react/socket:^1.12
composer require react/socket:^1.13
```
See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades.

View File

@ -34,16 +34,16 @@
"require": {
"php": ">=5.3.0",
"evenement\/evenement": "^3.0 || ^2.0 || ^1.0",
"react\/dns": "^1.8",
"react\/dns": "^1.11",
"react\/event-loop": "^1.2",
"react\/promise": "^3 || ^2.6 || ^1.2.1",
"react\/promise-timer": "^1.9",
"react\/stream": "^1.2"
},
"require-dev": {
"phpunit\/phpunit": "^9.3 || ^5.7 || ^4.8.35",
"phpunit\/phpunit": "^9.5 || ^5.7 || ^4.8.35",
"react\/async": "^4 || ^3 || ^2",
"react\/promise-stream": "^1.4"
"react\/promise-stream": "^1.4",
"react\/promise-timer": "^1.9"
},
"autoload": {
"psr-4": {

View File

@ -125,7 +125,7 @@ final class Connector implements ConnectorInterface
$scheme = (string) \substr($uri, 0, \strpos($uri, '://'));
}
if (!isset($this->connectors[$scheme])) {
return \RectorPrefix202306\React\Promise\reject(new \RuntimeException('No connector available for URI scheme "' . $scheme . '" (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : 22));
return \RectorPrefix202306\React\Promise\reject(new \RuntimeException('No connector available for URI scheme "' . $scheme . '" (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)));
}
return $this->connectors[$scheme]->connect($uri);
}

View File

@ -27,7 +27,7 @@ final class DnsConnector implements ConnectorInterface
$parts = \parse_url($uri);
}
if (!$parts || !isset($parts['host'])) {
return Promise\reject(new \InvalidArgumentException('Given URI "' . $original . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : 22));
return Promise\reject(new \InvalidArgumentException('Given URI "' . $original . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)));
}
$host = \trim($parts['host'], '[]');
$connector = $this->connector;

View File

@ -79,7 +79,7 @@ final class FdServer extends EventEmitter implements ServerInterface
$fd = (int) $m[1];
}
if (!\is_int($fd) || $fd < 0 || $fd >= \PHP_INT_MAX) {
throw new \InvalidArgumentException('Invalid FD number given (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : 22);
throw new \InvalidArgumentException('Invalid FD number given (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22));
}
$this->loop = $loop ?: Loop::get();
$errno = 0;

View File

@ -38,7 +38,7 @@ final class HappyEyeBallsConnector implements ConnectorInterface
$parts = \parse_url($uri);
}
if (!$parts || !isset($parts['host'])) {
return Promise\reject(new \InvalidArgumentException('Given URI "' . $original . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : 22));
return Promise\reject(new \InvalidArgumentException('Given URI "' . $original . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)));
}
$host = \trim($parts['host'], '[]');
// skip DNS lookup / URI manipulation if this URI already contains an IP

View File

@ -30,7 +30,7 @@ final class SecureConnector implements ConnectorInterface
}
$parts = \parse_url($uri);
if (!$parts || !isset($parts['scheme']) || $parts['scheme'] !== 'tls') {
return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : 22));
return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)));
}
$context = $this->context;
$encryption = $this->streamEncryption;

View File

@ -44,7 +44,7 @@ final class SocketServer extends EventEmitter implements ServerInterface
$server = new FdServer($uri, $loop);
} else {
if (\preg_match('#^(?:\\w+://)?\\d+$#', $uri)) {
throw new \InvalidArgumentException('Invalid URI given (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : 22);
throw new \InvalidArgumentException('Invalid URI given (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22));
}
$server = new TcpServer(\str_replace('tls://', '', $uri), $loop, $context['tcp']);
if ($scheme === 'tls') {
@ -107,24 +107,39 @@ final class SocketServer extends EventEmitter implements ServerInterface
* The errno and errstr values describes the type of error that has been
* encountered. This method tries to look up the given errstr and find a
* matching errno value which can be useful to provide more context to error
* messages. It goes through the list of known errno constants when
* ext-sockets is available to find an errno matching the given errstr.
* messages. It goes through the list of known errno constants when either
* `ext-sockets`, `ext-posix` or `ext-pcntl` is available to find an errno
* matching the given errstr.
*
* @param string $errstr
* @return int errno value (e.g. value of `SOCKET_ECONNREFUSED`) or 0 if not found
* @internal
* @copyright Copyright (c) 2018 Christian Lück, taken from https://github.com/clue/errno with permission
* @copyright Copyright (c) 2023 Christian Lück, taken from https://github.com/clue/errno with permission
* @codeCoverageIgnore
*/
public static function errno($errstr)
{
if (\function_exists('socket_strerror')) {
// PHP defines the required `strerror()` function through either `ext-sockets`, `ext-posix` or `ext-pcntl`
$strerror = \function_exists('socket_strerror') ? 'socket_strerror' : (\function_exists('posix_strerror') ? 'posix_strerror' : (\function_exists('pcntl_strerror') ? 'pcntl_strerror' : null));
if ($strerror !== null) {
\assert(\is_string($strerror) && \is_callable($strerror));
// PHP defines most useful errno constants like `ECONNREFUSED` through constants in `ext-sockets` like `SOCKET_ECONNREFUSED`
// PHP also defines a hand full of errno constants like `EMFILE` through constants in `ext-pcntl` like `PCNTL_EMFILE`
// go through list of all defined constants like `SOCKET_E*` and `PCNTL_E*` and see if they match the given `$errstr`
foreach (\get_defined_constants(\false) as $name => $value) {
if (\strpos($name, 'SOCKET_E') === 0 && \socket_strerror($value) === $errstr) {
if (\is_int($value) && (\strpos($name, 'SOCKET_E') === 0 || \strpos($name, 'PCNTL_E') === 0) && $strerror($value) === $errstr) {
return $value;
}
}
// if we reach this, no matching errno constant could be found (unlikely when `ext-sockets` is available)
// go through list of all possible errno values from 1 to `MAX_ERRNO` and see if they match the given `$errstr`
for ($errno = 1, $max = \defined('RectorPrefix202306\\MAX_ERRNO') ? \RectorPrefix202306\MAX_ERRNO : 4095; $errno <= $max; ++$errno) {
if ($strerror($errno) === $errstr) {
return $errno;
}
}
}
// if we reach this, no matching errno value could be found (unlikely when either `ext-sockets`, `ext-posix` or `ext-pcntl` is available)
return 0;
}
/**
@ -134,8 +149,8 @@ final class SocketServer extends EventEmitter implements ServerInterface
* This method tries to look up the given errno value and find a matching
* errno constant name which can be useful to provide more context and more
* descriptive error messages. It goes through the list of known errno
* constants when ext-sockets is available to find the matching errno
* constant name.
* constants when either `ext-sockets` or `ext-pcntl` is available to find
* the matching errno constant name.
*
* Because this method is used to append more context to error messages, the
* constant name will be prefixed with a space and put between parenthesis
@ -144,18 +159,20 @@ final class SocketServer extends EventEmitter implements ServerInterface
* @param int $errno
* @return string e.g. ` (ECONNREFUSED)` or empty string if no matching const for the given errno could be found
* @internal
* @copyright Copyright (c) 2018 Christian Lück, taken from https://github.com/clue/errno with permission
* @copyright Copyright (c) 2023 Christian Lück, taken from https://github.com/clue/errno with permission
* @codeCoverageIgnore
*/
public static function errconst($errno)
{
if (\function_exists('socket_strerror')) {
foreach (\get_defined_constants(\false) as $name => $value) {
if ($value === $errno && \strpos($name, 'SOCKET_E') === 0) {
return ' (' . \substr($name, 7) . ')';
}
// PHP defines most useful errno constants like `ECONNREFUSED` through constants in `ext-sockets` like `SOCKET_ECONNREFUSED`
// PHP also defines a hand full of errno constants like `EMFILE` through constants in `ext-pcntl` like `PCNTL_EMFILE`
// go through list of all defined constants like `SOCKET_E*` and `PCNTL_E*` and see if they match the given `$errno`
foreach (\get_defined_constants(\false) as $name => $value) {
if ($value === $errno && (\strpos($name, 'SOCKET_E') === 0 || \strpos($name, 'PCNTL_E') === 0)) {
return ' (' . \substr($name, \strpos($name, '_') + 1) . ')';
}
}
// if we reach this, no matching errno constant could be found (unlikely when `ext-sockets` is available)
return '';
}
}

View File

@ -23,11 +23,11 @@ final class TcpConnector implements ConnectorInterface
}
$parts = \parse_url($uri);
if (!$parts || !isset($parts['scheme'], $parts['host'], $parts['port']) || $parts['scheme'] !== 'tcp') {
return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : 22));
return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)));
}
$ip = \trim($parts['host'], '[]');
if (@\inet_pton($ip) === \false) {
return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" does not contain a valid host IP (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : 22));
return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" does not contain a valid host IP (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)));
}
// use context given in constructor
$context = array('socket' => $this->context);

View File

@ -148,10 +148,10 @@ final class TcpServer extends EventEmitter implements ServerInterface
}
// ensure URI contains TCP scheme, host and port
if (!$parts || !isset($parts['scheme'], $parts['host'], $parts['port']) || $parts['scheme'] !== 'tcp') {
throw new \InvalidArgumentException('Invalid URI "' . $uri . '" given (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : 22);
throw new \InvalidArgumentException('Invalid URI "' . $uri . '" given (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22));
}
if (@\inet_pton(\trim($parts['host'], '[]')) === \false) {
throw new \InvalidArgumentException('Given URI "' . $uri . '" does not contain a valid host IP (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : 22);
throw new \InvalidArgumentException('Given URI "' . $uri . '" does not contain a valid host IP (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22));
}
$this->master = @\stream_socket_server($uri, $errno, $errstr, \STREAM_SERVER_BIND | \STREAM_SERVER_LISTEN, \stream_context_create(array('socket' => $context + array('backlog' => 511))));
if (\false === $this->master) {

View File

@ -4,8 +4,7 @@ namespace RectorPrefix202306\React\Socket;
use RectorPrefix202306\React\EventLoop\Loop;
use RectorPrefix202306\React\EventLoop\LoopInterface;
use RectorPrefix202306\React\Promise\Timer;
use RectorPrefix202306\React\Promise\Timer\TimeoutException;
use RectorPrefix202306\React\Promise\Promise;
final class TimeoutConnector implements ConnectorInterface
{
private $connector;
@ -19,25 +18,43 @@ final class TimeoutConnector implements ConnectorInterface
}
public function connect($uri)
{
return Timer\timeout($this->connector->connect($uri), $this->timeout, $this->loop)->then(null, self::handler($uri));
}
/**
* Creates a static rejection handler that reports a proper error message in case of a timeout.
*
* This uses a private static helper method to ensure this closure is not
* bound to this instance and the exception trace does not include a
* reference to this instance and its connector stack as a result.
*
* @param string $uri
* @return callable
*/
private static function handler($uri)
{
return function (\Exception $e) use($uri) {
if ($e instanceof TimeoutException) {
throw new \RuntimeException('Connection to ' . $uri . ' timed out after ' . $e->getTimeout() . ' seconds (ETIMEDOUT)', \defined('SOCKET_ETIMEDOUT') ? \SOCKET_ETIMEDOUT : 110);
$promise = $this->connector->connect($uri);
$loop = $this->loop;
$time = $this->timeout;
return new Promise(function ($resolve, $reject) use($loop, $time, $promise, $uri) {
$timer = null;
$promise = $promise->then(function ($v) use(&$timer, $loop, $resolve) {
if ($timer) {
$loop->cancelTimer($timer);
}
$timer = \false;
$resolve($v);
}, function ($v) use(&$timer, $loop, $reject) {
if ($timer) {
$loop->cancelTimer($timer);
}
$timer = \false;
$reject($v);
});
// promise already resolved => no need to start timer
if ($timer === \false) {
return;
}
throw $e;
};
// start timeout timer which will cancel the pending promise
$timer = $loop->addTimer($time, function () use($time, &$promise, $reject, $uri) {
$reject(new \RuntimeException('Connection to ' . $uri . ' timed out after ' . $time . ' seconds (ETIMEDOUT)', \defined('SOCKET_ETIMEDOUT') ? \SOCKET_ETIMEDOUT : 110));
// Cancel pending connection to clean up any underlying resources and references.
// Avoid garbage references in call stack by passing pending promise by reference.
\assert(\method_exists($promise, 'cancel'));
$promise->cancel();
$promise = null;
});
}, function () use(&$promise) {
// Cancelling this promise will cancel the pending connection, thus triggering the rejection logic above.
// Avoid garbage references in call stack by passing pending promise by reference.
\assert(\method_exists($promise, 'cancel'));
$promise->cancel();
$promise = null;
});
}
}

View File

@ -25,7 +25,7 @@ final class UnixConnector implements ConnectorInterface
if (\strpos($path, '://') === \false) {
$path = 'unix://' . $path;
} elseif (\substr($path, 0, 7) !== 'unix://') {
return Promise\reject(new \InvalidArgumentException('Given URI "' . $path . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : 22));
return Promise\reject(new \InvalidArgumentException('Given URI "' . $path . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)));
}
$resource = @\stream_socket_client($path, $errno, $errstr, 1.0);
if (!$resource) {

View File

@ -54,7 +54,7 @@ final class UnixServer extends EventEmitter implements ServerInterface
if (\strpos($path, '://') === \false) {
$path = 'unix://' . $path;
} elseif (\substr($path, 0, 7) !== 'unix://') {
throw new \InvalidArgumentException('Given URI "' . $path . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : 22);
throw new \InvalidArgumentException('Given URI "' . $path . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22));
}
$errno = 0;
$errstr = '';