repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Expr/BinaryOp/Mul.php | lib/PhpParser/Node/Expr/BinaryOp/Mul.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\BinaryOp;
class Mul extends BinaryOp {
public function getOperatorSigil(): string {
return '*';
}
public function getType(): string {
return 'Expr_BinaryOp_Mul';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Expr/BinaryOp/BitwiseXor.php | lib/PhpParser/Node/Expr/BinaryOp/BitwiseXor.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\BinaryOp;
class BitwiseXor extends BinaryOp {
public function getOperatorSigil(): string {
return '^';
}
public function getType(): string {
return 'Expr_BinaryOp_BitwiseXor';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Expr/BinaryOp/LogicalAnd.php | lib/PhpParser/Node/Expr/BinaryOp/LogicalAnd.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\BinaryOp;
class LogicalAnd extends BinaryOp {
public function getOperatorSigil(): string {
return 'and';
}
public function getType(): string {
return 'Expr_BinaryOp_LogicalAnd';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Expr/BinaryOp/Greater.php | lib/PhpParser/Node/Expr/BinaryOp/Greater.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\BinaryOp;
class Greater extends BinaryOp {
public function getOperatorSigil(): string {
return '>';
}
public function getType(): string {
return 'Expr_BinaryOp_Greater';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Expr/BinaryOp/ShiftLeft.php | lib/PhpParser/Node/Expr/BinaryOp/ShiftLeft.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\BinaryOp;
class ShiftLeft extends BinaryOp {
public function getOperatorSigil(): string {
return '<<';
}
public function getType(): string {
return 'Expr_BinaryOp_ShiftLeft';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Expr/BinaryOp/Identical.php | lib/PhpParser/Node/Expr/BinaryOp/Identical.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\BinaryOp;
class Identical extends BinaryOp {
public function getOperatorSigil(): string {
return '===';
}
public function getType(): string {
return 'Expr_BinaryOp_Identical';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Expr/BinaryOp/Pipe.php | lib/PhpParser/Node/Expr/BinaryOp/Pipe.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\BinaryOp;
class Pipe extends BinaryOp {
public function getOperatorSigil(): string {
return '|>';
}
public function getType(): string {
return 'Expr_BinaryOp_Pipe';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Expr/BinaryOp/NotEqual.php | lib/PhpParser/Node/Expr/BinaryOp/NotEqual.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\BinaryOp;
class NotEqual extends BinaryOp {
public function getOperatorSigil(): string {
return '!=';
}
public function getType(): string {
return 'Expr_BinaryOp_NotEqual';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Expr/BinaryOp/BooleanAnd.php | lib/PhpParser/Node/Expr/BinaryOp/BooleanAnd.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\BinaryOp;
class BooleanAnd extends BinaryOp {
public function getOperatorSigil(): string {
return '&&';
}
public function getType(): string {
return 'Expr_BinaryOp_BooleanAnd';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Expr/BinaryOp/Pow.php | lib/PhpParser/Node/Expr/BinaryOp/Pow.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\BinaryOp;
class Pow extends BinaryOp {
public function getOperatorSigil(): string {
return '**';
}
public function getType(): string {
return 'Expr_BinaryOp_Pow';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Expr/BinaryOp/Concat.php | lib/PhpParser/Node/Expr/BinaryOp/Concat.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\BinaryOp;
class Concat extends BinaryOp {
public function getOperatorSigil(): string {
return '.';
}
public function getType(): string {
return 'Expr_BinaryOp_Concat';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Expr/BinaryOp/Coalesce.php | lib/PhpParser/Node/Expr/BinaryOp/Coalesce.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\BinaryOp;
class Coalesce extends BinaryOp {
public function getOperatorSigil(): string {
return '??';
}
public function getType(): string {
return 'Expr_BinaryOp_Coalesce';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/Float_.php | lib/PhpParser/Node/Scalar/Float_.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar;
use PhpParser\Node\Scalar;
class Float_ extends Scalar {
/** @var float Number value */
public float $value;
/**
* Constructs a float number scalar node.
*
* @param float $value Value of the number
* @param array<string, mixed> $attributes Additional attributes
*/
public function __construct(float $value, array $attributes = []) {
$this->attributes = $attributes;
$this->value = $value;
}
public function getSubNodeNames(): array {
return ['value'];
}
/**
* @param mixed[] $attributes
*/
public static function fromString(string $str, array $attributes = []): Float_ {
$attributes['rawValue'] = $str;
$float = self::parse($str);
return new Float_($float, $attributes);
}
/**
* @internal
*
* Parses a DNUMBER token like PHP would.
*
* @param string $str A string number
*
* @return float The parsed number
*/
public static function parse(string $str): float {
$str = str_replace('_', '', $str);
// Check whether this is one of the special integer notations.
if ('0' === $str[0]) {
// hex
if ('x' === $str[1] || 'X' === $str[1]) {
return hexdec($str);
}
// bin
if ('b' === $str[1] || 'B' === $str[1]) {
return bindec($str);
}
// oct, but only if the string does not contain any of '.eE'.
if (false === strpbrk($str, '.eE')) {
// substr($str, 0, strcspn($str, '89')) cuts the string at the first invalid digit
// (8 or 9) so that only the digits before that are used.
return octdec(substr($str, 0, strcspn($str, '89')));
}
}
// dec
return (float) $str;
}
public function getType(): string {
return 'Scalar_Float';
}
}
// @deprecated compatibility alias
class_alias(Float_::class, DNumber::class);
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/InterpolatedString.php | lib/PhpParser/Node/Scalar/InterpolatedString.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar;
use PhpParser\Node\Expr;
use PhpParser\Node\InterpolatedStringPart;
use PhpParser\Node\Scalar;
class InterpolatedString extends Scalar {
/** @var (Expr|InterpolatedStringPart)[] list of string parts */
public array $parts;
/**
* Constructs an interpolated string node.
*
* @param (Expr|InterpolatedStringPart)[] $parts Interpolated string parts
* @param array<string, mixed> $attributes Additional attributes
*/
public function __construct(array $parts, array $attributes = []) {
$this->attributes = $attributes;
$this->parts = $parts;
}
public function getSubNodeNames(): array {
return ['parts'];
}
public function getType(): string {
return 'Scalar_InterpolatedString';
}
}
// @deprecated compatibility alias
class_alias(InterpolatedString::class, Encapsed::class);
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/EncapsedStringPart.php | lib/PhpParser/Node/Scalar/EncapsedStringPart.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar;
use PhpParser\Node\InterpolatedStringPart;
require __DIR__ . '/../InterpolatedStringPart.php';
if (false) {
/**
* For classmap-authoritative support.
*
* @deprecated use \PhpParser\Node\InterpolatedStringPart instead.
*/
class EncapsedStringPart extends InterpolatedStringPart {
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/DNumber.php | lib/PhpParser/Node/Scalar/DNumber.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar;
require __DIR__ . '/Float_.php';
if (false) {
/**
* For classmap-authoritative support.
*
* @deprecated use \PhpParser\Node\Scalar\Float_ instead.
*/
class DNumber extends Float_ {
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/String_.php | lib/PhpParser/Node/Scalar/String_.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar;
use PhpParser\Error;
use PhpParser\Node\Scalar;
class String_ extends Scalar {
/* For use in "kind" attribute */
public const KIND_SINGLE_QUOTED = 1;
public const KIND_DOUBLE_QUOTED = 2;
public const KIND_HEREDOC = 3;
public const KIND_NOWDOC = 4;
/** @var string String value */
public string $value;
/** @var array<string, string> Escaped character to its decoded value */
protected static array $replacements = [
'\\' => '\\',
'$' => '$',
'n' => "\n",
'r' => "\r",
't' => "\t",
'f' => "\f",
'v' => "\v",
'e' => "\x1B",
];
/**
* Constructs a string scalar node.
*
* @param string $value Value of the string
* @param array<string, mixed> $attributes Additional attributes
*/
public function __construct(string $value, array $attributes = []) {
$this->attributes = $attributes;
$this->value = $value;
}
public function getSubNodeNames(): array {
return ['value'];
}
/**
* @param array<string, mixed> $attributes
* @param bool $parseUnicodeEscape Whether to parse PHP 7 \u escapes
*/
public static function fromString(string $str, array $attributes = [], bool $parseUnicodeEscape = true): self {
$attributes['kind'] = ($str[0] === "'" || ($str[1] === "'" && ($str[0] === 'b' || $str[0] === 'B')))
? Scalar\String_::KIND_SINGLE_QUOTED
: Scalar\String_::KIND_DOUBLE_QUOTED;
$attributes['rawValue'] = $str;
$string = self::parse($str, $parseUnicodeEscape);
return new self($string, $attributes);
}
/**
* @internal
*
* Parses a string token.
*
* @param string $str String token content
* @param bool $parseUnicodeEscape Whether to parse PHP 7 \u escapes
*
* @return string The parsed string
*/
public static function parse(string $str, bool $parseUnicodeEscape = true): string {
$bLength = 0;
if ('b' === $str[0] || 'B' === $str[0]) {
$bLength = 1;
}
if ('\'' === $str[$bLength]) {
return str_replace(
['\\\\', '\\\''],
['\\', '\''],
substr($str, $bLength + 1, -1)
);
} else {
return self::parseEscapeSequences(
substr($str, $bLength + 1, -1), '"', $parseUnicodeEscape
);
}
}
/**
* @internal
*
* Parses escape sequences in strings (all string types apart from single quoted).
*
* @param string $str String without quotes
* @param null|string $quote Quote type
* @param bool $parseUnicodeEscape Whether to parse PHP 7 \u escapes
*
* @return string String with escape sequences parsed
*/
public static function parseEscapeSequences(string $str, ?string $quote, bool $parseUnicodeEscape = true): string {
if (null !== $quote) {
$str = str_replace('\\' . $quote, $quote, $str);
}
$extra = '';
if ($parseUnicodeEscape) {
$extra = '|u\{([0-9a-fA-F]+)\}';
}
return preg_replace_callback(
'~\\\\([\\\\$nrtfve]|[xX][0-9a-fA-F]{1,2}|[0-7]{1,3}' . $extra . ')~',
function ($matches) {
$str = $matches[1];
if (isset(self::$replacements[$str])) {
return self::$replacements[$str];
}
if ('x' === $str[0] || 'X' === $str[0]) {
return chr(hexdec(substr($str, 1)));
}
if ('u' === $str[0]) {
$dec = hexdec($matches[2]);
// If it overflowed to float, treat as INT_MAX, it will throw an error anyway.
return self::codePointToUtf8(\is_int($dec) ? $dec : \PHP_INT_MAX);
} else {
return chr(octdec($str) & 255);
}
},
$str
);
}
/**
* Converts a Unicode code point to its UTF-8 encoded representation.
*
* @param int $num Code point
*
* @return string UTF-8 representation of code point
*/
private static function codePointToUtf8(int $num): string {
if ($num <= 0x7F) {
return chr($num);
}
if ($num <= 0x7FF) {
return chr(($num >> 6) + 0xC0) . chr(($num & 0x3F) + 0x80);
}
if ($num <= 0xFFFF) {
return chr(($num >> 12) + 0xE0) . chr((($num >> 6) & 0x3F) + 0x80) . chr(($num & 0x3F) + 0x80);
}
if ($num <= 0x1FFFFF) {
return chr(($num >> 18) + 0xF0) . chr((($num >> 12) & 0x3F) + 0x80)
. chr((($num >> 6) & 0x3F) + 0x80) . chr(($num & 0x3F) + 0x80);
}
throw new Error('Invalid UTF-8 codepoint escape sequence: Codepoint too large');
}
public function getType(): string {
return 'Scalar_String';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/MagicConst.php | lib/PhpParser/Node/Scalar/MagicConst.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar;
use PhpParser\Node\Scalar;
abstract class MagicConst extends Scalar {
/**
* Constructs a magic constant node.
*
* @param array<string, mixed> $attributes Additional attributes
*/
public function __construct(array $attributes = []) {
$this->attributes = $attributes;
}
public function getSubNodeNames(): array {
return [];
}
/**
* Get name of magic constant.
*
* @return string Name of magic constant
*/
abstract public function getName(): string;
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/LNumber.php | lib/PhpParser/Node/Scalar/LNumber.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar;
require __DIR__ . '/Int_.php';
if (false) {
/**
* For classmap-authoritative support.
*
* @deprecated use \PhpParser\Node\Scalar\Int_ instead.
*/
class LNumber extends Int_ {
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/Int_.php | lib/PhpParser/Node/Scalar/Int_.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar;
use PhpParser\Error;
use PhpParser\Node\Scalar;
class Int_ extends Scalar {
/* For use in "kind" attribute */
public const KIND_BIN = 2;
public const KIND_OCT = 8;
public const KIND_DEC = 10;
public const KIND_HEX = 16;
/** @var int Number value */
public int $value;
/**
* Constructs an integer number scalar node.
*
* @param int $value Value of the number
* @param array<string, mixed> $attributes Additional attributes
*/
public function __construct(int $value, array $attributes = []) {
$this->attributes = $attributes;
$this->value = $value;
}
public function getSubNodeNames(): array {
return ['value'];
}
/**
* Constructs an Int node from a string number literal.
*
* @param string $str String number literal (decimal, octal, hex or binary)
* @param array<string, mixed> $attributes Additional attributes
* @param bool $allowInvalidOctal Whether to allow invalid octal numbers (PHP 5)
*
* @return Int_ The constructed LNumber, including kind attribute
*/
public static function fromString(string $str, array $attributes = [], bool $allowInvalidOctal = false): Int_ {
$attributes['rawValue'] = $str;
$str = str_replace('_', '', $str);
if ('0' !== $str[0] || '0' === $str) {
$attributes['kind'] = Int_::KIND_DEC;
return new Int_((int) $str, $attributes);
}
if ('x' === $str[1] || 'X' === $str[1]) {
$attributes['kind'] = Int_::KIND_HEX;
return new Int_(hexdec($str), $attributes);
}
if ('b' === $str[1] || 'B' === $str[1]) {
$attributes['kind'] = Int_::KIND_BIN;
return new Int_(bindec($str), $attributes);
}
if (!$allowInvalidOctal && strpbrk($str, '89')) {
throw new Error('Invalid numeric literal', $attributes);
}
// Strip optional explicit octal prefix.
if ('o' === $str[1] || 'O' === $str[1]) {
$str = substr($str, 2);
}
// use intval instead of octdec to get proper cutting behavior with malformed numbers
$attributes['kind'] = Int_::KIND_OCT;
return new Int_(intval($str, 8), $attributes);
}
public function getType(): string {
return 'Scalar_Int';
}
}
// @deprecated compatibility alias
class_alias(Int_::class, LNumber::class);
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/Encapsed.php | lib/PhpParser/Node/Scalar/Encapsed.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar;
require __DIR__ . '/InterpolatedString.php';
if (false) {
/**
* For classmap-authoritative support.
*
* @deprecated use \PhpParser\Node\Scalar\InterpolatedString instead.
*/
class Encapsed extends InterpolatedString {
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/MagicConst/Method.php | lib/PhpParser/Node/Scalar/MagicConst/Method.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar\MagicConst;
use PhpParser\Node\Scalar\MagicConst;
class Method extends MagicConst {
public function getName(): string {
return '__METHOD__';
}
public function getType(): string {
return 'Scalar_MagicConst_Method';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/MagicConst/Class_.php | lib/PhpParser/Node/Scalar/MagicConst/Class_.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar\MagicConst;
use PhpParser\Node\Scalar\MagicConst;
class Class_ extends MagicConst {
public function getName(): string {
return '__CLASS__';
}
public function getType(): string {
return 'Scalar_MagicConst_Class';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/MagicConst/Line.php | lib/PhpParser/Node/Scalar/MagicConst/Line.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar\MagicConst;
use PhpParser\Node\Scalar\MagicConst;
class Line extends MagicConst {
public function getName(): string {
return '__LINE__';
}
public function getType(): string {
return 'Scalar_MagicConst_Line';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/MagicConst/Property.php | lib/PhpParser/Node/Scalar/MagicConst/Property.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar\MagicConst;
use PhpParser\Node\Scalar\MagicConst;
class Property extends MagicConst {
public function getName(): string {
return '__PROPERTY__';
}
public function getType(): string {
return 'Scalar_MagicConst_Property';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/MagicConst/Namespace_.php | lib/PhpParser/Node/Scalar/MagicConst/Namespace_.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar\MagicConst;
use PhpParser\Node\Scalar\MagicConst;
class Namespace_ extends MagicConst {
public function getName(): string {
return '__NAMESPACE__';
}
public function getType(): string {
return 'Scalar_MagicConst_Namespace';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/MagicConst/File.php | lib/PhpParser/Node/Scalar/MagicConst/File.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar\MagicConst;
use PhpParser\Node\Scalar\MagicConst;
class File extends MagicConst {
public function getName(): string {
return '__FILE__';
}
public function getType(): string {
return 'Scalar_MagicConst_File';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/MagicConst/Dir.php | lib/PhpParser/Node/Scalar/MagicConst/Dir.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar\MagicConst;
use PhpParser\Node\Scalar\MagicConst;
class Dir extends MagicConst {
public function getName(): string {
return '__DIR__';
}
public function getType(): string {
return 'Scalar_MagicConst_Dir';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/MagicConst/Function_.php | lib/PhpParser/Node/Scalar/MagicConst/Function_.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar\MagicConst;
use PhpParser\Node\Scalar\MagicConst;
class Function_ extends MagicConst {
public function getName(): string {
return '__FUNCTION__';
}
public function getType(): string {
return 'Scalar_MagicConst_Function';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Node/Scalar/MagicConst/Trait_.php | lib/PhpParser/Node/Scalar/MagicConst/Trait_.php | <?php declare(strict_types=1);
namespace PhpParser\Node\Scalar\MagicConst;
use PhpParser\Node\Scalar\MagicConst;
class Trait_ extends MagicConst {
public function getName(): string {
return '__TRAIT__';
}
public function getType(): string {
return 'Scalar_MagicConst_Trait';
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Parser/Php8.php | lib/PhpParser/Parser/Php8.php | <?php declare(strict_types=1);
namespace PhpParser\Parser;
use PhpParser\Error;
use PhpParser\Modifiers;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar;
use PhpParser\Node\Stmt;
/* This is an automatically GENERATED file, which should not be manually edited.
* Instead edit one of the following:
* * the grammar file grammar/php.y
* * the skeleton file grammar/parser.template
* * the preprocessing script grammar/rebuildParsers.php
*/
class Php8 extends \PhpParser\ParserAbstract
{
public const YYERRTOK = 256;
public const T_VOID_CAST = 257;
public const T_THROW = 258;
public const T_INCLUDE = 259;
public const T_INCLUDE_ONCE = 260;
public const T_EVAL = 261;
public const T_REQUIRE = 262;
public const T_REQUIRE_ONCE = 263;
public const T_LOGICAL_OR = 264;
public const T_LOGICAL_XOR = 265;
public const T_LOGICAL_AND = 266;
public const T_PRINT = 267;
public const T_YIELD = 268;
public const T_DOUBLE_ARROW = 269;
public const T_YIELD_FROM = 270;
public const T_PLUS_EQUAL = 271;
public const T_MINUS_EQUAL = 272;
public const T_MUL_EQUAL = 273;
public const T_DIV_EQUAL = 274;
public const T_CONCAT_EQUAL = 275;
public const T_MOD_EQUAL = 276;
public const T_AND_EQUAL = 277;
public const T_OR_EQUAL = 278;
public const T_XOR_EQUAL = 279;
public const T_SL_EQUAL = 280;
public const T_SR_EQUAL = 281;
public const T_POW_EQUAL = 282;
public const T_COALESCE_EQUAL = 283;
public const T_COALESCE = 284;
public const T_BOOLEAN_OR = 285;
public const T_BOOLEAN_AND = 286;
public const T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG = 287;
public const T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG = 288;
public const T_IS_EQUAL = 289;
public const T_IS_NOT_EQUAL = 290;
public const T_IS_IDENTICAL = 291;
public const T_IS_NOT_IDENTICAL = 292;
public const T_SPACESHIP = 293;
public const T_IS_SMALLER_OR_EQUAL = 294;
public const T_IS_GREATER_OR_EQUAL = 295;
public const T_PIPE = 296;
public const T_SL = 297;
public const T_SR = 298;
public const T_INSTANCEOF = 299;
public const T_INC = 300;
public const T_DEC = 301;
public const T_INT_CAST = 302;
public const T_DOUBLE_CAST = 303;
public const T_STRING_CAST = 304;
public const T_ARRAY_CAST = 305;
public const T_OBJECT_CAST = 306;
public const T_BOOL_CAST = 307;
public const T_UNSET_CAST = 308;
public const T_POW = 309;
public const T_NEW = 310;
public const T_CLONE = 311;
public const T_EXIT = 312;
public const T_IF = 313;
public const T_ELSEIF = 314;
public const T_ELSE = 315;
public const T_ENDIF = 316;
public const T_LNUMBER = 317;
public const T_DNUMBER = 318;
public const T_STRING = 319;
public const T_STRING_VARNAME = 320;
public const T_VARIABLE = 321;
public const T_NUM_STRING = 322;
public const T_INLINE_HTML = 323;
public const T_ENCAPSED_AND_WHITESPACE = 324;
public const T_CONSTANT_ENCAPSED_STRING = 325;
public const T_ECHO = 326;
public const T_DO = 327;
public const T_WHILE = 328;
public const T_ENDWHILE = 329;
public const T_FOR = 330;
public const T_ENDFOR = 331;
public const T_FOREACH = 332;
public const T_ENDFOREACH = 333;
public const T_DECLARE = 334;
public const T_ENDDECLARE = 335;
public const T_AS = 336;
public const T_SWITCH = 337;
public const T_MATCH = 338;
public const T_ENDSWITCH = 339;
public const T_CASE = 340;
public const T_DEFAULT = 341;
public const T_BREAK = 342;
public const T_CONTINUE = 343;
public const T_GOTO = 344;
public const T_FUNCTION = 345;
public const T_FN = 346;
public const T_CONST = 347;
public const T_RETURN = 348;
public const T_TRY = 349;
public const T_CATCH = 350;
public const T_FINALLY = 351;
public const T_USE = 352;
public const T_INSTEADOF = 353;
public const T_GLOBAL = 354;
public const T_STATIC = 355;
public const T_ABSTRACT = 356;
public const T_FINAL = 357;
public const T_PRIVATE = 358;
public const T_PROTECTED = 359;
public const T_PUBLIC = 360;
public const T_READONLY = 361;
public const T_PUBLIC_SET = 362;
public const T_PROTECTED_SET = 363;
public const T_PRIVATE_SET = 364;
public const T_VAR = 365;
public const T_UNSET = 366;
public const T_ISSET = 367;
public const T_EMPTY = 368;
public const T_HALT_COMPILER = 369;
public const T_CLASS = 370;
public const T_TRAIT = 371;
public const T_INTERFACE = 372;
public const T_ENUM = 373;
public const T_EXTENDS = 374;
public const T_IMPLEMENTS = 375;
public const T_OBJECT_OPERATOR = 376;
public const T_NULLSAFE_OBJECT_OPERATOR = 377;
public const T_LIST = 378;
public const T_ARRAY = 379;
public const T_CALLABLE = 380;
public const T_CLASS_C = 381;
public const T_TRAIT_C = 382;
public const T_METHOD_C = 383;
public const T_FUNC_C = 384;
public const T_PROPERTY_C = 385;
public const T_LINE = 386;
public const T_FILE = 387;
public const T_START_HEREDOC = 388;
public const T_END_HEREDOC = 389;
public const T_DOLLAR_OPEN_CURLY_BRACES = 390;
public const T_CURLY_OPEN = 391;
public const T_PAAMAYIM_NEKUDOTAYIM = 392;
public const T_NAMESPACE = 393;
public const T_NS_C = 394;
public const T_DIR = 395;
public const T_NS_SEPARATOR = 396;
public const T_ELLIPSIS = 397;
public const T_NAME_FULLY_QUALIFIED = 398;
public const T_NAME_QUALIFIED = 399;
public const T_NAME_RELATIVE = 400;
public const T_ATTRIBUTE = 401;
protected int $tokenToSymbolMapSize = 402;
protected int $actionTableSize = 1537;
protected int $gotoTableSize = 642;
protected int $invalidSymbol = 174;
protected int $errorSymbol = 1;
protected int $defaultAction = -32766;
protected int $unexpectedTokenRule = 32767;
protected int $YY2TBLSTATE = 452;
protected int $numNonLeafStates = 767;
protected array $symbolToName = array(
"EOF",
"error",
"T_VOID_CAST",
"T_THROW",
"T_INCLUDE",
"T_INCLUDE_ONCE",
"T_EVAL",
"T_REQUIRE",
"T_REQUIRE_ONCE",
"','",
"T_LOGICAL_OR",
"T_LOGICAL_XOR",
"T_LOGICAL_AND",
"T_PRINT",
"T_YIELD",
"T_DOUBLE_ARROW",
"T_YIELD_FROM",
"'='",
"T_PLUS_EQUAL",
"T_MINUS_EQUAL",
"T_MUL_EQUAL",
"T_DIV_EQUAL",
"T_CONCAT_EQUAL",
"T_MOD_EQUAL",
"T_AND_EQUAL",
"T_OR_EQUAL",
"T_XOR_EQUAL",
"T_SL_EQUAL",
"T_SR_EQUAL",
"T_POW_EQUAL",
"T_COALESCE_EQUAL",
"'?'",
"':'",
"T_COALESCE",
"T_BOOLEAN_OR",
"T_BOOLEAN_AND",
"'|'",
"'^'",
"T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG",
"T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG",
"T_IS_EQUAL",
"T_IS_NOT_EQUAL",
"T_IS_IDENTICAL",
"T_IS_NOT_IDENTICAL",
"T_SPACESHIP",
"'<'",
"T_IS_SMALLER_OR_EQUAL",
"'>'",
"T_IS_GREATER_OR_EQUAL",
"T_PIPE",
"'.'",
"T_SL",
"T_SR",
"'+'",
"'-'",
"'*'",
"'/'",
"'%'",
"'!'",
"T_INSTANCEOF",
"'~'",
"T_INC",
"T_DEC",
"T_INT_CAST",
"T_DOUBLE_CAST",
"T_STRING_CAST",
"T_ARRAY_CAST",
"T_OBJECT_CAST",
"T_BOOL_CAST",
"T_UNSET_CAST",
"'@'",
"T_POW",
"'['",
"T_NEW",
"T_CLONE",
"T_EXIT",
"T_IF",
"T_ELSEIF",
"T_ELSE",
"T_ENDIF",
"T_LNUMBER",
"T_DNUMBER",
"T_STRING",
"T_STRING_VARNAME",
"T_VARIABLE",
"T_NUM_STRING",
"T_INLINE_HTML",
"T_ENCAPSED_AND_WHITESPACE",
"T_CONSTANT_ENCAPSED_STRING",
"T_ECHO",
"T_DO",
"T_WHILE",
"T_ENDWHILE",
"T_FOR",
"T_ENDFOR",
"T_FOREACH",
"T_ENDFOREACH",
"T_DECLARE",
"T_ENDDECLARE",
"T_AS",
"T_SWITCH",
"T_MATCH",
"T_ENDSWITCH",
"T_CASE",
"T_DEFAULT",
"T_BREAK",
"T_CONTINUE",
"T_GOTO",
"T_FUNCTION",
"T_FN",
"T_CONST",
"T_RETURN",
"T_TRY",
"T_CATCH",
"T_FINALLY",
"T_USE",
"T_INSTEADOF",
"T_GLOBAL",
"T_STATIC",
"T_ABSTRACT",
"T_FINAL",
"T_PRIVATE",
"T_PROTECTED",
"T_PUBLIC",
"T_READONLY",
"T_PUBLIC_SET",
"T_PROTECTED_SET",
"T_PRIVATE_SET",
"T_VAR",
"T_UNSET",
"T_ISSET",
"T_EMPTY",
"T_HALT_COMPILER",
"T_CLASS",
"T_TRAIT",
"T_INTERFACE",
"T_ENUM",
"T_EXTENDS",
"T_IMPLEMENTS",
"T_OBJECT_OPERATOR",
"T_NULLSAFE_OBJECT_OPERATOR",
"T_LIST",
"T_ARRAY",
"T_CALLABLE",
"T_CLASS_C",
"T_TRAIT_C",
"T_METHOD_C",
"T_FUNC_C",
"T_PROPERTY_C",
"T_LINE",
"T_FILE",
"T_START_HEREDOC",
"T_END_HEREDOC",
"T_DOLLAR_OPEN_CURLY_BRACES",
"T_CURLY_OPEN",
"T_PAAMAYIM_NEKUDOTAYIM",
"T_NAMESPACE",
"T_NS_C",
"T_DIR",
"T_NS_SEPARATOR",
"T_ELLIPSIS",
"T_NAME_FULLY_QUALIFIED",
"T_NAME_QUALIFIED",
"T_NAME_RELATIVE",
"T_ATTRIBUTE",
"';'",
"']'",
"'('",
"')'",
"'{'",
"'}'",
"'`'",
"'\"'",
"'$'"
);
protected array $tokenToSymbol = array(
0, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 58, 172, 174, 173, 57, 174, 174,
167, 168, 55, 53, 9, 54, 50, 56, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 32, 165,
45, 17, 47, 31, 70, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 72, 174, 166, 37, 174, 171, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 169, 36, 170, 60, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
174, 174, 174, 174, 174, 174, 1, 2, 3, 4,
5, 6, 7, 8, 10, 11, 12, 13, 14, 15,
16, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 33, 34, 35, 38, 39, 40,
41, 42, 43, 44, 46, 48, 49, 51, 52, 59,
61, 62, 63, 64, 65, 66, 67, 68, 69, 71,
73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
93, 94, 95, 96, 97, 98, 99, 100, 101, 102,
103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122,
123, 124, 125, 126, 127, 128, 129, 130, 131, 132,
133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, 144, 145, 146, 147, 148, 149, 150, 151, 152,
153, 154, 155, 156, 157, 158, 159, 160, 161, 162,
163, 164
);
protected array $action = array(
132, 133, 134, 582, 135, 136, 162, 779, 780, 781,
137, 41, 863,-32766, 970, 1404, -584, 974, 973, 1302,
0, 395, 396, 455, 246, 854,-32766,-32766,-32766,-32766,
-32766, 440,-32766, 27,-32766, 773, 772,-32766,-32766,-32766,
-32766, 508,-32766,-32766,-32766,-32766,-32766,-32766,-32766,-32766,
131,-32766,-32766,-32766,-32766, 437, 782, 859, 1148,-32766,
949,-32766,-32766,-32766,-32766,-32766,-32766, 972, 1385, 300,
271, 53, 398, 786, 787, 788, 789, 305, 865, 441,
-341, 39, 254, -584, -584, -195, 843, 790, 791, 792,
793, 794, 795, 796, 797, 798, 799, 819, 583, 820,
821, 822, 823, 811, 812, 353, 354, 814, 815, 800,
801, 802, 804, 805, 806, 368, 846, 847, 848, 849,
850, 584, 1062, -194, 856, 807, 808, 585, 586, 3,
831, 829, 830, 842, 826, 827, 4, 860, 587, 588,
825, 589, 590, 591, 592, 939, 593, 594, 5, 854,
-32766,-32766,-32766, 828, 595, 596,-32766, 138, 764, 132,
133, 134, 582, 135, 136, 1098, 779, 780, 781, 137,
41,-32766,-32766,-32766,-32766,-32766,-32766, -275, 1302, 613,
153, 1071, 749, 990, 991,-32766,-32766,-32766, 992,-32766,
891,-32766, 892,-32766, 773, 772,-32766, 986, 1309, 397,
396,-32766,-32766,-32766, 858, 299, 630,-32766,-32766, 440,
502, 736,-32766,-32766, 437, 782,-32767,-32767,-32767,-32767,
106, 107, 108, 109, 951,-32766, 1021, 29, 734, 271,
53, 398, 786, 787, 788, 789, 144, 1071, 441, -341,
332, 38, 864, 862, -195, 843, 790, 791, 792, 793,
794, 795, 796, 797, 798, 799, 819, 583, 820, 821,
822, 823, 811, 812, 353, 354, 814, 815, 800, 801,
802, 804, 805, 806, 368, 846, 847, 848, 849, 850,
584, 863, -194, 139, 807, 808, 585, 586, 323, 831,
829, 830, 842, 826, 827, 1370, 148, 587, 588, 825,
589, 590, 591, 592, 245, 593, 594, 395, 396,-32766,
-32766,-32766, 828, 595, 596, -85, 138, 440, 132, 133,
134, 582, 135, 136, 1095, 779, 780, 781, 137, 41,
-32766,-32766,-32766,-32766,-32766, 51, 578, 1302, 257,-32766,
636, 107, 108, 109,-32766,-32766,-32766, 503,-32766, 316,
-32766,-32766,-32766, 773, 772,-32766, -383, 166, -383, 1022,
-32766,-32766,-32766, 305, 79, 1133,-32766,-32766, 1414, 762,
332, 1415,-32766, 437, 782,-32766, 1071, 110, 111, 112,
113, 114, -85, 283,-32766, 477, 478, 479, 271, 53,
398, 786, 787, 788, 789, 115, 407, 441, 10,-32766,
299, 1341, 306, 307, 843, 790, 791, 792, 793, 794,
795, 796, 797, 798, 799, 819, 583, 820, 821, 822,
823, 811, 812, 353, 354, 814, 815, 800, 801, 802,
804, 805, 806, 368, 846, 847, 848, 849, 850, 584,
320, 1068, -582, 807, 808, 585, 586, 1389, 831, 829,
830, 842, 826, 827, 329, 1388, 587, 588, 825, 589,
590, 591, 592, 86, 593, 594, 1071, 332,-32766,-32766,
-32766, 828, 595, 596, 349, 151, -581, 132, 133, 134,
582, 135, 136, 1100, 779, 780, 781, 137, 41,-32766,
290,-32766,-32766,-32766,-32766,-32766,-32766,-32766,-32767,-32767,
-32767,-32767,-32767,-32766,-32766,-32766, 891, 1175, 892, -582,
-582, 754, 773, 772, 1159, 1160, 1161, 1155, 1154, 1153,
1162, 1156, 1157, 1158,-32766, -582,-32766,-32766,-32766,-32766,
-32766,-32766,-32766, 782,-32766,-32766,-32766, -588, -78,-32766,
-32766,-32766, 350, -581, -581,-32766,-32766, 271, 53, 398,
786, 787, 788, 789, 383,-32766, 441,-32766,-32766, -581,
-32766, 773, 772, 843, 790, 791, 792, 793, 794, 795,
796, 797, 798, 799, 819, 583, 820, 821, 822, 823,
811, 812, 353, 354, 814, 815, 800, 801, 802, 804,
805, 806, 368, 846, 847, 848, 849, 850, 584, -620,
1068, -620, 807, 808, 585, 586, 389, 831, 829, 830,
842, 826, 827, 441, 405, 587, 588, 825, 589, 590,
591, 592, 333, 593, 594, 1071, 87, 88, 89, 459,
828, 595, 596, 460, 151, 803, 774, 775, 776, 777,
778, 854, 779, 780, 781, 816, 817, 40, 461, 90,
91, 92, 93, 94, 95, 96, 97, 98, 99, 100,
101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
111, 112, 113, 114, 462, 283, 1329, 1159, 1160, 1161,
1155, 1154, 1153, 1162, 1156, 1157, 1158, 115, 869, 488,
489, 782, 1304, 1303, 1305, 108, 109, 1132, 154,-32766,
-32766, 1134, 679, 23, 156, 783, 784, 785, 786, 787,
788, 789, 698, 699, 852, 152, 423, -580, 393, 394,
157, 843, 790, 791, 792, 793, 794, 795, 796, 797,
798, 799, 819, 841, 820, 821, 822, 823, 811, 812,
813, 840, 814, 815, 800, 801, 802, 804, 805, 806,
845, 846, 847, 848, 849, 850, 851, 1094, -578, 863,
807, 808, 809, 810, -58, 831, 829, 830, 842, 826,
827, 399, 400, 818, 824, 825, 832, 833, 835, 834,
294, 836, 837, 158, -580, -580, 160, 294, 828, 839,
838, 54, 55, 56, 57, 534, 58, 59, 36, -110,
-580, -57, 60, 61, -110, 62, -110, 670, 671, 129,
130, 312, -587, 140, -110, -110, -110, -110, -110, -110,
-110, -110, -110, -110, -110, -578, -578, 141, 147, 949,
161, 712, -87, 163, 164, 165, -84, 949, -78, -73,
-72, -578, 63, 64, 143, -309, -71, 65, 332, 66,
251, 252, 67, 68, 69, 70, 71, 72, 73, 74,
739, 31, 276, 47, 457, 535, -357, 713, 740, 1335,
1336, 536, -70, 863, 1068, -69, -68, 1333, 45, 22,
537, 949, 538, -67, 539, -66, 540, 52, -65, 541,
542, 714, 715, -46, 48, 49, 463, 392, 391, 1071,
50, 543, -18, 145, 281, 1302, 381, 348, 291, 750,
1304, 1303, 1305, 1295, 939, 753, 290, 948, 545, 546,
547, 150, 939, 290, -305, 295, 288, 289, 292, 293,
549, 550, 338, 1321, 1322, 1323, 1324, 1326, 1318, 1319,
304, 1300, 296, 301, 302, 283, 1325, 1320, 773, 772,
1304, 1303, 1305, 305, 308, 309, 75, -154, -154, -154,
327, 328, 332, 966, 854, 1070, 939, 149, 115, 1416,
388, 680, -154, 708, -154, 725, -154, 13, -154, 668,
723, 313, 31, 277, 1304, 1303, 1305, 863, 390,-32766,
600, 1166, 987, 951, 863, 310, 701, 734, 1333, 990,
991, 951,-32766, 686, 544, 734, 949, 685, 606, 1340,
485, 513, 925, 986, -110, -110, -110, 35, 116, 117,
118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
128, 702, 949, 634, 1295, 773, 772, 741, -579, 305,
-614, 1334, 0, 0, 0, 951, 311, 949, 0, 734,
-154, 549, 550, 319, 1321, 1322, 1323, 1324, 1326, 1318,
1319, 1209, 1211, 744, 0, 1342, 0, 1325, 1320, -544,
-534, 0, -578,-32766, -4, 949, 11, 77, 751, 1302,
30, 387, 328, 332, 862, 43,-32766,-32766,-32766, -613,
-32766, 939,-32766, 968,-32766, 44, 759,-32766, 1330, 773,
772, 760,-32766,-32766,-32766, -579, -579, 882,-32766,-32766,
930, 1031, 1008, 1015,-32766, 437, 1005, 939, 1016, 928,
1003, -579, 1137, 1140, 1141, 1138,-32766, 1177, 1139, 1145,
37, 874, 939, -586, 1357, 1374, 1407,-32766, 673, -578,
-578, -612, -588, 1302, -587, -586, -585, 31, 276, -528,
-32766,-32766,-32766, 1,-32766, -578,-32766, 78,-32766, 863,
939,-32766, 32, 1333, -278, 33,-32766,-32766,-32766, 42,
1007, 46,-32766,-32766, 734, 76, 80, 81,-32766, 437,
82, 83, 390, 84, 453, 31, 277, 85, 146, 303,
-32766, 155, 159, 990, 991, 249, 951, 863, 544, 1295,
734, 1333, 334, 369, 370, 371, 548, 986, -110, -110,
-110, 951, 372, 326, 373, 734, 374, 550, 375, 1321,
1322, 1323, 1324, 1326, 1318, 1319, 376, 377, 422, 378,
21, -50, 1325, 1320, 379, 382, 454, 1295, 577, 951,
380, 384, 77, 734, -4, -276, -275, 328, 332, 15,
16, 17, 18, 20, 363, 550, 421, 1321, 1322, 1323,
1324, 1326, 1318, 1319, 142, 504, 505, 512, 515, 516,
1325, 1320, 949, 517, 518,-32766, 522, 523, 524, 531,
77, 1302, 611, 718, 1101, 328, 332, 1097,-32766,-32766,
-32766, 1250,-32766, 1331,-32766, 949,-32766, 1099, 1096,-32766,
1077, 1290, 1309, 1073,-32766,-32766,-32766, -280,-32766, -102,
-32766,-32766, 14, 19, 1302, 24,-32766, 437, 323, 420,
625,-32766,-32766,-32766, 631,-32766, 659,-32766,-32766,-32766,
724, 1254,-32766, -16, 1308, 1251, 1386,-32766,-32766,-32766,
735,-32766, 738,-32766,-32766, 742, 743, 1302, 745,-32766,
437, 746, 747, 748,-32766,-32766,-32766, 939,-32766, 300,
-32766,-32766,-32766, 752, 1309,-32766, 764, 737, 332, 765,
-32766,-32766,-32766, -253, -253, -253,-32766,-32766, 426, 390,
939, 756,-32766, 437, 926, 863, 1411, 1413, 885, 884,
990, 991, 980, 1023,-32766, 544, -252, -252, -252, 1412,
979, 977, 390, 925, 986, -110, -110, -110, 978, 981,
1283, 959, 969, 990, 991, 957, 1176, 1172, 544, 1126,
-110, -110, 1013, 1014, 657, -110, 925, 986, -110, -110,
-110, 1410, 2, 1368, -110, 1268, 951, 1383, 0, 0,
734, -253, 0,-32766, 0, 0,-32766, 863, 1059, 1054,
1053, 1052, 1058, 1055, 1056, 1057, 0, 0, 0, 951,
0, 0, 0, 734, -252, 305, 0, 0, 79, 0,
0, 1071, 0, 0, 332, 0, 0, 0, 0, 0,
0, 0, -110, -110, 0, 0, 0, -110, 0, 0,
0, 0, 0, 0, 0, 299, -110, 0, 0, 0,
0, 0, 0, 0, 0,-32766, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 305, 0, 0,
79, 0, 0, 0, 0, 0, 332
);
protected array $actionCheck = array(
3, 4, 5, 6, 7, 8, 17, 10, 11, 12,
13, 14, 84, 76, 1, 87, 72, 74, 75, 82,
0, 108, 109, 110, 15, 82, 89, 90, 91, 10,
93, 118, 95, 103, 97, 38, 39, 100, 10, 11,
12, 104, 105, 106, 107, 10, 11, 12, 111, 112,
15, 10, 11, 12, 117, 118, 59, 82, 128, 31,
1, 33, 34, 35, 36, 37, 129, 124, 1, 31,
73, 74, 75, 76, 77, 78, 79, 164, 1, 82,
9, 153, 154, 139, 140, 9, 89, 90, 91, 92,
93, 94, 95, 96, 97, 98, 99, 100, 101, 102,
103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122,
123, 124, 1, 9, 82, 128, 129, 130, 131, 9,
133, 134, 135, 136, 137, 138, 9, 162, 141, 142,
143, 144, 145, 146, 147, 86, 149, 150, 9, 82,
10, 11, 12, 156, 157, 158, 118, 160, 169, 3,
4, 5, 6, 7, 8, 168, 10, 11, 12, 13,
14, 31, 76, 33, 34, 35, 36, 168, 82, 83,
15, 143, 169, 119, 120, 89, 90, 91, 124, 93,
108, 95, 110, 97, 38, 39, 100, 133, 1, 108,
109, 105, 106, 107, 162, 167, 1, 111, 112, 118,
32, 169, 118, 117, 118, 59, 45, 46, 47, 48,
49, 50, 51, 52, 165, 129, 32, 9, 169, 73,
74, 75, 76, 77, 78, 79, 169, 143, 82, 168,
173, 9, 165, 161, 168, 89, 90, 91, 92, 93,
94, 95, 96, 97, 98, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 111, 112, 113,
114, 115, 116, 117, 118, 119, 120, 121, 122, 123,
124, 84, 168, 9, 128, 129, 130, 131, 168, 133,
134, 135, 136, 137, 138, 1, 9, 141, 142, 143,
144, 145, 146, 147, 99, 149, 150, 108, 109, 10,
11, 12, 156, 157, 158, 32, 160, 118, 3, 4,
5, 6, 7, 8, 168, 10, 11, 12, 13, 14,
31, 76, 33, 34, 35, 72, 87, 82, 9, 142,
54, 50, 51, 52, 89, 90, 91, 169, 93, 9,
95, 118, 97, 38, 39, 100, 108, 15, 110, 165,
105, 106, 107, 164, 167, 165, 111, 112, 82, 169,
173, 85, 117, 118, 59, 118, 143, 53, 54, 55,
56, 57, 99, 59, 129, 134, 135, 136, 73, 74,
75, 76, 77, 78, 79, 71, 108, 82, 110, 142,
167, 152, 139, 140, 89, 90, 91, 92, 93, 94,
95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
115, 116, 117, 118, 119, 120, 121, 122, 123, 124,
9, 118, 72, 128, 129, 130, 131, 1, 133, 134,
135, 136, 137, 138, 9, 9, 141, 142, 143, 144,
145, 146, 147, 169, 149, 150, 143, 173, 10, 11,
12, 156, 157, 158, 9, 160, 72, 3, 4, 5,
6, 7, 8, 168, 10, 11, 12, 13, 14, 31,
167, 33, 34, 35, 36, 37, 38, 39, 40, 41,
42, 43, 44, 10, 11, 12, 108, 165, 110, 139,
140, 169, 38, 39, 118, 119, 120, 121, 122, 123,
124, 125, 126, 127, 31, 155, 33, 34, 35, 36,
37, 38, 39, 59, 10, 11, 12, 167, 17, 10,
11, 12, 9, 139, 140, 10, 11, 73, 74, 75,
76, 77, 78, 79, 9, 31, 82, 33, 34, 155,
31, 38, 39, 89, 90, 91, 92, 93, 94, 95,
96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
106, 107, 108, 109, 110, 111, 112, 113, 114, 115,
116, 117, 118, 119, 120, 121, 122, 123, 124, 166,
118, 168, 128, 129, 130, 131, 9, 133, 134, 135,
136, 137, 138, 82, 9, 141, 142, 143, 144, 145,
146, 147, 72, 149, 150, 143, 10, 11, 12, 9,
156, 157, 158, 9, 160, 3, 4, 5, 6, 7,
8, 82, 10, 11, 12, 13, 14, 31, 9, 33,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
54, 55, 56, 57, 9, 59, 1, 118, 119, 120,
121, 122, 123, 124, 125, 126, 127, 71, 9, 139,
140, 59, 161, 162, 163, 51, 52, 1, 15, 53,
54, 170, 77, 78, 15, 73, 74, 75, 76, 77,
78, 79, 77, 78, 82, 103, 104, 72, 108, 109,
15, 89, 90, 91, 92, 93, 94, 95, 96, 97,
98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
118, 119, 120, 121, 122, 123, 124, 1, 72, 84,
128, 129, 130, 131, 17, 133, 134, 135, 136, 137,
138, 108, 109, 141, 142, 143, 144, 145, 146, 147,
31, 149, 150, 15, 139, 140, 15, 31, 156, 157,
158, 2, 3, 4, 5, 6, 7, 8, 15, 103,
155, 17, 13, 14, 108, 16, 110, 113, 114, 17,
17, 115, 167, 17, 118, 119, 120, 121, 122, 123,
124, 125, 126, 127, 128, 139, 140, 17, 17, 1,
17, 82, 32, 17, 17, 17, 32, 1, 32, 32,
32, 155, 53, 54, 169, 36, 32, 58, 173, 60,
61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
32, 72, 73, 74, 75, 76, 170, 118, 32, 80,
81, 82, 32, 84, 118, 32, 32, 88, 89, 90,
91, 1, 93, 32, 95, 32, 97, 72, 32, 100,
101, 142, 143, 32, 105, 106, 107, 108, 109, 143,
111, 112, 32, 32, 32, 82, 117, 118, 32, 32,
161, 162, 163, 124, 86, 32, 167, 32, 129, 130,
131, 32, 86, 167, 36, 38, 36, 36, 36, 36,
141, 142, 36, 144, 145, 146, 147, 148, 149, 150,
151, 118, 38, 38, 38, 59, 157, 158, 38, 39,
161, 162, 163, 164, 139, 140, 167, 77, 78, 79,
171, 172, 173, 39, 82, 142, 86, 72, 71, 85,
155, 92, 92, 79, 94, 94, 96, 99, 98, 115,
82, 116, 72, 73, 161, 162, 163, 84, 108, 87,
91, 84, 133, 165, 84, 137, 96, 169, 88, 119,
120, 165, 142, 102, 124, 169, 1, 98, 159, 152,
99, 99, 132, 133, 134, 135, 136, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 102, 1, 159, 124, 38, 39, 32, 72, 164,
167, 172, -1, -1, -1, 165, 138, 1, -1, 169,
170, 141, 142, 137, 144, 145, 146, 147, 148, 149,
150, 61, 62, 32, -1, 152, -1, 157, 158, 155,
155, -1, 72, 76, 0, 1, 155, 167, 32, 82,
155, 155, 172, 173, 161, 165, 89, 90, 91, 167,
93, 86, 95, 160, 97, 165, 165, 100, 166, 38,
39, 165, 105, 106, 107, 139, 140, 165, 111, 112,
165, 165, 165, 165, 117, 118, 165, 86, 165, 165,
165, 155, 165, 165, 165, 165, 129, 165, 165, 165,
169, 166, 86, 167, 166, 166, 166, 76, 166, 139,
140, 167, 167, 82, 167, 167, 167, 72, 73, 167,
89, 90, 91, 167, 93, 155, 95, 160, 97, 84,
86, 100, 167, 88, 168, 167, 105, 106, 107, 167,
165, 167, 111, 112, 169, 167, 167, 167, 117, 118,
167, 167, 108, 167, 110, 72, 73, 167, 167, 115,
129, 167, 167, 119, 120, 167, 165, 84, 124, 124,
169, 88, 167, 167, 167, 167, 132, 133, 134, 135,
136, 165, 167, 169, 167, 169, 167, 142, 167, 144,
145, 146, 147, 148, 149, 150, 167, 167, 170, 167,
156, 32, 157, 158, 167, 167, 167, 124, 167, 165,
167, 169, 167, 169, 170, 168, 168, 172, 173, 168,
168, 168, 168, 168, 168, 142, 168, 144, 145, 146,
147, 148, 149, 150, 32, 168, 168, 168, 168, 168,
157, 158, 1, 168, 168, 76, 168, 168, 168, 168,
167, 82, 168, 168, 168, 172, 173, 168, 89, 90,
91, 168, 93, 168, 95, 1, 97, 168, 168, 100,
168, 168, 1, 168, 105, 106, 107, 168, 76, 168,
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | true |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Parser/Php7.php | lib/PhpParser/Parser/Php7.php | <?php declare(strict_types=1);
namespace PhpParser\Parser;
use PhpParser\Error;
use PhpParser\Modifiers;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar;
use PhpParser\Node\Stmt;
/* This is an automatically GENERATED file, which should not be manually edited.
* Instead edit one of the following:
* * the grammar file grammar/php.y
* * the skeleton file grammar/parser.template
* * the preprocessing script grammar/rebuildParsers.php
*/
class Php7 extends \PhpParser\ParserAbstract
{
public const YYERRTOK = 256;
public const T_VOID_CAST = 257;
public const T_THROW = 258;
public const T_INCLUDE = 259;
public const T_INCLUDE_ONCE = 260;
public const T_EVAL = 261;
public const T_REQUIRE = 262;
public const T_REQUIRE_ONCE = 263;
public const T_LOGICAL_OR = 264;
public const T_LOGICAL_XOR = 265;
public const T_LOGICAL_AND = 266;
public const T_PRINT = 267;
public const T_YIELD = 268;
public const T_DOUBLE_ARROW = 269;
public const T_YIELD_FROM = 270;
public const T_PLUS_EQUAL = 271;
public const T_MINUS_EQUAL = 272;
public const T_MUL_EQUAL = 273;
public const T_DIV_EQUAL = 274;
public const T_CONCAT_EQUAL = 275;
public const T_MOD_EQUAL = 276;
public const T_AND_EQUAL = 277;
public const T_OR_EQUAL = 278;
public const T_XOR_EQUAL = 279;
public const T_SL_EQUAL = 280;
public const T_SR_EQUAL = 281;
public const T_POW_EQUAL = 282;
public const T_COALESCE_EQUAL = 283;
public const T_COALESCE = 284;
public const T_BOOLEAN_OR = 285;
public const T_BOOLEAN_AND = 286;
public const T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG = 287;
public const T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG = 288;
public const T_IS_EQUAL = 289;
public const T_IS_NOT_EQUAL = 290;
public const T_IS_IDENTICAL = 291;
public const T_IS_NOT_IDENTICAL = 292;
public const T_SPACESHIP = 293;
public const T_IS_SMALLER_OR_EQUAL = 294;
public const T_IS_GREATER_OR_EQUAL = 295;
public const T_SL = 296;
public const T_SR = 297;
public const T_INSTANCEOF = 298;
public const T_INC = 299;
public const T_DEC = 300;
public const T_INT_CAST = 301;
public const T_DOUBLE_CAST = 302;
public const T_STRING_CAST = 303;
public const T_ARRAY_CAST = 304;
public const T_OBJECT_CAST = 305;
public const T_BOOL_CAST = 306;
public const T_UNSET_CAST = 307;
public const T_POW = 308;
public const T_NEW = 309;
public const T_CLONE = 310;
public const T_EXIT = 311;
public const T_IF = 312;
public const T_ELSEIF = 313;
public const T_ELSE = 314;
public const T_ENDIF = 315;
public const T_LNUMBER = 316;
public const T_DNUMBER = 317;
public const T_STRING = 318;
public const T_STRING_VARNAME = 319;
public const T_VARIABLE = 320;
public const T_NUM_STRING = 321;
public const T_INLINE_HTML = 322;
public const T_ENCAPSED_AND_WHITESPACE = 323;
public const T_CONSTANT_ENCAPSED_STRING = 324;
public const T_ECHO = 325;
public const T_DO = 326;
public const T_WHILE = 327;
public const T_ENDWHILE = 328;
public const T_FOR = 329;
public const T_ENDFOR = 330;
public const T_FOREACH = 331;
public const T_ENDFOREACH = 332;
public const T_DECLARE = 333;
public const T_ENDDECLARE = 334;
public const T_AS = 335;
public const T_SWITCH = 336;
public const T_MATCH = 337;
public const T_ENDSWITCH = 338;
public const T_CASE = 339;
public const T_DEFAULT = 340;
public const T_BREAK = 341;
public const T_CONTINUE = 342;
public const T_GOTO = 343;
public const T_FUNCTION = 344;
public const T_FN = 345;
public const T_CONST = 346;
public const T_RETURN = 347;
public const T_TRY = 348;
public const T_CATCH = 349;
public const T_FINALLY = 350;
public const T_USE = 351;
public const T_INSTEADOF = 352;
public const T_GLOBAL = 353;
public const T_STATIC = 354;
public const T_ABSTRACT = 355;
public const T_FINAL = 356;
public const T_PRIVATE = 357;
public const T_PROTECTED = 358;
public const T_PUBLIC = 359;
public const T_READONLY = 360;
public const T_PUBLIC_SET = 361;
public const T_PROTECTED_SET = 362;
public const T_PRIVATE_SET = 363;
public const T_VAR = 364;
public const T_UNSET = 365;
public const T_ISSET = 366;
public const T_EMPTY = 367;
public const T_HALT_COMPILER = 368;
public const T_CLASS = 369;
public const T_TRAIT = 370;
public const T_INTERFACE = 371;
public const T_ENUM = 372;
public const T_EXTENDS = 373;
public const T_IMPLEMENTS = 374;
public const T_OBJECT_OPERATOR = 375;
public const T_NULLSAFE_OBJECT_OPERATOR = 376;
public const T_LIST = 377;
public const T_ARRAY = 378;
public const T_CALLABLE = 379;
public const T_CLASS_C = 380;
public const T_TRAIT_C = 381;
public const T_METHOD_C = 382;
public const T_FUNC_C = 383;
public const T_PROPERTY_C = 384;
public const T_LINE = 385;
public const T_FILE = 386;
public const T_START_HEREDOC = 387;
public const T_END_HEREDOC = 388;
public const T_DOLLAR_OPEN_CURLY_BRACES = 389;
public const T_CURLY_OPEN = 390;
public const T_PAAMAYIM_NEKUDOTAYIM = 391;
public const T_NAMESPACE = 392;
public const T_NS_C = 393;
public const T_DIR = 394;
public const T_NS_SEPARATOR = 395;
public const T_ELLIPSIS = 396;
public const T_NAME_FULLY_QUALIFIED = 397;
public const T_NAME_QUALIFIED = 398;
public const T_NAME_RELATIVE = 399;
public const T_ATTRIBUTE = 400;
protected int $tokenToSymbolMapSize = 401;
protected int $actionTableSize = 1578;
protected int $gotoTableSize = 698;
protected int $invalidSymbol = 173;
protected int $errorSymbol = 1;
protected int $defaultAction = -32766;
protected int $unexpectedTokenRule = 32767;
protected int $YY2TBLSTATE = 445;
protected int $numNonLeafStates = 754;
protected array $symbolToName = array(
"EOF",
"error",
"T_VOID_CAST",
"T_THROW",
"T_INCLUDE",
"T_INCLUDE_ONCE",
"T_EVAL",
"T_REQUIRE",
"T_REQUIRE_ONCE",
"','",
"T_LOGICAL_OR",
"T_LOGICAL_XOR",
"T_LOGICAL_AND",
"T_PRINT",
"T_YIELD",
"T_DOUBLE_ARROW",
"T_YIELD_FROM",
"'='",
"T_PLUS_EQUAL",
"T_MINUS_EQUAL",
"T_MUL_EQUAL",
"T_DIV_EQUAL",
"T_CONCAT_EQUAL",
"T_MOD_EQUAL",
"T_AND_EQUAL",
"T_OR_EQUAL",
"T_XOR_EQUAL",
"T_SL_EQUAL",
"T_SR_EQUAL",
"T_POW_EQUAL",
"T_COALESCE_EQUAL",
"'?'",
"':'",
"T_COALESCE",
"T_BOOLEAN_OR",
"T_BOOLEAN_AND",
"'|'",
"'^'",
"T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG",
"T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG",
"T_IS_EQUAL",
"T_IS_NOT_EQUAL",
"T_IS_IDENTICAL",
"T_IS_NOT_IDENTICAL",
"T_SPACESHIP",
"'<'",
"T_IS_SMALLER_OR_EQUAL",
"'>'",
"T_IS_GREATER_OR_EQUAL",
"T_SL",
"T_SR",
"'+'",
"'-'",
"'.'",
"'*'",
"'/'",
"'%'",
"'!'",
"T_INSTANCEOF",
"'~'",
"T_INC",
"T_DEC",
"T_INT_CAST",
"T_DOUBLE_CAST",
"T_STRING_CAST",
"T_ARRAY_CAST",
"T_OBJECT_CAST",
"T_BOOL_CAST",
"T_UNSET_CAST",
"'@'",
"T_POW",
"'['",
"T_NEW",
"T_CLONE",
"T_EXIT",
"T_IF",
"T_ELSEIF",
"T_ELSE",
"T_ENDIF",
"T_LNUMBER",
"T_DNUMBER",
"T_STRING",
"T_STRING_VARNAME",
"T_VARIABLE",
"T_NUM_STRING",
"T_INLINE_HTML",
"T_ENCAPSED_AND_WHITESPACE",
"T_CONSTANT_ENCAPSED_STRING",
"T_ECHO",
"T_DO",
"T_WHILE",
"T_ENDWHILE",
"T_FOR",
"T_ENDFOR",
"T_FOREACH",
"T_ENDFOREACH",
"T_DECLARE",
"T_ENDDECLARE",
"T_AS",
"T_SWITCH",
"T_MATCH",
"T_ENDSWITCH",
"T_CASE",
"T_DEFAULT",
"T_BREAK",
"T_CONTINUE",
"T_GOTO",
"T_FUNCTION",
"T_FN",
"T_CONST",
"T_RETURN",
"T_TRY",
"T_CATCH",
"T_FINALLY",
"T_USE",
"T_INSTEADOF",
"T_GLOBAL",
"T_STATIC",
"T_ABSTRACT",
"T_FINAL",
"T_PRIVATE",
"T_PROTECTED",
"T_PUBLIC",
"T_READONLY",
"T_PUBLIC_SET",
"T_PROTECTED_SET",
"T_PRIVATE_SET",
"T_VAR",
"T_UNSET",
"T_ISSET",
"T_EMPTY",
"T_HALT_COMPILER",
"T_CLASS",
"T_TRAIT",
"T_INTERFACE",
"T_ENUM",
"T_EXTENDS",
"T_IMPLEMENTS",
"T_OBJECT_OPERATOR",
"T_NULLSAFE_OBJECT_OPERATOR",
"T_LIST",
"T_ARRAY",
"T_CALLABLE",
"T_CLASS_C",
"T_TRAIT_C",
"T_METHOD_C",
"T_FUNC_C",
"T_PROPERTY_C",
"T_LINE",
"T_FILE",
"T_START_HEREDOC",
"T_END_HEREDOC",
"T_DOLLAR_OPEN_CURLY_BRACES",
"T_CURLY_OPEN",
"T_PAAMAYIM_NEKUDOTAYIM",
"T_NAMESPACE",
"T_NS_C",
"T_DIR",
"T_NS_SEPARATOR",
"T_ELLIPSIS",
"T_NAME_FULLY_QUALIFIED",
"T_NAME_QUALIFIED",
"T_NAME_RELATIVE",
"T_ATTRIBUTE",
"';'",
"']'",
"'('",
"')'",
"'{'",
"'}'",
"'`'",
"'\"'",
"'$'"
);
protected array $tokenToSymbol = array(
0, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 57, 171, 173, 172, 56, 173, 173,
166, 167, 54, 51, 9, 52, 53, 55, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 32, 164,
45, 17, 47, 31, 69, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 71, 173, 165, 37, 173, 170, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 168, 36, 169, 59, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
173, 173, 173, 173, 173, 173, 1, 2, 3, 4,
5, 6, 7, 8, 10, 11, 12, 13, 14, 15,
16, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29, 30, 33, 34, 35, 38, 39, 40,
41, 42, 43, 44, 46, 48, 49, 50, 58, 60,
61, 62, 63, 64, 65, 66, 67, 68, 70, 72,
73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
93, 94, 95, 96, 97, 98, 99, 100, 101, 102,
103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122,
123, 124, 125, 126, 127, 128, 129, 130, 131, 132,
133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
143, 144, 145, 146, 147, 148, 149, 150, 151, 152,
153, 154, 155, 156, 157, 158, 159, 160, 161, 162,
163
);
protected array $action = array(
133, 134, 135, 575, 136, 137, 1049, 766, 767, 768,
138, 41, 850, -341, 495, 1390,-32766,-32766,-32766, 1008,
841, 1145, 1146, 1147, 1141, 1140, 1139, 1148, 1142, 1143,
1144,-32766,-32766,-32766, -195, 760, 759,-32766, -194,-32766,
-32766,-32766,-32766,-32766,-32766,-32766,-32767,-32767,-32767,-32767,
-32767, 0,-32766, 3, 4, 769, 1145, 1146, 1147, 1141,
1140, 1139, 1148, 1142, 1143, 1144, 388, 389, 448, 272,
53, 391, 773, 774, 775, 776, 433, 5, 434, 571,
337, 39, 254, 29, 298, 830, 777, 778, 779, 780,
781, 782, 783, 784, 785, 786, 806, 576, 807, 808,
809, 810, 798, 799, 353, 354, 801, 802, 787, 788,
789, 791, 792, 793, 364, 833, 834, 835, 836, 837,
577, -382, 306, -382, 794, 795, 578, 579, 244, 818,
816, 817, 829, 813, 814, 1313, 38, 580, 581, 812,
582, 583, 584, 585, 1325, 586, 587, 481, 482, -628,
496, 1009, 815, 588, 589, 140, 139, -628, 133, 134,
135, 575, 136, 137, 1085, 766, 767, 768, 138, 41,
-32766, -341, 1046, 1041, 1040, 1039, 1045, 1042, 1043, 1044,
-32766,-32766,-32766,-32767,-32767,-32767,-32767, 106, 107, 108,
109, 110, -195, 760, 759, 1058, -194,-32766,-32766,-32766,
149,-32766, 852,-32766,-32766,-32766,-32766,-32766,-32766,-32766,
936, 303, 257, 769,-32766,-32766,-32766, 850,-32766, 297,
-32766,-32766,-32766,-32766,-32766, 1371, 1355, 272, 53, 391,
773, 774, 775, 776, -625,-32766, 434,-32766,-32766,-32766,
-32766, 730, -625, 830, 777, 778, 779, 780, 781, 782,
783, 784, 785, 786, 806, 576, 807, 808, 809, 810,
798, 799, 353, 354, 801, 802, 787, 788, 789, 791,
792, 793, 364, 833, 834, 835, 836, 837, 577, -579,
-275, 317, 794, 795, 578, 579, -577, 818, 816, 817,
829, 813, 814, 957, 926, 580, 581, 812, 582, 583,
584, 585, 144, 586, 587, 841, 336,-32766,-32766,-32766,
815, 588, 589, -628, 139, -628, 133, 134, 135, 575,
136, 137, 1082, 766, 767, 768, 138, 41,-32766, 1375,
-32766,-32766,-32766,-32766,-32766,-32766,-32766, 1374, 629, 388,
389,-32766,-32766,-32766,-32766,-32766, -579, -579, 1081, 433,
321, 760, 759, -577, -577,-32766, 1293,-32766,-32766, 111,
112, 113, -579, 282, 843, 851, 623, 1400, 936, -577,
1401, 769, 333, 938, -585, 114, -579, 725, 294, 298,
1119, -584, 349, -577, 752, 272, 53, 391, 773, 774,
775, 776, 145, 86, 434, 306, 336, 336, -625, 731,
-625, 830, 777, 778, 779, 780, 781, 782, 783, 784,
785, 786, 806, 576, 807, 808, 809, 810, 798, 799,
353, 354, 801, 802, 787, 788, 789, 791, 792, 793,
364, 833, 834, 835, 836, 837, 577, -576, 850, -578,
794, 795, 578, 579, 845, 818, 816, 817, 829, 813,
814, 727, 926, 580, 581, 812, 582, 583, 584, 585,
740, 586, 587, 243, 1055,-32766,-32766, -85, 815, 588,
589, 878, 152, 879, 133, 134, 135, 575, 136, 137,
1087, 766, 767, 768, 138, 41, 350, 961, 960, 1058,
1058, 1058,-32766,-32766,-32766, 841,-32766, 131, 977, 978,
400, 1055, 10, 979, -576, -576, -578, -578, 378, 760,
759, 936, 973, 290, 297, 297,-32766, 846, 936, 154,
-576, 79, -578, 382, 849, 936, 1058, 336, 878, 769,
879, 938, -583, -85, -576, 725, -578, 959, 108, 109,
110, 1058, 732, 272, 53, 391, 773, 774, 775, 776,
290, 155, 434, 470, 471, 472, 735, 760, 759, 830,
777, 778, 779, 780, 781, 782, 783, 784, 785, 786,
806, 576, 807, 808, 809, 810, 798, 799, 353, 354,
801, 802, 787, 788, 789, 791, 792, 793, 364, 833,
834, 835, 836, 837, 577, 926, 434, 847, 794, 795,
578, 579, 926, 818, 816, 817, 829, 813, 814, 926,
398, 580, 581, 812, 582, 583, 584, 585, 452, 586,
587, 157, 87, 88, 89, 453, 815, 588, 589, 454,
152, 790, 761, 762, 763, 764, 765, 158, 766, 767,
768, 803, 804, 40, 27, 90, 91, 92, 93, 94,
95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
105, 106, 107, 108, 109, 110, 111, 112, 113, 1134,
282, 1055, 455,-32766, 994, 1288, 1287, 1289, 725, 390,
389, 938, 114, 856, 1120, 725, 769, 159, 938, 433,
672, 23, 725, 1118, 691, 692, 1058,-32766, 153, 416,
770, 771, 772, 773, 774, 775, 776, -78, -619, 839,
-619, -581, 386, 387, 392, 393, 830, 777, 778, 779,
780, 781, 782, 783, 784, 785, 786, 806, 828, 807,
808, 809, 810, 798, 799, 800, 827, 801, 802, 787,
788, 789, 791, 792, 793, 832, 833, 834, 835, 836,
837, 838, 161, 663, 664, 794, 795, 796, 797, 36,
818, 816, 817, 829, 813, 814, -58, -57, 805, 811,
812, 819, 820, 822, 821, -87, 823, 824, -581, -581,
128, 129, 141, 815, 826, 825, 54, 55, 56, 57,
527, 58, 59, 142, -110, 148, 162, 60, 61, -110,
62, -110, 936, 163, 164, 165, 313, 166, -581, -110,
-110, -110, -110, -110, -110, -110, -110, -110, -110, -110,
1293, -84, 953, -78, -73, -72, -71, -70, -69, -68,
-67, -66, -65, 742, -46, 63, 64, -18, -575, 1286,
146, 65, 51, 66, 251, 252, 67, 68, 69, 70,
71, 72, 73, 74, 281, 31, 273, 47, 450, 528,
291, -357, 741, 1319, 1320, 529, 744, 850, 935, 151,
295, 1317, 45, 22, 530, 1284, 531, -309, 532, -305,
533, 286, 936, 534, 535, 287, 926, 292, 48, 49,
456, 385, 384, 293, 50, 536, 342, 296, 282, 1057,
376, 348, 850, 299, 300, -575, -575, 1279, 114, 307,
308, 701, 538, 539, 540, 150, 841,-32766, 1288, 1287,
1289, -575, 850, 294, 542, 543, 1402, 1305, 1306, 1307,
1308, 1310, 1302, 1303, 305, -575, 716, -110, -110, 130,
1309, 1304, -110, 593, 1288, 1287, 1289, 306, 13, 673,
75, -110, 1152, 678, 331, 332, 336, -154, -154, -154,
-32766, 718, 694, -4, 936, 938, 926, 314, 478, 725,
506, 1324, -154, 705, -154, 679, -154, 695, -154, 974,
1326, -541, 306, 312, 311, 79, 849, 661, 383, 43,
320, 336, 37, 1252, 0, 0, 52, 0, 0, 977,
978, 0, 760, 759, 537,-32766, 0, 0, 0, 706,
0, 0, 912, 973, -110, -110, -110, 35, 115, 116,
117, 118, 119, 120, 121, 122, 123, 124, 125, 126,
127, -531, 11, 707, 708, 31, 274, 30, 380, 955,
599, -613, 306, 627, 0, 938, 0, 850, 926, 725,
-154, 1317, 1288, 1287, 1289, 44, -612, 749, 290, 750,
1194, 1196, 869, 309, 310, 917, 1018, 995, 1002, 992,
383, -575, 446, 1003, 915, 990, 1123, 304, 1126, 381,
1127, 977, 978, 1124, 1125, 1131, 537, 1279, 1314, 861,
330, 760, 759, 132, 541, 973, -110, -110, -110, 1341,
1359, 1393, 1293, 666, 542, 543, -611, 1305, 1306, 1307,
1308, 1310, 1302, 1303, -585, -584, -583, -582, 21, -525,
1309, 1304, 1, 32, 760, 759, 33, 938,-32766, -278,
77, 725, -4, -16, 1286, 332, 336, 42, -575, -575,
46,-32766,-32766,-32766, 76,-32766, 80,-32766, 81,-32766,
82, 83,-32766, 84, -575, 85, 147,-32766,-32766,-32766,
156,-32766, 160,-32766,-32766, 249, 379, 1286, -575,-32766,
430, 31, 273, 338,-32766,-32766,-32766, 365,-32766, 366,
-32766,-32766,-32766, 850, 850,-32766, 367, 1317, 368, 369,
-32766,-32766,-32766, 370, 371, 372,-32766,-32766, 373, 374,
375, 377,-32766, 430, 447, 570, 31, 274, -276, -275,
15, 16, 78, 17,-32766, 18, 20, 414, 850, -110,
-110, 497, 1317, 1279, -110, 498, 505, 508, 509, 510,
511, 515, 516, -110, 517, 525, 604, 711, 1088, 1084,
1234, 543,-32766, 1305, 1306, 1307, 1308, 1310, 1302, 1303,
1315, 1086, 1083, -50, 1064, 1274, 1309, 1304, 1279, 1060,
-280, -102, 14, 19, 306, 24, 77, 79, 415, 303,
413, 332, 336, 336, 618, 624, 543, 652, 1305, 1306,
1307, 1308, 1310, 1302, 1303, 717, 143, 1238, 1292, 1235,
1372, 1309, 1304, 726, 729, 733,-32766, 734, 736, 737,
738, 77, 1286, 419, 739, 743, 332, 336, 728,-32766,
-32766,-32766, 746,-32766, 913,-32766, 1397,-32766, 1399, 872,
-32766, 871, 967, 1010, 1398,-32766,-32766,-32766, 966,-32766,
964,-32766,-32766, 965, 968, 1286, 1267,-32766, 430, 946,
956, 944,-32766,-32766,-32766, 1000,-32766, 1001,-32766,-32766,
-32766, 650, 1396,-32766, 1353, 1342, 1360, 1369,-32766,-32766,
-32766, 1318,-32766, 336,-32766,-32766, 936, 0, 1286, 0,
-32766, 430, 0, 0, 0,-32766,-32766,-32766, 0,-32766,
0,-32766,-32766,-32766, 0, 0,-32766, 0, 0, 936,
0,-32766,-32766,-32766, 0,-32766, 0,-32766,-32766, 0,
0, 1286, 0,-32766, 430, 0, 0, 0,-32766,-32766,
-32766, 0,-32766, 0,-32766,-32766,-32766, 0, 0,-32766,
0, 0, 0, 501,-32766,-32766,-32766, 0,-32766, 0,
-32766,-32766, 0, 0, 1286, 606,-32766, 430, 0, 0,
0,-32766,-32766,-32766, 0,-32766, 0,-32766,-32766,-32766,
926, 0,-32766, 2, 0, 0, 0,-32766,-32766,-32766,
0, 0, 0,-32766,-32766, 0, -253, -253, -253,-32766,
430, 0, 383, 926, 0, 0, 0, 0, 0, 0,
0,-32766, 0, 977, 978, 0, 0, 0, 537, -252,
-252, -252, 0, 0, 0, 383, 912, 973, -110, -110,
-110, 0, 0, 0, 0, 0, 977, 978, 0, 0,
0, 537, 0, 0, 0, 0, 0, 0, 0, 912,
973, -110, -110, -110,-32766, 0, 0, 0, 0, 938,
1286, 0, 0, 725, -253, 0, 0,-32766,-32766,-32766,
0,-32766, 0,-32766, 0,-32766, 0, 0,-32766, 0,
0, 0, 938,-32766,-32766,-32766, 725, -252, 0,-32766,
-32766, 0, 0, 0, 0,-32766, 430, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,-32766
);
protected array $actionCheck = array(
3, 4, 5, 6, 7, 8, 1, 10, 11, 12,
13, 14, 83, 9, 32, 86, 10, 11, 12, 32,
81, 117, 118, 119, 120, 121, 122, 123, 124, 125,
126, 10, 11, 12, 9, 38, 39, 31, 9, 33,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
44, 0, 31, 9, 9, 58, 117, 118, 119, 120,
121, 122, 123, 124, 125, 126, 107, 108, 109, 72,
73, 74, 75, 76, 77, 78, 117, 9, 81, 86,
71, 152, 153, 9, 31, 88, 89, 90, 91, 92,
93, 94, 95, 96, 97, 98, 99, 100, 101, 102,
103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122,
123, 107, 163, 109, 127, 128, 129, 130, 15, 132,
133, 134, 135, 136, 137, 1, 9, 140, 141, 142,
143, 144, 145, 146, 151, 148, 149, 138, 139, 1,
168, 164, 155, 156, 157, 9, 159, 9, 3, 4,
5, 6, 7, 8, 167, 10, 11, 12, 13, 14,
117, 167, 119, 120, 121, 122, 123, 124, 125, 126,
10, 11, 12, 45, 46, 47, 48, 49, 50, 51,
52, 53, 167, 38, 39, 142, 167, 10, 11, 12,
9, 31, 1, 33, 34, 35, 36, 37, 38, 39,
1, 167, 9, 58, 10, 11, 12, 83, 31, 166,
33, 34, 35, 36, 37, 1, 1, 72, 73, 74,
75, 76, 77, 78, 1, 31, 81, 33, 34, 35,
36, 32, 9, 88, 89, 90, 91, 92, 93, 94,
95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
115, 116, 117, 118, 119, 120, 121, 122, 123, 71,
167, 9, 127, 128, 129, 130, 71, 132, 133, 134,
135, 136, 137, 1, 85, 140, 141, 142, 143, 144,
145, 146, 168, 148, 149, 81, 172, 10, 11, 12,
155, 156, 157, 165, 159, 167, 3, 4, 5, 6,
7, 8, 167, 10, 11, 12, 13, 14, 31, 1,
33, 34, 35, 10, 10, 11, 12, 9, 52, 107,
108, 10, 11, 12, 10, 11, 138, 139, 1, 117,
9, 38, 39, 138, 139, 31, 1, 33, 34, 54,
55, 56, 154, 58, 81, 164, 1, 81, 1, 154,
84, 58, 9, 164, 166, 70, 168, 168, 31, 31,
164, 166, 9, 168, 168, 72, 73, 74, 75, 76,
77, 78, 168, 168, 81, 163, 172, 172, 165, 32,
167, 88, 89, 90, 91, 92, 93, 94, 95, 96,
97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
107, 108, 109, 110, 111, 112, 113, 114, 115, 116,
117, 118, 119, 120, 121, 122, 123, 71, 83, 71,
127, 128, 129, 130, 161, 132, 133, 134, 135, 136,
137, 168, 85, 140, 141, 142, 143, 144, 145, 146,
168, 148, 149, 98, 117, 117, 117, 32, 155, 156,
157, 107, 159, 109, 3, 4, 5, 6, 7, 8,
167, 10, 11, 12, 13, 14, 9, 73, 74, 142,
142, 142, 10, 11, 12, 81, 141, 15, 118, 119,
107, 117, 109, 123, 138, 139, 138, 139, 9, 38,
39, 1, 132, 166, 166, 166, 117, 81, 1, 15,
154, 166, 154, 9, 160, 1, 142, 172, 107, 58,
109, 164, 166, 98, 168, 168, 168, 123, 51, 52,
53, 142, 32, 72, 73, 74, 75, 76, 77, 78,
166, 15, 81, 133, 134, 135, 32, 38, 39, 88,
89, 90, 91, 92, 93, 94, 95, 96, 97, 98,
99, 100, 101, 102, 103, 104, 105, 106, 107, 108,
109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
119, 120, 121, 122, 123, 85, 81, 161, 127, 128,
129, 130, 85, 132, 133, 134, 135, 136, 137, 85,
9, 140, 141, 142, 143, 144, 145, 146, 9, 148,
149, 15, 10, 11, 12, 9, 155, 156, 157, 9,
159, 3, 4, 5, 6, 7, 8, 15, 10, 11,
12, 13, 14, 31, 102, 33, 34, 35, 36, 37,
38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 127,
58, 117, 9, 117, 164, 160, 161, 162, 168, 107,
108, 164, 70, 9, 169, 168, 58, 15, 164, 117,
76, 77, 168, 1, 76, 77, 142, 141, 102, 103,
72, 73, 74, 75, 76, 77, 78, 17, 165, 81,
167, 71, 107, 108, 107, 108, 88, 89, 90, 91,
92, 93, 94, 95, 96, 97, 98, 99, 100, 101,
102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
122, 123, 15, 112, 113, 127, 128, 129, 130, 15,
132, 133, 134, 135, 136, 137, 17, 17, 140, 141,
142, 143, 144, 145, 146, 32, 148, 149, 138, 139,
17, 17, 17, 155, 156, 157, 2, 3, 4, 5,
6, 7, 8, 17, 102, 17, 17, 13, 14, 107,
16, 109, 1, 17, 17, 17, 114, 17, 168, 117,
118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
1, 32, 39, 32, 32, 32, 32, 32, 32, 32,
32, 32, 32, 32, 32, 51, 52, 32, 71, 81,
32, 57, 71, 59, 60, 61, 62, 63, 64, 65,
66, 67, 68, 69, 32, 71, 72, 73, 74, 75,
32, 169, 32, 79, 80, 81, 32, 83, 32, 32,
38, 87, 88, 89, 90, 117, 92, 36, 94, 36,
96, 36, 1, 99, 100, 36, 85, 36, 104, 105,
106, 107, 108, 36, 110, 111, 36, 38, 58, 141,
116, 117, 83, 38, 38, 138, 139, 123, 70, 138,
139, 78, 128, 129, 130, 71, 81, 86, 160, 161,
162, 154, 83, 31, 140, 141, 84, 143, 144, 145,
146, 147, 148, 149, 150, 168, 81, 118, 119, 168,
156, 157, 123, 90, 160, 161, 162, 163, 98, 91,
166, 132, 83, 97, 170, 171, 172, 76, 77, 78,
141, 93, 95, 0, 1, 164, 85, 115, 98, 168,
98, 151, 91, 81, 93, 101, 95, 101, 97, 132,
151, 154, 163, 137, 136, 166, 160, 114, 107, 164,
136, 172, 168, 170, -1, -1, 71, -1, -1, 118,
119, -1, 38, 39, 123, 141, -1, -1, -1, 117,
-1, -1, 131, 132, 133, 134, 135, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 154, 154, 141, 142, 71, 72, 154, 154, 159,
158, 166, 163, 158, -1, 164, -1, 83, 85, 168,
169, 87, 160, 161, 162, 164, 166, 164, 166, 164,
60, 61, 164, 138, 139, 164, 164, 164, 164, 164,
107, 71, 109, 164, 164, 164, 164, 114, 164, 154,
164, 118, 119, 164, 164, 164, 123, 123, 165, 165,
168, 38, 39, 168, 131, 132, 133, 134, 135, 165,
165, 165, 1, 165, 140, 141, 166, 143, 144, 145,
146, 147, 148, 149, 166, 166, 166, 166, 155, 166,
156, 157, 166, 166, 38, 39, 166, 164, 75, 167,
166, 168, 169, 32, 81, 171, 172, 166, 138, 139,
166, 88, 89, 90, 166, 92, 166, 94, 166, 96,
166, 166, 99, 166, 154, 166, 166, 104, 105, 106,
166, 75, 166, 110, 111, 166, 168, 81, 168, 116,
117, 71, 72, 166, 88, 89, 90, 166, 92, 166,
94, 128, 96, 83, 83, 99, 166, 87, 166, 166,
104, 105, 106, 166, 166, 166, 110, 111, 166, 166,
166, 166, 116, 117, 166, 166, 71, 72, 167, 167,
167, 167, 159, 167, 128, 167, 167, 167, 83, 118,
119, 167, 87, 123, 123, 167, 167, 167, 167, 167,
167, 167, 167, 132, 167, 167, 167, 167, 167, 167,
167, 141, 141, 143, 144, 145, 146, 147, 148, 149,
167, 167, 167, 32, 167, 167, 156, 157, 123, 167,
167, 167, 167, 167, 163, 167, 166, 166, 169, 167,
167, 171, 172, 172, 167, 167, 141, 167, 143, 144,
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | true |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/ErrorHandler/Throwing.php | lib/PhpParser/ErrorHandler/Throwing.php | <?php declare(strict_types=1);
namespace PhpParser\ErrorHandler;
use PhpParser\Error;
use PhpParser\ErrorHandler;
/**
* Error handler that handles all errors by throwing them.
*
* This is the default strategy used by all components.
*/
class Throwing implements ErrorHandler {
public function handleError(Error $error): void {
throw $error;
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/ErrorHandler/Collecting.php | lib/PhpParser/ErrorHandler/Collecting.php | <?php declare(strict_types=1);
namespace PhpParser\ErrorHandler;
use PhpParser\Error;
use PhpParser\ErrorHandler;
/**
* Error handler that collects all errors into an array.
*
* This allows graceful handling of errors.
*/
class Collecting implements ErrorHandler {
/** @var Error[] Collected errors */
private array $errors = [];
public function handleError(Error $error): void {
$this->errors[] = $error;
}
/**
* Get collected errors.
*
* @return Error[]
*/
public function getErrors(): array {
return $this->errors;
}
/**
* Check whether there are any errors.
*/
public function hasErrors(): bool {
return !empty($this->errors);
}
/**
* Reset/clear collected errors.
*/
public function clearErrors(): void {
$this->errors = [];
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Comment/Doc.php | lib/PhpParser/Comment/Doc.php | <?php declare(strict_types=1);
namespace PhpParser\Comment;
class Doc extends \PhpParser\Comment {
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Internal/TokenStream.php | lib/PhpParser/Internal/TokenStream.php | <?php declare(strict_types=1);
namespace PhpParser\Internal;
use PhpParser\Token;
/**
* Provides operations on token streams, for use by pretty printer.
*
* @internal
*/
class TokenStream {
/** @var Token[] Tokens (in PhpToken::tokenize() format) */
private array $tokens;
/** @var int[] Map from position to indentation */
private array $indentMap;
/**
* Create token stream instance.
*
* @param Token[] $tokens Tokens in PhpToken::tokenize() format
*/
public function __construct(array $tokens, int $tabWidth) {
$this->tokens = $tokens;
$this->indentMap = $this->calcIndentMap($tabWidth);
}
/**
* Whether the given position is immediately surrounded by parenthesis.
*
* @param int $startPos Start position
* @param int $endPos End position
*/
public function haveParens(int $startPos, int $endPos): bool {
return $this->haveTokenImmediatelyBefore($startPos, '(')
&& $this->haveTokenImmediatelyAfter($endPos, ')');
}
/**
* Whether the given position is immediately surrounded by braces.
*
* @param int $startPos Start position
* @param int $endPos End position
*/
public function haveBraces(int $startPos, int $endPos): bool {
return ($this->haveTokenImmediatelyBefore($startPos, '{')
|| $this->haveTokenImmediatelyBefore($startPos, T_CURLY_OPEN))
&& $this->haveTokenImmediatelyAfter($endPos, '}');
}
/**
* Check whether the position is directly preceded by a certain token type.
*
* During this check whitespace and comments are skipped.
*
* @param int $pos Position before which the token should occur
* @param int|string $expectedTokenType Token to check for
*
* @return bool Whether the expected token was found
*/
public function haveTokenImmediatelyBefore(int $pos, $expectedTokenType): bool {
$tokens = $this->tokens;
$pos--;
for (; $pos >= 0; $pos--) {
$token = $tokens[$pos];
if ($token->is($expectedTokenType)) {
return true;
}
if (!$token->isIgnorable()) {
break;
}
}
return false;
}
/**
* Check whether the position is directly followed by a certain token type.
*
* During this check whitespace and comments are skipped.
*
* @param int $pos Position after which the token should occur
* @param int|string $expectedTokenType Token to check for
*
* @return bool Whether the expected token was found
*/
public function haveTokenImmediatelyAfter(int $pos, $expectedTokenType): bool {
$tokens = $this->tokens;
$pos++;
for ($c = \count($tokens); $pos < $c; $pos++) {
$token = $tokens[$pos];
if ($token->is($expectedTokenType)) {
return true;
}
if (!$token->isIgnorable()) {
break;
}
}
return false;
}
/** @param int|string|(int|string)[] $skipTokenType */
public function skipLeft(int $pos, $skipTokenType): int {
$tokens = $this->tokens;
$pos = $this->skipLeftWhitespace($pos);
if ($skipTokenType === \T_WHITESPACE) {
return $pos;
}
if (!$tokens[$pos]->is($skipTokenType)) {
// Shouldn't happen. The skip token MUST be there
throw new \Exception('Encountered unexpected token');
}
$pos--;
return $this->skipLeftWhitespace($pos);
}
/** @param int|string|(int|string)[] $skipTokenType */
public function skipRight(int $pos, $skipTokenType): int {
$tokens = $this->tokens;
$pos = $this->skipRightWhitespace($pos);
if ($skipTokenType === \T_WHITESPACE) {
return $pos;
}
if (!$tokens[$pos]->is($skipTokenType)) {
// Shouldn't happen. The skip token MUST be there
throw new \Exception('Encountered unexpected token');
}
$pos++;
return $this->skipRightWhitespace($pos);
}
/**
* Return first non-whitespace token position smaller or equal to passed position.
*
* @param int $pos Token position
* @return int Non-whitespace token position
*/
public function skipLeftWhitespace(int $pos): int {
$tokens = $this->tokens;
for (; $pos >= 0; $pos--) {
if (!$tokens[$pos]->isIgnorable()) {
break;
}
}
return $pos;
}
/**
* Return first non-whitespace position greater or equal to passed position.
*
* @param int $pos Token position
* @return int Non-whitespace token position
*/
public function skipRightWhitespace(int $pos): int {
$tokens = $this->tokens;
for ($count = \count($tokens); $pos < $count; $pos++) {
if (!$tokens[$pos]->isIgnorable()) {
break;
}
}
return $pos;
}
/** @param int|string|(int|string)[] $findTokenType */
public function findRight(int $pos, $findTokenType): int {
$tokens = $this->tokens;
for ($count = \count($tokens); $pos < $count; $pos++) {
if ($tokens[$pos]->is($findTokenType)) {
return $pos;
}
}
return -1;
}
/**
* Whether the given position range contains a certain token type.
*
* @param int $startPos Starting position (inclusive)
* @param int $endPos Ending position (exclusive)
* @param int|string $tokenType Token type to look for
* @return bool Whether the token occurs in the given range
*/
public function haveTokenInRange(int $startPos, int $endPos, $tokenType): bool {
$tokens = $this->tokens;
for ($pos = $startPos; $pos < $endPos; $pos++) {
if ($tokens[$pos]->is($tokenType)) {
return true;
}
}
return false;
}
public function haveTagInRange(int $startPos, int $endPos): bool {
return $this->haveTokenInRange($startPos, $endPos, \T_OPEN_TAG)
|| $this->haveTokenInRange($startPos, $endPos, \T_CLOSE_TAG);
}
/**
* Get indentation before token position.
*
* @param int $pos Token position
*
* @return int Indentation depth (in spaces)
*/
public function getIndentationBefore(int $pos): int {
return $this->indentMap[$pos];
}
/**
* Get the code corresponding to a token offset range, optionally adjusted for indentation.
*
* @param int $from Token start position (inclusive)
* @param int $to Token end position (exclusive)
* @param int $indent By how much the code should be indented (can be negative as well)
*
* @return string Code corresponding to token range, adjusted for indentation
*/
public function getTokenCode(int $from, int $to, int $indent): string {
$tokens = $this->tokens;
$result = '';
for ($pos = $from; $pos < $to; $pos++) {
$token = $tokens[$pos];
$id = $token->id;
$text = $token->text;
if ($id === \T_CONSTANT_ENCAPSED_STRING || $id === \T_ENCAPSED_AND_WHITESPACE) {
$result .= $text;
} else {
// TODO Handle non-space indentation
if ($indent < 0) {
$result .= str_replace("\n" . str_repeat(" ", -$indent), "\n", $text);
} elseif ($indent > 0) {
$result .= str_replace("\n", "\n" . str_repeat(" ", $indent), $text);
} else {
$result .= $text;
}
}
}
return $result;
}
/**
* Precalculate the indentation at every token position.
*
* @return int[] Token position to indentation map
*/
private function calcIndentMap(int $tabWidth): array {
$indentMap = [];
$indent = 0;
foreach ($this->tokens as $i => $token) {
$indentMap[] = $indent;
if ($token->id === \T_WHITESPACE) {
$content = $token->text;
$newlinePos = \strrpos($content, "\n");
if (false !== $newlinePos) {
$indent = $this->getIndent(\substr($content, $newlinePos + 1), $tabWidth);
} elseif ($i === 1 && $this->tokens[0]->id === \T_OPEN_TAG &&
$this->tokens[0]->text[\strlen($this->tokens[0]->text) - 1] === "\n") {
// Special case: Newline at the end of opening tag followed by whitespace.
$indent = $this->getIndent($content, $tabWidth);
}
}
}
// Add a sentinel for one past end of the file
$indentMap[] = $indent;
return $indentMap;
}
private function getIndent(string $ws, int $tabWidth): int {
$spaces = \substr_count($ws, " ");
$tabs = \substr_count($ws, "\t");
assert(\strlen($ws) === $spaces + $tabs);
return $spaces + $tabs * $tabWidth;
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Internal/TokenPolyfill.php | lib/PhpParser/Internal/TokenPolyfill.php | <?php declare(strict_types=1);
namespace PhpParser\Internal;
if (\PHP_VERSION_ID >= 80000) {
class TokenPolyfill extends \PhpToken {
}
return;
}
/**
* This is a polyfill for the PhpToken class introduced in PHP 8.0. We do not actually polyfill
* PhpToken, because composer might end up picking a different polyfill implementation, which does
* not meet our requirements.
*
* @internal
*/
class TokenPolyfill {
/** @var int The ID of the token. Either a T_* constant of a character code < 256. */
public int $id;
/** @var string The textual content of the token. */
public string $text;
/** @var int The 1-based starting line of the token (or -1 if unknown). */
public int $line;
/** @var int The 0-based starting position of the token (or -1 if unknown). */
public int $pos;
/** @var array<int, bool> Tokens ignored by the PHP parser. */
private const IGNORABLE_TOKENS = [
\T_WHITESPACE => true,
\T_COMMENT => true,
\T_DOC_COMMENT => true,
\T_OPEN_TAG => true,
];
/** @var array<int, bool> Tokens that may be part of a T_NAME_* identifier. */
private static array $identifierTokens;
/**
* Create a Token with the given ID and text, as well optional line and position information.
*/
final public function __construct(int $id, string $text, int $line = -1, int $pos = -1) {
$this->id = $id;
$this->text = $text;
$this->line = $line;
$this->pos = $pos;
}
/**
* Get the name of the token. For single-char tokens this will be the token character.
* Otherwise it will be a T_* style name, or null if the token ID is unknown.
*/
public function getTokenName(): ?string {
if ($this->id < 256) {
return \chr($this->id);
}
$name = token_name($this->id);
return $name === 'UNKNOWN' ? null : $name;
}
/**
* Check whether the token is of the given kind. The kind may be either an integer that matches
* the token ID, a string that matches the token text, or an array of integers/strings. In the
* latter case, the function returns true if any of the kinds in the array match.
*
* @param int|string|(int|string)[] $kind
*/
public function is($kind): bool {
if (\is_int($kind)) {
return $this->id === $kind;
}
if (\is_string($kind)) {
return $this->text === $kind;
}
if (\is_array($kind)) {
foreach ($kind as $entry) {
if (\is_int($entry)) {
if ($this->id === $entry) {
return true;
}
} elseif (\is_string($entry)) {
if ($this->text === $entry) {
return true;
}
} else {
throw new \TypeError(
'Argument #1 ($kind) must only have elements of type string|int, ' .
gettype($entry) . ' given');
}
}
return false;
}
throw new \TypeError(
'Argument #1 ($kind) must be of type string|int|array, ' .gettype($kind) . ' given');
}
/**
* Check whether this token would be ignored by the PHP parser. Returns true for T_WHITESPACE,
* T_COMMENT, T_DOC_COMMENT and T_OPEN_TAG, and false for everything else.
*/
public function isIgnorable(): bool {
return isset(self::IGNORABLE_TOKENS[$this->id]);
}
/**
* Return the textual content of the token.
*/
public function __toString(): string {
return $this->text;
}
/**
* Tokenize the given source code and return an array of tokens.
*
* This performs certain canonicalizations to match the PHP 8.0 token format:
* * Bad characters are represented using T_BAD_CHARACTER rather than omitted.
* * T_COMMENT does not include trailing newlines, instead the newline is part of a following
* T_WHITESPACE token.
* * Namespaced names are represented using T_NAME_* tokens.
*
* @return static[]
*/
public static function tokenize(string $code, int $flags = 0): array {
self::init();
$tokens = [];
$line = 1;
$pos = 0;
$origTokens = \token_get_all($code, $flags);
$numTokens = \count($origTokens);
for ($i = 0; $i < $numTokens; $i++) {
$token = $origTokens[$i];
if (\is_string($token)) {
if (\strlen($token) === 2) {
// b" and B" are tokenized as single-char tokens, even though they aren't.
$tokens[] = new static(\ord('"'), $token, $line, $pos);
$pos += 2;
} else {
$tokens[] = new static(\ord($token), $token, $line, $pos);
$pos++;
}
} else {
$id = $token[0];
$text = $token[1];
// Emulate PHP 8.0 comment format, which does not include trailing whitespace anymore.
if ($id === \T_COMMENT && \substr($text, 0, 2) !== '/*' &&
\preg_match('/(\r\n|\n|\r)$/D', $text, $matches)
) {
$trailingNewline = $matches[0];
$text = \substr($text, 0, -\strlen($trailingNewline));
$tokens[] = new static($id, $text, $line, $pos);
$pos += \strlen($text);
if ($i + 1 < $numTokens && $origTokens[$i + 1][0] === \T_WHITESPACE) {
// Move trailing newline into following T_WHITESPACE token, if it already exists.
$origTokens[$i + 1][1] = $trailingNewline . $origTokens[$i + 1][1];
$origTokens[$i + 1][2]--;
} else {
// Otherwise, we need to create a new T_WHITESPACE token.
$tokens[] = new static(\T_WHITESPACE, $trailingNewline, $line, $pos);
$line++;
$pos += \strlen($trailingNewline);
}
continue;
}
// Emulate PHP 8.0 T_NAME_* tokens, by combining sequences of T_NS_SEPARATOR and
// T_STRING into a single token.
if (($id === \T_NS_SEPARATOR || isset(self::$identifierTokens[$id]))) {
$newText = $text;
$lastWasSeparator = $id === \T_NS_SEPARATOR;
for ($j = $i + 1; $j < $numTokens; $j++) {
if ($lastWasSeparator) {
if (!isset(self::$identifierTokens[$origTokens[$j][0]])) {
break;
}
$lastWasSeparator = false;
} else {
if ($origTokens[$j][0] !== \T_NS_SEPARATOR) {
break;
}
$lastWasSeparator = true;
}
$newText .= $origTokens[$j][1];
}
if ($lastWasSeparator) {
// Trailing separator is not part of the name.
$j--;
$newText = \substr($newText, 0, -1);
}
if ($j > $i + 1) {
if ($id === \T_NS_SEPARATOR) {
$id = \T_NAME_FULLY_QUALIFIED;
} elseif ($id === \T_NAMESPACE) {
$id = \T_NAME_RELATIVE;
} else {
$id = \T_NAME_QUALIFIED;
}
$tokens[] = new static($id, $newText, $line, $pos);
$pos += \strlen($newText);
$i = $j - 1;
continue;
}
}
$tokens[] = new static($id, $text, $line, $pos);
$line += \substr_count($text, "\n");
$pos += \strlen($text);
}
}
return $tokens;
}
/** Initialize private static state needed by tokenize(). */
private static function init(): void {
if (isset(self::$identifierTokens)) {
return;
}
// Based on semi_reserved production.
self::$identifierTokens = \array_fill_keys([
\T_STRING,
\T_STATIC, \T_ABSTRACT, \T_FINAL, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_READONLY,
\T_INCLUDE, \T_INCLUDE_ONCE, \T_EVAL, \T_REQUIRE, \T_REQUIRE_ONCE, \T_LOGICAL_OR, \T_LOGICAL_XOR, \T_LOGICAL_AND,
\T_INSTANCEOF, \T_NEW, \T_CLONE, \T_EXIT, \T_IF, \T_ELSEIF, \T_ELSE, \T_ENDIF, \T_ECHO, \T_DO, \T_WHILE,
\T_ENDWHILE, \T_FOR, \T_ENDFOR, \T_FOREACH, \T_ENDFOREACH, \T_DECLARE, \T_ENDDECLARE, \T_AS, \T_TRY, \T_CATCH,
\T_FINALLY, \T_THROW, \T_USE, \T_INSTEADOF, \T_GLOBAL, \T_VAR, \T_UNSET, \T_ISSET, \T_EMPTY, \T_CONTINUE, \T_GOTO,
\T_FUNCTION, \T_CONST, \T_RETURN, \T_PRINT, \T_YIELD, \T_LIST, \T_SWITCH, \T_ENDSWITCH, \T_CASE, \T_DEFAULT,
\T_BREAK, \T_ARRAY, \T_CALLABLE, \T_EXTENDS, \T_IMPLEMENTS, \T_NAMESPACE, \T_TRAIT, \T_INTERFACE, \T_CLASS,
\T_CLASS_C, \T_TRAIT_C, \T_FUNC_C, \T_METHOD_C, \T_LINE, \T_FILE, \T_DIR, \T_NS_C, \T_HALT_COMPILER, \T_FN,
\T_MATCH,
], true);
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Internal/PrintableNewAnonClassNode.php | lib/PhpParser/Internal/PrintableNewAnonClassNode.php | <?php declare(strict_types=1);
namespace PhpParser\Internal;
use PhpParser\Node;
use PhpParser\Node\Expr;
/**
* This node is used internally by the format-preserving pretty printer to print anonymous classes.
*
* The normal anonymous class structure violates assumptions about the order of token offsets.
* Namely, the constructor arguments are part of the Expr\New_ node and follow the class node, even
* though they are actually interleaved with them. This special node type is used temporarily to
* restore a sane token offset order.
*
* @internal
*/
class PrintableNewAnonClassNode extends Expr {
/** @var Node\AttributeGroup[] PHP attribute groups */
public array $attrGroups;
/** @var int Modifiers */
public int $flags;
/** @var (Node\Arg|Node\VariadicPlaceholder)[] Arguments */
public array $args;
/** @var null|Node\Name Name of extended class */
public ?Node\Name $extends;
/** @var Node\Name[] Names of implemented interfaces */
public array $implements;
/** @var Node\Stmt[] Statements */
public array $stmts;
/**
* @param Node\AttributeGroup[] $attrGroups PHP attribute groups
* @param (Node\Arg|Node\VariadicPlaceholder)[] $args Arguments
* @param Node\Name|null $extends Name of extended class
* @param Node\Name[] $implements Names of implemented interfaces
* @param Node\Stmt[] $stmts Statements
* @param array<string, mixed> $attributes Attributes
*/
public function __construct(
array $attrGroups, int $flags, array $args, ?Node\Name $extends, array $implements,
array $stmts, array $attributes
) {
parent::__construct($attributes);
$this->attrGroups = $attrGroups;
$this->flags = $flags;
$this->args = $args;
$this->extends = $extends;
$this->implements = $implements;
$this->stmts = $stmts;
}
public static function fromNewNode(Expr\New_ $newNode): self {
$class = $newNode->class;
assert($class instanceof Node\Stmt\Class_);
// We don't assert that $class->name is null here, to allow consumers to assign unique names
// to anonymous classes for their own purposes. We simplify ignore the name here.
return new self(
$class->attrGroups, $class->flags, $newNode->args, $class->extends, $class->implements,
$class->stmts, $newNode->getAttributes()
);
}
public function getType(): string {
return 'Expr_PrintableNewAnonClass';
}
public function getSubNodeNames(): array {
return ['attrGroups', 'flags', 'args', 'extends', 'implements', 'stmts'];
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Internal/Differ.php | lib/PhpParser/Internal/Differ.php | <?php declare(strict_types=1);
namespace PhpParser\Internal;
/**
* Implements the Myers diff algorithm.
*
* Myers, Eugene W. "An O (ND) difference algorithm and its variations."
* Algorithmica 1.1 (1986): 251-266.
*
* @template T
* @internal
*/
class Differ {
/** @var callable(T, T): bool */
private $isEqual;
/**
* Create differ over the given equality relation.
*
* @param callable(T, T): bool $isEqual Equality relation
*/
public function __construct(callable $isEqual) {
$this->isEqual = $isEqual;
}
/**
* Calculate diff (edit script) from $old to $new.
*
* @param T[] $old Original array
* @param T[] $new New array
*
* @return DiffElem[] Diff (edit script)
*/
public function diff(array $old, array $new): array {
$old = \array_values($old);
$new = \array_values($new);
list($trace, $x, $y) = $this->calculateTrace($old, $new);
return $this->extractDiff($trace, $x, $y, $old, $new);
}
/**
* Calculate diff, including "replace" operations.
*
* If a sequence of remove operations is followed by the same number of add operations, these
* will be coalesced into replace operations.
*
* @param T[] $old Original array
* @param T[] $new New array
*
* @return DiffElem[] Diff (edit script), including replace operations
*/
public function diffWithReplacements(array $old, array $new): array {
return $this->coalesceReplacements($this->diff($old, $new));
}
/**
* @param T[] $old
* @param T[] $new
* @return array{array<int, array<int, int>>, int, int}
*/
private function calculateTrace(array $old, array $new): array {
$n = \count($old);
$m = \count($new);
$max = $n + $m;
$v = [1 => 0];
$trace = [];
for ($d = 0; $d <= $max; $d++) {
$trace[] = $v;
for ($k = -$d; $k <= $d; $k += 2) {
if ($k === -$d || ($k !== $d && $v[$k - 1] < $v[$k + 1])) {
$x = $v[$k + 1];
} else {
$x = $v[$k - 1] + 1;
}
$y = $x - $k;
while ($x < $n && $y < $m && ($this->isEqual)($old[$x], $new[$y])) {
$x++;
$y++;
}
$v[$k] = $x;
if ($x >= $n && $y >= $m) {
return [$trace, $x, $y];
}
}
}
throw new \Exception('Should not happen');
}
/**
* @param array<int, array<int, int>> $trace
* @param T[] $old
* @param T[] $new
* @return DiffElem[]
*/
private function extractDiff(array $trace, int $x, int $y, array $old, array $new): array {
$result = [];
for ($d = \count($trace) - 1; $d >= 0; $d--) {
$v = $trace[$d];
$k = $x - $y;
if ($k === -$d || ($k !== $d && $v[$k - 1] < $v[$k + 1])) {
$prevK = $k + 1;
} else {
$prevK = $k - 1;
}
$prevX = $v[$prevK];
$prevY = $prevX - $prevK;
while ($x > $prevX && $y > $prevY) {
$result[] = new DiffElem(DiffElem::TYPE_KEEP, $old[$x - 1], $new[$y - 1]);
$x--;
$y--;
}
if ($d === 0) {
break;
}
while ($x > $prevX) {
$result[] = new DiffElem(DiffElem::TYPE_REMOVE, $old[$x - 1], null);
$x--;
}
while ($y > $prevY) {
$result[] = new DiffElem(DiffElem::TYPE_ADD, null, $new[$y - 1]);
$y--;
}
}
return array_reverse($result);
}
/**
* Coalesce equal-length sequences of remove+add into a replace operation.
*
* @param DiffElem[] $diff
* @return DiffElem[]
*/
private function coalesceReplacements(array $diff): array {
$newDiff = [];
$c = \count($diff);
for ($i = 0; $i < $c; $i++) {
$diffType = $diff[$i]->type;
if ($diffType !== DiffElem::TYPE_REMOVE) {
$newDiff[] = $diff[$i];
continue;
}
$j = $i;
while ($j < $c && $diff[$j]->type === DiffElem::TYPE_REMOVE) {
$j++;
}
$k = $j;
while ($k < $c && $diff[$k]->type === DiffElem::TYPE_ADD) {
$k++;
}
if ($j - $i === $k - $j) {
$len = $j - $i;
for ($n = 0; $n < $len; $n++) {
$newDiff[] = new DiffElem(
DiffElem::TYPE_REPLACE, $diff[$i + $n]->old, $diff[$j + $n]->new
);
}
} else {
for (; $i < $k; $i++) {
$newDiff[] = $diff[$i];
}
}
$i = $k - 1;
}
return $newDiff;
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/Internal/DiffElem.php | lib/PhpParser/Internal/DiffElem.php | <?php declare(strict_types=1);
namespace PhpParser\Internal;
/**
* @internal
*/
class DiffElem {
public const TYPE_KEEP = 0;
public const TYPE_REMOVE = 1;
public const TYPE_ADD = 2;
public const TYPE_REPLACE = 3;
/** @var int One of the TYPE_* constants */
public int $type;
/** @var mixed Is null for add operations */
public $old;
/** @var mixed Is null for remove operations */
public $new;
/**
* @param int $type One of the TYPE_* constants
* @param mixed $old Is null for add operations
* @param mixed $new Is null for remove operations
*/
public function __construct(int $type, $old, $new) {
$this->type = $type;
$this->old = $old;
$this->new = $new;
}
}
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/lib/PhpParser/PrettyPrinter/Standard.php | lib/PhpParser/PrettyPrinter/Standard.php | <?php declare(strict_types=1);
namespace PhpParser\PrettyPrinter;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\AssignOp;
use PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\Cast;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar;
use PhpParser\Node\Scalar\MagicConst;
use PhpParser\Node\Stmt;
use PhpParser\PrettyPrinterAbstract;
class Standard extends PrettyPrinterAbstract {
// Special nodes
protected function pParam(Node\Param $node): string {
return $this->pAttrGroups($node->attrGroups, $this->phpVersion->supportsAttributes())
. $this->pModifiers($node->flags)
. ($node->type ? $this->p($node->type) . ' ' : '')
. ($node->byRef ? '&' : '')
. ($node->variadic ? '...' : '')
. $this->p($node->var)
. ($node->default ? ' = ' . $this->p($node->default) : '')
. ($node->hooks ? ' {' . $this->pStmts($node->hooks) . $this->nl . '}' : '');
}
protected function pArg(Node\Arg $node): string {
return ($node->name ? $node->name->toString() . ': ' : '')
. ($node->byRef ? '&' : '') . ($node->unpack ? '...' : '')
. $this->p($node->value);
}
protected function pVariadicPlaceholder(Node\VariadicPlaceholder $node): string {
return '...';
}
protected function pConst(Node\Const_ $node): string {
return $node->name . ' = ' . $this->p($node->value);
}
protected function pNullableType(Node\NullableType $node): string {
return '?' . $this->p($node->type);
}
protected function pUnionType(Node\UnionType $node): string {
$types = [];
foreach ($node->types as $typeNode) {
if ($typeNode instanceof Node\IntersectionType) {
$types[] = '('. $this->p($typeNode) . ')';
continue;
}
$types[] = $this->p($typeNode);
}
return implode('|', $types);
}
protected function pIntersectionType(Node\IntersectionType $node): string {
return $this->pImplode($node->types, '&');
}
protected function pIdentifier(Node\Identifier $node): string {
return $node->name;
}
protected function pVarLikeIdentifier(Node\VarLikeIdentifier $node): string {
return '$' . $node->name;
}
protected function pAttribute(Node\Attribute $node): string {
return $this->p($node->name)
. ($node->args ? '(' . $this->pCommaSeparated($node->args) . ')' : '');
}
protected function pAttributeGroup(Node\AttributeGroup $node): string {
return '#[' . $this->pCommaSeparated($node->attrs) . ']';
}
// Names
protected function pName(Name $node): string {
return $node->name;
}
protected function pName_FullyQualified(Name\FullyQualified $node): string {
return '\\' . $node->name;
}
protected function pName_Relative(Name\Relative $node): string {
return 'namespace\\' . $node->name;
}
// Magic Constants
protected function pScalar_MagicConst_Class(MagicConst\Class_ $node): string {
return '__CLASS__';
}
protected function pScalar_MagicConst_Dir(MagicConst\Dir $node): string {
return '__DIR__';
}
protected function pScalar_MagicConst_File(MagicConst\File $node): string {
return '__FILE__';
}
protected function pScalar_MagicConst_Function(MagicConst\Function_ $node): string {
return '__FUNCTION__';
}
protected function pScalar_MagicConst_Line(MagicConst\Line $node): string {
return '__LINE__';
}
protected function pScalar_MagicConst_Method(MagicConst\Method $node): string {
return '__METHOD__';
}
protected function pScalar_MagicConst_Namespace(MagicConst\Namespace_ $node): string {
return '__NAMESPACE__';
}
protected function pScalar_MagicConst_Trait(MagicConst\Trait_ $node): string {
return '__TRAIT__';
}
protected function pScalar_MagicConst_Property(MagicConst\Property $node): string {
return '__PROPERTY__';
}
// Scalars
private function indentString(string $str): string {
return str_replace("\n", $this->nl, $str);
}
protected function pScalar_String(Scalar\String_ $node): string {
$kind = $node->getAttribute('kind', Scalar\String_::KIND_SINGLE_QUOTED);
switch ($kind) {
case Scalar\String_::KIND_NOWDOC:
$label = $node->getAttribute('docLabel');
if ($label && !$this->containsEndLabel($node->value, $label)) {
$shouldIdent = $this->phpVersion->supportsFlexibleHeredoc();
$nl = $shouldIdent ? $this->nl : $this->newline;
if ($node->value === '') {
return "<<<'$label'$nl$label{$this->docStringEndToken}";
}
// Make sure trailing \r is not combined with following \n into CRLF.
if ($node->value[strlen($node->value) - 1] !== "\r") {
$value = $shouldIdent ? $this->indentString($node->value) : $node->value;
return "<<<'$label'$nl$value$nl$label{$this->docStringEndToken}";
}
}
/* break missing intentionally */
// no break
case Scalar\String_::KIND_SINGLE_QUOTED:
return $this->pSingleQuotedString($node->value);
case Scalar\String_::KIND_HEREDOC:
$label = $node->getAttribute('docLabel');
$escaped = $this->escapeString($node->value, null);
if ($label && !$this->containsEndLabel($escaped, $label)) {
$nl = $this->phpVersion->supportsFlexibleHeredoc() ? $this->nl : $this->newline;
if ($escaped === '') {
return "<<<$label$nl$label{$this->docStringEndToken}";
}
return "<<<$label$nl$escaped$nl$label{$this->docStringEndToken}";
}
/* break missing intentionally */
// no break
case Scalar\String_::KIND_DOUBLE_QUOTED:
return '"' . $this->escapeString($node->value, '"') . '"';
}
throw new \Exception('Invalid string kind');
}
protected function pScalar_InterpolatedString(Scalar\InterpolatedString $node): string {
if ($node->getAttribute('kind') === Scalar\String_::KIND_HEREDOC) {
$label = $node->getAttribute('docLabel');
if ($label && !$this->encapsedContainsEndLabel($node->parts, $label)) {
$nl = $this->phpVersion->supportsFlexibleHeredoc() ? $this->nl : $this->newline;
if (count($node->parts) === 1
&& $node->parts[0] instanceof Node\InterpolatedStringPart
&& $node->parts[0]->value === ''
) {
return "<<<$label$nl$label{$this->docStringEndToken}";
}
return "<<<$label$nl" . $this->pEncapsList($node->parts, null)
. "$nl$label{$this->docStringEndToken}";
}
}
return '"' . $this->pEncapsList($node->parts, '"') . '"';
}
protected function pScalar_Int(Scalar\Int_ $node): string {
if ($node->getAttribute('shouldPrintRawValue') === true) {
return $node->getAttribute('rawValue');
}
if ($node->value === -\PHP_INT_MAX - 1) {
// PHP_INT_MIN cannot be represented as a literal,
// because the sign is not part of the literal
return '(-' . \PHP_INT_MAX . '-1)';
}
$kind = $node->getAttribute('kind', Scalar\Int_::KIND_DEC);
if (Scalar\Int_::KIND_DEC === $kind) {
return (string) $node->value;
}
if ($node->value < 0) {
$sign = '-';
$str = (string) -$node->value;
} else {
$sign = '';
$str = (string) $node->value;
}
switch ($kind) {
case Scalar\Int_::KIND_BIN:
return $sign . '0b' . base_convert($str, 10, 2);
case Scalar\Int_::KIND_OCT:
return $sign . '0' . base_convert($str, 10, 8);
case Scalar\Int_::KIND_HEX:
return $sign . '0x' . base_convert($str, 10, 16);
}
throw new \Exception('Invalid number kind');
}
protected function pScalar_Float(Scalar\Float_ $node): string {
if (!is_finite($node->value)) {
if ($node->value === \INF) {
return '1.0E+1000';
}
if ($node->value === -\INF) {
return '-1.0E+1000';
} else {
return '\NAN';
}
}
// Try to find a short full-precision representation
$stringValue = sprintf('%.16G', $node->value);
if ($node->value !== (float) $stringValue) {
$stringValue = sprintf('%.17G', $node->value);
}
// %G is locale dependent and there exists no locale-independent alternative. We don't want
// mess with switching locales here, so let's assume that a comma is the only non-standard
// decimal separator we may encounter...
$stringValue = str_replace(',', '.', $stringValue);
// ensure that number is really printed as float
return preg_match('/^-?[0-9]+$/', $stringValue) ? $stringValue . '.0' : $stringValue;
}
// Assignments
protected function pExpr_Assign(Expr\Assign $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Expr\Assign::class, $this->p($node->var) . ' = ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_AssignRef(Expr\AssignRef $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Expr\AssignRef::class, $this->p($node->var) . ' =& ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_AssignOp_Plus(AssignOp\Plus $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(AssignOp\Plus::class, $this->p($node->var) . ' += ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_AssignOp_Minus(AssignOp\Minus $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(AssignOp\Minus::class, $this->p($node->var) . ' -= ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_AssignOp_Mul(AssignOp\Mul $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(AssignOp\Mul::class, $this->p($node->var) . ' *= ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_AssignOp_Div(AssignOp\Div $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(AssignOp\Div::class, $this->p($node->var) . ' /= ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_AssignOp_Concat(AssignOp\Concat $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(AssignOp\Concat::class, $this->p($node->var) . ' .= ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_AssignOp_Mod(AssignOp\Mod $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(AssignOp\Mod::class, $this->p($node->var) . ' %= ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_AssignOp_BitwiseAnd(AssignOp\BitwiseAnd $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(AssignOp\BitwiseAnd::class, $this->p($node->var) . ' &= ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_AssignOp_BitwiseOr(AssignOp\BitwiseOr $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(AssignOp\BitwiseOr::class, $this->p($node->var) . ' |= ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_AssignOp_BitwiseXor(AssignOp\BitwiseXor $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(AssignOp\BitwiseXor::class, $this->p($node->var) . ' ^= ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_AssignOp_ShiftLeft(AssignOp\ShiftLeft $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(AssignOp\ShiftLeft::class, $this->p($node->var) . ' <<= ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_AssignOp_ShiftRight(AssignOp\ShiftRight $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(AssignOp\ShiftRight::class, $this->p($node->var) . ' >>= ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_AssignOp_Pow(AssignOp\Pow $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(AssignOp\Pow::class, $this->p($node->var) . ' **= ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_AssignOp_Coalesce(AssignOp\Coalesce $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(AssignOp\Coalesce::class, $this->p($node->var) . ' ??= ', $node->expr, $precedence, $lhsPrecedence);
}
// Binary expressions
protected function pExpr_BinaryOp_Plus(BinaryOp\Plus $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\Plus::class, $node->left, ' + ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_Minus(BinaryOp\Minus $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\Minus::class, $node->left, ' - ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_Mul(BinaryOp\Mul $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\Mul::class, $node->left, ' * ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_Div(BinaryOp\Div $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\Div::class, $node->left, ' / ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_Concat(BinaryOp\Concat $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\Concat::class, $node->left, ' . ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_Mod(BinaryOp\Mod $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\Mod::class, $node->left, ' % ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_BooleanAnd(BinaryOp\BooleanAnd $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\BooleanAnd::class, $node->left, ' && ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_BooleanOr(BinaryOp\BooleanOr $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\BooleanOr::class, $node->left, ' || ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_BitwiseAnd(BinaryOp\BitwiseAnd $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\BitwiseAnd::class, $node->left, ' & ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_BitwiseOr(BinaryOp\BitwiseOr $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\BitwiseOr::class, $node->left, ' | ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_BitwiseXor(BinaryOp\BitwiseXor $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\BitwiseXor::class, $node->left, ' ^ ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_ShiftLeft(BinaryOp\ShiftLeft $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\ShiftLeft::class, $node->left, ' << ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_ShiftRight(BinaryOp\ShiftRight $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\ShiftRight::class, $node->left, ' >> ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_Pow(BinaryOp\Pow $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\Pow::class, $node->left, ' ** ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_LogicalAnd(BinaryOp\LogicalAnd $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\LogicalAnd::class, $node->left, ' and ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_LogicalOr(BinaryOp\LogicalOr $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\LogicalOr::class, $node->left, ' or ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_LogicalXor(BinaryOp\LogicalXor $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\LogicalXor::class, $node->left, ' xor ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_Equal(BinaryOp\Equal $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\Equal::class, $node->left, ' == ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_NotEqual(BinaryOp\NotEqual $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\NotEqual::class, $node->left, ' != ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_Identical(BinaryOp\Identical $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\Identical::class, $node->left, ' === ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_NotIdentical(BinaryOp\NotIdentical $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\NotIdentical::class, $node->left, ' !== ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_Spaceship(BinaryOp\Spaceship $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\Spaceship::class, $node->left, ' <=> ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_Greater(BinaryOp\Greater $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\Greater::class, $node->left, ' > ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_GreaterOrEqual(BinaryOp\GreaterOrEqual $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\GreaterOrEqual::class, $node->left, ' >= ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_Smaller(BinaryOp\Smaller $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\Smaller::class, $node->left, ' < ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_SmallerOrEqual(BinaryOp\SmallerOrEqual $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\SmallerOrEqual::class, $node->left, ' <= ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_Coalesce(BinaryOp\Coalesce $node, int $precedence, int $lhsPrecedence): string {
return $this->pInfixOp(BinaryOp\Coalesce::class, $node->left, ' ?? ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_BinaryOp_Pipe(BinaryOp\Pipe $node, int $precedence, int $lhsPrecedence): string {
if ($node->right instanceof Expr\ArrowFunction) {
// Force parentheses around arrow functions.
$lhsPrecedence = $this->precedenceMap[Expr\ArrowFunction::class][0];
}
return $this->pInfixOp(BinaryOp\Pipe::class, $node->left, ' |> ', $node->right, $precedence, $lhsPrecedence);
}
protected function pExpr_Instanceof(Expr\Instanceof_ $node, int $precedence, int $lhsPrecedence): string {
return $this->pPostfixOp(
Expr\Instanceof_::class, $node->expr,
' instanceof ' . $this->pNewOperand($node->class),
$precedence, $lhsPrecedence);
}
// Unary expressions
protected function pExpr_BooleanNot(Expr\BooleanNot $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Expr\BooleanNot::class, '!', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_BitwiseNot(Expr\BitwiseNot $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Expr\BitwiseNot::class, '~', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_UnaryMinus(Expr\UnaryMinus $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Expr\UnaryMinus::class, '-', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_UnaryPlus(Expr\UnaryPlus $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Expr\UnaryPlus::class, '+', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_PreInc(Expr\PreInc $node): string {
return '++' . $this->p($node->var);
}
protected function pExpr_PreDec(Expr\PreDec $node): string {
return '--' . $this->p($node->var);
}
protected function pExpr_PostInc(Expr\PostInc $node): string {
return $this->p($node->var) . '++';
}
protected function pExpr_PostDec(Expr\PostDec $node): string {
return $this->p($node->var) . '--';
}
protected function pExpr_ErrorSuppress(Expr\ErrorSuppress $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Expr\ErrorSuppress::class, '@', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_YieldFrom(Expr\YieldFrom $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Expr\YieldFrom::class, 'yield from ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_Print(Expr\Print_ $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Expr\Print_::class, 'print ', $node->expr, $precedence, $lhsPrecedence);
}
// Casts
protected function pExpr_Cast_Int(Cast\Int_ $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Cast\Int_::class, '(int) ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_Cast_Double(Cast\Double $node, int $precedence, int $lhsPrecedence): string {
$kind = $node->getAttribute('kind', Cast\Double::KIND_DOUBLE);
if ($kind === Cast\Double::KIND_DOUBLE) {
$cast = '(double)';
} elseif ($kind === Cast\Double::KIND_FLOAT) {
$cast = '(float)';
} else {
assert($kind === Cast\Double::KIND_REAL);
$cast = '(real)';
}
return $this->pPrefixOp(Cast\Double::class, $cast . ' ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_Cast_String(Cast\String_ $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Cast\String_::class, '(string) ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_Cast_Array(Cast\Array_ $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Cast\Array_::class, '(array) ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_Cast_Object(Cast\Object_ $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Cast\Object_::class, '(object) ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_Cast_Bool(Cast\Bool_ $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Cast\Bool_::class, '(bool) ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_Cast_Unset(Cast\Unset_ $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Cast\Unset_::class, '(unset) ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_Cast_Void(Cast\Void_ $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(Cast\Void_::class, '(void) ', $node->expr, $precedence, $lhsPrecedence);
}
// Function calls and similar constructs
protected function pExpr_FuncCall(Expr\FuncCall $node): string {
return $this->pCallLhs($node->name)
. '(' . $this->pMaybeMultiline($node->args) . ')';
}
protected function pExpr_MethodCall(Expr\MethodCall $node): string {
return $this->pDereferenceLhs($node->var) . '->' . $this->pObjectProperty($node->name)
. '(' . $this->pMaybeMultiline($node->args) . ')';
}
protected function pExpr_NullsafeMethodCall(Expr\NullsafeMethodCall $node): string {
return $this->pDereferenceLhs($node->var) . '?->' . $this->pObjectProperty($node->name)
. '(' . $this->pMaybeMultiline($node->args) . ')';
}
protected function pExpr_StaticCall(Expr\StaticCall $node): string {
return $this->pStaticDereferenceLhs($node->class) . '::'
. ($node->name instanceof Expr
? ($node->name instanceof Expr\Variable
? $this->p($node->name)
: '{' . $this->p($node->name) . '}')
: $node->name)
. '(' . $this->pMaybeMultiline($node->args) . ')';
}
protected function pExpr_Empty(Expr\Empty_ $node): string {
return 'empty(' . $this->p($node->expr) . ')';
}
protected function pExpr_Isset(Expr\Isset_ $node): string {
return 'isset(' . $this->pCommaSeparated($node->vars) . ')';
}
protected function pExpr_Eval(Expr\Eval_ $node): string {
return 'eval(' . $this->p($node->expr) . ')';
}
protected function pExpr_Include(Expr\Include_ $node, int $precedence, int $lhsPrecedence): string {
static $map = [
Expr\Include_::TYPE_INCLUDE => 'include',
Expr\Include_::TYPE_INCLUDE_ONCE => 'include_once',
Expr\Include_::TYPE_REQUIRE => 'require',
Expr\Include_::TYPE_REQUIRE_ONCE => 'require_once',
];
return $this->pPrefixOp(Expr\Include_::class, $map[$node->type] . ' ', $node->expr, $precedence, $lhsPrecedence);
}
protected function pExpr_List(Expr\List_ $node): string {
$syntax = $node->getAttribute('kind',
$this->phpVersion->supportsShortArrayDestructuring() ? Expr\List_::KIND_ARRAY : Expr\List_::KIND_LIST);
if ($syntax === Expr\List_::KIND_ARRAY) {
return '[' . $this->pMaybeMultiline($node->items, true) . ']';
} else {
return 'list(' . $this->pMaybeMultiline($node->items, true) . ')';
}
}
// Other
protected function pExpr_Error(Expr\Error $node): string {
throw new \LogicException('Cannot pretty-print AST with Error nodes');
}
protected function pExpr_Variable(Expr\Variable $node): string {
if ($node->name instanceof Expr) {
return '${' . $this->p($node->name) . '}';
} else {
return '$' . $node->name;
}
}
protected function pExpr_Array(Expr\Array_ $node): string {
$syntax = $node->getAttribute('kind',
$this->shortArraySyntax ? Expr\Array_::KIND_SHORT : Expr\Array_::KIND_LONG);
if ($syntax === Expr\Array_::KIND_SHORT) {
return '[' . $this->pMaybeMultiline($node->items, true) . ']';
} else {
return 'array(' . $this->pMaybeMultiline($node->items, true) . ')';
}
}
protected function pKey(?Node $node): string {
if ($node === null) {
return '';
}
// => is not really an operator and does not typically participate in precedence resolution.
// However, there is an exception if yield expressions with keys are involved:
// [yield $a => $b] is interpreted as [(yield $a => $b)], so we need to ensure that
// [(yield $a) => $b] is printed with parentheses. We approximate this by lowering the LHS
// precedence to that of yield (which will also print unnecessary parentheses for rare low
// precedence unary operators like include).
$yieldPrecedence = $this->precedenceMap[Expr\Yield_::class][0];
return $this->p($node, self::MAX_PRECEDENCE, $yieldPrecedence) . ' => ';
}
protected function pArrayItem(Node\ArrayItem $node): string {
return $this->pKey($node->key)
. ($node->byRef ? '&' : '')
. ($node->unpack ? '...' : '')
. $this->p($node->value);
}
protected function pExpr_ArrayDimFetch(Expr\ArrayDimFetch $node): string {
return $this->pDereferenceLhs($node->var)
. '[' . (null !== $node->dim ? $this->p($node->dim) : '') . ']';
}
protected function pExpr_ConstFetch(Expr\ConstFetch $node): string {
return $this->p($node->name);
}
protected function pExpr_ClassConstFetch(Expr\ClassConstFetch $node): string {
return $this->pStaticDereferenceLhs($node->class) . '::' . $this->pObjectProperty($node->name);
}
protected function pExpr_PropertyFetch(Expr\PropertyFetch $node): string {
return $this->pDereferenceLhs($node->var) . '->' . $this->pObjectProperty($node->name);
}
protected function pExpr_NullsafePropertyFetch(Expr\NullsafePropertyFetch $node): string {
return $this->pDereferenceLhs($node->var) . '?->' . $this->pObjectProperty($node->name);
}
protected function pExpr_StaticPropertyFetch(Expr\StaticPropertyFetch $node): string {
return $this->pStaticDereferenceLhs($node->class) . '::$' . $this->pObjectProperty($node->name);
}
protected function pExpr_ShellExec(Expr\ShellExec $node): string {
return '`' . $this->pEncapsList($node->parts, '`') . '`';
}
protected function pExpr_Closure(Expr\Closure $node): string {
return $this->pAttrGroups($node->attrGroups, true)
. $this->pStatic($node->static)
. 'function ' . ($node->byRef ? '&' : '')
. '(' . $this->pParams($node->params) . ')'
. (!empty($node->uses) ? ' use (' . $this->pCommaSeparated($node->uses) . ')' : '')
. (null !== $node->returnType ? ': ' . $this->p($node->returnType) : '')
. ' {' . $this->pStmts($node->stmts) . $this->nl . '}';
}
protected function pExpr_Match(Expr\Match_ $node): string {
return 'match (' . $this->p($node->cond) . ') {'
. $this->pCommaSeparatedMultiline($node->arms, true)
. $this->nl
. '}';
}
protected function pMatchArm(Node\MatchArm $node): string {
$result = '';
if ($node->conds) {
for ($i = 0, $c = \count($node->conds); $i + 1 < $c; $i++) {
$result .= $this->p($node->conds[$i]) . ', ';
}
$result .= $this->pKey($node->conds[$i]);
} else {
$result = 'default => ';
}
return $result . $this->p($node->body);
}
protected function pExpr_ArrowFunction(Expr\ArrowFunction $node, int $precedence, int $lhsPrecedence): string {
return $this->pPrefixOp(
Expr\ArrowFunction::class,
$this->pAttrGroups($node->attrGroups, true)
. $this->pStatic($node->static)
. 'fn' . ($node->byRef ? '&' : '')
. '(' . $this->pParams($node->params) . ')'
. (null !== $node->returnType ? ': ' . $this->p($node->returnType) : '')
. ' => ',
$node->expr, $precedence, $lhsPrecedence);
}
protected function pClosureUse(Node\ClosureUse $node): string {
return ($node->byRef ? '&' : '') . $this->p($node->var);
}
protected function pExpr_New(Expr\New_ $node): string {
if ($node->class instanceof Stmt\Class_) {
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | true |
nikic/PHP-Parser | https://github.com/nikic/PHP-Parser/blob/8c360e27327c8bd29e1c57721574709d0d706118/test_old/run.php | test_old/run.php | <?php
error_reporting(E_ALL);
ini_set('short_open_tag', false);
if ('cli' !== php_sapi_name()) {
die('This script is designed for running on the command line.');
}
function showHelp($error) {
die($error . "\n\n" .
<<<OUTPUT
This script has to be called with the following signature:
php run.php [--no-progress] testType pathToTestFiles
The test type must be one of: PHP, Symfony
The following options are available:
--no-progress Disables showing which file is currently tested.
--verbose Print more information for failures.
--php-version=VERSION PHP version to use for lexing/parsing.
OUTPUT
);
}
$allowedOptions = [
'--no-progress' => true,
'--verbose' => true,
'--php-version' => true,
];
$options = array();
$arguments = array();
// remove script name from argv
array_shift($argv);
foreach ($argv as $arg) {
if ('-' === $arg[0]) {
$parts = explode('=', $arg);
$name = $parts[0];
if (!isset($allowedOptions[$name])) {
showHelp("Unknown option \"$name\"");
}
$options[$name] = $parts[1] ?? true;
} else {
$arguments[] = $arg;
}
}
if (count($arguments) !== 2) {
showHelp('Too few arguments passed!');
}
$showProgress = !isset($options['--no-progress']);
$verbose = isset($options['--verbose']);
$phpVersion = $options['--php-version'] ?? '8.0';
$testType = $arguments[0];
$dir = $arguments[1];
require_once __DIR__ . '/../vendor/autoload.php';
switch ($testType) {
case 'Symfony':
$fileFilter = function($path) {
if (!preg_match('~\.php$~', $path)) {
return false;
}
if (preg_match('~(?:
# invalid php code
dependency-injection.Tests.Fixtures.xml.xml_with_wrong_ext
# difference in nop statement
| framework-bundle.Resources.views.Form.choice_widget_options\.html
# difference due to INF
| yaml.Tests.InlineTest
)\.php$~x', $path)) {
return false;
}
return true;
};
$codeExtractor = function($file, $code) {
return $code;
};
break;
case 'PHP':
$fileFilter = function($path) {
return preg_match('~\.phpt$~', $path);
};
$codeExtractor = function($file, $code) {
if (preg_match('~(?:
# skeleton files
ext.gmp.tests.001
| ext.skeleton.tests.00\d
# multibyte encoded files
| ext.mbstring.tests.zend_multibyte-01
| Zend.tests.multibyte.multibyte_encoding_001
| Zend.tests.multibyte.multibyte_encoding_004
| Zend.tests.multibyte.multibyte_encoding_005
# invalid code due to missing WS after opening tag
| tests.run-test.bug75042-3
# contains invalid chars, which we treat as parse error
| Zend.tests.warning_during_heredoc_scan_ahead
# pretty print differences due to negative LNumbers
| Zend.tests.neg_num_string
| Zend.tests.numeric_strings.neg_num_string
| Zend.tests.bug72918
# pretty print difference due to nop statements
| ext.mbstring.tests.htmlent
| ext.standard.tests.file.fread_basic
# its too hard to emulate these on old PHP versions
| Zend.tests.flexible-heredoc-complex-test[1-4]
# whitespace in namespaced name
| Zend.tests.bug55086
| Zend.tests.grammar.regression_010
# not worth emulating on old PHP versions
| Zend.tests.type_declarations.intersection_types.parsing_comment
# comments in property fetch syntax, not emulated on old PHP versions
| Zend.tests.gh14961
# harmless pretty print difference for clone($x, )
| Zend.tests.clone.ast
)\.phpt$~x', $file)) {
return null;
}
if (!preg_match('~--FILE--\s*(.*?)\n--[A-Z]+--~s', $code, $matches)) {
return null;
}
if (preg_match('~--EXPECT(?:F|REGEX)?--\s*(?:Parse|Fatal) error~', $code)) {
return null;
}
return $matches[1];
};
break;
default:
showHelp('Test type must be one of: PHP or Symfony');
}
$parser = (new PhpParser\ParserFactory())->createForVersion(PhpParser\PhpVersion::fromString($phpVersion));
$prettyPrinter = new PhpParser\PrettyPrinter\Standard;
$nodeDumper = new PhpParser\NodeDumper;
$cloningTraverser = new PhpParser\NodeTraverser;
$cloningTraverser->addVisitor(new PhpParser\NodeVisitor\CloningVisitor);
$parseFail = $fpppFail = $ppFail = $compareFail = $count = 0;
$readTime = $parseTime = $cloneTime = 0;
$fpppTime = $ppTime = $reparseTime = $compareTime = 0;
$totalStartTime = microtime(true);
foreach (new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir),
RecursiveIteratorIterator::LEAVES_ONLY)
as $file) {
if (!$fileFilter($file)) {
continue;
}
$startTime = microtime(true);
$origCode = file_get_contents($file);
$readTime += microtime(true) - $startTime;
if (null === $origCode = $codeExtractor($file, $origCode)) {
continue;
}
set_time_limit(10);
++$count;
if ($showProgress) {
echo substr(str_pad('Testing file ' . $count . ': ' . substr($file, strlen($dir)), 79), 0, 79), "\r";
}
try {
$startTime = microtime(true);
$origStmts = $parser->parse($origCode);
$parseTime += microtime(true) - $startTime;
$origTokens = $parser->getTokens();
$startTime = microtime(true);
$stmts = $cloningTraverser->traverse($origStmts);
$cloneTime += microtime(true) - $startTime;
$startTime = microtime(true);
$code = $prettyPrinter->printFormatPreserving($stmts, $origStmts, $origTokens);
$fpppTime += microtime(true) - $startTime;
if ($code !== $origCode) {
echo $file, ":\n Result of format-preserving pretty-print differs\n";
if ($verbose) {
echo "FPPP output:\n=====\n$code\n=====\n\n";
}
++$fpppFail;
}
$startTime = microtime(true);
$code = "<?php\n" . $prettyPrinter->prettyPrint($stmts);
$ppTime += microtime(true) - $startTime;
try {
$startTime = microtime(true);
$ppStmts = $parser->parse($code);
$reparseTime += microtime(true) - $startTime;
$startTime = microtime(true);
$same = $nodeDumper->dump($stmts) == $nodeDumper->dump($ppStmts);
$compareTime += microtime(true) - $startTime;
if (!$same) {
echo $file, ":\n Result of initial parse and parse after pretty print differ\n";
if ($verbose) {
echo "Pretty printer output:\n=====\n$code\n=====\n\n";
}
++$compareFail;
}
} catch (PhpParser\Error $e) {
echo $file, ":\n Parse of pretty print failed with message: {$e->getMessage()}\n";
if ($verbose) {
echo "Pretty printer output:\n=====\n$code\n=====\n\n";
}
++$ppFail;
}
} catch (PhpParser\Error $e) {
echo $file, ":\n Parse failed with message: {$e->getMessage()}\n";
++$parseFail;
} catch (Throwable $e) {
echo $file, ":\n Unknown error occurred: $e\n";
}
}
if (0 === $parseFail && 0 === $ppFail && 0 === $compareFail) {
$exit = 0;
echo "\n\n", 'All tests passed.', "\n";
} else {
$exit = 1;
echo "\n\n", '==========', "\n\n", 'There were: ', "\n";
if (0 !== $parseFail) {
echo ' ', $parseFail, ' parse failures.', "\n";
}
if (0 !== $ppFail) {
echo ' ', $ppFail, ' pretty print failures.', "\n";
}
if (0 !== $fpppFail) {
echo ' ', $fpppFail, ' FPPP failures.', "\n";
}
if (0 !== $compareFail) {
echo ' ', $compareFail, ' compare failures.', "\n";
}
}
echo "\n",
'Tested files: ', $count, "\n",
"\n",
'Reading files took: ', $readTime, "\n",
'Parsing took: ', $parseTime, "\n",
'Cloning took: ', $cloneTime, "\n",
'FPPP took: ', $fpppTime, "\n",
'Pretty printing took: ', $ppTime, "\n",
'Reparsing took: ', $reparseTime, "\n",
'Comparing took: ', $compareTime, "\n",
"\n",
'Total time: ', microtime(true) - $totalStartTime, "\n",
'Maximum memory usage: ', memory_get_peak_usage(true), "\n";
exit($exit);
| php | BSD-3-Clause | 8c360e27327c8bd29e1c57721574709d0d706118 | 2026-01-04T15:02:34.433891Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/.php-cs-fixer.dist.php | .php-cs-fixer.dist.php | <?php
$config = (new PhpCsFixer\Config())
->setRiskyAllowed(true)
->setRules([
'@PHP71Migration:risky' => true,
'@PHPUnit75Migration:risky' => true,
'@PSR12:risky' => true,
'@Symfony' => true,
'declare_strict_types' => false,
'global_namespace_import' => false,
'no_superfluous_phpdoc_tags' => [
'allow_mixed' => true,
],
'phpdoc_annotation_without_dot' => false,
'phpdoc_summary' => false,
'phpdoc_to_comment' => false,
'single_line_throw' => false,
'void_return' => false,
'yoda_style' => false,
])
->setFinder(
PhpCsFixer\Finder::create()
->in(__DIR__.'/src')
->in(__DIR__.'/tests')
->name('*.php')
)
;
return $config;
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/RetryMiddleware.php | src/RetryMiddleware.php | <?php
namespace GuzzleHttp;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Middleware that retries requests based on the boolean result of
* invoking the provided "decider" function.
*
* @final
*/
class RetryMiddleware
{
/**
* @var callable(RequestInterface, array): PromiseInterface
*/
private $nextHandler;
/**
* @var callable
*/
private $decider;
/**
* @var callable(int)
*/
private $delay;
/**
* @param callable $decider Function that accepts the number of retries,
* a request, [response], and [exception] and
* returns true if the request is to be
* retried.
* @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke.
* @param (callable(int): int)|null $delay Function that accepts the number of retries
* and returns the number of
* milliseconds to delay.
*/
public function __construct(callable $decider, callable $nextHandler, ?callable $delay = null)
{
$this->decider = $decider;
$this->nextHandler = $nextHandler;
$this->delay = $delay ?: __CLASS__.'::exponentialDelay';
}
/**
* Default exponential backoff delay function.
*
* @return int milliseconds.
*/
public static function exponentialDelay(int $retries): int
{
return (int) 2 ** ($retries - 1) * 1000;
}
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
if (!isset($options['retries'])) {
$options['retries'] = 0;
}
$fn = $this->nextHandler;
return $fn($request, $options)
->then(
$this->onFulfilled($request, $options),
$this->onRejected($request, $options)
);
}
/**
* Execute fulfilled closure
*/
private function onFulfilled(RequestInterface $request, array $options): callable
{
return function ($value) use ($request, $options) {
if (!($this->decider)(
$options['retries'],
$request,
$value,
null
)) {
return $value;
}
return $this->doRetry($request, $options, $value);
};
}
/**
* Execute rejected closure
*/
private function onRejected(RequestInterface $req, array $options): callable
{
return function ($reason) use ($req, $options) {
if (!($this->decider)(
$options['retries'],
$req,
null,
$reason
)) {
return P\Create::rejectionFor($reason);
}
return $this->doRetry($req, $options);
};
}
private function doRetry(RequestInterface $request, array $options, ?ResponseInterface $response = null): PromiseInterface
{
$options['delay'] = ($this->delay)(++$options['retries'], $response, $request);
return $this($request, $options);
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/functions_include.php | src/functions_include.php | <?php
// Don't redefine the functions if included multiple times.
if (!\function_exists('GuzzleHttp\describe_type')) {
require __DIR__.'/functions.php';
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/MessageFormatter.php | src/MessageFormatter.php | <?php
namespace GuzzleHttp;
use Psr\Http\Message\MessageInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Formats log messages using variable substitutions for requests, responses,
* and other transactional data.
*
* The following variable substitutions are supported:
*
* - {request}: Full HTTP request message
* - {response}: Full HTTP response message
* - {ts}: ISO 8601 date in GMT
* - {date_iso_8601} ISO 8601 date in GMT
* - {date_common_log} Apache common log date using the configured timezone.
* - {host}: Host of the request
* - {method}: Method of the request
* - {uri}: URI of the request
* - {version}: Protocol version
* - {target}: Request target of the request (path + query + fragment)
* - {hostname}: Hostname of the machine that sent the request
* - {code}: Status code of the response (if available)
* - {phrase}: Reason phrase of the response (if available)
* - {error}: Any error messages (if available)
* - {req_header_*}: Replace `*` with the lowercased name of a request header to add to the message
* - {res_header_*}: Replace `*` with the lowercased name of a response header to add to the message
* - {req_headers}: Request headers
* - {res_headers}: Response headers
* - {req_body}: Request body
* - {res_body}: Response body
*
* @final
*/
class MessageFormatter implements MessageFormatterInterface
{
/**
* Apache Common Log Format.
*
* @see https://httpd.apache.org/docs/2.4/logs.html#common
*
* @var string
*/
public const CLF = '{hostname} {req_header_User-Agent} - [{date_common_log}] "{method} {target} HTTP/{version}" {code} {res_header_Content-Length}';
public const DEBUG = ">>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}";
public const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}';
/**
* @var string Template used to format log messages
*/
private $template;
/**
* @param string $template Log message template
*/
public function __construct(?string $template = self::CLF)
{
$this->template = $template ?: self::CLF;
}
/**
* Returns a formatted message string.
*
* @param RequestInterface $request Request that was sent
* @param ResponseInterface|null $response Response that was received
* @param \Throwable|null $error Exception that was received
*/
public function format(RequestInterface $request, ?ResponseInterface $response = null, ?\Throwable $error = null): string
{
$cache = [];
/** @var string */
return \preg_replace_callback(
'/{\s*([A-Za-z_\-\.0-9]+)\s*}/',
function (array $matches) use ($request, $response, $error, &$cache) {
if (isset($cache[$matches[1]])) {
return $cache[$matches[1]];
}
$result = '';
switch ($matches[1]) {
case 'request':
$result = Psr7\Message::toString($request);
break;
case 'response':
$result = $response ? Psr7\Message::toString($response) : '';
break;
case 'req_headers':
$result = \trim($request->getMethod()
.' '.$request->getRequestTarget())
.' HTTP/'.$request->getProtocolVersion()."\r\n"
.$this->headers($request);
break;
case 'res_headers':
$result = $response ?
\sprintf(
'HTTP/%s %d %s',
$response->getProtocolVersion(),
$response->getStatusCode(),
$response->getReasonPhrase()
)."\r\n".$this->headers($response)
: 'NULL';
break;
case 'req_body':
$result = $request->getBody()->__toString();
break;
case 'res_body':
if (!$response instanceof ResponseInterface) {
$result = 'NULL';
break;
}
$body = $response->getBody();
if (!$body->isSeekable()) {
$result = 'RESPONSE_NOT_LOGGEABLE';
break;
}
$result = $response->getBody()->__toString();
break;
case 'ts':
case 'date_iso_8601':
$result = \gmdate('c');
break;
case 'date_common_log':
$result = \date('d/M/Y:H:i:s O');
break;
case 'method':
$result = $request->getMethod();
break;
case 'version':
$result = $request->getProtocolVersion();
break;
case 'uri':
case 'url':
$result = $request->getUri()->__toString();
break;
case 'target':
$result = $request->getRequestTarget();
break;
case 'req_version':
$result = $request->getProtocolVersion();
break;
case 'res_version':
$result = $response
? $response->getProtocolVersion()
: 'NULL';
break;
case 'host':
$result = $request->getHeaderLine('Host');
break;
case 'hostname':
$result = \gethostname();
break;
case 'code':
$result = $response ? $response->getStatusCode() : 'NULL';
break;
case 'phrase':
$result = $response ? $response->getReasonPhrase() : 'NULL';
break;
case 'error':
$result = $error ? $error->getMessage() : 'NULL';
break;
default:
// handle prefixed dynamic headers
if (\strpos($matches[1], 'req_header_') === 0) {
$result = $request->getHeaderLine(\substr($matches[1], 11));
} elseif (\strpos($matches[1], 'res_header_') === 0) {
$result = $response
? $response->getHeaderLine(\substr($matches[1], 11))
: 'NULL';
}
}
$cache[$matches[1]] = $result;
return $result;
},
$this->template
);
}
/**
* Get headers from message as string
*/
private function headers(MessageInterface $message): string
{
$result = '';
foreach ($message->getHeaders() as $name => $values) {
$result .= $name.': '.\implode(', ', $values)."\r\n";
}
return \trim($result);
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/RedirectMiddleware.php | src/RedirectMiddleware.php | <?php
namespace GuzzleHttp;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\TooManyRedirectsException;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* Request redirect middleware.
*
* Apply this middleware like other middleware using
* {@see \GuzzleHttp\Middleware::redirect()}.
*
* @final
*/
class RedirectMiddleware
{
public const HISTORY_HEADER = 'X-Guzzle-Redirect-History';
public const STATUS_HISTORY_HEADER = 'X-Guzzle-Redirect-Status-History';
/**
* @var array
*/
public static $defaultSettings = [
'max' => 5,
'protocols' => ['http', 'https'],
'strict' => false,
'referer' => false,
'track_redirects' => false,
];
/**
* @var callable(RequestInterface, array): PromiseInterface
*/
private $nextHandler;
/**
* @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke.
*/
public function __construct(callable $nextHandler)
{
$this->nextHandler = $nextHandler;
}
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
$fn = $this->nextHandler;
if (empty($options['allow_redirects'])) {
return $fn($request, $options);
}
if ($options['allow_redirects'] === true) {
$options['allow_redirects'] = self::$defaultSettings;
} elseif (!\is_array($options['allow_redirects'])) {
throw new \InvalidArgumentException('allow_redirects must be true, false, or array');
} else {
// Merge the default settings with the provided settings
$options['allow_redirects'] += self::$defaultSettings;
}
if (empty($options['allow_redirects']['max'])) {
return $fn($request, $options);
}
return $fn($request, $options)
->then(function (ResponseInterface $response) use ($request, $options) {
return $this->checkRedirect($request, $options, $response);
});
}
/**
* @return ResponseInterface|PromiseInterface
*/
public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response)
{
if (\strpos((string) $response->getStatusCode(), '3') !== 0
|| !$response->hasHeader('Location')
) {
return $response;
}
$this->guardMax($request, $response, $options);
$nextRequest = $this->modifyRequest($request, $options, $response);
// If authorization is handled by curl, unset it if URI is cross-origin.
if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $nextRequest->getUri()) && defined('\CURLOPT_HTTPAUTH')) {
unset(
$options['curl'][\CURLOPT_HTTPAUTH],
$options['curl'][\CURLOPT_USERPWD]
);
}
if (isset($options['allow_redirects']['on_redirect'])) {
($options['allow_redirects']['on_redirect'])(
$request,
$response,
$nextRequest->getUri()
);
}
$promise = $this($nextRequest, $options);
// Add headers to be able to track history of redirects.
if (!empty($options['allow_redirects']['track_redirects'])) {
return $this->withTracking(
$promise,
(string) $nextRequest->getUri(),
$response->getStatusCode()
);
}
return $promise;
}
/**
* Enable tracking on promise.
*/
private function withTracking(PromiseInterface $promise, string $uri, int $statusCode): PromiseInterface
{
return $promise->then(
static function (ResponseInterface $response) use ($uri, $statusCode) {
// Note that we are pushing to the front of the list as this
// would be an earlier response than what is currently present
// in the history header.
$historyHeader = $response->getHeader(self::HISTORY_HEADER);
$statusHeader = $response->getHeader(self::STATUS_HISTORY_HEADER);
\array_unshift($historyHeader, $uri);
\array_unshift($statusHeader, (string) $statusCode);
return $response->withHeader(self::HISTORY_HEADER, $historyHeader)
->withHeader(self::STATUS_HISTORY_HEADER, $statusHeader);
}
);
}
/**
* Check for too many redirects.
*
* @throws TooManyRedirectsException Too many redirects.
*/
private function guardMax(RequestInterface $request, ResponseInterface $response, array &$options): void
{
$current = $options['__redirect_count']
?? 0;
$options['__redirect_count'] = $current + 1;
$max = $options['allow_redirects']['max'];
if ($options['__redirect_count'] > $max) {
throw new TooManyRedirectsException("Will not follow more than {$max} redirects", $request, $response);
}
}
public function modifyRequest(RequestInterface $request, array $options, ResponseInterface $response): RequestInterface
{
// Request modifications to apply.
$modify = [];
$protocols = $options['allow_redirects']['protocols'];
// Use a GET request if this is an entity enclosing request and we are
// not forcing RFC compliance, but rather emulating what all browsers
// would do.
$statusCode = $response->getStatusCode();
if ($statusCode == 303
|| ($statusCode <= 302 && !$options['allow_redirects']['strict'])
) {
$safeMethods = ['GET', 'HEAD', 'OPTIONS'];
$requestMethod = $request->getMethod();
$modify['method'] = in_array($requestMethod, $safeMethods) ? $requestMethod : 'GET';
$modify['body'] = '';
}
$uri = self::redirectUri($request, $response, $protocols);
if (isset($options['idn_conversion']) && ($options['idn_conversion'] !== false)) {
$idnOptions = ($options['idn_conversion'] === true) ? \IDNA_DEFAULT : $options['idn_conversion'];
$uri = Utils::idnUriConvert($uri, $idnOptions);
}
$modify['uri'] = $uri;
Psr7\Message::rewindBody($request);
// Add the Referer header if it is told to do so and only
// add the header if we are not redirecting from https to http.
if ($options['allow_redirects']['referer']
&& $modify['uri']->getScheme() === $request->getUri()->getScheme()
) {
$uri = $request->getUri()->withUserInfo('');
$modify['set_headers']['Referer'] = (string) $uri;
} else {
$modify['remove_headers'][] = 'Referer';
}
// Remove Authorization and Cookie headers if URI is cross-origin.
if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $modify['uri'])) {
$modify['remove_headers'][] = 'Authorization';
$modify['remove_headers'][] = 'Cookie';
}
return Psr7\Utils::modifyRequest($request, $modify);
}
/**
* Set the appropriate URL on the request based on the location header.
*/
private static function redirectUri(
RequestInterface $request,
ResponseInterface $response,
array $protocols
): UriInterface {
$location = Psr7\UriResolver::resolve(
$request->getUri(),
new Psr7\Uri($response->getHeaderLine('Location'))
);
// Ensure that the redirect URI is allowed based on the protocols.
if (!\in_array($location->getScheme(), $protocols)) {
throw new BadResponseException(\sprintf('Redirect URI, %s, does not use one of the allowed redirect protocols: %s', $location, \implode(', ', $protocols)), $request, $response);
}
return $location;
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Client.php | src/Client.php | <?php
namespace GuzzleHttp;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\InvalidArgumentException;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* @final
*/
class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
{
use ClientTrait;
/**
* @var array Default request options
*/
private $config;
/**
* Clients accept an array of constructor parameters.
*
* Here's an example of creating a client using a base_uri and an array of
* default request options to apply to each request:
*
* $client = new Client([
* 'base_uri' => 'http://www.foo.com/1.0/',
* 'timeout' => 0,
* 'allow_redirects' => false,
* 'proxy' => '192.168.16.1:10'
* ]);
*
* Client configuration settings include the following options:
*
* - handler: (callable) Function that transfers HTTP requests over the
* wire. The function is called with a Psr7\Http\Message\RequestInterface
* and array of transfer options, and must return a
* GuzzleHttp\Promise\PromiseInterface that is fulfilled with a
* Psr7\Http\Message\ResponseInterface on success.
* If no handler is provided, a default handler will be created
* that enables all of the request options below by attaching all of the
* default middleware to the handler.
* - base_uri: (string|UriInterface) Base URI of the client that is merged
* into relative URIs. Can be a string or instance of UriInterface.
* - **: any request option
*
* @param array $config Client configuration settings.
*
* @see RequestOptions for a list of available request options.
*/
public function __construct(array $config = [])
{
if (!isset($config['handler'])) {
$config['handler'] = HandlerStack::create();
} elseif (!\is_callable($config['handler'])) {
throw new InvalidArgumentException('handler must be a callable');
}
// Convert the base_uri to a UriInterface
if (isset($config['base_uri'])) {
$config['base_uri'] = Psr7\Utils::uriFor($config['base_uri']);
}
$this->configureDefaults($config);
}
/**
* @param string $method
* @param array $args
*
* @return PromiseInterface|ResponseInterface
*
* @deprecated Client::__call will be removed in guzzlehttp/guzzle:8.0.
*/
public function __call($method, $args)
{
if (\count($args) < 1) {
throw new InvalidArgumentException('Magic request methods require a URI and optional options array');
}
$uri = $args[0];
$opts = $args[1] ?? [];
return \substr($method, -5) === 'Async'
? $this->requestAsync(\substr($method, 0, -5), $uri, $opts)
: $this->request($method, $uri, $opts);
}
/**
* Asynchronously send an HTTP request.
*
* @param array $options Request options to apply to the given
* request and to the transfer. See \GuzzleHttp\RequestOptions.
*/
public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface
{
// Merge the base URI into the request URI if needed.
$options = $this->prepareDefaults($options);
return $this->transfer(
$request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')),
$options
);
}
/**
* Send an HTTP request.
*
* @param array $options Request options to apply to the given
* request and to the transfer. See \GuzzleHttp\RequestOptions.
*
* @throws GuzzleException
*/
public function send(RequestInterface $request, array $options = []): ResponseInterface
{
$options[RequestOptions::SYNCHRONOUS] = true;
return $this->sendAsync($request, $options)->wait();
}
/**
* The HttpClient PSR (PSR-18) specify this method.
*
* {@inheritDoc}
*/
public function sendRequest(RequestInterface $request): ResponseInterface
{
$options[RequestOptions::SYNCHRONOUS] = true;
$options[RequestOptions::ALLOW_REDIRECTS] = false;
$options[RequestOptions::HTTP_ERRORS] = false;
return $this->sendAsync($request, $options)->wait();
}
/**
* Create and send an asynchronous HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply. See \GuzzleHttp\RequestOptions.
*/
public function requestAsync(string $method, $uri = '', array $options = []): PromiseInterface
{
$options = $this->prepareDefaults($options);
// Remove request modifying parameter because it can be done up-front.
$headers = $options['headers'] ?? [];
$body = $options['body'] ?? null;
$version = $options['version'] ?? '1.1';
// Merge the URI into the base URI.
$uri = $this->buildUri(Psr7\Utils::uriFor($uri), $options);
if (\is_array($body)) {
throw $this->invalidBody();
}
$request = new Psr7\Request($method, $uri, $headers, $body, $version);
// Remove the option so that they are not doubly-applied.
unset($options['headers'], $options['body'], $options['version']);
return $this->transfer($request, $options);
}
/**
* Create and send an HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string $method HTTP method.
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply. See \GuzzleHttp\RequestOptions.
*
* @throws GuzzleException
*/
public function request(string $method, $uri = '', array $options = []): ResponseInterface
{
$options[RequestOptions::SYNCHRONOUS] = true;
return $this->requestAsync($method, $uri, $options)->wait();
}
/**
* Get a client configuration option.
*
* These options include default request options of the client, a "handler"
* (if utilized by the concrete client), and a "base_uri" if utilized by
* the concrete client.
*
* @param string|null $option The config option to retrieve.
*
* @return mixed
*
* @deprecated Client::getConfig will be removed in guzzlehttp/guzzle:8.0.
*/
public function getConfig(?string $option = null)
{
return $option === null
? $this->config
: ($this->config[$option] ?? null);
}
private function buildUri(UriInterface $uri, array $config): UriInterface
{
if (isset($config['base_uri'])) {
$uri = Psr7\UriResolver::resolve(Psr7\Utils::uriFor($config['base_uri']), $uri);
}
if (isset($config['idn_conversion']) && ($config['idn_conversion'] !== false)) {
$idnOptions = ($config['idn_conversion'] === true) ? \IDNA_DEFAULT : $config['idn_conversion'];
$uri = Utils::idnUriConvert($uri, $idnOptions);
}
return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri;
}
/**
* Configures the default options for a client.
*/
private function configureDefaults(array $config): void
{
$defaults = [
'allow_redirects' => RedirectMiddleware::$defaultSettings,
'http_errors' => true,
'decode_content' => true,
'verify' => true,
'cookies' => false,
'idn_conversion' => false,
];
// Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set.
// We can only trust the HTTP_PROXY environment variable in a CLI
// process due to the fact that PHP has no reliable mechanism to
// get environment variables that start with "HTTP_".
if (\PHP_SAPI === 'cli' && ($proxy = Utils::getenv('HTTP_PROXY'))) {
$defaults['proxy']['http'] = $proxy;
}
if ($proxy = Utils::getenv('HTTPS_PROXY')) {
$defaults['proxy']['https'] = $proxy;
}
if ($noProxy = Utils::getenv('NO_PROXY')) {
$cleanedNoProxy = \str_replace(' ', '', $noProxy);
$defaults['proxy']['no'] = \explode(',', $cleanedNoProxy);
}
$this->config = $config + $defaults;
if (!empty($config['cookies']) && $config['cookies'] === true) {
$this->config['cookies'] = new CookieJar();
}
// Add the default user-agent header.
if (!isset($this->config['headers'])) {
$this->config['headers'] = ['User-Agent' => Utils::defaultUserAgent()];
} else {
// Add the User-Agent header if one was not already set.
foreach (\array_keys($this->config['headers']) as $name) {
if (\strtolower($name) === 'user-agent') {
return;
}
}
$this->config['headers']['User-Agent'] = Utils::defaultUserAgent();
}
}
/**
* Merges default options into the array.
*
* @param array $options Options to modify by reference
*/
private function prepareDefaults(array $options): array
{
$defaults = $this->config;
if (!empty($defaults['headers'])) {
// Default headers are only added if they are not present.
$defaults['_conditional'] = $defaults['headers'];
unset($defaults['headers']);
}
// Special handling for headers is required as they are added as
// conditional headers and as headers passed to a request ctor.
if (\array_key_exists('headers', $options)) {
// Allows default headers to be unset.
if ($options['headers'] === null) {
$defaults['_conditional'] = [];
unset($options['headers']);
} elseif (!\is_array($options['headers'])) {
throw new InvalidArgumentException('headers must be an array');
}
}
// Shallow merge defaults underneath options.
$result = $options + $defaults;
// Remove null values.
foreach ($result as $k => $v) {
if ($v === null) {
unset($result[$k]);
}
}
return $result;
}
/**
* Transfers the given request and applies request options.
*
* The URI of the request is not modified and the request options are used
* as-is without merging in default options.
*
* @param array $options See \GuzzleHttp\RequestOptions.
*/
private function transfer(RequestInterface $request, array $options): PromiseInterface
{
$request = $this->applyOptions($request, $options);
/** @var HandlerStack $handler */
$handler = $options['handler'];
try {
return P\Create::promiseFor($handler($request, $options));
} catch (\Exception $e) {
return P\Create::rejectionFor($e);
}
}
/**
* Applies the array of request options to a request.
*/
private function applyOptions(RequestInterface $request, array &$options): RequestInterface
{
$modify = [
'set_headers' => [],
];
if (isset($options['headers'])) {
if (array_keys($options['headers']) === range(0, count($options['headers']) - 1)) {
throw new InvalidArgumentException('The headers array must have header name as keys.');
}
$modify['set_headers'] = $options['headers'];
unset($options['headers']);
}
if (isset($options['form_params'])) {
if (isset($options['multipart'])) {
throw new InvalidArgumentException('You cannot use '
.'form_params and multipart at the same time. Use the '
.'form_params option if you want to send application/'
.'x-www-form-urlencoded requests, and the multipart '
.'option to send multipart/form-data requests.');
}
$options['body'] = \http_build_query($options['form_params'], '', '&');
unset($options['form_params']);
// Ensure that we don't have the header in different case and set the new value.
$options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']);
$options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded';
}
if (isset($options['multipart'])) {
$options['body'] = new Psr7\MultipartStream($options['multipart']);
unset($options['multipart']);
}
if (isset($options['json'])) {
$options['body'] = Utils::jsonEncode($options['json']);
unset($options['json']);
// Ensure that we don't have the header in different case and set the new value.
$options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']);
$options['_conditional']['Content-Type'] = 'application/json';
}
if (!empty($options['decode_content'])
&& $options['decode_content'] !== true
) {
// Ensure that we don't have the header in different case and set the new value.
$options['_conditional'] = Psr7\Utils::caselessRemove(['Accept-Encoding'], $options['_conditional']);
$modify['set_headers']['Accept-Encoding'] = $options['decode_content'];
}
if (isset($options['body'])) {
if (\is_array($options['body'])) {
throw $this->invalidBody();
}
$modify['body'] = Psr7\Utils::streamFor($options['body']);
unset($options['body']);
}
if (!empty($options['auth']) && \is_array($options['auth'])) {
$value = $options['auth'];
$type = isset($value[2]) ? \strtolower($value[2]) : 'basic';
switch ($type) {
case 'basic':
// Ensure that we don't have the header in different case and set the new value.
$modify['set_headers'] = Psr7\Utils::caselessRemove(['Authorization'], $modify['set_headers']);
$modify['set_headers']['Authorization'] = 'Basic '
.\base64_encode("$value[0]:$value[1]");
break;
case 'digest':
// @todo: Do not rely on curl
$options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_DIGEST;
$options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]";
break;
case 'ntlm':
$options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_NTLM;
$options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]";
break;
}
}
if (isset($options['query'])) {
$value = $options['query'];
if (\is_array($value)) {
$value = \http_build_query($value, '', '&', \PHP_QUERY_RFC3986);
}
if (!\is_string($value)) {
throw new InvalidArgumentException('query must be a string or array');
}
$modify['query'] = $value;
unset($options['query']);
}
// Ensure that sink is not an invalid value.
if (isset($options['sink'])) {
// TODO: Add more sink validation?
if (\is_bool($options['sink'])) {
throw new InvalidArgumentException('sink must not be a boolean');
}
}
if (isset($options['version'])) {
$modify['version'] = $options['version'];
}
$request = Psr7\Utils::modifyRequest($request, $modify);
if ($request->getBody() instanceof Psr7\MultipartStream) {
// Use a multipart/form-data POST if a Content-Type is not set.
// Ensure that we don't have the header in different case and set the new value.
$options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']);
$options['_conditional']['Content-Type'] = 'multipart/form-data; boundary='
.$request->getBody()->getBoundary();
}
// Merge in conditional headers if they are not present.
if (isset($options['_conditional'])) {
// Build up the changes so it's in a single clone of the message.
$modify = [];
foreach ($options['_conditional'] as $k => $v) {
if (!$request->hasHeader($k)) {
$modify['set_headers'][$k] = $v;
}
}
$request = Psr7\Utils::modifyRequest($request, $modify);
// Don't pass this internal value along to middleware/handlers.
unset($options['_conditional']);
}
return $request;
}
/**
* Return an InvalidArgumentException with pre-set message.
*/
private function invalidBody(): InvalidArgumentException
{
return new InvalidArgumentException('Passing in the "body" request '
.'option as an array to send a request is not supported. '
.'Please use the "form_params" request option to send a '
.'application/x-www-form-urlencoded request, or the "multipart" '
.'request option to send a multipart/form-data request.');
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/ClientTrait.php | src/ClientTrait.php | <?php
namespace GuzzleHttp;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* Client interface for sending HTTP requests.
*/
trait ClientTrait
{
/**
* Create and send an HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string $method HTTP method.
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
abstract public function request(string $method, $uri, array $options = []): ResponseInterface;
/**
* Create and send an HTTP GET request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function get($uri, array $options = []): ResponseInterface
{
return $this->request('GET', $uri, $options);
}
/**
* Create and send an HTTP HEAD request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function head($uri, array $options = []): ResponseInterface
{
return $this->request('HEAD', $uri, $options);
}
/**
* Create and send an HTTP PUT request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function put($uri, array $options = []): ResponseInterface
{
return $this->request('PUT', $uri, $options);
}
/**
* Create and send an HTTP POST request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function post($uri, array $options = []): ResponseInterface
{
return $this->request('POST', $uri, $options);
}
/**
* Create and send an HTTP PATCH request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function patch($uri, array $options = []): ResponseInterface
{
return $this->request('PATCH', $uri, $options);
}
/**
* Create and send an HTTP DELETE request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function delete($uri, array $options = []): ResponseInterface
{
return $this->request('DELETE', $uri, $options);
}
/**
* Create and send an asynchronous HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
abstract public function requestAsync(string $method, $uri, array $options = []): PromiseInterface;
/**
* Create and send an asynchronous HTTP GET request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function getAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('GET', $uri, $options);
}
/**
* Create and send an asynchronous HTTP HEAD request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function headAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('HEAD', $uri, $options);
}
/**
* Create and send an asynchronous HTTP PUT request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function putAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('PUT', $uri, $options);
}
/**
* Create and send an asynchronous HTTP POST request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function postAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('POST', $uri, $options);
}
/**
* Create and send an asynchronous HTTP PATCH request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function patchAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('PATCH', $uri, $options);
}
/**
* Create and send an asynchronous HTTP DELETE request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function deleteAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('DELETE', $uri, $options);
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Pool.php | src/Pool.php | <?php
namespace GuzzleHttp;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\EachPromise;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Promise\PromisorInterface;
use Psr\Http\Message\RequestInterface;
/**
* Sends an iterator of requests concurrently using a capped pool size.
*
* The pool will read from an iterator until it is cancelled or until the
* iterator is consumed. When a request is yielded, the request is sent after
* applying the "request_options" request options (if provided in the ctor).
*
* When a function is yielded by the iterator, the function is provided the
* "request_options" array that should be merged on top of any existing
* options, and the function MUST then return a wait-able promise.
*
* @final
*/
class Pool implements PromisorInterface
{
/**
* @var EachPromise
*/
private $each;
/**
* @param ClientInterface $client Client used to send the requests.
* @param array|\Iterator $requests Requests or functions that return
* requests to send concurrently.
* @param array $config Associative array of options
* - concurrency: (int) Maximum number of requests to send concurrently
* - options: Array of request options to apply to each request.
* - fulfilled: (callable) Function to invoke when a request completes.
* - rejected: (callable) Function to invoke when a request is rejected.
*/
public function __construct(ClientInterface $client, $requests, array $config = [])
{
if (!isset($config['concurrency'])) {
$config['concurrency'] = 25;
}
if (isset($config['options'])) {
$opts = $config['options'];
unset($config['options']);
} else {
$opts = [];
}
$iterable = P\Create::iterFor($requests);
$requests = static function () use ($iterable, $client, $opts) {
foreach ($iterable as $key => $rfn) {
if ($rfn instanceof RequestInterface) {
yield $key => $client->sendAsync($rfn, $opts);
} elseif (\is_callable($rfn)) {
yield $key => $rfn($opts);
} else {
throw new \InvalidArgumentException('Each value yielded by the iterator must be a Psr7\Http\Message\RequestInterface or a callable that returns a promise that fulfills with a Psr7\Message\Http\ResponseInterface object.');
}
}
};
$this->each = new EachPromise($requests(), $config);
}
/**
* Get promise
*/
public function promise(): PromiseInterface
{
return $this->each->promise();
}
/**
* Sends multiple requests concurrently and returns an array of responses
* and exceptions that uses the same ordering as the provided requests.
*
* IMPORTANT: This method keeps every request and response in memory, and
* as such, is NOT recommended when sending a large number or an
* indeterminate number of requests concurrently.
*
* @param ClientInterface $client Client used to send the requests
* @param array|\Iterator $requests Requests to send concurrently.
* @param array $options Passes through the options available in
* {@see Pool::__construct}
*
* @return array Returns an array containing the response or an exception
* in the same order that the requests were sent.
*
* @throws \InvalidArgumentException if the event format is incorrect.
*/
public static function batch(ClientInterface $client, $requests, array $options = []): array
{
$res = [];
self::cmpCallback($options, 'fulfilled', $res);
self::cmpCallback($options, 'rejected', $res);
$pool = new static($client, $requests, $options);
$pool->promise()->wait();
\ksort($res);
return $res;
}
/**
* Execute callback(s)
*/
private static function cmpCallback(array &$options, string $name, array &$results): void
{
if (!isset($options[$name])) {
$options[$name] = static function ($v, $k) use (&$results) {
$results[$k] = $v;
};
} else {
$currentFn = $options[$name];
$options[$name] = static function ($v, $k) use (&$results, $currentFn) {
$currentFn($v, $k);
$results[$k] = $v;
};
}
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Middleware.php | src/Middleware.php | <?php
namespace GuzzleHttp;
use GuzzleHttp\Cookie\CookieJarInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
/**
* Functions used to create and wrap handlers with handler middleware.
*/
final class Middleware
{
/**
* Middleware that adds cookies to requests.
*
* The options array must be set to a CookieJarInterface in order to use
* cookies. This is typically handled for you by a client.
*
* @return callable Returns a function that accepts the next handler.
*/
public static function cookies(): callable
{
return static function (callable $handler): callable {
return static function ($request, array $options) use ($handler) {
if (empty($options['cookies'])) {
return $handler($request, $options);
} elseif (!($options['cookies'] instanceof CookieJarInterface)) {
throw new \InvalidArgumentException('cookies must be an instance of GuzzleHttp\Cookie\CookieJarInterface');
}
$cookieJar = $options['cookies'];
$request = $cookieJar->withCookieHeader($request);
return $handler($request, $options)
->then(
static function (ResponseInterface $response) use ($cookieJar, $request): ResponseInterface {
$cookieJar->extractCookies($request, $response);
return $response;
}
);
};
};
}
/**
* Middleware that throws exceptions for 4xx or 5xx responses when the
* "http_errors" request option is set to true.
*
* @param BodySummarizerInterface|null $bodySummarizer The body summarizer to use in exception messages.
*
* @return callable(callable): callable Returns a function that accepts the next handler.
*/
public static function httpErrors(?BodySummarizerInterface $bodySummarizer = null): callable
{
return static function (callable $handler) use ($bodySummarizer): callable {
return static function ($request, array $options) use ($handler, $bodySummarizer) {
if (empty($options['http_errors'])) {
return $handler($request, $options);
}
return $handler($request, $options)->then(
static function (ResponseInterface $response) use ($request, $bodySummarizer) {
$code = $response->getStatusCode();
if ($code < 400) {
return $response;
}
throw RequestException::create($request, $response, null, [], $bodySummarizer);
}
);
};
};
}
/**
* Middleware that pushes history data to an ArrayAccess container.
*
* @param array|\ArrayAccess<int, array> $container Container to hold the history (by reference).
*
* @return callable(callable): callable Returns a function that accepts the next handler.
*
* @throws \InvalidArgumentException if container is not an array or ArrayAccess.
*/
public static function history(&$container): callable
{
if (!\is_array($container) && !$container instanceof \ArrayAccess) {
throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess');
}
return static function (callable $handler) use (&$container): callable {
return static function (RequestInterface $request, array $options) use ($handler, &$container) {
return $handler($request, $options)->then(
static function ($value) use ($request, &$container, $options) {
$container[] = [
'request' => $request,
'response' => $value,
'error' => null,
'options' => $options,
];
return $value;
},
static function ($reason) use ($request, &$container, $options) {
$container[] = [
'request' => $request,
'response' => null,
'error' => $reason,
'options' => $options,
];
return P\Create::rejectionFor($reason);
}
);
};
};
}
/**
* Middleware that invokes a callback before and after sending a request.
*
* The provided listener cannot modify or alter the response. It simply
* "taps" into the chain to be notified before returning the promise. The
* before listener accepts a request and options array, and the after
* listener accepts a request, options array, and response promise.
*
* @param callable $before Function to invoke before forwarding the request.
* @param callable $after Function invoked after forwarding.
*
* @return callable Returns a function that accepts the next handler.
*/
public static function tap(?callable $before = null, ?callable $after = null): callable
{
return static function (callable $handler) use ($before, $after): callable {
return static function (RequestInterface $request, array $options) use ($handler, $before, $after) {
if ($before) {
$before($request, $options);
}
$response = $handler($request, $options);
if ($after) {
$after($request, $options, $response);
}
return $response;
};
};
}
/**
* Middleware that handles request redirects.
*
* @return callable Returns a function that accepts the next handler.
*/
public static function redirect(): callable
{
return static function (callable $handler): RedirectMiddleware {
return new RedirectMiddleware($handler);
};
}
/**
* Middleware that retries requests based on the boolean result of
* invoking the provided "decider" function.
*
* If no delay function is provided, a simple implementation of exponential
* backoff will be utilized.
*
* @param callable $decider Function that accepts the number of retries,
* a request, [response], and [exception] and
* returns true if the request is to be retried.
* @param callable $delay Function that accepts the number of retries and
* returns the number of milliseconds to delay.
*
* @return callable Returns a function that accepts the next handler.
*/
public static function retry(callable $decider, ?callable $delay = null): callable
{
return static function (callable $handler) use ($decider, $delay): RetryMiddleware {
return new RetryMiddleware($decider, $handler, $delay);
};
}
/**
* Middleware that logs requests, responses, and errors using a message
* formatter.
*
* @param LoggerInterface $logger Logs messages.
* @param MessageFormatterInterface|MessageFormatter $formatter Formatter used to create message strings.
* @param string $logLevel Level at which to log requests.
*
* @phpstan-param \Psr\Log\LogLevel::* $logLevel Level at which to log requests.
*
* @return callable Returns a function that accepts the next handler.
*/
public static function log(LoggerInterface $logger, $formatter, string $logLevel = 'info'): callable
{
// To be compatible with Guzzle 7.1.x we need to allow users to pass a MessageFormatter
if (!$formatter instanceof MessageFormatter && !$formatter instanceof MessageFormatterInterface) {
throw new \LogicException(sprintf('Argument 2 to %s::log() must be of type %s', self::class, MessageFormatterInterface::class));
}
return static function (callable $handler) use ($logger, $formatter, $logLevel): callable {
return static function (RequestInterface $request, array $options = []) use ($handler, $logger, $formatter, $logLevel) {
return $handler($request, $options)->then(
static function ($response) use ($logger, $request, $formatter, $logLevel): ResponseInterface {
$message = $formatter->format($request, $response);
$logger->log($logLevel, $message);
return $response;
},
static function ($reason) use ($logger, $request, $formatter): PromiseInterface {
$response = $reason instanceof RequestException ? $reason->getResponse() : null;
$message = $formatter->format($request, $response, P\Create::exceptionFor($reason));
$logger->error($message);
return P\Create::rejectionFor($reason);
}
);
};
};
}
/**
* This middleware adds a default content-type if possible, a default
* content-length or transfer-encoding header, and the expect header.
*/
public static function prepareBody(): callable
{
return static function (callable $handler): PrepareBodyMiddleware {
return new PrepareBodyMiddleware($handler);
};
}
/**
* Middleware that applies a map function to the request before passing to
* the next handler.
*
* @param callable $fn Function that accepts a RequestInterface and returns
* a RequestInterface.
*/
public static function mapRequest(callable $fn): callable
{
return static function (callable $handler) use ($fn): callable {
return static function (RequestInterface $request, array $options) use ($handler, $fn) {
return $handler($fn($request), $options);
};
};
}
/**
* Middleware that applies a map function to the resolved promise's
* response.
*
* @param callable $fn Function that accepts a ResponseInterface and
* returns a ResponseInterface.
*/
public static function mapResponse(callable $fn): callable
{
return static function (callable $handler) use ($fn): callable {
return static function (RequestInterface $request, array $options) use ($handler, $fn) {
return $handler($request, $options)->then($fn);
};
};
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/PrepareBodyMiddleware.php | src/PrepareBodyMiddleware.php | <?php
namespace GuzzleHttp;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
/**
* Prepares requests that contain a body, adding the Content-Length,
* Content-Type, and Expect headers.
*
* @final
*/
class PrepareBodyMiddleware
{
/**
* @var callable(RequestInterface, array): PromiseInterface
*/
private $nextHandler;
/**
* @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke.
*/
public function __construct(callable $nextHandler)
{
$this->nextHandler = $nextHandler;
}
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
$fn = $this->nextHandler;
// Don't do anything if the request has no body.
if ($request->getBody()->getSize() === 0) {
return $fn($request, $options);
}
$modify = [];
// Add a default content-type if possible.
if (!$request->hasHeader('Content-Type')) {
if ($uri = $request->getBody()->getMetadata('uri')) {
if (is_string($uri) && $type = Psr7\MimeType::fromFilename($uri)) {
$modify['set_headers']['Content-Type'] = $type;
}
}
}
// Add a default content-length or transfer-encoding header.
if (!$request->hasHeader('Content-Length')
&& !$request->hasHeader('Transfer-Encoding')
) {
$size = $request->getBody()->getSize();
if ($size !== null) {
$modify['set_headers']['Content-Length'] = $size;
} else {
$modify['set_headers']['Transfer-Encoding'] = 'chunked';
}
}
// Add the expect header if needed.
$this->addExpectHeader($request, $options, $modify);
return $fn(Psr7\Utils::modifyRequest($request, $modify), $options);
}
/**
* Add expect header
*/
private function addExpectHeader(RequestInterface $request, array $options, array &$modify): void
{
// Determine if the Expect header should be used
if ($request->hasHeader('Expect')) {
return;
}
$expect = $options['expect'] ?? null;
// Return if disabled or using HTTP/1.0
if ($expect === false || $request->getProtocolVersion() === '1.0') {
return;
}
// The expect header is unconditionally enabled
if ($expect === true) {
$modify['set_headers']['Expect'] = '100-Continue';
return;
}
// By default, send the expect header when the payload is > 1mb
if ($expect === null) {
$expect = 1048576;
}
// Always add if the body cannot be rewound, the size cannot be
// determined, or the size is greater than the cutoff threshold
$body = $request->getBody();
$size = $body->getSize();
if ($size === null || $size >= (int) $expect || !$body->isSeekable()) {
$modify['set_headers']['Expect'] = '100-Continue';
}
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/RequestOptions.php | src/RequestOptions.php | <?php
namespace GuzzleHttp;
/**
* This class contains a list of built-in Guzzle request options.
*
* @see https://docs.guzzlephp.org/en/latest/request-options.html
*/
final class RequestOptions
{
/**
* allow_redirects: (bool|array) Controls redirect behavior. Pass false
* to disable redirects, pass true to enable redirects, pass an
* associative to provide custom redirect settings. Defaults to "false".
* This option only works if your handler has the RedirectMiddleware. When
* passing an associative array, you can provide the following key value
* pairs:
*
* - max: (int, default=5) maximum number of allowed redirects.
* - strict: (bool, default=false) Set to true to use strict redirects
* meaning redirect POST requests with POST requests vs. doing what most
* browsers do which is redirect POST requests with GET requests
* - referer: (bool, default=false) Set to true to enable the Referer
* header.
* - protocols: (array, default=['http', 'https']) Allowed redirect
* protocols.
* - on_redirect: (callable) PHP callable that is invoked when a redirect
* is encountered. The callable is invoked with the request, the redirect
* response that was received, and the effective URI. Any return value
* from the on_redirect function is ignored.
*/
public const ALLOW_REDIRECTS = 'allow_redirects';
/**
* auth: (array) Pass an array of HTTP authentication parameters to use
* with the request. The array must contain the username in index [0],
* the password in index [1], and you can optionally provide a built-in
* authentication type in index [2]. Pass null to disable authentication
* for a request.
*/
public const AUTH = 'auth';
/**
* body: (resource|string|null|int|float|StreamInterface|callable|\Iterator)
* Body to send in the request.
*/
public const BODY = 'body';
/**
* cert: (string|array) Set to a string to specify the path to a file
* containing a PEM formatted SSL client side certificate. If a password
* is required, then set cert to an array containing the path to the PEM
* file in the first array element followed by the certificate password
* in the second array element.
*/
public const CERT = 'cert';
/**
* cookies: (bool|GuzzleHttp\Cookie\CookieJarInterface, default=false)
* Specifies whether or not cookies are used in a request or what cookie
* jar to use or what cookies to send. This option only works if your
* handler has the `cookie` middleware. Valid values are `false` and
* an instance of {@see Cookie\CookieJarInterface}.
*/
public const COOKIES = 'cookies';
/**
* connect_timeout: (float, default=0) Float describing the number of
* seconds to wait while trying to connect to a server. Use 0 to wait
* 300 seconds (the default behavior).
*/
public const CONNECT_TIMEOUT = 'connect_timeout';
/**
* crypto_method: (int) A value describing the minimum TLS protocol
* version to use.
*
* This setting must be set to one of the
* ``STREAM_CRYPTO_METHOD_TLS*_CLIENT`` constants. PHP 7.4 or higher is
* required in order to use TLS 1.3, and cURL 7.34.0 or higher is required
* in order to specify a crypto method, with cURL 7.52.0 or higher being
* required to use TLS 1.3.
*/
public const CRYPTO_METHOD = 'crypto_method';
/**
* debug: (bool|resource) Set to true or set to a PHP stream returned by
* fopen() enable debug output with the HTTP handler used to send a
* request.
*/
public const DEBUG = 'debug';
/**
* decode_content: (bool, default=true) Specify whether or not
* Content-Encoding responses (gzip, deflate, etc.) are automatically
* decoded.
*/
public const DECODE_CONTENT = 'decode_content';
/**
* delay: (int) The amount of time to delay before sending in milliseconds.
*/
public const DELAY = 'delay';
/**
* expect: (bool|integer) Controls the behavior of the
* "Expect: 100-Continue" header.
*
* Set to `true` to enable the "Expect: 100-Continue" header for all
* requests that sends a body. Set to `false` to disable the
* "Expect: 100-Continue" header for all requests. Set to a number so that
* the size of the payload must be greater than the number in order to send
* the Expect header. Setting to a number will send the Expect header for
* all requests in which the size of the payload cannot be determined or
* where the body is not rewindable.
*
* By default, Guzzle will add the "Expect: 100-Continue" header when the
* size of the body of a request is greater than 1 MB and a request is
* using HTTP/1.1.
*/
public const EXPECT = 'expect';
/**
* form_params: (array) Associative array of form field names to values
* where each value is a string or array of strings. Sets the Content-Type
* header to application/x-www-form-urlencoded when no Content-Type header
* is already present.
*/
public const FORM_PARAMS = 'form_params';
/**
* headers: (array) Associative array of HTTP headers. Each value MUST be
* a string or array of strings.
*/
public const HEADERS = 'headers';
/**
* http_errors: (bool, default=true) Set to false to disable exceptions
* when a non- successful HTTP response is received. By default,
* exceptions will be thrown for 4xx and 5xx responses. This option only
* works if your handler has the `httpErrors` middleware.
*/
public const HTTP_ERRORS = 'http_errors';
/**
* idn: (bool|int, default=true) A combination of IDNA_* constants for
* idn_to_ascii() PHP's function (see "options" parameter). Set to false to
* disable IDN support completely, or to true to use the default
* configuration (IDNA_DEFAULT constant).
*/
public const IDN_CONVERSION = 'idn_conversion';
/**
* json: (mixed) Adds JSON data to a request. The provided value is JSON
* encoded and a Content-Type header of application/json will be added to
* the request if no Content-Type header is already present.
*/
public const JSON = 'json';
/**
* multipart: (array) Array of associative arrays, each containing a
* required "name" key mapping to the form field, name, a required
* "contents" key mapping to a StreamInterface|resource|string, an
* optional "headers" associative array of custom headers, and an
* optional "filename" key mapping to a string to send as the filename in
* the part. If no "filename" key is present, then no "filename" attribute
* will be added to the part.
*/
public const MULTIPART = 'multipart';
/**
* on_headers: (callable) A callable that is invoked when the HTTP headers
* of the response have been received but the body has not yet begun to
* download.
*/
public const ON_HEADERS = 'on_headers';
/**
* on_stats: (callable) allows you to get access to transfer statistics of
* a request and access the lower level transfer details of the handler
* associated with your client. ``on_stats`` is a callable that is invoked
* when a handler has finished sending a request. The callback is invoked
* with transfer statistics about the request, the response received, or
* the error encountered. Included in the data is the total amount of time
* taken to send the request.
*/
public const ON_STATS = 'on_stats';
/**
* progress: (callable) Defines a function to invoke when transfer
* progress is made. The function accepts the following positional
* arguments: the total number of bytes expected to be downloaded, the
* number of bytes downloaded so far, the number of bytes expected to be
* uploaded, the number of bytes uploaded so far.
*/
public const PROGRESS = 'progress';
/**
* proxy: (string|array) Pass a string to specify an HTTP proxy, or an
* array to specify different proxies for different protocols (where the
* key is the protocol and the value is a proxy string).
*/
public const PROXY = 'proxy';
/**
* query: (array|string) Associative array of query string values to add
* to the request. This option uses PHP's http_build_query() to create
* the string representation. Pass a string value if you need more
* control than what this method provides
*/
public const QUERY = 'query';
/**
* sink: (resource|string|StreamInterface) Where the data of the
* response is written to. Defaults to a PHP temp stream. Providing a
* string will write data to a file by the given name.
*/
public const SINK = 'sink';
/**
* synchronous: (bool) Set to true to inform HTTP handlers that you intend
* on waiting on the response. This can be useful for optimizations. Note
* that a promise is still returned if you are using one of the async
* client methods.
*/
public const SYNCHRONOUS = 'synchronous';
/**
* ssl_key: (array|string) Specify the path to a file containing a private
* SSL key in PEM format. If a password is required, then set to an array
* containing the path to the SSL key in the first array element followed
* by the password required for the certificate in the second element.
*/
public const SSL_KEY = 'ssl_key';
/**
* stream: Set to true to attempt to stream a response rather than
* download it all up-front.
*/
public const STREAM = 'stream';
/**
* verify: (bool|string, default=true) Describes the SSL certificate
* verification behavior of a request. Set to true to enable SSL
* certificate verification using the system CA bundle when available
* (the default). Set to false to disable certificate verification (this
* is insecure!). Set to a string to provide the path to a CA bundle on
* disk to enable verification using a custom certificate.
*/
public const VERIFY = 'verify';
/**
* timeout: (float, default=0) Float describing the timeout of the
* request in seconds. Use 0 to wait indefinitely (the default behavior).
*/
public const TIMEOUT = 'timeout';
/**
* read_timeout: (float, default=default_socket_timeout ini setting) Float describing
* the body read timeout, for stream requests.
*/
public const READ_TIMEOUT = 'read_timeout';
/**
* version: (float) Specifies the HTTP protocol version to attempt to use.
*/
public const VERSION = 'version';
/**
* force_ip_resolve: (bool) Force client to use only ipv4 or ipv6 protocol
*/
public const FORCE_IP_RESOLVE = 'force_ip_resolve';
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/functions.php | src/functions.php | <?php
namespace GuzzleHttp;
/**
* Debug function used to describe the provided value type and class.
*
* @param mixed $input Any type of variable to describe the type of. This
* parameter misses a typehint because of that.
*
* @return string Returns a string containing the type of the variable and
* if a class is provided, the class name.
*
* @deprecated describe_type will be removed in guzzlehttp/guzzle:8.0. Use Utils::describeType instead.
*/
function describe_type($input): string
{
return Utils::describeType($input);
}
/**
* Parses an array of header lines into an associative array of headers.
*
* @param iterable $lines Header lines array of strings in the following
* format: "Name: Value"
*
* @deprecated headers_from_lines will be removed in guzzlehttp/guzzle:8.0. Use Utils::headersFromLines instead.
*/
function headers_from_lines(iterable $lines): array
{
return Utils::headersFromLines($lines);
}
/**
* Returns a debug stream based on the provided variable.
*
* @param mixed $value Optional value
*
* @return resource
*
* @deprecated debug_resource will be removed in guzzlehttp/guzzle:8.0. Use Utils::debugResource instead.
*/
function debug_resource($value = null)
{
return Utils::debugResource($value);
}
/**
* Chooses and creates a default handler to use based on the environment.
*
* The returned handler is not wrapped by any default middlewares.
*
* @return callable(\Psr\Http\Message\RequestInterface, array): Promise\PromiseInterface Returns the best handler for the given system.
*
* @throws \RuntimeException if no viable Handler is available.
*
* @deprecated choose_handler will be removed in guzzlehttp/guzzle:8.0. Use Utils::chooseHandler instead.
*/
function choose_handler(): callable
{
return Utils::chooseHandler();
}
/**
* Get the default User-Agent string to use with Guzzle.
*
* @deprecated default_user_agent will be removed in guzzlehttp/guzzle:8.0. Use Utils::defaultUserAgent instead.
*/
function default_user_agent(): string
{
return Utils::defaultUserAgent();
}
/**
* Returns the default cacert bundle for the current system.
*
* First, the openssl.cafile and curl.cainfo php.ini settings are checked.
* If those settings are not configured, then the common locations for
* bundles found on Red Hat, CentOS, Fedora, Ubuntu, Debian, FreeBSD, OS X
* and Windows are checked. If any of these file locations are found on
* disk, they will be utilized.
*
* Note: the result of this function is cached for subsequent calls.
*
* @throws \RuntimeException if no bundle can be found.
*
* @deprecated default_ca_bundle will be removed in guzzlehttp/guzzle:8.0. This function is not needed in PHP 5.6+.
*/
function default_ca_bundle(): string
{
return Utils::defaultCaBundle();
}
/**
* Creates an associative array of lowercase header names to the actual
* header casing.
*
* @deprecated normalize_header_keys will be removed in guzzlehttp/guzzle:8.0. Use Utils::normalizeHeaderKeys instead.
*/
function normalize_header_keys(array $headers): array
{
return Utils::normalizeHeaderKeys($headers);
}
/**
* Returns true if the provided host matches any of the no proxy areas.
*
* This method will strip a port from the host if it is present. Each pattern
* can be matched with an exact match (e.g., "foo.com" == "foo.com") or a
* partial match: (e.g., "foo.com" == "baz.foo.com" and ".foo.com" ==
* "baz.foo.com", but ".foo.com" != "foo.com").
*
* Areas are matched in the following cases:
* 1. "*" (without quotes) always matches any hosts.
* 2. An exact match.
* 3. The area starts with "." and the area is the last part of the host. e.g.
* '.mit.edu' will match any host that ends with '.mit.edu'.
*
* @param string $host Host to check against the patterns.
* @param string[] $noProxyArray An array of host patterns.
*
* @throws Exception\InvalidArgumentException
*
* @deprecated is_host_in_noproxy will be removed in guzzlehttp/guzzle:8.0. Use Utils::isHostInNoProxy instead.
*/
function is_host_in_noproxy(string $host, array $noProxyArray): bool
{
return Utils::isHostInNoProxy($host, $noProxyArray);
}
/**
* Wrapper for json_decode that throws when an error occurs.
*
* @param string $json JSON data to parse
* @param bool $assoc When true, returned objects will be converted
* into associative arrays.
* @param int $depth User specified recursion depth.
* @param int $options Bitmask of JSON decode options.
*
* @return object|array|string|int|float|bool|null
*
* @throws Exception\InvalidArgumentException if the JSON cannot be decoded.
*
* @see https://www.php.net/manual/en/function.json-decode.php
* @deprecated json_decode will be removed in guzzlehttp/guzzle:8.0. Use Utils::jsonDecode instead.
*/
function json_decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)
{
return Utils::jsonDecode($json, $assoc, $depth, $options);
}
/**
* Wrapper for JSON encoding that throws when an error occurs.
*
* @param mixed $value The value being encoded
* @param int $options JSON encode option bitmask
* @param int $depth Set the maximum depth. Must be greater than zero.
*
* @throws Exception\InvalidArgumentException if the JSON cannot be encoded.
*
* @see https://www.php.net/manual/en/function.json-encode.php
* @deprecated json_encode will be removed in guzzlehttp/guzzle:8.0. Use Utils::jsonEncode instead.
*/
function json_encode($value, int $options = 0, int $depth = 512): string
{
return Utils::jsonEncode($value, $options, $depth);
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/HandlerStack.php | src/HandlerStack.php | <?php
namespace GuzzleHttp;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Creates a composed Guzzle handler function by stacking middlewares on top of
* an HTTP handler function.
*
* @final
*/
class HandlerStack
{
/**
* @var (callable(RequestInterface, array): PromiseInterface)|null
*/
private $handler;
/**
* @var array{(callable(callable(RequestInterface, array): PromiseInterface): callable), (string|null)}[]
*/
private $stack = [];
/**
* @var (callable(RequestInterface, array): PromiseInterface)|null
*/
private $cached;
/**
* Creates a default handler stack that can be used by clients.
*
* The returned handler will wrap the provided handler or use the most
* appropriate default handler for your system. The returned HandlerStack has
* support for cookies, redirects, HTTP error exceptions, and preparing a body
* before sending.
*
* The returned handler stack can be passed to a client in the "handler"
* option.
*
* @param (callable(RequestInterface, array): PromiseInterface)|null $handler HTTP handler function to use with the stack. If no
* handler is provided, the best handler for your
* system will be utilized.
*/
public static function create(?callable $handler = null): self
{
$stack = new self($handler ?: Utils::chooseHandler());
$stack->push(Middleware::httpErrors(), 'http_errors');
$stack->push(Middleware::redirect(), 'allow_redirects');
$stack->push(Middleware::cookies(), 'cookies');
$stack->push(Middleware::prepareBody(), 'prepare_body');
return $stack;
}
/**
* @param (callable(RequestInterface, array): PromiseInterface)|null $handler Underlying HTTP handler.
*/
public function __construct(?callable $handler = null)
{
$this->handler = $handler;
}
/**
* Invokes the handler stack as a composed handler
*
* @return ResponseInterface|PromiseInterface
*/
public function __invoke(RequestInterface $request, array $options)
{
$handler = $this->resolve();
return $handler($request, $options);
}
/**
* Dumps a string representation of the stack.
*
* @return string
*/
public function __toString()
{
$depth = 0;
$stack = [];
if ($this->handler !== null) {
$stack[] = '0) Handler: '.$this->debugCallable($this->handler);
}
$result = '';
foreach (\array_reverse($this->stack) as $tuple) {
++$depth;
$str = "{$depth}) Name: '{$tuple[1]}', ";
$str .= 'Function: '.$this->debugCallable($tuple[0]);
$result = "> {$str}\n{$result}";
$stack[] = $str;
}
foreach (\array_keys($stack) as $k) {
$result .= "< {$stack[$k]}\n";
}
return $result;
}
/**
* Set the HTTP handler that actually returns a promise.
*
* @param callable(RequestInterface, array): PromiseInterface $handler Accepts a request and array of options and
* returns a Promise.
*/
public function setHandler(callable $handler): void
{
$this->handler = $handler;
$this->cached = null;
}
/**
* Returns true if the builder has a handler.
*/
public function hasHandler(): bool
{
return $this->handler !== null;
}
/**
* Unshift a middleware to the bottom of the stack.
*
* @param callable(callable): callable $middleware Middleware function
* @param string $name Name to register for this middleware.
*/
public function unshift(callable $middleware, ?string $name = null): void
{
\array_unshift($this->stack, [$middleware, $name]);
$this->cached = null;
}
/**
* Push a middleware to the top of the stack.
*
* @param callable(callable): callable $middleware Middleware function
* @param string $name Name to register for this middleware.
*/
public function push(callable $middleware, string $name = ''): void
{
$this->stack[] = [$middleware, $name];
$this->cached = null;
}
/**
* Add a middleware before another middleware by name.
*
* @param string $findName Middleware to find
* @param callable(callable): callable $middleware Middleware function
* @param string $withName Name to register for this middleware.
*/
public function before(string $findName, callable $middleware, string $withName = ''): void
{
$this->splice($findName, $withName, $middleware, true);
}
/**
* Add a middleware after another middleware by name.
*
* @param string $findName Middleware to find
* @param callable(callable): callable $middleware Middleware function
* @param string $withName Name to register for this middleware.
*/
public function after(string $findName, callable $middleware, string $withName = ''): void
{
$this->splice($findName, $withName, $middleware, false);
}
/**
* Remove a middleware by instance or name from the stack.
*
* @param callable|string $remove Middleware to remove by instance or name.
*/
public function remove($remove): void
{
if (!is_string($remove) && !is_callable($remove)) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a callable or string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->cached = null;
$idx = \is_callable($remove) ? 0 : 1;
$this->stack = \array_values(\array_filter(
$this->stack,
static function ($tuple) use ($idx, $remove) {
return $tuple[$idx] !== $remove;
}
));
}
/**
* Compose the middleware and handler into a single callable function.
*
* @return callable(RequestInterface, array): PromiseInterface
*/
public function resolve(): callable
{
if ($this->cached === null) {
if (($prev = $this->handler) === null) {
throw new \LogicException('No handler has been specified');
}
foreach (\array_reverse($this->stack) as $fn) {
/** @var callable(RequestInterface, array): PromiseInterface $prev */
$prev = $fn[0]($prev);
}
$this->cached = $prev;
}
return $this->cached;
}
private function findByName(string $name): int
{
foreach ($this->stack as $k => $v) {
if ($v[1] === $name) {
return $k;
}
}
throw new \InvalidArgumentException("Middleware not found: $name");
}
/**
* Splices a function into the middleware list at a specific position.
*/
private function splice(string $findName, string $withName, callable $middleware, bool $before): void
{
$this->cached = null;
$idx = $this->findByName($findName);
$tuple = [$middleware, $withName];
if ($before) {
if ($idx === 0) {
\array_unshift($this->stack, $tuple);
} else {
$replacement = [$tuple, $this->stack[$idx]];
\array_splice($this->stack, $idx, 1, $replacement);
}
} elseif ($idx === \count($this->stack) - 1) {
$this->stack[] = $tuple;
} else {
$replacement = [$this->stack[$idx], $tuple];
\array_splice($this->stack, $idx, 1, $replacement);
}
}
/**
* Provides a debug string for a given callable.
*
* @param callable|string $fn Function to write as a string.
*/
private function debugCallable($fn): string
{
if (\is_string($fn)) {
return "callable({$fn})";
}
if (\is_array($fn)) {
return \is_string($fn[0])
? "callable({$fn[0]}::{$fn[1]})"
: "callable(['".\get_class($fn[0])."', '{$fn[1]}'])";
}
/** @var object $fn */
return 'callable('.\spl_object_hash($fn).')';
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/BodySummarizerInterface.php | src/BodySummarizerInterface.php | <?php
namespace GuzzleHttp;
use Psr\Http\Message\MessageInterface;
interface BodySummarizerInterface
{
/**
* Returns a summarized message body.
*/
public function summarize(MessageInterface $message): ?string;
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/ClientInterface.php | src/ClientInterface.php | <?php
namespace GuzzleHttp;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* Client interface for sending HTTP requests.
*/
interface ClientInterface
{
/**
* The Guzzle major version.
*/
public const MAJOR_VERSION = 7;
/**
* Send an HTTP request.
*
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
*
* @throws GuzzleException
*/
public function send(RequestInterface $request, array $options = []): ResponseInterface;
/**
* Asynchronously send an HTTP request.
*
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
*/
public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface;
/**
* Create and send an HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string $method HTTP method.
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function request(string $method, $uri, array $options = []): ResponseInterface;
/**
* Create and send an asynchronous HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function requestAsync(string $method, $uri, array $options = []): PromiseInterface;
/**
* Get a client configuration option.
*
* These options include default request options of the client, a "handler"
* (if utilized by the concrete client), and a "base_uri" if utilized by
* the concrete client.
*
* @param string|null $option The config option to retrieve.
*
* @return mixed
*
* @deprecated ClientInterface::getConfig will be removed in guzzlehttp/guzzle:8.0.
*/
public function getConfig(?string $option = null);
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Utils.php | src/Utils.php | <?php
namespace GuzzleHttp;
use GuzzleHttp\Exception\InvalidArgumentException;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Handler\CurlMultiHandler;
use GuzzleHttp\Handler\Proxy;
use GuzzleHttp\Handler\StreamHandler;
use Psr\Http\Message\UriInterface;
final class Utils
{
/**
* Debug function used to describe the provided value type and class.
*
* @param mixed $input
*
* @return string Returns a string containing the type of the variable and
* if a class is provided, the class name.
*/
public static function describeType($input): string
{
switch (\gettype($input)) {
case 'object':
return 'object('.\get_class($input).')';
case 'array':
return 'array('.\count($input).')';
default:
\ob_start();
\var_dump($input);
// normalize float vs double
/** @var string $varDumpContent */
$varDumpContent = \ob_get_clean();
return \str_replace('double(', 'float(', \rtrim($varDumpContent));
}
}
/**
* Parses an array of header lines into an associative array of headers.
*
* @param iterable $lines Header lines array of strings in the following
* format: "Name: Value"
*/
public static function headersFromLines(iterable $lines): array
{
$headers = [];
foreach ($lines as $line) {
$parts = \explode(':', $line, 2);
$headers[\trim($parts[0])][] = isset($parts[1]) ? \trim($parts[1]) : null;
}
return $headers;
}
/**
* Returns a debug stream based on the provided variable.
*
* @param mixed $value Optional value
*
* @return resource
*/
public static function debugResource($value = null)
{
if (\is_resource($value)) {
return $value;
}
if (\defined('STDOUT')) {
return \STDOUT;
}
return Psr7\Utils::tryFopen('php://output', 'w');
}
/**
* Chooses and creates a default handler to use based on the environment.
*
* The returned handler is not wrapped by any default middlewares.
*
* @return callable(\Psr\Http\Message\RequestInterface, array): Promise\PromiseInterface Returns the best handler for the given system.
*
* @throws \RuntimeException if no viable Handler is available.
*/
public static function chooseHandler(): callable
{
$handler = null;
if (\defined('CURLOPT_CUSTOMREQUEST') && \function_exists('curl_version') && version_compare(curl_version()['version'], '7.21.2') >= 0) {
if (\function_exists('curl_multi_exec') && \function_exists('curl_exec')) {
$handler = Proxy::wrapSync(new CurlMultiHandler(), new CurlHandler());
} elseif (\function_exists('curl_exec')) {
$handler = new CurlHandler();
} elseif (\function_exists('curl_multi_exec')) {
$handler = new CurlMultiHandler();
}
}
if (\ini_get('allow_url_fopen')) {
$handler = $handler
? Proxy::wrapStreaming($handler, new StreamHandler())
: new StreamHandler();
} elseif (!$handler) {
throw new \RuntimeException('GuzzleHttp requires cURL, the allow_url_fopen ini setting, or a custom HTTP handler.');
}
return $handler;
}
/**
* Get the default User-Agent string to use with Guzzle.
*/
public static function defaultUserAgent(): string
{
return sprintf('GuzzleHttp/%d', ClientInterface::MAJOR_VERSION);
}
/**
* Returns the default cacert bundle for the current system.
*
* First, the openssl.cafile and curl.cainfo php.ini settings are checked.
* If those settings are not configured, then the common locations for
* bundles found on Red Hat, CentOS, Fedora, Ubuntu, Debian, FreeBSD, OS X
* and Windows are checked. If any of these file locations are found on
* disk, they will be utilized.
*
* Note: the result of this function is cached for subsequent calls.
*
* @throws \RuntimeException if no bundle can be found.
*
* @deprecated Utils::defaultCaBundle will be removed in guzzlehttp/guzzle:8.0. This method is not needed in PHP 5.6+.
*/
public static function defaultCaBundle(): string
{
static $cached = null;
static $cafiles = [
// Red Hat, CentOS, Fedora (provided by the ca-certificates package)
'/etc/pki/tls/certs/ca-bundle.crt',
// Ubuntu, Debian (provided by the ca-certificates package)
'/etc/ssl/certs/ca-certificates.crt',
// FreeBSD (provided by the ca_root_nss package)
'/usr/local/share/certs/ca-root-nss.crt',
// SLES 12 (provided by the ca-certificates package)
'/var/lib/ca-certificates/ca-bundle.pem',
// OS X provided by homebrew (using the default path)
'/usr/local/etc/openssl/cert.pem',
// Google app engine
'/etc/ca-certificates.crt',
// Windows?
'C:\\windows\\system32\\curl-ca-bundle.crt',
'C:\\windows\\curl-ca-bundle.crt',
];
if ($cached) {
return $cached;
}
if ($ca = \ini_get('openssl.cafile')) {
return $cached = $ca;
}
if ($ca = \ini_get('curl.cainfo')) {
return $cached = $ca;
}
foreach ($cafiles as $filename) {
if (\file_exists($filename)) {
return $cached = $filename;
}
}
throw new \RuntimeException(
<<< EOT
No system CA bundle could be found in any of the the common system locations.
PHP versions earlier than 5.6 are not properly configured to use the system's
CA bundle by default. In order to verify peer certificates, you will need to
supply the path on disk to a certificate bundle to the 'verify' request
option: https://docs.guzzlephp.org/en/latest/request-options.html#verify. If
you do not need a specific certificate bundle, then Mozilla provides a commonly
used CA bundle which can be downloaded here (provided by the maintainer of
cURL): https://curl.haxx.se/ca/cacert.pem. Once you have a CA bundle available
on disk, you can set the 'openssl.cafile' PHP ini setting to point to the path
to the file, allowing you to omit the 'verify' request option. See
https://curl.haxx.se/docs/sslcerts.html for more information.
EOT
);
}
/**
* Creates an associative array of lowercase header names to the actual
* header casing.
*/
public static function normalizeHeaderKeys(array $headers): array
{
$result = [];
foreach (\array_keys($headers) as $key) {
$result[\strtolower($key)] = $key;
}
return $result;
}
/**
* Returns true if the provided host matches any of the no proxy areas.
*
* This method will strip a port from the host if it is present. Each pattern
* can be matched with an exact match (e.g., "foo.com" == "foo.com") or a
* partial match: (e.g., "foo.com" == "baz.foo.com" and ".foo.com" ==
* "baz.foo.com", but ".foo.com" != "foo.com").
*
* Areas are matched in the following cases:
* 1. "*" (without quotes) always matches any hosts.
* 2. An exact match.
* 3. The area starts with "." and the area is the last part of the host. e.g.
* '.mit.edu' will match any host that ends with '.mit.edu'.
*
* @param string $host Host to check against the patterns.
* @param string[] $noProxyArray An array of host patterns.
*
* @throws InvalidArgumentException
*/
public static function isHostInNoProxy(string $host, array $noProxyArray): bool
{
if (\strlen($host) === 0) {
throw new InvalidArgumentException('Empty host provided');
}
// Strip port if present.
[$host] = \explode(':', $host, 2);
foreach ($noProxyArray as $area) {
// Always match on wildcards.
if ($area === '*') {
return true;
}
if (empty($area)) {
// Don't match on empty values.
continue;
}
if ($area === $host) {
// Exact matches.
return true;
}
// Special match if the area when prefixed with ".". Remove any
// existing leading "." and add a new leading ".".
$area = '.'.\ltrim($area, '.');
if (\substr($host, -\strlen($area)) === $area) {
return true;
}
}
return false;
}
/**
* Wrapper for json_decode that throws when an error occurs.
*
* @param string $json JSON data to parse
* @param bool $assoc When true, returned objects will be converted
* into associative arrays.
* @param int $depth User specified recursion depth.
* @param int $options Bitmask of JSON decode options.
*
* @return object|array|string|int|float|bool|null
*
* @throws InvalidArgumentException if the JSON cannot be decoded.
*
* @see https://www.php.net/manual/en/function.json-decode.php
*/
public static function jsonDecode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)
{
$data = \json_decode($json, $assoc, $depth, $options);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_decode error: '.\json_last_error_msg());
}
return $data;
}
/**
* Wrapper for JSON encoding that throws when an error occurs.
*
* @param mixed $value The value being encoded
* @param int $options JSON encode option bitmask
* @param int $depth Set the maximum depth. Must be greater than zero.
*
* @throws InvalidArgumentException if the JSON cannot be encoded.
*
* @see https://www.php.net/manual/en/function.json-encode.php
*/
public static function jsonEncode($value, int $options = 0, int $depth = 512): string
{
$json = \json_encode($value, $options, $depth);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_encode error: '.\json_last_error_msg());
}
/** @var string */
return $json;
}
/**
* Wrapper for the hrtime() or microtime() functions
* (depending on the PHP version, one of the two is used)
*
* @return float UNIX timestamp
*
* @internal
*/
public static function currentTime(): float
{
return (float) \function_exists('hrtime') ? \hrtime(true) / 1e9 : \microtime(true);
}
/**
* @throws InvalidArgumentException
*
* @internal
*/
public static function idnUriConvert(UriInterface $uri, int $options = 0): UriInterface
{
if ($uri->getHost()) {
$asciiHost = self::idnToAsci($uri->getHost(), $options, $info);
if ($asciiHost === false) {
$errorBitSet = $info['errors'] ?? 0;
$errorConstants = array_filter(array_keys(get_defined_constants()), static function (string $name): bool {
return substr($name, 0, 11) === 'IDNA_ERROR_';
});
$errors = [];
foreach ($errorConstants as $errorConstant) {
if ($errorBitSet & constant($errorConstant)) {
$errors[] = $errorConstant;
}
}
$errorMessage = 'IDN conversion failed';
if ($errors) {
$errorMessage .= ' (errors: '.implode(', ', $errors).')';
}
throw new InvalidArgumentException($errorMessage);
}
if ($uri->getHost() !== $asciiHost) {
// Replace URI only if the ASCII version is different
$uri = $uri->withHost($asciiHost);
}
}
return $uri;
}
/**
* @internal
*/
public static function getenv(string $name): ?string
{
if (isset($_SERVER[$name])) {
return (string) $_SERVER[$name];
}
if (\PHP_SAPI === 'cli' && ($value = \getenv($name)) !== false && $value !== null) {
return (string) $value;
}
return null;
}
/**
* @return string|false
*/
private static function idnToAsci(string $domain, int $options, ?array &$info = [])
{
if (\function_exists('idn_to_ascii') && \defined('INTL_IDNA_VARIANT_UTS46')) {
return \idn_to_ascii($domain, $options, \INTL_IDNA_VARIANT_UTS46, $info);
}
throw new \Error('ext-idn or symfony/polyfill-intl-idn not loaded or too old');
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/BodySummarizer.php | src/BodySummarizer.php | <?php
namespace GuzzleHttp;
use Psr\Http\Message\MessageInterface;
final class BodySummarizer implements BodySummarizerInterface
{
/**
* @var int|null
*/
private $truncateAt;
public function __construct(?int $truncateAt = null)
{
$this->truncateAt = $truncateAt;
}
/**
* Returns a summarized message body.
*/
public function summarize(MessageInterface $message): ?string
{
return $this->truncateAt === null
? Psr7\Message::bodySummary($message)
: Psr7\Message::bodySummary($message, $this->truncateAt);
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/MessageFormatterInterface.php | src/MessageFormatterInterface.php | <?php
namespace GuzzleHttp;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
interface MessageFormatterInterface
{
/**
* Returns a formatted message string.
*
* @param RequestInterface $request Request that was sent
* @param ResponseInterface|null $response Response that was received
* @param \Throwable|null $error Exception that was received
*/
public function format(RequestInterface $request, ?ResponseInterface $response = null, ?\Throwable $error = null): string;
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/TransferStats.php | src/TransferStats.php | <?php
namespace GuzzleHttp;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* Represents data at the point after it was transferred either successfully
* or after a network error.
*/
final class TransferStats
{
/**
* @var RequestInterface
*/
private $request;
/**
* @var ResponseInterface|null
*/
private $response;
/**
* @var float|null
*/
private $transferTime;
/**
* @var array
*/
private $handlerStats;
/**
* @var mixed|null
*/
private $handlerErrorData;
/**
* @param RequestInterface $request Request that was sent.
* @param ResponseInterface|null $response Response received (if any)
* @param float|null $transferTime Total handler transfer time.
* @param mixed $handlerErrorData Handler error data.
* @param array $handlerStats Handler specific stats.
*/
public function __construct(
RequestInterface $request,
?ResponseInterface $response = null,
?float $transferTime = null,
$handlerErrorData = null,
array $handlerStats = []
) {
$this->request = $request;
$this->response = $response;
$this->transferTime = $transferTime;
$this->handlerErrorData = $handlerErrorData;
$this->handlerStats = $handlerStats;
}
public function getRequest(): RequestInterface
{
return $this->request;
}
/**
* Returns the response that was received (if any).
*/
public function getResponse(): ?ResponseInterface
{
return $this->response;
}
/**
* Returns true if a response was received.
*/
public function hasResponse(): bool
{
return $this->response !== null;
}
/**
* Gets handler specific error data.
*
* This might be an exception, a integer representing an error code, or
* anything else. Relying on this value assumes that you know what handler
* you are using.
*
* @return mixed
*/
public function getHandlerErrorData()
{
return $this->handlerErrorData;
}
/**
* Get the effective URI the request was sent to.
*/
public function getEffectiveUri(): UriInterface
{
return $this->request->getUri();
}
/**
* Get the estimated time the request was being transferred by the handler.
*
* @return float|null Time in seconds.
*/
public function getTransferTime(): ?float
{
return $this->transferTime;
}
/**
* Gets an array of all of the handler specific transfer data.
*/
public function getHandlerStats(): array
{
return $this->handlerStats;
}
/**
* Get a specific handler statistic from the handler by name.
*
* @param string $stat Handler specific transfer stat to retrieve.
*
* @return mixed|null
*/
public function getHandlerStat(string $stat)
{
return $this->handlerStats[$stat] ?? null;
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Handler/Proxy.php | src/Handler/Proxy.php | <?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\RequestOptions;
use Psr\Http\Message\RequestInterface;
/**
* Provides basic proxies for handlers.
*
* @final
*/
class Proxy
{
/**
* Sends synchronous requests to a specific handler while sending all other
* requests to another handler.
*
* @param callable(RequestInterface, array): PromiseInterface $default Handler used for normal responses
* @param callable(RequestInterface, array): PromiseInterface $sync Handler used for synchronous responses.
*
* @return callable(RequestInterface, array): PromiseInterface Returns the composed handler.
*/
public static function wrapSync(callable $default, callable $sync): callable
{
return static function (RequestInterface $request, array $options) use ($default, $sync): PromiseInterface {
return empty($options[RequestOptions::SYNCHRONOUS]) ? $default($request, $options) : $sync($request, $options);
};
}
/**
* Sends streaming requests to a streaming compatible handler while sending
* all other requests to a default handler.
*
* This, for example, could be useful for taking advantage of the
* performance benefits of curl while still supporting true streaming
* through the StreamHandler.
*
* @param callable(RequestInterface, array): PromiseInterface $default Handler used for non-streaming responses
* @param callable(RequestInterface, array): PromiseInterface $streaming Handler used for streaming responses
*
* @return callable(RequestInterface, array): PromiseInterface Returns the composed handler.
*/
public static function wrapStreaming(callable $default, callable $streaming): callable
{
return static function (RequestInterface $request, array $options) use ($default, $streaming): PromiseInterface {
return empty($options['stream']) ? $default($request, $options) : $streaming($request, $options);
};
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Handler/HeaderProcessor.php | src/Handler/HeaderProcessor.php | <?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Utils;
/**
* @internal
*/
final class HeaderProcessor
{
/**
* Returns the HTTP version, status code, reason phrase, and headers.
*
* @param string[] $headers
*
* @return array{0:string, 1:int, 2:?string, 3:array}
*
* @throws \RuntimeException
*/
public static function parseHeaders(array $headers): array
{
if ($headers === []) {
throw new \RuntimeException('Expected a non-empty array of header data');
}
$parts = \explode(' ', \array_shift($headers), 3);
$version = \explode('/', $parts[0])[1] ?? null;
if ($version === null) {
throw new \RuntimeException('HTTP version missing from header data');
}
$status = $parts[1] ?? null;
if ($status === null) {
throw new \RuntimeException('HTTP status code missing from header data');
}
return [$version, (int) $status, $parts[2] ?? null, Utils::headersFromLines($headers)];
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Handler/CurlHandler.php | src/Handler/CurlHandler.php | <?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
/**
* HTTP handler that uses cURL easy handles as a transport layer.
*
* When using the CurlHandler, custom curl options can be specified as an
* associative array of curl option constants mapping to values in the
* **curl** key of the "client" key of the request.
*
* @final
*/
class CurlHandler
{
/**
* @var CurlFactoryInterface
*/
private $factory;
/**
* Accepts an associative array of options:
*
* - handle_factory: Optional curl factory used to create cURL handles.
*
* @param array{handle_factory?: ?CurlFactoryInterface} $options Array of options to use with the handler
*/
public function __construct(array $options = [])
{
$this->factory = $options['handle_factory']
?? new CurlFactory(3);
}
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
if (isset($options['delay'])) {
\usleep($options['delay'] * 1000);
}
$easy = $this->factory->create($request, $options);
\curl_exec($easy->handle);
$easy->errno = \curl_errno($easy->handle);
return CurlFactory::finish($this, $easy, $this->factory);
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Handler/CurlFactoryInterface.php | src/Handler/CurlFactoryInterface.php | <?php
namespace GuzzleHttp\Handler;
use Psr\Http\Message\RequestInterface;
interface CurlFactoryInterface
{
/**
* Creates a cURL handle resource.
*
* @param RequestInterface $request Request
* @param array $options Transfer options
*
* @throws \RuntimeException when an option cannot be applied
*/
public function create(RequestInterface $request, array $options): EasyHandle;
/**
* Release an easy handle, allowing it to be reused or closed.
*
* This function must call unset on the easy handle's "handle" property.
*/
public function release(EasyHandle $easy): void;
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Handler/EasyHandle.php | src/Handler/EasyHandle.php | <?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Utils;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
/**
* Represents a cURL easy handle and the data it populates.
*
* @internal
*/
final class EasyHandle
{
/**
* @var resource|\CurlHandle cURL resource
*/
public $handle;
/**
* @var StreamInterface Where data is being written
*/
public $sink;
/**
* @var array Received HTTP headers so far
*/
public $headers = [];
/**
* @var ResponseInterface|null Received response (if any)
*/
public $response;
/**
* @var RequestInterface Request being sent
*/
public $request;
/**
* @var array Request options
*/
public $options = [];
/**
* @var int cURL error number (if any)
*/
public $errno = 0;
/**
* @var \Throwable|null Exception during on_headers (if any)
*/
public $onHeadersException;
/**
* @var \Exception|null Exception during createResponse (if any)
*/
public $createResponseException;
/**
* Attach a response to the easy handle based on the received headers.
*
* @throws \RuntimeException if no headers have been received or the first
* header line is invalid.
*/
public function createResponse(): void
{
[$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($this->headers);
$normalizedKeys = Utils::normalizeHeaderKeys($headers);
if (!empty($this->options['decode_content']) && isset($normalizedKeys['content-encoding'])) {
$headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']];
unset($headers[$normalizedKeys['content-encoding']]);
if (isset($normalizedKeys['content-length'])) {
$headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']];
$bodyLength = (int) $this->sink->getSize();
if ($bodyLength) {
$headers[$normalizedKeys['content-length']] = $bodyLength;
} else {
unset($headers[$normalizedKeys['content-length']]);
}
}
}
// Attach a response to the easy handle with the parsed headers.
$this->response = new Response(
$status,
$headers,
$this->sink,
$ver,
$reason
);
}
/**
* @param string $name
*
* @return void
*
* @throws \BadMethodCallException
*/
public function __get($name)
{
$msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: '.$name;
throw new \BadMethodCallException($msg);
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Handler/MockHandler.php | src/Handler/MockHandler.php | <?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\TransferStats;
use GuzzleHttp\Utils;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
/**
* Handler that returns responses or throw exceptions from a queue.
*
* @final
*/
class MockHandler implements \Countable
{
/**
* @var array
*/
private $queue = [];
/**
* @var RequestInterface|null
*/
private $lastRequest;
/**
* @var array
*/
private $lastOptions = [];
/**
* @var callable|null
*/
private $onFulfilled;
/**
* @var callable|null
*/
private $onRejected;
/**
* Creates a new MockHandler that uses the default handler stack list of
* middlewares.
*
* @param array|null $queue Array of responses, callables, or exceptions.
* @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled.
* @param callable|null $onRejected Callback to invoke when the return value is rejected.
*/
public static function createWithMiddleware(?array $queue = null, ?callable $onFulfilled = null, ?callable $onRejected = null): HandlerStack
{
return HandlerStack::create(new self($queue, $onFulfilled, $onRejected));
}
/**
* The passed in value must be an array of
* {@see ResponseInterface} objects, Exceptions,
* callables, or Promises.
*
* @param array<int, mixed>|null $queue The parameters to be passed to the append function, as an indexed array.
* @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled.
* @param callable|null $onRejected Callback to invoke when the return value is rejected.
*/
public function __construct(?array $queue = null, ?callable $onFulfilled = null, ?callable $onRejected = null)
{
$this->onFulfilled = $onFulfilled;
$this->onRejected = $onRejected;
if ($queue) {
// array_values included for BC
$this->append(...array_values($queue));
}
}
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
if (!$this->queue) {
throw new \OutOfBoundsException('Mock queue is empty');
}
if (isset($options['delay']) && \is_numeric($options['delay'])) {
\usleep((int) $options['delay'] * 1000);
}
$this->lastRequest = $request;
$this->lastOptions = $options;
$response = \array_shift($this->queue);
if (isset($options['on_headers'])) {
if (!\is_callable($options['on_headers'])) {
throw new \InvalidArgumentException('on_headers must be callable');
}
try {
$options['on_headers']($response);
} catch (\Exception $e) {
$msg = 'An error was encountered during the on_headers event';
$response = new RequestException($msg, $request, $response, $e);
}
}
if (\is_callable($response)) {
$response = $response($request, $options);
}
$response = $response instanceof \Throwable
? P\Create::rejectionFor($response)
: P\Create::promiseFor($response);
return $response->then(
function (?ResponseInterface $value) use ($request, $options) {
$this->invokeStats($request, $options, $value);
if ($this->onFulfilled) {
($this->onFulfilled)($value);
}
if ($value !== null && isset($options['sink'])) {
$contents = (string) $value->getBody();
$sink = $options['sink'];
if (\is_resource($sink)) {
\fwrite($sink, $contents);
} elseif (\is_string($sink)) {
\file_put_contents($sink, $contents);
} elseif ($sink instanceof StreamInterface) {
$sink->write($contents);
}
}
return $value;
},
function ($reason) use ($request, $options) {
$this->invokeStats($request, $options, null, $reason);
if ($this->onRejected) {
($this->onRejected)($reason);
}
return P\Create::rejectionFor($reason);
}
);
}
/**
* Adds one or more variadic requests, exceptions, callables, or promises
* to the queue.
*
* @param mixed ...$values
*/
public function append(...$values): void
{
foreach ($values as $value) {
if ($value instanceof ResponseInterface
|| $value instanceof \Throwable
|| $value instanceof PromiseInterface
|| \is_callable($value)
) {
$this->queue[] = $value;
} else {
throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found '.Utils::describeType($value));
}
}
}
/**
* Get the last received request.
*/
public function getLastRequest(): ?RequestInterface
{
return $this->lastRequest;
}
/**
* Get the last received request options.
*/
public function getLastOptions(): array
{
return $this->lastOptions;
}
/**
* Returns the number of remaining items in the queue.
*/
public function count(): int
{
return \count($this->queue);
}
public function reset(): void
{
$this->queue = [];
}
/**
* @param mixed $reason Promise or reason.
*/
private function invokeStats(
RequestInterface $request,
array $options,
?ResponseInterface $response = null,
$reason = null
): void {
if (isset($options['on_stats'])) {
$transferTime = $options['transfer_time'] ?? 0;
$stats = new TransferStats($request, $response, $transferTime, $reason);
($options['on_stats'])($stats);
}
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Handler/StreamHandler.php | src/Handler/StreamHandler.php | <?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7;
use GuzzleHttp\TransferStats;
use GuzzleHttp\Utils;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriInterface;
/**
* HTTP handler that uses PHP's HTTP stream wrapper.
*
* @final
*/
class StreamHandler
{
/**
* @var array
*/
private $lastHeaders = [];
/**
* Sends an HTTP request.
*
* @param RequestInterface $request Request to send.
* @param array $options Request transfer options.
*/
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
// Sleep if there is a delay specified.
if (isset($options['delay'])) {
\usleep($options['delay'] * 1000);
}
$protocolVersion = $request->getProtocolVersion();
if ('1.0' !== $protocolVersion && '1.1' !== $protocolVersion) {
throw new ConnectException(sprintf('HTTP/%s is not supported by the stream handler.', $protocolVersion), $request);
}
$startTime = isset($options['on_stats']) ? Utils::currentTime() : null;
try {
// Does not support the expect header.
$request = $request->withoutHeader('Expect');
// Append a content-length header if body size is zero to match
// the behavior of `CurlHandler`
if (
(
0 === \strcasecmp('PUT', $request->getMethod())
|| 0 === \strcasecmp('POST', $request->getMethod())
)
&& 0 === $request->getBody()->getSize()
) {
$request = $request->withHeader('Content-Length', '0');
}
return $this->createResponse(
$request,
$options,
$this->createStream($request, $options),
$startTime
);
} catch (\InvalidArgumentException $e) {
throw $e;
} catch (\Exception $e) {
// Determine if the error was a networking error.
$message = $e->getMessage();
// This list can probably get more comprehensive.
if (false !== \strpos($message, 'getaddrinfo') // DNS lookup failed
|| false !== \strpos($message, 'Connection refused')
|| false !== \strpos($message, "couldn't connect to host") // error on HHVM
|| false !== \strpos($message, 'connection attempt failed')
) {
$e = new ConnectException($e->getMessage(), $request, $e);
} else {
$e = RequestException::wrapException($request, $e);
}
$this->invokeStats($options, $request, $startTime, null, $e);
return P\Create::rejectionFor($e);
}
}
private function invokeStats(
array $options,
RequestInterface $request,
?float $startTime,
?ResponseInterface $response = null,
?\Throwable $error = null
): void {
if (isset($options['on_stats'])) {
$stats = new TransferStats($request, $response, Utils::currentTime() - $startTime, $error, []);
($options['on_stats'])($stats);
}
}
/**
* @param resource $stream
*/
private function createResponse(RequestInterface $request, array $options, $stream, ?float $startTime): PromiseInterface
{
$hdrs = $this->lastHeaders;
$this->lastHeaders = [];
try {
[$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs);
} catch (\Exception $e) {
return P\Create::rejectionFor(
new RequestException('An error was encountered while creating the response', $request, null, $e)
);
}
[$stream, $headers] = $this->checkDecode($options, $headers, $stream);
$stream = Psr7\Utils::streamFor($stream);
$sink = $stream;
if (\strcasecmp('HEAD', $request->getMethod())) {
$sink = $this->createSink($stream, $options);
}
try {
$response = new Psr7\Response($status, $headers, $sink, $ver, $reason);
} catch (\Exception $e) {
return P\Create::rejectionFor(
new RequestException('An error was encountered while creating the response', $request, null, $e)
);
}
if (isset($options['on_headers'])) {
try {
$options['on_headers']($response);
} catch (\Exception $e) {
return P\Create::rejectionFor(
new RequestException('An error was encountered during the on_headers event', $request, $response, $e)
);
}
}
// Do not drain when the request is a HEAD request because they have
// no body.
if ($sink !== $stream) {
$this->drain($stream, $sink, $response->getHeaderLine('Content-Length'));
}
$this->invokeStats($options, $request, $startTime, $response, null);
return new FulfilledPromise($response);
}
private function createSink(StreamInterface $stream, array $options): StreamInterface
{
if (!empty($options['stream'])) {
return $stream;
}
$sink = $options['sink'] ?? Psr7\Utils::tryFopen('php://temp', 'r+');
return \is_string($sink) ? new Psr7\LazyOpenStream($sink, 'w+') : Psr7\Utils::streamFor($sink);
}
/**
* @param resource $stream
*/
private function checkDecode(array $options, array $headers, $stream): array
{
// Automatically decode responses when instructed.
if (!empty($options['decode_content'])) {
$normalizedKeys = Utils::normalizeHeaderKeys($headers);
if (isset($normalizedKeys['content-encoding'])) {
$encoding = $headers[$normalizedKeys['content-encoding']];
if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') {
$stream = new Psr7\InflateStream(Psr7\Utils::streamFor($stream));
$headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']];
// Remove content-encoding header
unset($headers[$normalizedKeys['content-encoding']]);
// Fix content-length header
if (isset($normalizedKeys['content-length'])) {
$headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']];
$length = (int) $stream->getSize();
if ($length === 0) {
unset($headers[$normalizedKeys['content-length']]);
} else {
$headers[$normalizedKeys['content-length']] = [$length];
}
}
}
}
}
return [$stream, $headers];
}
/**
* Drains the source stream into the "sink" client option.
*
* @param string $contentLength Header specifying the amount of
* data to read.
*
* @throws \RuntimeException when the sink option is invalid.
*/
private function drain(StreamInterface $source, StreamInterface $sink, string $contentLength): StreamInterface
{
// If a content-length header is provided, then stop reading once
// that number of bytes has been read. This can prevent infinitely
// reading from a stream when dealing with servers that do not honor
// Connection: Close headers.
Psr7\Utils::copyToStream(
$source,
$sink,
(\strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1
);
$sink->seek(0);
$source->close();
return $sink;
}
/**
* Create a resource and check to ensure it was created successfully
*
* @param callable $callback Callable that returns stream resource
*
* @return resource
*
* @throws \RuntimeException on error
*/
private function createResource(callable $callback)
{
$errors = [];
\set_error_handler(static function ($_, $msg, $file, $line) use (&$errors): bool {
$errors[] = [
'message' => $msg,
'file' => $file,
'line' => $line,
];
return true;
});
try {
$resource = $callback();
} finally {
\restore_error_handler();
}
if (!$resource) {
$message = 'Error creating resource: ';
foreach ($errors as $err) {
foreach ($err as $key => $value) {
$message .= "[$key] $value".\PHP_EOL;
}
}
throw new \RuntimeException(\trim($message));
}
return $resource;
}
/**
* @return resource
*/
private function createStream(RequestInterface $request, array $options)
{
static $methods;
if (!$methods) {
$methods = \array_flip(\get_class_methods(__CLASS__));
}
if (!\in_array($request->getUri()->getScheme(), ['http', 'https'])) {
throw new RequestException(\sprintf("The scheme '%s' is not supported.", $request->getUri()->getScheme()), $request);
}
// HTTP/1.1 streams using the PHP stream wrapper require a
// Connection: close header
if ($request->getProtocolVersion() === '1.1'
&& !$request->hasHeader('Connection')
) {
$request = $request->withHeader('Connection', 'close');
}
// Ensure SSL is verified by default
if (!isset($options['verify'])) {
$options['verify'] = true;
}
$params = [];
$context = $this->getDefaultContext($request);
if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) {
throw new \InvalidArgumentException('on_headers must be callable');
}
if (!empty($options)) {
foreach ($options as $key => $value) {
$method = "add_{$key}";
if (isset($methods[$method])) {
$this->{$method}($request, $context, $value, $params);
}
}
}
if (isset($options['stream_context'])) {
if (!\is_array($options['stream_context'])) {
throw new \InvalidArgumentException('stream_context must be an array');
}
$context = \array_replace_recursive($context, $options['stream_context']);
}
// Microsoft NTLM authentication only supported with curl handler
if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) {
throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler');
}
$uri = $this->resolveHost($request, $options);
$contextResource = $this->createResource(
static function () use ($context, $params) {
return \stream_context_create($context, $params);
}
);
return $this->createResource(
function () use ($uri, $contextResource, $context, $options, $request) {
$resource = @\fopen((string) $uri, 'r', false, $contextResource);
// See https://wiki.php.net/rfc/deprecations_php_8_5#deprecate_the_http_response_header_predefined_variable
if (function_exists('http_get_last_response_headers')) {
/** @var array|null */
$http_response_header = \http_get_last_response_headers();
}
$this->lastHeaders = $http_response_header ?? [];
if (false === $resource) {
throw new ConnectException(sprintf('Connection refused for URI %s', $uri), $request, null, $context);
}
if (isset($options['read_timeout'])) {
$readTimeout = $options['read_timeout'];
$sec = (int) $readTimeout;
$usec = ($readTimeout - $sec) * 100000;
\stream_set_timeout($resource, $sec, $usec);
}
return $resource;
}
);
}
private function resolveHost(RequestInterface $request, array $options): UriInterface
{
$uri = $request->getUri();
if (isset($options['force_ip_resolve']) && !\filter_var($uri->getHost(), \FILTER_VALIDATE_IP)) {
if ('v4' === $options['force_ip_resolve']) {
$records = \dns_get_record($uri->getHost(), \DNS_A);
if (false === $records || !isset($records[0]['ip'])) {
throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request);
}
return $uri->withHost($records[0]['ip']);
}
if ('v6' === $options['force_ip_resolve']) {
$records = \dns_get_record($uri->getHost(), \DNS_AAAA);
if (false === $records || !isset($records[0]['ipv6'])) {
throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request);
}
return $uri->withHost('['.$records[0]['ipv6'].']');
}
}
return $uri;
}
private function getDefaultContext(RequestInterface $request): array
{
$headers = '';
foreach ($request->getHeaders() as $name => $value) {
foreach ($value as $val) {
$headers .= "$name: $val\r\n";
}
}
$context = [
'http' => [
'method' => $request->getMethod(),
'header' => $headers,
'protocol_version' => $request->getProtocolVersion(),
'ignore_errors' => true,
'follow_location' => 0,
],
'ssl' => [
'peer_name' => $request->getUri()->getHost(),
],
];
$body = (string) $request->getBody();
if ('' !== $body) {
$context['http']['content'] = $body;
// Prevent the HTTP handler from adding a Content-Type header.
if (!$request->hasHeader('Content-Type')) {
$context['http']['header'] .= "Content-Type:\r\n";
}
}
$context['http']['header'] = \rtrim($context['http']['header']);
return $context;
}
/**
* @param mixed $value as passed via Request transfer options.
*/
private function add_proxy(RequestInterface $request, array &$options, $value, array &$params): void
{
$uri = null;
if (!\is_array($value)) {
$uri = $value;
} else {
$scheme = $request->getUri()->getScheme();
if (isset($value[$scheme])) {
if (!isset($value['no']) || !Utils::isHostInNoProxy($request->getUri()->getHost(), $value['no'])) {
$uri = $value[$scheme];
}
}
}
if (!$uri) {
return;
}
$parsed = $this->parse_proxy($uri);
$options['http']['proxy'] = $parsed['proxy'];
if ($parsed['auth']) {
if (!isset($options['http']['header'])) {
$options['http']['header'] = [];
}
$options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}";
}
}
/**
* Parses the given proxy URL to make it compatible with the format PHP's stream context expects.
*/
private function parse_proxy(string $url): array
{
$parsed = \parse_url($url);
if ($parsed !== false && isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
if (isset($parsed['host']) && isset($parsed['port'])) {
$auth = null;
if (isset($parsed['user']) && isset($parsed['pass'])) {
$auth = \base64_encode("{$parsed['user']}:{$parsed['pass']}");
}
return [
'proxy' => "tcp://{$parsed['host']}:{$parsed['port']}",
'auth' => $auth ? "Basic {$auth}" : null,
];
}
}
// Return proxy as-is.
return [
'proxy' => $url,
'auth' => null,
];
}
/**
* @param mixed $value as passed via Request transfer options.
*/
private function add_timeout(RequestInterface $request, array &$options, $value, array &$params): void
{
if ($value > 0) {
$options['http']['timeout'] = $value;
}
}
/**
* @param mixed $value as passed via Request transfer options.
*/
private function add_crypto_method(RequestInterface $request, array &$options, $value, array &$params): void
{
if (
$value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
|| $value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
|| $value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
|| (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT)
) {
$options['http']['crypto_method'] = $value;
return;
}
throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
}
/**
* @param mixed $value as passed via Request transfer options.
*/
private function add_verify(RequestInterface $request, array &$options, $value, array &$params): void
{
if ($value === false) {
$options['ssl']['verify_peer'] = false;
$options['ssl']['verify_peer_name'] = false;
return;
}
if (\is_string($value)) {
$options['ssl']['cafile'] = $value;
if (!\file_exists($value)) {
throw new \RuntimeException("SSL CA bundle not found: $value");
}
} elseif ($value !== true) {
throw new \InvalidArgumentException('Invalid verify request option');
}
$options['ssl']['verify_peer'] = true;
$options['ssl']['verify_peer_name'] = true;
$options['ssl']['allow_self_signed'] = false;
}
/**
* @param mixed $value as passed via Request transfer options.
*/
private function add_cert(RequestInterface $request, array &$options, $value, array &$params): void
{
if (\is_array($value)) {
$options['ssl']['passphrase'] = $value[1];
$value = $value[0];
}
if (!\file_exists($value)) {
throw new \RuntimeException("SSL certificate not found: {$value}");
}
$options['ssl']['local_cert'] = $value;
}
/**
* @param mixed $value as passed via Request transfer options.
*/
private function add_progress(RequestInterface $request, array &$options, $value, array &$params): void
{
self::addNotification(
$params,
static function ($code, $a, $b, $c, $transferred, $total) use ($value) {
if ($code == \STREAM_NOTIFY_PROGRESS) {
// The upload progress cannot be determined. Use 0 for cURL compatibility:
// https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html
$value($total, $transferred, 0, 0);
}
}
);
}
/**
* @param mixed $value as passed via Request transfer options.
*/
private function add_debug(RequestInterface $request, array &$options, $value, array &$params): void
{
if ($value === false) {
return;
}
static $map = [
\STREAM_NOTIFY_CONNECT => 'CONNECT',
\STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED',
\STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT',
\STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS',
\STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS',
\STREAM_NOTIFY_REDIRECTED => 'REDIRECTED',
\STREAM_NOTIFY_PROGRESS => 'PROGRESS',
\STREAM_NOTIFY_FAILURE => 'FAILURE',
\STREAM_NOTIFY_COMPLETED => 'COMPLETED',
\STREAM_NOTIFY_RESOLVE => 'RESOLVE',
];
static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max'];
$value = Utils::debugResource($value);
$ident = $request->getMethod().' '.$request->getUri()->withFragment('');
self::addNotification(
$params,
static function (int $code, ...$passed) use ($ident, $value, $map, $args): void {
\fprintf($value, '<%s> [%s] ', $ident, $map[$code]);
foreach (\array_filter($passed) as $i => $v) {
\fwrite($value, $args[$i].': "'.$v.'" ');
}
\fwrite($value, "\n");
}
);
}
private static function addNotification(array &$params, callable $notify): void
{
// Wrap the existing function if needed.
if (!isset($params['notification'])) {
$params['notification'] = $notify;
} else {
$params['notification'] = self::callArray([
$params['notification'],
$notify,
]);
}
}
private static function callArray(array $functions): callable
{
return static function (...$args) use ($functions) {
foreach ($functions as $fn) {
$fn(...$args);
}
};
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Handler/CurlFactory.php | src/Handler/CurlFactory.php | <?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\LazyOpenStream;
use GuzzleHttp\TransferStats;
use GuzzleHttp\Utils;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\UriInterface;
/**
* Creates curl resources from a request
*
* @final
*/
class CurlFactory implements CurlFactoryInterface
{
public const CURL_VERSION_STR = 'curl_version';
/**
* @deprecated
*/
public const LOW_CURL_VERSION_NUMBER = '7.21.2';
/**
* @var resource[]|\CurlHandle[]
*/
private $handles = [];
/**
* @var int Total number of idle handles to keep in cache
*/
private $maxHandles;
/**
* @param int $maxHandles Maximum number of idle handles.
*/
public function __construct(int $maxHandles)
{
$this->maxHandles = $maxHandles;
}
public function create(RequestInterface $request, array $options): EasyHandle
{
$protocolVersion = $request->getProtocolVersion();
if ('2' === $protocolVersion || '2.0' === $protocolVersion) {
if (!self::supportsHttp2()) {
throw new ConnectException('HTTP/2 is supported by the cURL handler, however libcurl is built without HTTP/2 support.', $request);
}
} elseif ('1.0' !== $protocolVersion && '1.1' !== $protocolVersion) {
throw new ConnectException(sprintf('HTTP/%s is not supported by the cURL handler.', $protocolVersion), $request);
}
if (isset($options['curl']['body_as_string'])) {
$options['_body_as_string'] = $options['curl']['body_as_string'];
unset($options['curl']['body_as_string']);
}
$easy = new EasyHandle();
$easy->request = $request;
$easy->options = $options;
$conf = $this->getDefaultConf($easy);
$this->applyMethod($easy, $conf);
$this->applyHandlerOptions($easy, $conf);
$this->applyHeaders($easy, $conf);
unset($conf['_headers']);
// Add handler options from the request configuration options
if (isset($options['curl'])) {
$conf = \array_replace($conf, $options['curl']);
}
$conf[\CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy);
$easy->handle = $this->handles ? \array_pop($this->handles) : \curl_init();
curl_setopt_array($easy->handle, $conf);
return $easy;
}
private static function supportsHttp2(): bool
{
static $supportsHttp2 = null;
if (null === $supportsHttp2) {
$supportsHttp2 = self::supportsTls12()
&& defined('CURL_VERSION_HTTP2')
&& (\CURL_VERSION_HTTP2 & \curl_version()['features']);
}
return $supportsHttp2;
}
private static function supportsTls12(): bool
{
static $supportsTls12 = null;
if (null === $supportsTls12) {
$supportsTls12 = \CURL_SSLVERSION_TLSv1_2 & \curl_version()['features'];
}
return $supportsTls12;
}
private static function supportsTls13(): bool
{
static $supportsTls13 = null;
if (null === $supportsTls13) {
$supportsTls13 = defined('CURL_SSLVERSION_TLSv1_3')
&& (\CURL_SSLVERSION_TLSv1_3 & \curl_version()['features']);
}
return $supportsTls13;
}
public function release(EasyHandle $easy): void
{
$resource = $easy->handle;
unset($easy->handle);
if (\count($this->handles) >= $this->maxHandles) {
if (PHP_VERSION_ID < 80000) {
\curl_close($resource);
}
} else {
// Remove all callback functions as they can hold onto references
// and are not cleaned up by curl_reset. Using curl_setopt_array
// does not work for some reason, so removing each one
// individually.
\curl_setopt($resource, \CURLOPT_HEADERFUNCTION, null);
\curl_setopt($resource, \CURLOPT_READFUNCTION, null);
\curl_setopt($resource, \CURLOPT_WRITEFUNCTION, null);
\curl_setopt($resource, \CURLOPT_PROGRESSFUNCTION, null);
\curl_reset($resource);
$this->handles[] = $resource;
}
}
/**
* Completes a cURL transaction, either returning a response promise or a
* rejected promise.
*
* @param callable(RequestInterface, array): PromiseInterface $handler
* @param CurlFactoryInterface $factory Dictates how the handle is released
*/
public static function finish(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface
{
if (isset($easy->options['on_stats'])) {
self::invokeStats($easy);
}
if (!$easy->response || $easy->errno) {
return self::finishError($handler, $easy, $factory);
}
// Return the response if it is present and there is no error.
$factory->release($easy);
// Rewind the body of the response if possible.
$body = $easy->response->getBody();
if ($body->isSeekable()) {
$body->rewind();
}
return new FulfilledPromise($easy->response);
}
private static function invokeStats(EasyHandle $easy): void
{
$curlStats = \curl_getinfo($easy->handle);
$curlStats['appconnect_time'] = \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME);
$stats = new TransferStats(
$easy->request,
$easy->response,
$curlStats['total_time'],
$easy->errno,
$curlStats
);
($easy->options['on_stats'])($stats);
}
/**
* @param callable(RequestInterface, array): PromiseInterface $handler
*/
private static function finishError(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface
{
// Get error information and release the handle to the factory.
$ctx = [
'errno' => $easy->errno,
'error' => \curl_error($easy->handle),
'appconnect_time' => \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME),
] + \curl_getinfo($easy->handle);
$ctx[self::CURL_VERSION_STR] = self::getCurlVersion();
$factory->release($easy);
// Retry when nothing is present or when curl failed to rewind.
if (empty($easy->options['_err_message']) && (!$easy->errno || $easy->errno == 65)) {
return self::retryFailedRewind($handler, $easy, $ctx);
}
return self::createRejection($easy, $ctx);
}
private static function getCurlVersion(): string
{
static $curlVersion = null;
if (null === $curlVersion) {
$curlVersion = \curl_version()['version'];
}
return $curlVersion;
}
private static function createRejection(EasyHandle $easy, array $ctx): PromiseInterface
{
static $connectionErrors = [
\CURLE_OPERATION_TIMEOUTED => true,
\CURLE_COULDNT_RESOLVE_HOST => true,
\CURLE_COULDNT_CONNECT => true,
\CURLE_SSL_CONNECT_ERROR => true,
\CURLE_GOT_NOTHING => true,
];
if ($easy->createResponseException) {
return P\Create::rejectionFor(
new RequestException(
'An error was encountered while creating the response',
$easy->request,
$easy->response,
$easy->createResponseException,
$ctx
)
);
}
// If an exception was encountered during the onHeaders event, then
// return a rejected promise that wraps that exception.
if ($easy->onHeadersException) {
return P\Create::rejectionFor(
new RequestException(
'An error was encountered during the on_headers event',
$easy->request,
$easy->response,
$easy->onHeadersException,
$ctx
)
);
}
$uri = $easy->request->getUri();
$sanitizedError = self::sanitizeCurlError($ctx['error'] ?? '', $uri);
$message = \sprintf(
'cURL error %s: %s (%s)',
$ctx['errno'],
$sanitizedError,
'see https://curl.haxx.se/libcurl/c/libcurl-errors.html'
);
if ('' !== $sanitizedError) {
$redactedUriString = \GuzzleHttp\Psr7\Utils::redactUserInfo($uri)->__toString();
if ($redactedUriString !== '' && false === \strpos($sanitizedError, $redactedUriString)) {
$message .= \sprintf(' for %s', $redactedUriString);
}
}
// Create a connection exception if it was a specific error code.
$error = isset($connectionErrors[$easy->errno])
? new ConnectException($message, $easy->request, null, $ctx)
: new RequestException($message, $easy->request, $easy->response, null, $ctx);
return P\Create::rejectionFor($error);
}
private static function sanitizeCurlError(string $error, UriInterface $uri): string
{
if ('' === $error) {
return $error;
}
$baseUri = $uri->withQuery('')->withFragment('');
$baseUriString = $baseUri->__toString();
if ('' === $baseUriString) {
return $error;
}
$redactedUriString = \GuzzleHttp\Psr7\Utils::redactUserInfo($baseUri)->__toString();
return str_replace($baseUriString, $redactedUriString, $error);
}
/**
* @return array<int|string, mixed>
*/
private function getDefaultConf(EasyHandle $easy): array
{
$conf = [
'_headers' => $easy->request->getHeaders(),
\CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(),
\CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''),
\CURLOPT_RETURNTRANSFER => false,
\CURLOPT_HEADER => false,
\CURLOPT_CONNECTTIMEOUT => 300,
];
if (\defined('CURLOPT_PROTOCOLS')) {
$conf[\CURLOPT_PROTOCOLS] = \CURLPROTO_HTTP | \CURLPROTO_HTTPS;
}
$version = $easy->request->getProtocolVersion();
if ('2' === $version || '2.0' === $version) {
$conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0;
} elseif ('1.1' === $version) {
$conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1;
} else {
$conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0;
}
return $conf;
}
private function applyMethod(EasyHandle $easy, array &$conf): void
{
$body = $easy->request->getBody();
$size = $body->getSize();
if ($size === null || $size > 0) {
$this->applyBody($easy->request, $easy->options, $conf);
return;
}
$method = $easy->request->getMethod();
if ($method === 'PUT' || $method === 'POST') {
// See https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2
if (!$easy->request->hasHeader('Content-Length')) {
$conf[\CURLOPT_HTTPHEADER][] = 'Content-Length: 0';
}
} elseif ($method === 'HEAD') {
$conf[\CURLOPT_NOBODY] = true;
unset(
$conf[\CURLOPT_WRITEFUNCTION],
$conf[\CURLOPT_READFUNCTION],
$conf[\CURLOPT_FILE],
$conf[\CURLOPT_INFILE]
);
}
}
private function applyBody(RequestInterface $request, array $options, array &$conf): void
{
$size = $request->hasHeader('Content-Length')
? (int) $request->getHeaderLine('Content-Length')
: null;
// Send the body as a string if the size is less than 1MB OR if the
// [curl][body_as_string] request value is set.
if (($size !== null && $size < 1000000) || !empty($options['_body_as_string'])) {
$conf[\CURLOPT_POSTFIELDS] = (string) $request->getBody();
// Don't duplicate the Content-Length header
$this->removeHeader('Content-Length', $conf);
$this->removeHeader('Transfer-Encoding', $conf);
} else {
$conf[\CURLOPT_UPLOAD] = true;
if ($size !== null) {
$conf[\CURLOPT_INFILESIZE] = $size;
$this->removeHeader('Content-Length', $conf);
}
$body = $request->getBody();
if ($body->isSeekable()) {
$body->rewind();
}
$conf[\CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use ($body) {
return $body->read($length);
};
}
// If the Expect header is not present, prevent curl from adding it
if (!$request->hasHeader('Expect')) {
$conf[\CURLOPT_HTTPHEADER][] = 'Expect:';
}
// cURL sometimes adds a content-type by default. Prevent this.
if (!$request->hasHeader('Content-Type')) {
$conf[\CURLOPT_HTTPHEADER][] = 'Content-Type:';
}
}
private function applyHeaders(EasyHandle $easy, array &$conf): void
{
foreach ($conf['_headers'] as $name => $values) {
foreach ($values as $value) {
$value = (string) $value;
if ($value === '') {
// cURL requires a special format for empty headers.
// See https://github.com/guzzle/guzzle/issues/1882 for more details.
$conf[\CURLOPT_HTTPHEADER][] = "$name;";
} else {
$conf[\CURLOPT_HTTPHEADER][] = "$name: $value";
}
}
}
// Remove the Accept header if one was not set
if (!$easy->request->hasHeader('Accept')) {
$conf[\CURLOPT_HTTPHEADER][] = 'Accept:';
}
}
/**
* Remove a header from the options array.
*
* @param string $name Case-insensitive header to remove
* @param array $options Array of options to modify
*/
private function removeHeader(string $name, array &$options): void
{
foreach (\array_keys($options['_headers']) as $key) {
if (!\strcasecmp($key, $name)) {
unset($options['_headers'][$key]);
return;
}
}
}
private function applyHandlerOptions(EasyHandle $easy, array &$conf): void
{
$options = $easy->options;
if (isset($options['verify'])) {
if ($options['verify'] === false) {
unset($conf[\CURLOPT_CAINFO]);
$conf[\CURLOPT_SSL_VERIFYHOST] = 0;
$conf[\CURLOPT_SSL_VERIFYPEER] = false;
} else {
$conf[\CURLOPT_SSL_VERIFYHOST] = 2;
$conf[\CURLOPT_SSL_VERIFYPEER] = true;
if (\is_string($options['verify'])) {
// Throw an error if the file/folder/link path is not valid or doesn't exist.
if (!\file_exists($options['verify'])) {
throw new \InvalidArgumentException("SSL CA bundle not found: {$options['verify']}");
}
// If it's a directory or a link to a directory use CURLOPT_CAPATH.
// If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO.
if (
\is_dir($options['verify'])
|| (
\is_link($options['verify']) === true
&& ($verifyLink = \readlink($options['verify'])) !== false
&& \is_dir($verifyLink)
)
) {
$conf[\CURLOPT_CAPATH] = $options['verify'];
} else {
$conf[\CURLOPT_CAINFO] = $options['verify'];
}
}
}
}
if (!isset($options['curl'][\CURLOPT_ENCODING]) && !empty($options['decode_content'])) {
$accept = $easy->request->getHeaderLine('Accept-Encoding');
if ($accept) {
$conf[\CURLOPT_ENCODING] = $accept;
} else {
// The empty string enables all available decoders and implicitly
// sets a matching 'Accept-Encoding' header.
$conf[\CURLOPT_ENCODING] = '';
// But as the user did not specify any encoding preference,
// let's leave it up to server by preventing curl from sending
// the header, which will be interpreted as 'Accept-Encoding: *'.
// https://www.rfc-editor.org/rfc/rfc9110#field.accept-encoding
$conf[\CURLOPT_HTTPHEADER][] = 'Accept-Encoding:';
}
}
if (!isset($options['sink'])) {
// Use a default temp stream if no sink was set.
$options['sink'] = \GuzzleHttp\Psr7\Utils::tryFopen('php://temp', 'w+');
}
$sink = $options['sink'];
if (!\is_string($sink)) {
$sink = \GuzzleHttp\Psr7\Utils::streamFor($sink);
} elseif (!\is_dir(\dirname($sink))) {
// Ensure that the directory exists before failing in curl.
throw new \RuntimeException(\sprintf('Directory %s does not exist for sink value of %s', \dirname($sink), $sink));
} else {
$sink = new LazyOpenStream($sink, 'w+');
}
$easy->sink = $sink;
$conf[\CURLOPT_WRITEFUNCTION] = static function ($ch, $write) use ($sink): int {
return $sink->write($write);
};
$timeoutRequiresNoSignal = false;
if (isset($options['timeout'])) {
$timeoutRequiresNoSignal |= $options['timeout'] < 1;
$conf[\CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000;
}
// CURL default value is CURL_IPRESOLVE_WHATEVER
if (isset($options['force_ip_resolve'])) {
if ('v4' === $options['force_ip_resolve']) {
$conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V4;
} elseif ('v6' === $options['force_ip_resolve']) {
$conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V6;
}
}
if (isset($options['connect_timeout'])) {
$timeoutRequiresNoSignal |= $options['connect_timeout'] < 1;
$conf[\CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000;
}
if ($timeoutRequiresNoSignal && \strtoupper(\substr(\PHP_OS, 0, 3)) !== 'WIN') {
$conf[\CURLOPT_NOSIGNAL] = true;
}
if (isset($options['proxy'])) {
if (!\is_array($options['proxy'])) {
$conf[\CURLOPT_PROXY] = $options['proxy'];
} else {
$scheme = $easy->request->getUri()->getScheme();
if (isset($options['proxy'][$scheme])) {
$host = $easy->request->getUri()->getHost();
if (isset($options['proxy']['no']) && Utils::isHostInNoProxy($host, $options['proxy']['no'])) {
unset($conf[\CURLOPT_PROXY]);
} else {
$conf[\CURLOPT_PROXY] = $options['proxy'][$scheme];
}
}
}
}
if (isset($options['crypto_method'])) {
$protocolVersion = $easy->request->getProtocolVersion();
// If HTTP/2, upgrade TLS 1.0 and 1.1 to 1.2
if ('2' === $protocolVersion || '2.0' === $protocolVersion) {
if (
\STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT === $options['crypto_method']
|| \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT === $options['crypto_method']
|| \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT === $options['crypto_method']
) {
$conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_2;
} elseif (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT === $options['crypto_method']) {
if (!self::supportsTls13()) {
throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.3 not supported by your version of cURL');
}
$conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_3;
} else {
throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
}
} elseif (\STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT === $options['crypto_method']) {
$conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_0;
} elseif (\STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT === $options['crypto_method']) {
$conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_1;
} elseif (\STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT === $options['crypto_method']) {
if (!self::supportsTls12()) {
throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.2 not supported by your version of cURL');
}
$conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_2;
} elseif (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT === $options['crypto_method']) {
if (!self::supportsTls13()) {
throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.3 not supported by your version of cURL');
}
$conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_3;
} else {
throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
}
}
if (isset($options['cert'])) {
$cert = $options['cert'];
if (\is_array($cert)) {
$conf[\CURLOPT_SSLCERTPASSWD] = $cert[1];
$cert = $cert[0];
}
if (!\file_exists($cert)) {
throw new \InvalidArgumentException("SSL certificate not found: {$cert}");
}
// OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files.
// see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html
$ext = pathinfo($cert, \PATHINFO_EXTENSION);
if (preg_match('#^(der|p12)$#i', $ext)) {
$conf[\CURLOPT_SSLCERTTYPE] = strtoupper($ext);
}
$conf[\CURLOPT_SSLCERT] = $cert;
}
if (isset($options['ssl_key'])) {
if (\is_array($options['ssl_key'])) {
if (\count($options['ssl_key']) === 2) {
[$sslKey, $conf[\CURLOPT_SSLKEYPASSWD]] = $options['ssl_key'];
} else {
[$sslKey] = $options['ssl_key'];
}
}
$sslKey = $sslKey ?? $options['ssl_key'];
if (!\file_exists($sslKey)) {
throw new \InvalidArgumentException("SSL private key not found: {$sslKey}");
}
$conf[\CURLOPT_SSLKEY] = $sslKey;
}
if (isset($options['progress'])) {
$progress = $options['progress'];
if (!\is_callable($progress)) {
throw new \InvalidArgumentException('progress client option must be callable');
}
$conf[\CURLOPT_NOPROGRESS] = false;
$conf[\CURLOPT_PROGRESSFUNCTION] = static function ($resource, int $downloadSize, int $downloaded, int $uploadSize, int $uploaded) use ($progress) {
$progress($downloadSize, $downloaded, $uploadSize, $uploaded);
};
}
if (!empty($options['debug'])) {
$conf[\CURLOPT_STDERR] = Utils::debugResource($options['debug']);
$conf[\CURLOPT_VERBOSE] = true;
}
}
/**
* This function ensures that a response was set on a transaction. If one
* was not set, then the request is retried if possible. This error
* typically means you are sending a payload, curl encountered a
* "Connection died, retrying a fresh connect" error, tried to rewind the
* stream, and then encountered a "necessary data rewind wasn't possible"
* error, causing the request to be sent through curl_multi_info_read()
* without an error status.
*
* @param callable(RequestInterface, array): PromiseInterface $handler
*/
private static function retryFailedRewind(callable $handler, EasyHandle $easy, array $ctx): PromiseInterface
{
try {
// Only rewind if the body has been read from.
$body = $easy->request->getBody();
if ($body->tell() > 0) {
$body->rewind();
}
} catch (\RuntimeException $e) {
$ctx['error'] = 'The connection unexpectedly failed without '
.'providing an error. The request would have been retried, '
.'but attempting to rewind the request body failed. '
.'Exception: '.$e;
return self::createRejection($easy, $ctx);
}
// Retry no more than 3 times before giving up.
if (!isset($easy->options['_curl_retries'])) {
$easy->options['_curl_retries'] = 1;
} elseif ($easy->options['_curl_retries'] == 2) {
$ctx['error'] = 'The cURL request was retried 3 times '
.'and did not succeed. The most likely reason for the failure '
.'is that cURL was unable to rewind the body of the request '
.'and subsequent retries resulted in the same error. Turn on '
.'the debug option to see what went wrong. See '
.'https://bugs.php.net/bug.php?id=47204 for more information.';
return self::createRejection($easy, $ctx);
} else {
++$easy->options['_curl_retries'];
}
return $handler($easy->request, $easy->options);
}
private function createHeaderFn(EasyHandle $easy): callable
{
if (isset($easy->options['on_headers'])) {
$onHeaders = $easy->options['on_headers'];
if (!\is_callable($onHeaders)) {
throw new \InvalidArgumentException('on_headers must be callable');
}
} else {
$onHeaders = null;
}
return static function ($ch, $h) use (
$onHeaders,
$easy,
&$startingResponse
) {
$value = \trim($h);
if ($value === '') {
$startingResponse = true;
try {
$easy->createResponse();
} catch (\Exception $e) {
$easy->createResponseException = $e;
return -1;
}
if ($onHeaders !== null) {
try {
$onHeaders($easy->response);
} catch (\Exception $e) {
// Associate the exception with the handle and trigger
// a curl header write error by returning 0.
$easy->onHeadersException = $e;
return -1;
}
}
} elseif ($startingResponse) {
$startingResponse = false;
$easy->headers = [$value];
} else {
$easy->headers[] = $value;
}
return \strlen($h);
};
}
public function __destruct()
{
foreach ($this->handles as $id => $handle) {
if (PHP_VERSION_ID < 80000) {
\curl_close($handle);
}
unset($this->handles[$id]);
}
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Handler/CurlMultiHandler.php | src/Handler/CurlMultiHandler.php | <?php
namespace GuzzleHttp\Handler;
use Closure;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Utils;
use Psr\Http\Message\RequestInterface;
/**
* Returns an asynchronous response using curl_multi_* functions.
*
* When using the CurlMultiHandler, custom curl options can be specified as an
* associative array of curl option constants mapping to values in the
* **curl** key of the provided request options.
*
* @final
*/
class CurlMultiHandler
{
/**
* @var CurlFactoryInterface
*/
private $factory;
/**
* @var int
*/
private $selectTimeout;
/**
* @var int Will be higher than 0 when `curl_multi_exec` is still running.
*/
private $active = 0;
/**
* @var array Request entry handles, indexed by handle id in `addRequest`.
*
* @see CurlMultiHandler::addRequest
*/
private $handles = [];
/**
* @var array<int, float> An array of delay times, indexed by handle id in `addRequest`.
*
* @see CurlMultiHandler::addRequest
*/
private $delays = [];
/**
* @var array<mixed> An associative array of CURLMOPT_* options and corresponding values for curl_multi_setopt()
*/
private $options = [];
/** @var resource|\CurlMultiHandle */
private $_mh;
/**
* This handler accepts the following options:
*
* - handle_factory: An optional factory used to create curl handles
* - select_timeout: Optional timeout (in seconds) to block before timing
* out while selecting curl handles. Defaults to 1 second.
* - options: An associative array of CURLMOPT_* options and
* corresponding values for curl_multi_setopt()
*/
public function __construct(array $options = [])
{
$this->factory = $options['handle_factory'] ?? new CurlFactory(50);
if (isset($options['select_timeout'])) {
$this->selectTimeout = $options['select_timeout'];
} elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) {
@trigger_error('Since guzzlehttp/guzzle 7.2.0: Using environment variable GUZZLE_CURL_SELECT_TIMEOUT is deprecated. Use option "select_timeout" instead.', \E_USER_DEPRECATED);
$this->selectTimeout = (int) $selectTimeout;
} else {
$this->selectTimeout = 1;
}
$this->options = $options['options'] ?? [];
// unsetting the property forces the first access to go through
// __get().
unset($this->_mh);
}
/**
* @param string $name
*
* @return resource|\CurlMultiHandle
*
* @throws \BadMethodCallException when another field as `_mh` will be gotten
* @throws \RuntimeException when curl can not initialize a multi handle
*/
public function __get($name)
{
if ($name !== '_mh') {
throw new \BadMethodCallException("Can not get other property as '_mh'.");
}
$multiHandle = \curl_multi_init();
if (false === $multiHandle) {
throw new \RuntimeException('Can not initialize curl multi handle.');
}
$this->_mh = $multiHandle;
foreach ($this->options as $option => $value) {
// A warning is raised in case of a wrong option.
curl_multi_setopt($this->_mh, $option, $value);
}
return $this->_mh;
}
public function __destruct()
{
if (isset($this->_mh)) {
\curl_multi_close($this->_mh);
unset($this->_mh);
}
}
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
$easy = $this->factory->create($request, $options);
$id = (int) $easy->handle;
$promise = new Promise(
[$this, 'execute'],
function () use ($id) {
return $this->cancel($id);
}
);
$this->addRequest(['easy' => $easy, 'deferred' => $promise]);
return $promise;
}
/**
* Ticks the curl event loop.
*/
public function tick(): void
{
// Add any delayed handles if needed.
if ($this->delays) {
$currentTime = Utils::currentTime();
foreach ($this->delays as $id => $delay) {
if ($currentTime >= $delay) {
unset($this->delays[$id]);
\curl_multi_add_handle(
$this->_mh,
$this->handles[$id]['easy']->handle
);
}
}
}
// Run curl_multi_exec in the queue to enable other async tasks to run
P\Utils::queue()->add(Closure::fromCallable([$this, 'tickInQueue']));
// Step through the task queue which may add additional requests.
P\Utils::queue()->run();
if ($this->active && \curl_multi_select($this->_mh, $this->selectTimeout) === -1) {
// Perform a usleep if a select returns -1.
// See: https://bugs.php.net/bug.php?id=61141
\usleep(250);
}
while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM) {
// Prevent busy looping for slow HTTP requests.
\curl_multi_select($this->_mh, $this->selectTimeout);
}
$this->processMessages();
}
/**
* Runs \curl_multi_exec() inside the event loop, to prevent busy looping
*/
private function tickInQueue(): void
{
if (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM) {
\curl_multi_select($this->_mh, 0);
P\Utils::queue()->add(Closure::fromCallable([$this, 'tickInQueue']));
}
}
/**
* Runs until all outstanding connections have completed.
*/
public function execute(): void
{
$queue = P\Utils::queue();
while ($this->handles || !$queue->isEmpty()) {
// If there are no transfers, then sleep for the next delay
if (!$this->active && $this->delays) {
\usleep($this->timeToNext());
}
$this->tick();
}
}
private function addRequest(array $entry): void
{
$easy = $entry['easy'];
$id = (int) $easy->handle;
$this->handles[$id] = $entry;
if (empty($easy->options['delay'])) {
\curl_multi_add_handle($this->_mh, $easy->handle);
} else {
$this->delays[$id] = Utils::currentTime() + ($easy->options['delay'] / 1000);
}
}
/**
* Cancels a handle from sending and removes references to it.
*
* @param int $id Handle ID to cancel and remove.
*
* @return bool True on success, false on failure.
*/
private function cancel($id): bool
{
if (!is_int($id)) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an integer to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
// Cannot cancel if it has been processed.
if (!isset($this->handles[$id])) {
return false;
}
$handle = $this->handles[$id]['easy']->handle;
unset($this->delays[$id], $this->handles[$id]);
\curl_multi_remove_handle($this->_mh, $handle);
if (PHP_VERSION_ID < 80000) {
\curl_close($handle);
}
return true;
}
private function processMessages(): void
{
while ($done = \curl_multi_info_read($this->_mh)) {
if ($done['msg'] !== \CURLMSG_DONE) {
// if it's not done, then it would be premature to remove the handle. ref https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216
continue;
}
$id = (int) $done['handle'];
\curl_multi_remove_handle($this->_mh, $done['handle']);
if (!isset($this->handles[$id])) {
// Probably was cancelled.
continue;
}
$entry = $this->handles[$id];
unset($this->handles[$id], $this->delays[$id]);
$entry['easy']->errno = $done['result'];
$entry['deferred']->resolve(
CurlFactory::finish($this, $entry['easy'], $this->factory)
);
}
}
private function timeToNext(): int
{
$currentTime = Utils::currentTime();
$nextTime = \PHP_INT_MAX;
foreach ($this->delays as $time) {
if ($time < $nextTime) {
$nextTime = $time;
}
}
return ((int) \max(0, $nextTime - $currentTime)) * 1000000;
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Exception/BadResponseException.php | src/Exception/BadResponseException.php | <?php
namespace GuzzleHttp\Exception;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Exception when an HTTP error occurs (4xx or 5xx error)
*/
class BadResponseException extends RequestException
{
public function __construct(
string $message,
RequestInterface $request,
ResponseInterface $response,
?\Throwable $previous = null,
array $handlerContext = []
) {
parent::__construct($message, $request, $response, $previous, $handlerContext);
}
/**
* Current exception and the ones that extend it will always have a response.
*/
public function hasResponse(): bool
{
return true;
}
/**
* This function narrows the return type from the parent class and does not allow it to be nullable.
*/
public function getResponse(): ResponseInterface
{
/** @var ResponseInterface */
return parent::getResponse();
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Exception/RequestException.php | src/Exception/RequestException.php | <?php
namespace GuzzleHttp\Exception;
use GuzzleHttp\BodySummarizer;
use GuzzleHttp\BodySummarizerInterface;
use Psr\Http\Client\RequestExceptionInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* HTTP Request exception
*/
class RequestException extends TransferException implements RequestExceptionInterface
{
/**
* @var RequestInterface
*/
private $request;
/**
* @var ResponseInterface|null
*/
private $response;
/**
* @var array
*/
private $handlerContext;
public function __construct(
string $message,
RequestInterface $request,
?ResponseInterface $response = null,
?\Throwable $previous = null,
array $handlerContext = []
) {
// Set the code of the exception if the response is set and not future.
$code = $response ? $response->getStatusCode() : 0;
parent::__construct($message, $code, $previous);
$this->request = $request;
$this->response = $response;
$this->handlerContext = $handlerContext;
}
/**
* Wrap non-RequestExceptions with a RequestException
*/
public static function wrapException(RequestInterface $request, \Throwable $e): RequestException
{
return $e instanceof RequestException ? $e : new RequestException($e->getMessage(), $request, null, $e);
}
/**
* Factory method to create a new exception with a normalized error message
*
* @param RequestInterface $request Request sent
* @param ResponseInterface $response Response received
* @param \Throwable|null $previous Previous exception
* @param array $handlerContext Optional handler context
* @param BodySummarizerInterface|null $bodySummarizer Optional body summarizer
*/
public static function create(
RequestInterface $request,
?ResponseInterface $response = null,
?\Throwable $previous = null,
array $handlerContext = [],
?BodySummarizerInterface $bodySummarizer = null
): self {
if (!$response) {
return new self(
'Error completing request',
$request,
null,
$previous,
$handlerContext
);
}
$level = (int) \floor($response->getStatusCode() / 100);
if ($level === 4) {
$label = 'Client error';
$className = ClientException::class;
} elseif ($level === 5) {
$label = 'Server error';
$className = ServerException::class;
} else {
$label = 'Unsuccessful request';
$className = __CLASS__;
}
$uri = \GuzzleHttp\Psr7\Utils::redactUserInfo($request->getUri());
// Client Error: `GET /` resulted in a `404 Not Found` response:
// <html> ... (truncated)
$message = \sprintf(
'%s: `%s %s` resulted in a `%s %s` response',
$label,
$request->getMethod(),
$uri->__toString(),
$response->getStatusCode(),
$response->getReasonPhrase()
);
$summary = ($bodySummarizer ?? new BodySummarizer())->summarize($response);
if ($summary !== null) {
$message .= ":\n{$summary}\n";
}
return new $className($message, $request, $response, $previous, $handlerContext);
}
/**
* Get the request that caused the exception
*/
public function getRequest(): RequestInterface
{
return $this->request;
}
/**
* Get the associated response
*/
public function getResponse(): ?ResponseInterface
{
return $this->response;
}
/**
* Check if a response was received
*/
public function hasResponse(): bool
{
return $this->response !== null;
}
/**
* Get contextual information about the error from the underlying handler.
*
* The contents of this array will vary depending on which handler you are
* using. It may also be just an empty array. Relying on this data will
* couple you to a specific handler, but can give more debug information
* when needed.
*/
public function getHandlerContext(): array
{
return $this->handlerContext;
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Exception/ServerException.php | src/Exception/ServerException.php | <?php
namespace GuzzleHttp\Exception;
/**
* Exception when a server error is encountered (5xx codes)
*/
class ServerException extends BadResponseException
{
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Exception/TransferException.php | src/Exception/TransferException.php | <?php
namespace GuzzleHttp\Exception;
class TransferException extends \RuntimeException implements GuzzleException
{
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Exception/GuzzleException.php | src/Exception/GuzzleException.php | <?php
namespace GuzzleHttp\Exception;
use Psr\Http\Client\ClientExceptionInterface;
interface GuzzleException extends ClientExceptionInterface
{
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Exception/InvalidArgumentException.php | src/Exception/InvalidArgumentException.php | <?php
namespace GuzzleHttp\Exception;
final class InvalidArgumentException extends \InvalidArgumentException implements GuzzleException
{
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Exception/TooManyRedirectsException.php | src/Exception/TooManyRedirectsException.php | <?php
namespace GuzzleHttp\Exception;
class TooManyRedirectsException extends RequestException
{
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Exception/ConnectException.php | src/Exception/ConnectException.php | <?php
namespace GuzzleHttp\Exception;
use Psr\Http\Client\NetworkExceptionInterface;
use Psr\Http\Message\RequestInterface;
/**
* Exception thrown when a connection cannot be established.
*
* Note that no response is present for a ConnectException
*/
class ConnectException extends TransferException implements NetworkExceptionInterface
{
/**
* @var RequestInterface
*/
private $request;
/**
* @var array
*/
private $handlerContext;
public function __construct(
string $message,
RequestInterface $request,
?\Throwable $previous = null,
array $handlerContext = []
) {
parent::__construct($message, 0, $previous);
$this->request = $request;
$this->handlerContext = $handlerContext;
}
/**
* Get the request that caused the exception
*/
public function getRequest(): RequestInterface
{
return $this->request;
}
/**
* Get contextual information about the error from the underlying handler.
*
* The contents of this array will vary depending on which handler you are
* using. It may also be just an empty array. Relying on this data will
* couple you to a specific handler, but can give more debug information
* when needed.
*/
public function getHandlerContext(): array
{
return $this->handlerContext;
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Exception/ClientException.php | src/Exception/ClientException.php | <?php
namespace GuzzleHttp\Exception;
/**
* Exception when a client error is encountered (4xx codes)
*/
class ClientException extends BadResponseException
{
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Cookie/CookieJar.php | src/Cookie/CookieJar.php | <?php
namespace GuzzleHttp\Cookie;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Cookie jar that stores cookies as an array
*/
class CookieJar implements CookieJarInterface
{
/**
* @var SetCookie[] Loaded cookie data
*/
private $cookies = [];
/**
* @var bool
*/
private $strictMode;
/**
* @param bool $strictMode Set to true to throw exceptions when invalid
* cookies are added to the cookie jar.
* @param array $cookieArray Array of SetCookie objects or a hash of
* arrays that can be used with the SetCookie
* constructor
*/
public function __construct(bool $strictMode = false, array $cookieArray = [])
{
$this->strictMode = $strictMode;
foreach ($cookieArray as $cookie) {
if (!($cookie instanceof SetCookie)) {
$cookie = new SetCookie($cookie);
}
$this->setCookie($cookie);
}
}
/**
* Create a new Cookie jar from an associative array and domain.
*
* @param array $cookies Cookies to create the jar from
* @param string $domain Domain to set the cookies to
*/
public static function fromArray(array $cookies, string $domain): self
{
$cookieJar = new self();
foreach ($cookies as $name => $value) {
$cookieJar->setCookie(new SetCookie([
'Domain' => $domain,
'Name' => $name,
'Value' => $value,
'Discard' => true,
]));
}
return $cookieJar;
}
/**
* Evaluate if this cookie should be persisted to storage
* that survives between requests.
*
* @param SetCookie $cookie Being evaluated.
* @param bool $allowSessionCookies If we should persist session cookies
*/
public static function shouldPersist(SetCookie $cookie, bool $allowSessionCookies = false): bool
{
if ($cookie->getExpires() || $allowSessionCookies) {
if (!$cookie->getDiscard()) {
return true;
}
}
return false;
}
/**
* Finds and returns the cookie based on the name
*
* @param string $name cookie name to search for
*
* @return SetCookie|null cookie that was found or null if not found
*/
public function getCookieByName(string $name): ?SetCookie
{
foreach ($this->cookies as $cookie) {
if ($cookie->getName() !== null && \strcasecmp($cookie->getName(), $name) === 0) {
return $cookie;
}
}
return null;
}
public function toArray(): array
{
return \array_map(static function (SetCookie $cookie): array {
return $cookie->toArray();
}, $this->getIterator()->getArrayCopy());
}
public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void
{
if (!$domain) {
$this->cookies = [];
return;
} elseif (!$path) {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($domain): bool {
return !$cookie->matchesDomain($domain);
}
);
} elseif (!$name) {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($path, $domain): bool {
return !($cookie->matchesPath($path)
&& $cookie->matchesDomain($domain));
}
);
} else {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($path, $domain, $name) {
return !($cookie->getName() == $name
&& $cookie->matchesPath($path)
&& $cookie->matchesDomain($domain));
}
);
}
}
public function clearSessionCookies(): void
{
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie): bool {
return !$cookie->getDiscard() && $cookie->getExpires();
}
);
}
public function setCookie(SetCookie $cookie): bool
{
// If the name string is empty (but not 0), ignore the set-cookie
// string entirely.
$name = $cookie->getName();
if (!$name && $name !== '0') {
return false;
}
// Only allow cookies with set and valid domain, name, value
$result = $cookie->validate();
if ($result !== true) {
if ($this->strictMode) {
throw new \RuntimeException('Invalid cookie: '.$result);
}
$this->removeCookieIfEmpty($cookie);
return false;
}
// Resolve conflicts with previously set cookies
foreach ($this->cookies as $i => $c) {
// Two cookies are identical, when their path, and domain are
// identical.
if ($c->getPath() != $cookie->getPath()
|| $c->getDomain() != $cookie->getDomain()
|| $c->getName() != $cookie->getName()
) {
continue;
}
// The previously set cookie is a discard cookie and this one is
// not so allow the new cookie to be set
if (!$cookie->getDiscard() && $c->getDiscard()) {
unset($this->cookies[$i]);
continue;
}
// If the new cookie's expiration is further into the future, then
// replace the old cookie
if ($cookie->getExpires() > $c->getExpires()) {
unset($this->cookies[$i]);
continue;
}
// If the value has changed, we better change it
if ($cookie->getValue() !== $c->getValue()) {
unset($this->cookies[$i]);
continue;
}
// The cookie exists, so no need to continue
return false;
}
$this->cookies[] = $cookie;
return true;
}
public function count(): int
{
return \count($this->cookies);
}
/**
* @return \ArrayIterator<int, SetCookie>
*/
public function getIterator(): \ArrayIterator
{
return new \ArrayIterator(\array_values($this->cookies));
}
public function extractCookies(RequestInterface $request, ResponseInterface $response): void
{
if ($cookieHeader = $response->getHeader('Set-Cookie')) {
foreach ($cookieHeader as $cookie) {
$sc = SetCookie::fromString($cookie);
if (!$sc->getDomain()) {
$sc->setDomain($request->getUri()->getHost());
}
if (0 !== \strpos($sc->getPath(), '/')) {
$sc->setPath($this->getCookiePathFromRequest($request));
}
if (!$sc->matchesDomain($request->getUri()->getHost())) {
continue;
}
// Note: At this point `$sc->getDomain()` being a public suffix should
// be rejected, but we don't want to pull in the full PSL dependency.
$this->setCookie($sc);
}
}
}
/**
* Computes cookie path following RFC 6265 section 5.1.4
*
* @see https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4
*/
private function getCookiePathFromRequest(RequestInterface $request): string
{
$uriPath = $request->getUri()->getPath();
if ('' === $uriPath) {
return '/';
}
if (0 !== \strpos($uriPath, '/')) {
return '/';
}
if ('/' === $uriPath) {
return '/';
}
$lastSlashPos = \strrpos($uriPath, '/');
if (0 === $lastSlashPos || false === $lastSlashPos) {
return '/';
}
return \substr($uriPath, 0, $lastSlashPos);
}
public function withCookieHeader(RequestInterface $request): RequestInterface
{
$values = [];
$uri = $request->getUri();
$scheme = $uri->getScheme();
$host = $uri->getHost();
$path = $uri->getPath() ?: '/';
foreach ($this->cookies as $cookie) {
if ($cookie->matchesPath($path)
&& $cookie->matchesDomain($host)
&& !$cookie->isExpired()
&& (!$cookie->getSecure() || $scheme === 'https')
) {
$values[] = $cookie->getName().'='
.$cookie->getValue();
}
}
return $values
? $request->withHeader('Cookie', \implode('; ', $values))
: $request;
}
/**
* If a cookie already exists and the server asks to set it again with a
* null value, the cookie must be deleted.
*/
private function removeCookieIfEmpty(SetCookie $cookie): void
{
$cookieValue = $cookie->getValue();
if ($cookieValue === null || $cookieValue === '') {
$this->clear(
$cookie->getDomain(),
$cookie->getPath(),
$cookie->getName()
);
}
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Cookie/SetCookie.php | src/Cookie/SetCookie.php | <?php
namespace GuzzleHttp\Cookie;
/**
* Set-Cookie object
*/
class SetCookie
{
/**
* @var array
*/
private static $defaults = [
'Name' => null,
'Value' => null,
'Domain' => null,
'Path' => '/',
'Max-Age' => null,
'Expires' => null,
'Secure' => false,
'Discard' => false,
'HttpOnly' => false,
];
/**
* @var array Cookie data
*/
private $data;
/**
* Create a new SetCookie object from a string.
*
* @param string $cookie Set-Cookie header string
*/
public static function fromString(string $cookie): self
{
// Create the default return array
$data = self::$defaults;
// Explode the cookie string using a series of semicolons
$pieces = \array_filter(\array_map('trim', \explode(';', $cookie)));
// The name of the cookie (first kvp) must exist and include an equal sign.
if (!isset($pieces[0]) || \strpos($pieces[0], '=') === false) {
return new self($data);
}
// Add the cookie pieces into the parsed data array
foreach ($pieces as $part) {
$cookieParts = \explode('=', $part, 2);
$key = \trim($cookieParts[0]);
$value = isset($cookieParts[1])
? \trim($cookieParts[1], " \n\r\t\0\x0B")
: true;
// Only check for non-cookies when cookies have been found
if (!isset($data['Name'])) {
$data['Name'] = $key;
$data['Value'] = $value;
} else {
foreach (\array_keys(self::$defaults) as $search) {
if (!\strcasecmp($search, $key)) {
if ($search === 'Max-Age') {
if (is_numeric($value)) {
$data[$search] = (int) $value;
}
} elseif ($search === 'Secure' || $search === 'Discard' || $search === 'HttpOnly') {
if ($value) {
$data[$search] = true;
}
} else {
$data[$search] = $value;
}
continue 2;
}
}
$data[$key] = $value;
}
}
return new self($data);
}
/**
* @param array $data Array of cookie data provided by a Cookie parser
*/
public function __construct(array $data = [])
{
$this->data = self::$defaults;
if (isset($data['Name'])) {
$this->setName($data['Name']);
}
if (isset($data['Value'])) {
$this->setValue($data['Value']);
}
if (isset($data['Domain'])) {
$this->setDomain($data['Domain']);
}
if (isset($data['Path'])) {
$this->setPath($data['Path']);
}
if (isset($data['Max-Age'])) {
$this->setMaxAge($data['Max-Age']);
}
if (isset($data['Expires'])) {
$this->setExpires($data['Expires']);
}
if (isset($data['Secure'])) {
$this->setSecure($data['Secure']);
}
if (isset($data['Discard'])) {
$this->setDiscard($data['Discard']);
}
if (isset($data['HttpOnly'])) {
$this->setHttpOnly($data['HttpOnly']);
}
// Set the remaining values that don't have extra validation logic
foreach (array_diff(array_keys($data), array_keys(self::$defaults)) as $key) {
$this->data[$key] = $data[$key];
}
// Extract the Expires value and turn it into a UNIX timestamp if needed
if (!$this->getExpires() && $this->getMaxAge()) {
// Calculate the Expires date
$this->setExpires(\time() + $this->getMaxAge());
} elseif (null !== ($expires = $this->getExpires()) && !\is_numeric($expires)) {
$this->setExpires($expires);
}
}
public function __toString()
{
$str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; ';
foreach ($this->data as $k => $v) {
if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) {
if ($k === 'Expires') {
$str .= 'Expires='.\gmdate('D, d M Y H:i:s \G\M\T', $v).'; ';
} else {
$str .= ($v === true ? $k : "{$k}={$v}").'; ';
}
}
}
return \rtrim($str, '; ');
}
public function toArray(): array
{
return $this->data;
}
/**
* Get the cookie name.
*
* @return string
*/
public function getName()
{
return $this->data['Name'];
}
/**
* Set the cookie name.
*
* @param string $name Cookie name
*/
public function setName($name): void
{
if (!is_string($name)) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Name'] = (string) $name;
}
/**
* Get the cookie value.
*
* @return string|null
*/
public function getValue()
{
return $this->data['Value'];
}
/**
* Set the cookie value.
*
* @param string $value Cookie value
*/
public function setValue($value): void
{
if (!is_string($value)) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Value'] = (string) $value;
}
/**
* Get the domain.
*
* @return string|null
*/
public function getDomain()
{
return $this->data['Domain'];
}
/**
* Set the domain of the cookie.
*
* @param string|null $domain
*/
public function setDomain($domain): void
{
if (!is_string($domain) && null !== $domain) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Domain'] = null === $domain ? null : (string) $domain;
}
/**
* Get the path.
*
* @return string
*/
public function getPath()
{
return $this->data['Path'];
}
/**
* Set the path of the cookie.
*
* @param string $path Path of the cookie
*/
public function setPath($path): void
{
if (!is_string($path)) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Path'] = (string) $path;
}
/**
* Maximum lifetime of the cookie in seconds.
*
* @return int|null
*/
public function getMaxAge()
{
return null === $this->data['Max-Age'] ? null : (int) $this->data['Max-Age'];
}
/**
* Set the max-age of the cookie.
*
* @param int|null $maxAge Max age of the cookie in seconds
*/
public function setMaxAge($maxAge): void
{
if (!is_int($maxAge) && null !== $maxAge) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Max-Age'] = $maxAge === null ? null : (int) $maxAge;
}
/**
* The UNIX timestamp when the cookie Expires.
*
* @return string|int|null
*/
public function getExpires()
{
return $this->data['Expires'];
}
/**
* Set the unix timestamp for which the cookie will expire.
*
* @param int|string|null $timestamp Unix timestamp or any English textual datetime description.
*/
public function setExpires($timestamp): void
{
if (!is_int($timestamp) && !is_string($timestamp) && null !== $timestamp) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int, string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Expires'] = null === $timestamp ? null : (\is_numeric($timestamp) ? (int) $timestamp : \strtotime((string) $timestamp));
}
/**
* Get whether or not this is a secure cookie.
*
* @return bool
*/
public function getSecure()
{
return $this->data['Secure'];
}
/**
* Set whether or not the cookie is secure.
*
* @param bool $secure Set to true or false if secure
*/
public function setSecure($secure): void
{
if (!is_bool($secure)) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Secure'] = (bool) $secure;
}
/**
* Get whether or not this is a session cookie.
*
* @return bool|null
*/
public function getDiscard()
{
return $this->data['Discard'];
}
/**
* Set whether or not this is a session cookie.
*
* @param bool $discard Set to true or false if this is a session cookie
*/
public function setDiscard($discard): void
{
if (!is_bool($discard)) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Discard'] = (bool) $discard;
}
/**
* Get whether or not this is an HTTP only cookie.
*
* @return bool
*/
public function getHttpOnly()
{
return $this->data['HttpOnly'];
}
/**
* Set whether or not this is an HTTP only cookie.
*
* @param bool $httpOnly Set to true or false if this is HTTP only
*/
public function setHttpOnly($httpOnly): void
{
if (!is_bool($httpOnly)) {
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['HttpOnly'] = (bool) $httpOnly;
}
/**
* Check if the cookie matches a path value.
*
* A request-path path-matches a given cookie-path if at least one of
* the following conditions holds:
*
* - The cookie-path and the request-path are identical.
* - The cookie-path is a prefix of the request-path, and the last
* character of the cookie-path is %x2F ("/").
* - The cookie-path is a prefix of the request-path, and the first
* character of the request-path that is not included in the cookie-
* path is a %x2F ("/") character.
*
* @param string $requestPath Path to check against
*/
public function matchesPath(string $requestPath): bool
{
$cookiePath = $this->getPath();
// Match on exact matches or when path is the default empty "/"
if ($cookiePath === '/' || $cookiePath == $requestPath) {
return true;
}
// Ensure that the cookie-path is a prefix of the request path.
if (0 !== \strpos($requestPath, $cookiePath)) {
return false;
}
// Match if the last character of the cookie-path is "/"
if (\substr($cookiePath, -1, 1) === '/') {
return true;
}
// Match if the first character not included in cookie path is "/"
return \substr($requestPath, \strlen($cookiePath), 1) === '/';
}
/**
* Check if the cookie matches a domain value.
*
* @param string $domain Domain to check against
*/
public function matchesDomain(string $domain): bool
{
$cookieDomain = $this->getDomain();
if (null === $cookieDomain) {
return true;
}
// Remove the leading '.' as per spec in RFC 6265.
// https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.3
$cookieDomain = \ltrim(\strtolower($cookieDomain), '.');
$domain = \strtolower($domain);
// Domain not set or exact match.
if ('' === $cookieDomain || $domain === $cookieDomain) {
return true;
}
// Matching the subdomain according to RFC 6265.
// https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3
if (\filter_var($domain, \FILTER_VALIDATE_IP)) {
return false;
}
return (bool) \preg_match('/\.'.\preg_quote($cookieDomain, '/').'$/', $domain);
}
/**
* Check if the cookie is expired.
*/
public function isExpired(): bool
{
return $this->getExpires() !== null && \time() > $this->getExpires();
}
/**
* Check if the cookie is valid according to RFC 6265.
*
* @return bool|string Returns true if valid or an error message if invalid
*/
public function validate()
{
$name = $this->getName();
if ($name === '') {
return 'The cookie name must not be empty';
}
// Check if any of the invalid characters are present in the cookie name
if (\preg_match(
'/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/',
$name
)) {
return 'Cookie name must not contain invalid characters: ASCII '
.'Control characters (0-31;127), space, tab and the '
.'following characters: ()<>@,;:\"/?={}';
}
// Value must not be null. 0 and empty string are valid. Empty strings
// are technically against RFC 6265, but known to happen in the wild.
$value = $this->getValue();
if ($value === null) {
return 'The cookie value must not be empty';
}
// Domains must not be empty, but can be 0. "0" is not a valid internet
// domain, but may be used as server name in a private network.
$domain = $this->getDomain();
if ($domain === null || $domain === '') {
return 'The cookie domain must not be empty';
}
return true;
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Cookie/CookieJarInterface.php | src/Cookie/CookieJarInterface.php | <?php
namespace GuzzleHttp\Cookie;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Stores HTTP cookies.
*
* It extracts cookies from HTTP requests, and returns them in HTTP responses.
* CookieJarInterface instances automatically expire contained cookies when
* necessary. Subclasses are also responsible for storing and retrieving
* cookies from a file, database, etc.
*
* @see https://docs.python.org/2/library/cookielib.html Inspiration
*
* @extends \IteratorAggregate<SetCookie>
*/
interface CookieJarInterface extends \Countable, \IteratorAggregate
{
/**
* Create a request with added cookie headers.
*
* If no matching cookies are found in the cookie jar, then no Cookie
* header is added to the request and the same request is returned.
*
* @param RequestInterface $request Request object to modify.
*
* @return RequestInterface returns the modified request.
*/
public function withCookieHeader(RequestInterface $request): RequestInterface;
/**
* Extract cookies from an HTTP response and store them in the CookieJar.
*
* @param RequestInterface $request Request that was sent
* @param ResponseInterface $response Response that was received
*/
public function extractCookies(RequestInterface $request, ResponseInterface $response): void;
/**
* Sets a cookie in the cookie jar.
*
* @param SetCookie $cookie Cookie to set.
*
* @return bool Returns true on success or false on failure
*/
public function setCookie(SetCookie $cookie): bool;
/**
* Remove cookies currently held in the cookie jar.
*
* Invoking this method without arguments will empty the whole cookie jar.
* If given a $domain argument only cookies belonging to that domain will
* be removed. If given a $domain and $path argument, cookies belonging to
* the specified path within that domain are removed. If given all three
* arguments, then the cookie with the specified name, path and domain is
* removed.
*
* @param string|null $domain Clears cookies matching a domain
* @param string|null $path Clears cookies matching a domain and path
* @param string|null $name Clears cookies matching a domain, path, and name
*/
public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void;
/**
* Discard all sessions cookies.
*
* Removes cookies that don't have an expire field or a have a discard
* field set to true. To be called when the user agent shuts down according
* to RFC 2965.
*/
public function clearSessionCookies(): void;
/**
* Converts the cookie jar to an array.
*/
public function toArray(): array;
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Cookie/FileCookieJar.php | src/Cookie/FileCookieJar.php | <?php
namespace GuzzleHttp\Cookie;
use GuzzleHttp\Utils;
/**
* Persists non-session cookies using a JSON formatted file
*/
class FileCookieJar extends CookieJar
{
/**
* @var string filename
*/
private $filename;
/**
* @var bool Control whether to persist session cookies or not.
*/
private $storeSessionCookies;
/**
* Create a new FileCookieJar object
*
* @param string $cookieFile File to store the cookie data
* @param bool $storeSessionCookies Set to true to store session cookies
* in the cookie jar.
*
* @throws \RuntimeException if the file cannot be found or created
*/
public function __construct(string $cookieFile, bool $storeSessionCookies = false)
{
parent::__construct();
$this->filename = $cookieFile;
$this->storeSessionCookies = $storeSessionCookies;
if (\file_exists($cookieFile)) {
$this->load($cookieFile);
}
}
/**
* Saves the file when shutting down
*/
public function __destruct()
{
$this->save($this->filename);
}
/**
* Saves the cookies to a file.
*
* @param string $filename File to save
*
* @throws \RuntimeException if the file cannot be found or created
*/
public function save(string $filename): void
{
$json = [];
/** @var SetCookie $cookie */
foreach ($this as $cookie) {
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
$json[] = $cookie->toArray();
}
}
$jsonStr = Utils::jsonEncode($json);
if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) {
throw new \RuntimeException("Unable to save file {$filename}");
}
}
/**
* Load cookies from a JSON formatted file.
*
* Old cookies are kept unless overwritten by newly loaded ones.
*
* @param string $filename Cookie file to load.
*
* @throws \RuntimeException if the file cannot be loaded.
*/
public function load(string $filename): void
{
$json = \file_get_contents($filename);
if (false === $json) {
throw new \RuntimeException("Unable to load file {$filename}");
}
if ($json === '') {
return;
}
$data = Utils::jsonDecode($json, true);
if (\is_array($data)) {
foreach ($data as $cookie) {
$this->setCookie(new SetCookie($cookie));
}
} elseif (\is_scalar($data) && !empty($data)) {
throw new \RuntimeException("Invalid cookie file: {$filename}");
}
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/src/Cookie/SessionCookieJar.php | src/Cookie/SessionCookieJar.php | <?php
namespace GuzzleHttp\Cookie;
/**
* Persists cookies in the client session
*/
class SessionCookieJar extends CookieJar
{
/**
* @var string session key
*/
private $sessionKey;
/**
* @var bool Control whether to persist session cookies or not.
*/
private $storeSessionCookies;
/**
* Create a new SessionCookieJar object
*
* @param string $sessionKey Session key name to store the cookie
* data in session
* @param bool $storeSessionCookies Set to true to store session cookies
* in the cookie jar.
*/
public function __construct(string $sessionKey, bool $storeSessionCookies = false)
{
parent::__construct();
$this->sessionKey = $sessionKey;
$this->storeSessionCookies = $storeSessionCookies;
$this->load();
}
/**
* Saves cookies to session when shutting down
*/
public function __destruct()
{
$this->save();
}
/**
* Save cookies to the client session
*/
public function save(): void
{
$json = [];
/** @var SetCookie $cookie */
foreach ($this as $cookie) {
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
$json[] = $cookie->toArray();
}
}
$_SESSION[$this->sessionKey] = \json_encode($json);
}
/**
* Load the contents of the client session into the data array
*/
protected function load(): void
{
if (!isset($_SESSION[$this->sessionKey])) {
return;
}
$data = \json_decode($_SESSION[$this->sessionKey], true);
if (\is_array($data)) {
foreach ($data as $cookie) {
$this->setCookie(new SetCookie($cookie));
}
} elseif (\strlen($data)) {
throw new \RuntimeException('Invalid cookie data');
}
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/PoolTest.php | tests/PoolTest.php | <?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Pool;
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestInterface;
class PoolTest extends TestCase
{
public function testValidatesIterable()
{
$p = new Pool(new Client(), 'foo');
$this->expectException(\InvalidArgumentException::class);
$p->promise()->wait();
}
public function testValidatesEachElement()
{
$c = new Client();
$requests = ['foo'];
$p = new Pool($c, new \ArrayIterator($requests));
$this->expectException(\InvalidArgumentException::class);
$p->promise()->wait();
}
/**
* @doesNotPerformAssertions
*/
public function testSendsAndRealizesFuture()
{
$c = $this->getClient();
$p = new Pool($c, [new Request('GET', 'http://example.com')]);
$p->promise()->wait();
}
/**
* @doesNotPerformAssertions
*/
public function testExecutesPendingWhenWaiting()
{
$r1 = new Promise(static function () use (&$r1) {
$r1->resolve(new Response());
});
$r2 = new Promise(static function () use (&$r2) {
$r2->resolve(new Response());
});
$r3 = new Promise(static function () use (&$r3) {
$r3->resolve(new Response());
});
$handler = new MockHandler([$r1, $r2, $r3]);
$c = new Client(['handler' => $handler]);
$p = new Pool($c, [
new Request('GET', 'http://example.com'),
new Request('GET', 'http://example.com'),
new Request('GET', 'http://example.com'),
], ['pool_size' => 2]);
$p->promise()->wait();
}
public function testUsesRequestOptions()
{
$h = [];
$handler = new MockHandler([
static function (RequestInterface $request) use (&$h) {
$h[] = $request;
return new Response();
},
]);
$c = new Client(['handler' => $handler]);
$opts = ['options' => ['headers' => ['x-foo' => 'bar']]];
$p = new Pool($c, [new Request('GET', 'http://example.com')], $opts);
$p->promise()->wait();
self::assertCount(1, $h);
self::assertTrue($h[0]->hasHeader('x-foo'));
}
public function testCanProvideCallablesThatReturnResponses()
{
$h = [];
$handler = new MockHandler([
static function (RequestInterface $request) use (&$h) {
$h[] = $request;
return new Response();
},
]);
$c = new Client(['handler' => $handler]);
$optHistory = [];
$fn = static function (array $opts) use (&$optHistory, $c) {
$optHistory = $opts;
return $c->request('GET', 'http://example.com', $opts);
};
$opts = ['options' => ['headers' => ['x-foo' => 'bar']]];
$p = new Pool($c, [$fn], $opts);
$p->promise()->wait();
self::assertCount(1, $h);
self::assertTrue($h[0]->hasHeader('x-foo'));
}
public function testBatchesResults()
{
$requests = [
new Request('GET', 'http://foo.com/200'),
new Request('GET', 'http://foo.com/201'),
new Request('GET', 'http://foo.com/202'),
new Request('GET', 'http://foo.com/404'),
];
$fn = static function (RequestInterface $request) {
return new Response(\substr($request->getUri()->getPath(), 1));
};
$mock = new MockHandler([$fn, $fn, $fn, $fn]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$results = Pool::batch($client, $requests);
self::assertCount(4, $results);
self::assertSame([0, 1, 2, 3], \array_keys($results));
self::assertSame(200, $results[0]->getStatusCode());
self::assertSame(201, $results[1]->getStatusCode());
self::assertSame(202, $results[2]->getStatusCode());
self::assertInstanceOf(ClientException::class, $results[3]);
}
public function testBatchesResultsWithCallbacks()
{
$requests = [
new Request('GET', 'http://foo.com/200'),
new Request('GET', 'http://foo.com/201'),
];
$mock = new MockHandler([
static function (RequestInterface $request) {
return new Response(\substr($request->getUri()->getPath(), 1));
},
]);
$client = new Client(['handler' => $mock]);
$results = Pool::batch($client, $requests, [
'fulfilled' => static function ($value) use (&$called) {
$called = true;
},
]);
self::assertCount(2, $results);
self::assertTrue($called);
}
public function testUsesYieldedKeyInFulfilledCallback()
{
$r1 = new Promise(static function () use (&$r1) {
$r1->resolve(new Response());
});
$r2 = new Promise(static function () use (&$r2) {
$r2->resolve(new Response());
});
$r3 = new Promise(static function () use (&$r3) {
$r3->resolve(new Response());
});
$handler = new MockHandler([$r1, $r2, $r3]);
$c = new Client(['handler' => $handler]);
$keys = [];
$requests = [
'request_1' => new Request('GET', 'http://example.com'),
'request_2' => new Request('GET', 'http://example.com'),
'request_3' => new Request('GET', 'http://example.com'),
];
$p = new Pool($c, $requests, [
'pool_size' => 2,
'fulfilled' => static function ($res, $index) use (&$keys) {
$keys[] = $index;
},
]);
$p->promise()->wait();
self::assertCount(3, $keys);
self::assertSame($keys, \array_keys($requests));
}
private function getClient($total = 1)
{
$queue = [];
for ($i = 0; $i < $total; ++$i) {
$queue[] = new Response();
}
$handler = new MockHandler($queue);
return new Client(['handler' => $handler]);
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/MessageFormatterTest.php | tests/MessageFormatterTest.php | <?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
/**
* @covers \GuzzleHttp\MessageFormatter
*/
class MessageFormatterTest extends TestCase
{
public function testCreatesWithClfByDefault()
{
$f = new MessageFormatter();
self::assertEquals(MessageFormatter::CLF, Helpers::readObjectAttribute($f, 'template'));
$f = new MessageFormatter(null);
self::assertEquals(MessageFormatter::CLF, Helpers::readObjectAttribute($f, 'template'));
}
public static function dateProvider()
{
return [
['{ts}', '/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}/'],
['{date_iso_8601}', '/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}/'],
['{date_common_log}', '/^\d\d\/[A-Z][a-z]{2}\/[0-9]{4}/'],
];
}
/**
* @dataProvider dateProvider
*/
public function testFormatsTimestamps(string $format, string $pattern)
{
$f = new MessageFormatter($format);
$request = new Request('GET', '/');
$result = $f->format($request);
if (method_exists($this, 'assertMatchesRegularExpression')) {
// PHPUnit 9
self::assertMatchesRegularExpression($pattern, $result);
} else {
// PHPUnit 8
self::assertRegExp($pattern, $result);
}
}
public static function formatProvider()
{
$request = new Request('PUT', '/', ['x-test' => 'abc'], Psr7\Utils::streamFor('foo'));
$response = new Response(200, ['X-Baz' => 'Bar'], Psr7\Utils::streamFor('baz'));
$err = new RequestException('Test', $request, $response);
return [
['{request}', [$request], Psr7\Message::toString($request)],
['{response}', [$request, $response], Psr7\Message::toString($response)],
['{request} {response}', [$request, $response], Psr7\Message::toString($request).' '.Psr7\Message::toString($response)],
// Empty response yields no value
['{request} {response}', [$request], Psr7\Message::toString($request).' '],
['{req_headers}', [$request], "PUT / HTTP/1.1\r\nx-test: abc"],
['{res_headers}', [$request, $response], "HTTP/1.1 200 OK\r\nX-Baz: Bar"],
['{res_headers}', [$request], 'NULL'],
['{req_body}', [$request], 'foo'],
['{res_body}', [$request, $response], 'baz'],
['{res_body}', [$request], 'NULL'],
['{method}', [$request], $request->getMethod()],
['{url}', [$request], $request->getUri()],
['{target}', [$request], $request->getRequestTarget()],
['{req_version}', [$request], $request->getProtocolVersion()],
['{res_version}', [$request, $response], $response->getProtocolVersion()],
['{res_version}', [$request], 'NULL'],
['{host}', [$request], $request->getHeaderLine('Host')],
['{hostname}', [$request, $response], \gethostname()],
['{hostname}{hostname}', [$request, $response], \gethostname().\gethostname()],
['{code}', [$request, $response], $response->getStatusCode()],
['{code}', [$request], 'NULL'],
['{phrase}', [$request, $response], $response->getReasonPhrase()],
['{phrase}', [$request], 'NULL'],
['{error}', [$request, $response, $err], 'Test'],
['{error}', [$request], 'NULL'],
['{req_header_x-test}', [$request], 'abc'],
['{req_header_x-not}', [$request], ''],
['{res_header_X-Baz}', [$request, $response], 'Bar'],
['{res_header_x-not}', [$request, $response], ''],
['{res_header_X-Baz}', [$request], 'NULL'],
];
}
/**
* @dataProvider formatProvider
*/
public function testFormatsMessages(string $template, array $args, $result)
{
$f = new MessageFormatter($template);
self::assertSame((string) $result, $f->format(...$args));
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/TestLogger.php | tests/TestLogger.php | <?php
namespace GuzzleHttp\Tests;
use Psr\Log\AbstractLogger;
/**
* Used for testing purposes.
*
* It records all records and gives you access to them for verification.
*/
class TestLogger extends AbstractLogger
{
public $records = [];
public $recordsByLevel = [];
public function log($level, $message, array $context = []): void
{
$record = [
'level' => $level,
'message' => $message,
'context' => $context,
];
$this->recordsByLevel[$record['level']][] = $record;
$this->records[] = $record;
}
public function hasRecords($level)
{
return isset($this->recordsByLevel[$level]);
}
public function hasRecord($record, $level)
{
if (is_string($record)) {
$record = ['message' => $record];
}
return $this->hasRecordThatPasses(static function ($rec) use ($record) {
if ($rec['message'] !== $record['message']) {
return false;
}
if (isset($record['context']) && $rec['context'] !== $record['context']) {
return false;
}
return true;
}, $level);
}
public function hasRecordThatContains($message, $level)
{
return $this->hasRecordThatPasses(static function ($rec) use ($message) {
return strpos($rec['message'], $message) !== false;
}, $level);
}
public function hasRecordThatMatches($regex, $level)
{
return $this->hasRecordThatPasses(static function ($rec) use ($regex) {
return preg_match($regex, $rec['message']) > 0;
}, $level);
}
public function hasRecordThatPasses(callable $predicate, $level)
{
if (!isset($this->recordsByLevel[$level])) {
return false;
}
foreach ($this->recordsByLevel[$level] as $i => $rec) {
if ($predicate($rec, $i)) {
return true;
}
}
return false;
}
public function __call($method, $args)
{
if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) {
$genericMethod = $matches[1].('Records' !== $matches[3] ? 'Record' : '').$matches[3];
$level = strtolower($matches[2]);
if (method_exists($this, $genericMethod)) {
$args[] = $level;
return ($this->{$genericMethod})(...$args);
}
}
throw new \BadMethodCallException('Call to undefined method '.static::class.'::'.$method.'()');
}
public function reset()
{
$this->records = [];
$this->recordsByLevel = [];
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/ClientTest.php | tests/ClientTest.php | <?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\RequestOptions;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
class ClientTest extends TestCase
{
public function testUsesDefaultHandler()
{
$client = new Client();
Server::enqueue([new Response(200, ['Content-Length' => 0])]);
$response = $client->get(Server::$url);
self::assertSame(200, $response->getStatusCode());
}
public function testValidatesArgsForMagicMethods()
{
$client = new Client();
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Magic request methods require a URI and optional options array');
$client->options();
}
public function testCanSendAsyncGetRequests()
{
$client = new Client();
Server::flush();
Server::enqueue([new Response(200, ['Content-Length' => 2], 'hi')]);
$p = $client->getAsync(Server::$url, ['query' => ['test' => 'foo']]);
self::assertInstanceOf(PromiseInterface::class, $p);
self::assertSame(200, $p->wait()->getStatusCode());
$received = Server::received(true);
self::assertCount(1, $received);
self::assertSame('test=foo', $received[0]->getUri()->getQuery());
}
public function testCanSendSynchronously()
{
$client = new Client(['handler' => new MockHandler([new Response()])]);
$request = new Request('GET', 'http://example.com');
$r = $client->send($request);
self::assertInstanceOf(ResponseInterface::class, $r);
self::assertSame(200, $r->getStatusCode());
}
public function testClientHasOptions()
{
$client = new Client([
'base_uri' => 'http://foo.com',
'timeout' => 2,
'headers' => ['bar' => 'baz'],
'handler' => new MockHandler(),
]);
$config = Helpers::readObjectAttribute($client, 'config');
self::assertArrayHasKey('base_uri', $config);
self::assertInstanceOf(Uri::class, $config['base_uri']);
self::assertSame('http://foo.com', (string) $config['base_uri']);
self::assertArrayHasKey('handler', $config);
self::assertNotNull($config['handler']);
self::assertArrayHasKey('timeout', $config);
self::assertSame(2, $config['timeout']);
}
public function testCanMergeOnBaseUri()
{
$mock = new MockHandler([new Response()]);
$client = new Client([
'base_uri' => 'http://foo.com/bar/',
'handler' => $mock,
]);
$client->get('baz');
self::assertSame(
'http://foo.com/bar/baz',
(string) $mock->getLastRequest()->getUri()
);
}
public function testCanMergeOnBaseUriWithRequest()
{
$mock = new MockHandler([new Response(), new Response()]);
$client = new Client([
'handler' => $mock,
'base_uri' => 'http://foo.com/bar/',
]);
$client->request('GET', new Uri('baz'));
self::assertSame(
'http://foo.com/bar/baz',
(string) $mock->getLastRequest()->getUri()
);
$client->request('GET', new Uri('baz'), ['base_uri' => 'http://example.com/foo/']);
self::assertSame(
'http://example.com/foo/baz',
(string) $mock->getLastRequest()->getUri(),
'Can overwrite the base_uri through the request options'
);
}
public function testCanUseRelativeUriWithSend()
{
$mock = new MockHandler([new Response()]);
$client = new Client([
'handler' => $mock,
'base_uri' => 'http://bar.com',
]);
$config = Helpers::readObjectAttribute($client, 'config');
self::assertSame('http://bar.com', (string) $config['base_uri']);
$request = new Request('GET', '/baz');
$client->send($request);
self::assertSame(
'http://bar.com/baz',
(string) $mock->getLastRequest()->getUri()
);
}
public function testMergesDefaultOptionsAndDoesNotOverwriteUa()
{
$client = new Client(['headers' => ['User-agent' => 'foo']]);
$config = Helpers::readObjectAttribute($client, 'config');
self::assertSame(['User-agent' => 'foo'], $config['headers']);
self::assertIsArray($config['allow_redirects']);
self::assertTrue($config['http_errors']);
self::assertTrue($config['decode_content']);
self::assertTrue($config['verify']);
}
public function testDoesNotOverwriteHeaderWithDefault()
{
$mock = new MockHandler([new Response()]);
$c = new Client([
'headers' => ['User-agent' => 'foo'],
'handler' => $mock,
]);
$c->get('http://example.com', ['headers' => ['User-Agent' => 'bar']]);
self::assertSame('bar', $mock->getLastRequest()->getHeaderLine('User-Agent'));
}
public function testDoesNotOverwriteHeaderWithDefaultInRequest()
{
$mock = new MockHandler([new Response()]);
$c = new Client([
'headers' => ['User-agent' => 'foo'],
'handler' => $mock,
]);
$request = new Request('GET', Server::$url, ['User-Agent' => 'bar']);
$c->send($request);
self::assertSame('bar', $mock->getLastRequest()->getHeaderLine('User-Agent'));
}
public function testDoesOverwriteHeaderWithSetRequestOption()
{
$mock = new MockHandler([new Response()]);
$c = new Client([
'headers' => ['User-agent' => 'foo'],
'handler' => $mock,
]);
$request = new Request('GET', Server::$url, ['User-Agent' => 'bar']);
$c->send($request, ['headers' => ['User-Agent' => 'YO']]);
self::assertSame('YO', $mock->getLastRequest()->getHeaderLine('User-Agent'));
}
public function testCanUnsetRequestOptionWithNull()
{
$mock = new MockHandler([new Response()]);
$c = new Client([
'headers' => ['foo' => 'bar'],
'handler' => $mock,
]);
$c->get('http://example.com', ['headers' => null]);
self::assertFalse($mock->getLastRequest()->hasHeader('foo'));
}
public function testAllowRedirectsCanBeTrue()
{
$mock = new MockHandler([new Response(200, [], 'foo')]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://foo.com', ['allow_redirects' => true]);
self::assertIsArray($mock->getLastOptions()['allow_redirects']);
}
public function testValidatesAllowRedirects()
{
$mock = new MockHandler([new Response(200, [], 'foo')]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('allow_redirects must be true, false, or array');
$client->get('http://foo.com', ['allow_redirects' => 'foo']);
}
public function testThrowsHttpErrorsByDefault()
{
$mock = new MockHandler([new Response(404)]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$this->expectException(\GuzzleHttp\Exception\ClientException::class);
$client->get('http://foo.com');
}
public function testValidatesCookies()
{
$mock = new MockHandler([new Response(200, [], 'foo')]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('cookies must be an instance of GuzzleHttp\\Cookie\\CookieJarInterface');
$client->get('http://foo.com', ['cookies' => 'foo']);
}
public function testSetCookieToTrueUsesSharedJar()
{
$mock = new MockHandler([
new Response(200, ['Set-Cookie' => 'foo=bar']),
new Response(),
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler, 'cookies' => true]);
$client->get('http://foo.com');
$client->get('http://foo.com');
self::assertSame('foo=bar', $mock->getLastRequest()->getHeaderLine('Cookie'));
}
public function testSetCookieToJar()
{
$mock = new MockHandler([
new Response(200, ['Set-Cookie' => 'foo=bar']),
new Response(),
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$jar = new CookieJar();
$client->get('http://foo.com', ['cookies' => $jar]);
$client->get('http://foo.com', ['cookies' => $jar]);
self::assertSame('foo=bar', $mock->getLastRequest()->getHeaderLine('Cookie'));
}
public function testCanDisableContentDecoding()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['decode_content' => false]);
$last = $mock->getLastRequest();
self::assertFalse($last->hasHeader('Accept-Encoding'));
self::assertFalse($mock->getLastOptions()['decode_content']);
}
public function testCanSetContentDecodingToValue()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['decode_content' => 'gzip']);
$last = $mock->getLastRequest();
self::assertSame('gzip', $last->getHeaderLine('Accept-Encoding'));
self::assertSame('gzip', $mock->getLastOptions()['decode_content']);
}
public function testAddsAcceptEncodingbyCurl()
{
$client = new Client(['curl' => [\CURLOPT_ENCODING => '']]);
Server::flush();
Server::enqueue([new Response()]);
$client->get(Server::$url);
$sent = Server::received()[0];
self::assertTrue($sent->hasHeader('Accept-Encoding'));
$mock = new MockHandler([new Response()]);
$client->get('http://foo.com', ['handler' => $mock]);
self::assertSame([\CURLOPT_ENCODING => ''], $mock->getLastOptions()['curl']);
}
public function testValidatesHeaders()
{
$mock = new MockHandler();
$client = new Client(['handler' => $mock]);
$this->expectException(\InvalidArgumentException::class);
$client->get('http://foo.com', ['headers' => 'foo']);
}
public function testAddsBody()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['body' => 'foo']);
$last = $mock->getLastRequest();
self::assertSame('foo', (string) $last->getBody());
}
public function testValidatesQuery()
{
$mock = new MockHandler();
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$this->expectException(\InvalidArgumentException::class);
$client->send($request, ['query' => false]);
}
public function testQueryCanBeString()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['query' => 'foo']);
self::assertSame('foo', $mock->getLastRequest()->getUri()->getQuery());
}
public function testQueryCanBeArray()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['query' => ['foo' => 'bar baz']]);
self::assertSame('foo=bar%20baz', $mock->getLastRequest()->getUri()->getQuery());
}
public function testCanAddJsonData()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['json' => ['foo' => 'bar']]);
$last = $mock->getLastRequest();
self::assertSame('{"foo":"bar"}', (string) $mock->getLastRequest()->getBody());
self::assertSame('application/json', $last->getHeaderLine('Content-Type'));
}
public function testCanAddJsonDataWithoutOverwritingContentType()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, [
'headers' => ['content-type' => 'foo'],
'json' => 'a',
]);
$last = $mock->getLastRequest();
self::assertSame('"a"', (string) $mock->getLastRequest()->getBody());
self::assertSame('foo', $last->getHeaderLine('Content-Type'));
}
public function testCanAddJsonDataWithNullHeader()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, [
'headers' => null,
'json' => 'a',
]);
$last = $mock->getLastRequest();
self::assertSame('"a"', (string) $mock->getLastRequest()->getBody());
self::assertSame('application/json', $last->getHeaderLine('Content-Type'));
}
public function testAuthCanBeTrue()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['auth' => false]);
$last = $mock->getLastRequest();
self::assertFalse($last->hasHeader('Authorization'));
}
public function testAuthCanBeArrayForBasicAuth()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['auth' => ['a', 'b']]);
$last = $mock->getLastRequest();
self::assertSame('Basic YTpi', $last->getHeaderLine('Authorization'));
}
public function testAuthCanBeArrayForDigestAuth()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['auth' => ['a', 'b', 'digest']]);
$last = $mock->getLastOptions();
self::assertSame([
\CURLOPT_HTTPAUTH => 2,
\CURLOPT_USERPWD => 'a:b',
], $last['curl']);
}
public function testAuthCanBeArrayForNtlmAuth()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['auth' => ['a', 'b', 'ntlm']]);
$last = $mock->getLastOptions();
self::assertSame([
\CURLOPT_HTTPAUTH => 8,
\CURLOPT_USERPWD => 'a:b',
], $last['curl']);
}
public function testAuthCanBeCustomType()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->get('http://foo.com', ['auth' => 'foo']);
$last = $mock->getLastOptions();
self::assertSame('foo', $last['auth']);
}
public function testCanAddFormParams()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->post('http://foo.com', [
'form_params' => [
'foo' => 'bar bam',
'baz' => ['boo' => 'qux'],
],
]);
$last = $mock->getLastRequest();
self::assertSame(
'application/x-www-form-urlencoded',
$last->getHeaderLine('Content-Type')
);
self::assertSame(
'foo=bar+bam&baz%5Bboo%5D=qux',
(string) $last->getBody()
);
}
public function testFormParamsEncodedProperly()
{
$separator = \ini_get('arg_separator.output');
\ini_set('arg_separator.output', '&');
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->post('http://foo.com', [
'form_params' => [
'foo' => 'bar bam',
'baz' => ['boo' => 'qux'],
],
]);
$last = $mock->getLastRequest();
self::assertSame(
'foo=bar+bam&baz%5Bboo%5D=qux',
(string) $last->getBody()
);
\ini_set('arg_separator.output', $separator);
}
public function testEnsuresThatFormParamsAndMultipartAreExclusive()
{
$client = new Client(['handler' => static function () {
}]);
$this->expectException(\InvalidArgumentException::class);
$client->post('http://foo.com', [
'form_params' => ['foo' => 'bar bam'],
'multipart' => [],
]);
}
public function testCanSendMultipart()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->post('http://foo.com', [
'multipart' => [
[
'name' => 'foo',
'contents' => 'bar',
],
[
'name' => 'test',
'contents' => \fopen(__FILE__, 'r'),
],
],
]);
$last = $mock->getLastRequest();
self::assertStringContainsString(
'multipart/form-data; boundary=',
$last->getHeaderLine('Content-Type')
);
self::assertStringContainsString(
'Content-Disposition: form-data; name="foo"',
(string) $last->getBody()
);
self::assertStringContainsString('bar', (string) $last->getBody());
self::assertStringContainsString(
'Content-Disposition: form-data; name="foo"'."\r\n",
(string) $last->getBody()
);
self::assertStringContainsString(
'Content-Disposition: form-data; name="test"; filename="ClientTest.php"',
(string) $last->getBody()
);
}
public function testCanSendMultipartWithExplicitBody()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->send(
new Request(
'POST',
'http://foo.com',
[],
new Psr7\MultipartStream(
[
[
'name' => 'foo',
'contents' => 'bar',
],
[
'name' => 'test',
'contents' => \fopen(__FILE__, 'r'),
],
]
)
)
);
$last = $mock->getLastRequest();
self::assertStringContainsString(
'multipart/form-data; boundary=',
$last->getHeaderLine('Content-Type')
);
self::assertStringContainsString(
'Content-Disposition: form-data; name="foo"',
(string) $last->getBody()
);
self::assertStringContainsString('bar', (string) $last->getBody());
self::assertStringContainsString(
'Content-Disposition: form-data; name="foo"'."\r\n",
(string) $last->getBody()
);
self::assertStringContainsString(
'Content-Disposition: form-data; name="test"; filename="ClientTest.php"',
(string) $last->getBody()
);
}
public function testUsesProxyEnvironmentVariables()
{
unset($_SERVER['HTTP_PROXY'], $_SERVER['HTTPS_PROXY'], $_SERVER['NO_PROXY']);
\putenv('HTTP_PROXY=');
\putenv('HTTPS_PROXY=');
\putenv('NO_PROXY=');
try {
$client = new Client();
$config = Helpers::readObjectAttribute($client, 'config');
self::assertArrayNotHasKey('proxy', $config);
\putenv('HTTP_PROXY=127.0.0.1');
$client = new Client();
$config = Helpers::readObjectAttribute($client, 'config');
self::assertArrayHasKey('proxy', $config);
self::assertSame(['http' => '127.0.0.1'], $config['proxy']);
\putenv('HTTPS_PROXY=127.0.0.2');
\putenv('NO_PROXY=127.0.0.3, 127.0.0.4');
$client = new Client();
$config = Helpers::readObjectAttribute($client, 'config');
self::assertArrayHasKey('proxy', $config);
self::assertSame(
['http' => '127.0.0.1', 'https' => '127.0.0.2', 'no' => ['127.0.0.3', '127.0.0.4']],
$config['proxy']
);
} finally {
\putenv('HTTP_PROXY=');
\putenv('HTTPS_PROXY=');
\putenv('NO_PROXY=');
}
}
public function testRequestSendsWithSync()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->request('GET', 'http://foo.com');
self::assertTrue($mock->getLastOptions()['synchronous']);
}
public function testSendSendsWithSync()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$client->send(new Request('GET', 'http://foo.com'));
self::assertTrue($mock->getLastOptions()['synchronous']);
}
public function testSendWithInvalidHeader()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('GET', 'http://foo.com');
$this->expectException(\GuzzleHttp\Exception\InvalidArgumentException::class);
$client->send($request, ['headers' => ['X-Foo: Bar']]);
}
public function testSendWithInvalidHeaders()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('GET', 'http://foo.com');
$this->expectException(\GuzzleHttp\Exception\InvalidArgumentException::class);
$client->send($request, ['headers' => ['X-Foo: Bar', 'X-Test: Fail']]);
}
public function testCanSetCustomHandler()
{
$mock = new MockHandler([new Response(500)]);
$client = new Client(['handler' => $mock]);
$mock2 = new MockHandler([new Response(200)]);
self::assertSame(
200,
$client->send(new Request('GET', 'http://foo.com'), [
'handler' => $mock2,
])->getStatusCode()
);
}
public function testProperlyBuildsQuery()
{
$mock = new MockHandler([new Response()]);
$client = new Client(['handler' => $mock]);
$request = new Request('PUT', 'http://foo.com');
$client->send($request, ['query' => ['foo' => 'bar', 'john' => 'doe']]);
self::assertSame('foo=bar&john=doe', $mock->getLastRequest()->getUri()->getQuery());
}
public function testSendSendsWithIpAddressAndPortAndHostHeaderInRequestTheHostShouldBePreserved()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['base_uri' => 'http://127.0.0.1:8585', 'handler' => $mockHandler]);
$request = new Request('GET', '/test', ['Host' => 'foo.com']);
$client->send($request);
self::assertSame('foo.com', $mockHandler->getLastRequest()->getHeader('Host')[0]);
}
public function testSendSendsWithDomainAndHostHeaderInRequestTheHostShouldBePreserved()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['base_uri' => 'http://foo2.com', 'handler' => $mockHandler]);
$request = new Request('GET', '/test', ['Host' => 'foo.com']);
$client->send($request);
self::assertSame('foo.com', $mockHandler->getLastRequest()->getHeader('Host')[0]);
}
public function testValidatesSink()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$this->expectException(\InvalidArgumentException::class);
$client->get('http://test.com', ['sink' => true]);
}
public function testHttpDefaultSchemeIfUriHasNone()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->request('GET', '//example.org/test');
self::assertSame('http://example.org/test', (string) $mockHandler->getLastRequest()->getUri());
}
public function testOnlyAddSchemeWhenHostIsPresent()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->request('GET', 'baz');
self::assertSame(
'baz',
(string) $mockHandler->getLastRequest()->getUri()
);
}
public function testThatVersionIsOverwrittenWhenSendingARequest()
{
$mockHandler = new MockHandler([new Response(), new Response()]);
$client = new Client(['handler' => $mockHandler]);
$request = new Request('get', '/bar', [], null, '1.1');
$client->send($request, [RequestOptions::VERSION => '1.0']);
self::assertSame(
'1.0',
$mockHandler->getLastRequest()->getProtocolVersion()
);
$request = new Request('get', '/bar', [], null, '1.0');
$client->send($request, [RequestOptions::VERSION => '1.1']);
self::assertSame(
'1.1',
$mockHandler->getLastRequest()->getProtocolVersion()
);
}
public function testHandlerIsCallable()
{
$this->expectException(\InvalidArgumentException::class);
new Client(['handler' => 'not_cllable']);
}
public function testResponseBodyAsString()
{
$responseBody = '{ "package": "guzzle" }';
$mock = new MockHandler([new Response(200, ['Content-Type' => 'application/json'], $responseBody)]);
$client = new Client(['handler' => $mock]);
$request = new Request('GET', 'http://foo.com');
$response = $client->send($request, ['json' => ['a' => 'b']]);
self::assertSame($responseBody, (string) $response->getBody());
}
public function testResponseContent()
{
$responseBody = '{ "package": "guzzle" }';
$mock = new MockHandler([new Response(200, ['Content-Type' => 'application/json'], $responseBody)]);
$client = new Client(['handler' => $mock]);
$request = new Request('POST', 'http://foo.com');
$response = $client->send($request, ['json' => ['a' => 'b']]);
self::assertSame($responseBody, $response->getBody()->getContents());
}
public function testIdnSupportDefaultValue()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$config = Helpers::readObjectAttribute($client, 'config');
self::assertFalse($config['idn_conversion']);
}
/**
* @requires extension idn
*/
public function testIdnIsTranslatedToAsciiWhenConversionIsEnabled()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->request('GET', 'https://яндекс.рф/images', ['idn_conversion' => true]);
$request = $mockHandler->getLastRequest();
self::assertSame('https://xn--d1acpjx3f.xn--p1ai/images', (string) $request->getUri());
self::assertSame('xn--d1acpjx3f.xn--p1ai', (string) $request->getHeaderLine('Host'));
}
public function testIdnStaysTheSameWhenConversionIsDisabled()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$client->request('GET', 'https://яндекс.рф/images', ['idn_conversion' => false]);
$request = $mockHandler->getLastRequest();
self::assertSame('https://яндекс.рф/images', (string) $request->getUri());
self::assertSame('яндекс.рф', (string) $request->getHeaderLine('Host'));
}
/**
* @requires extension idn
*/
public function testExceptionOnInvalidIdn()
{
$mockHandler = new MockHandler([new Response()]);
$client = new Client(['handler' => $mockHandler]);
$this->expectException(\GuzzleHttp\Exception\InvalidArgumentException::class);
$this->expectExceptionMessage('IDN conversion failed');
$client->request('GET', 'https://-яндекс.рф/images', ['idn_conversion' => true]);
}
/**
* @depends testCanUseRelativeUriWithSend
*
* @requires extension idn
*/
public function testIdnBaseUri()
{
$mock = new MockHandler([new Response()]);
$client = new Client([
'handler' => $mock,
'base_uri' => 'http://яндекс.рф',
'idn_conversion' => true,
]);
$config = Helpers::readObjectAttribute($client, 'config');
self::assertSame('http://яндекс.рф', (string) $config['base_uri']);
$request = new Request('GET', '/baz');
$client->send($request);
self::assertSame('http://xn--d1acpjx3f.xn--p1ai/baz', (string) $mock->getLastRequest()->getUri());
self::assertSame('xn--d1acpjx3f.xn--p1ai', (string) $mock->getLastRequest()->getHeaderLine('Host'));
}
/**
* @requires extension idn
*/
public function testIdnWithRedirect()
{
$mockHandler = new MockHandler([
new Response(302, ['Location' => 'http://www.tést.com/whatever']),
new Response(),
]);
$handler = HandlerStack::create($mockHandler);
$requests = [];
$handler->push(Middleware::history($requests));
$client = new Client(['handler' => $handler]);
$client->request('GET', 'https://яндекс.рф/images', [
RequestOptions::ALLOW_REDIRECTS => [
'referer' => true,
'track_redirects' => true,
],
'idn_conversion' => true,
]);
$request = $mockHandler->getLastRequest();
self::assertSame('http://www.xn--tst-bma.com/whatever', (string) $request->getUri());
self::assertSame('www.xn--tst-bma.com', (string) $request->getHeaderLine('Host'));
$request = $requests[0]['request'];
self::assertSame('https://xn--d1acpjx3f.xn--p1ai/images', (string) $request->getUri());
self::assertSame('xn--d1acpjx3f.xn--p1ai', (string) $request->getHeaderLine('Host'));
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/HandlerStackTest.php | tests/HandlerStackTest.php | <?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
class HandlerStackTest extends TestCase
{
public function testSetsHandlerInCtor()
{
$f = static function () {
};
$m1 = static function () {
};
$h = new HandlerStack($f, [$m1]);
self::assertTrue($h->hasHandler());
}
/**
* @doesNotPerformAssertions
*/
public function testCanSetDifferentHandlerAfterConstruction()
{
$f = static function () {
};
$h = new HandlerStack();
$h->setHandler($f);
$h->resolve();
}
public function testEnsuresHandlerIsSet()
{
$this->expectException(\LogicException::class);
$h = new HandlerStack();
$h->resolve();
}
public function testPushInOrder()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->push($meths[2]);
$builder->push($meths[3]);
$builder->push($meths[4]);
$composed = $builder->resolve();
self::assertSame('Hello - test123', $composed('test'));
self::assertSame(
[['a', 'test'], ['b', 'test1'], ['c', 'test12']],
$meths[0]
);
}
public function testUnshiftsInReverseOrder()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->unshift($meths[2]);
$builder->unshift($meths[3]);
$builder->unshift($meths[4]);
$composed = $builder->resolve();
self::assertSame('Hello - test321', $composed('test'));
self::assertSame(
[['c', 'test'], ['b', 'test3'], ['a', 'test32']],
$meths[0]
);
}
public function testCanRemoveMiddlewareByInstance()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->push($meths[2]);
$builder->push($meths[2]);
$builder->push($meths[3]);
$builder->push($meths[4]);
$builder->push($meths[2]);
$builder->remove($meths[3]);
$composed = $builder->resolve();
self::assertSame('Hello - test1131', $composed('test'));
}
public function testCanPrintMiddleware()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->push($meths[2], 'a');
$builder->push([__CLASS__, 'foo']);
$builder->push([$this, 'bar']);
$builder->push(__CLASS__.'::foo');
$lines = \explode("\n", (string) $builder);
self::assertStringContainsString("> 4) Name: 'a', Function: callable(", $lines[0]);
self::assertStringContainsString("> 3) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[1]);
self::assertStringContainsString("> 2) Name: '', Function: callable(['GuzzleHttp\\Tests\\HandlerStackTest', 'bar'])", $lines[2]);
self::assertStringContainsString("> 1) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[3]);
self::assertStringContainsString('< 0) Handler: callable(', $lines[4]);
self::assertStringContainsString("< 1) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[5]);
self::assertStringContainsString("< 2) Name: '', Function: callable(['GuzzleHttp\\Tests\\HandlerStackTest', 'bar'])", $lines[6]);
self::assertStringContainsString("< 3) Name: '', Function: callable(GuzzleHttp\\Tests\\HandlerStackTest::foo)", $lines[7]);
self::assertStringContainsString("< 4) Name: 'a', Function: callable(", $lines[8]);
}
public function testCanAddBeforeByName()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->push($meths[2], 'foo');
$builder->before('foo', $meths[3], 'baz');
$builder->before('baz', $meths[4], 'bar');
$builder->before('baz', $meths[4], 'qux');
$lines = \explode("\n", (string) $builder);
self::assertStringContainsString('> 4) Name: \'bar\'', $lines[0]);
self::assertStringContainsString('> 3) Name: \'qux\'', $lines[1]);
self::assertStringContainsString('> 2) Name: \'baz\'', $lines[2]);
self::assertStringContainsString('> 1) Name: \'foo\'', $lines[3]);
}
public function testEnsuresHandlerExistsByName()
{
$this->expectException(\InvalidArgumentException::class);
$builder = new HandlerStack();
$builder->before('foo', static function () {
});
}
public function testCanAddAfterByName()
{
$meths = $this->getFunctions();
$builder = new HandlerStack();
$builder->setHandler($meths[1]);
$builder->push($meths[2], 'a');
$builder->push($meths[3], 'b');
$builder->after('a', $meths[4], 'c');
$builder->after('b', $meths[4], 'd');
$lines = \explode("\n", (string) $builder);
self::assertStringContainsString('4) Name: \'a\'', $lines[0]);
self::assertStringContainsString('3) Name: \'c\'', $lines[1]);
self::assertStringContainsString('2) Name: \'b\'', $lines[2]);
self::assertStringContainsString('1) Name: \'d\'', $lines[3]);
}
public function testPicksUpCookiesFromRedirects()
{
$mock = new MockHandler([
new Response(301, [
'Location' => 'http://foo.com/baz',
'Set-Cookie' => 'foo=bar; Domain=foo.com',
]),
new Response(200),
]);
$handler = HandlerStack::create($mock);
$request = new Request('GET', 'http://foo.com/bar');
$jar = new CookieJar();
$response = $handler($request, [
'allow_redirects' => true,
'cookies' => $jar,
])->wait();
self::assertSame(200, $response->getStatusCode());
$lastRequest = $mock->getLastRequest();
self::assertSame('http://foo.com/baz', (string) $lastRequest->getUri());
self::assertSame('foo=bar', $lastRequest->getHeaderLine('Cookie'));
}
private function getFunctions()
{
$calls = [];
$a = static function (callable $next) use (&$calls) {
return static function ($v) use ($next, &$calls) {
$calls[] = ['a', $v];
return $next($v.'1');
};
};
$b = static function (callable $next) use (&$calls) {
return static function ($v) use ($next, &$calls) {
$calls[] = ['b', $v];
return $next($v.'2');
};
};
$c = static function (callable $next) use (&$calls) {
return static function ($v) use ($next, &$calls) {
$calls[] = ['c', $v];
return $next($v.'3');
};
};
$handler = static function ($v) {
return 'Hello - '.$v;
};
return [&$calls, $handler, $a, $b, $c];
}
public static function foo()
{
}
public function bar()
{
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Helpers.php | tests/Helpers.php | <?php
namespace GuzzleHttp\Tests;
class Helpers
{
public static function readObjectAttribute(object $object, string $attributeName)
{
$reflector = new \ReflectionObject($object);
do {
try {
$attribute = $reflector->getProperty($attributeName);
if (!$attribute || $attribute->isPublic()) {
return $object->$attributeName;
}
if (PHP_VERSION_ID < 80100) {
$attribute->setAccessible(true);
}
try {
return $attribute->getValue($object);
} finally {
if (PHP_VERSION_ID < 80100) {
$attribute->setAccessible(false);
}
}
} catch (\ReflectionException $e) {
// do nothing
}
} while ($reflector = $reflector->getParentClass());
throw new \Exception(
sprintf('Attribute "%s" not found in object.', $attributeName)
);
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/HttplugIntegrationTest.php | tests/HttplugIntegrationTest.php | <?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use Http\Client\Tests\HttpClientTest;
use Psr\Http\Client\ClientInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class HttplugIntegrationTest extends HttpClientTest
{
protected function createHttpAdapter(): ClientInterface
{
return new Client();
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/TransferStatsTest.php | tests/TransferStatsTest.php | <?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Psr7;
use GuzzleHttp\TransferStats;
use PHPUnit\Framework\TestCase;
class TransferStatsTest extends TestCase
{
public function testHasData()
{
$request = new Psr7\Request('GET', 'http://foo.com');
$response = new Psr7\Response();
$stats = new TransferStats(
$request,
$response,
10.5,
null,
['foo' => 'bar']
);
self::assertSame($request, $stats->getRequest());
self::assertSame($response, $stats->getResponse());
self::assertTrue($stats->hasResponse());
self::assertSame(['foo' => 'bar'], $stats->getHandlerStats());
self::assertSame('bar', $stats->getHandlerStat('foo'));
self::assertSame($request->getUri(), $stats->getEffectiveUri());
self::assertEquals(10.5, $stats->getTransferTime());
self::assertNull($stats->getHandlerErrorData());
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/bootstrap-phpstan.php | tests/bootstrap-phpstan.php | <?php
if (!\defined('IDNA_DEFAULT')) {
\define('IDNA_DEFAULT', 0);
}
if (!\defined('INTL_IDNA_VARIANT_UTS46')) {
\define('INTL_IDNA_VARIANT_UTS46', 1);
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/Server.php | tests/Server.php | <?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7;
use Psr\Http\Message\ResponseInterface;
/**
* The Server class is used to control a scripted webserver using node.js that
* will respond to HTTP requests with queued responses.
*
* Queued responses will be served to requests using a FIFO order. All requests
* received by the server are stored on the node.js server and can be retrieved
* by calling {@see Server::received()}.
*
* Mock responses that don't require data to be transmitted over HTTP a great
* for testing. Mock response, however, cannot test the actual sending of an
* HTTP request using cURL. This test server allows the simulation of any
* number of HTTP request response transactions to test the actual sending of
* requests over the wire without having to leave an internal network.
*/
class Server
{
/**
* @var Client
*/
private static $client;
private static $started = false;
public static $url = 'http://127.0.0.1:8126/';
public static $port = 8126;
/**
* Flush the received requests from the server
*
* @throws \RuntimeException
*/
public static function flush()
{
return self::getClient()->request('DELETE', 'guzzle-server/requests');
}
/**
* Queue an array of responses or a single response on the server.
*
* Any currently queued responses will be overwritten. Subsequent requests
* on the server will return queued responses in FIFO order.
*
* @param array|ResponseInterface $responses A single or array of Responses
* to queue.
*
* @throws \Exception
*/
public static function enqueue($responses)
{
$data = [];
foreach ((array) $responses as $response) {
if (!($response instanceof ResponseInterface)) {
throw new \Exception('Invalid response given.');
}
$headers = \array_map(static function ($h) {
return \implode(' ,', $h);
}, $response->getHeaders());
$data[] = [
'status' => (string) $response->getStatusCode(),
'reason' => $response->getReasonPhrase(),
'headers' => $headers,
'body' => \base64_encode((string) $response->getBody()),
];
}
self::getClient()->request('PUT', 'guzzle-server/responses', [
'json' => $data,
]);
}
/**
* Queue a single raw response manually, to handle cases where PSR7 response is not suitable.
*
* @param int|string $statusCode Status code for the response, e.g. 200
* @param string $reasonPhrase Status reason response e.g "OK"
* @param array $headers Array of headers to send in response
* @param string|null $body Body to send in response
*
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public static function enqueueRaw($statusCode, $reasonPhrase, $headers, $body)
{
$data = [
[
'status' => (string) $statusCode,
'reason' => $reasonPhrase,
'headers' => $headers,
'body' => \base64_encode((string) $body),
],
];
self::getClient()->request('PUT', 'guzzle-server/responses', [
'json' => $data,
]);
}
/**
* Get all of the received requests
*
* @return ResponseInterface[]
*
* @throws \RuntimeException
*/
public static function received()
{
if (!self::$started) {
return [];
}
$response = self::getClient()->request('GET', 'guzzle-server/requests');
$data = \json_decode($response->getBody(), true);
return \array_map(
static function ($message) {
$uri = $message['uri'];
if (isset($message['query_string'])) {
$uri .= '?'.$message['query_string'];
}
$response = new Psr7\Request(
$message['http_method'],
$uri,
$message['headers'],
$message['body'],
$message['version']
);
return $response->withUri(
$response->getUri()
->withScheme('http')
->withHost($response->getHeaderLine('host'))
);
},
$data
);
}
/**
* Stop running the node.js server
*/
public static function stop()
{
if (self::$started) {
self::getClient()->request('DELETE', 'guzzle-server');
}
self::$started = false;
}
public static function wait($maxTries = 5)
{
$tries = 0;
while (!self::isListening() && ++$tries < $maxTries) {
\usleep(50000 * $tries ** 2);
}
if (!self::isListening()) {
throw new \RuntimeException('Unable to contact node.js server');
}
}
public static function start()
{
if (self::$started) {
return;
}
if (!self::isListening()) {
\exec('node '.__DIR__.'/server.js '
.self::$port.' >> /tmp/server.log 2>&1 &');
self::wait();
}
self::$started = true;
}
private static function isListening()
{
try {
self::getClient()->request('GET', 'guzzle-server/perf', [
'connect_timeout' => 5,
'timeout' => 5,
]);
return true;
} catch (\Exception $e) {
return false;
}
}
private static function getClient()
{
if (!self::$client) {
self::$client = new Client([
'base_uri' => self::$url,
'sync' => true,
]);
}
return self::$client;
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/RetryMiddlewareTest.php | tests/RetryMiddlewareTest.php | <?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\RetryMiddleware;
use PHPUnit\Framework\TestCase;
class RetryMiddlewareTest extends TestCase
{
public function testRetriesWhenDeciderReturnsTrue()
{
$delayCalls = 0;
$calls = [];
$decider = static function (...$args) use (&$calls) {
$calls[] = $args;
return \count($calls) < 3;
};
$delay = static function ($retries, $response, $request) use (&$delayCalls) {
++$delayCalls;
self::assertSame($retries, $delayCalls);
self::assertInstanceOf(Response::class, $response);
self::assertInstanceOf(Request::class, $request);
return 1;
};
$m = Middleware::retry($decider, $delay);
$h = new MockHandler([new Response(200), new Response(201), new Response(202)]);
$f = $m($h);
$c = new Client(['handler' => $f]);
$p = $c->sendAsync(new Request('GET', 'http://test.com'), []);
$p->wait();
self::assertCount(3, $calls);
self::assertSame(2, $delayCalls);
self::assertSame(202, $p->wait()->getStatusCode());
}
public function testDoesNotRetryWhenDeciderReturnsFalse()
{
$decider = static function () {
return false;
};
$m = Middleware::retry($decider);
$h = new MockHandler([new Response(200)]);
$c = new Client(['handler' => $m($h)]);
$p = $c->sendAsync(new Request('GET', 'http://test.com'), []);
self::assertSame(200, $p->wait()->getStatusCode());
}
public function testCanRetryExceptions()
{
$calls = [];
$decider = static function (...$args) use (&$calls) {
$calls[] = $args;
return $args[3] instanceof \Exception;
};
$m = Middleware::retry($decider);
$h = new MockHandler([new \Exception(), new Response(201)]);
$c = new Client(['handler' => $m($h)]);
$p = $c->sendAsync(new Request('GET', 'http://test.com'), []);
self::assertSame(201, $p->wait()->getStatusCode());
self::assertCount(2, $calls);
self::assertSame(0, $calls[0][0]);
self::assertNull($calls[0][2]);
self::assertInstanceOf('Exception', $calls[0][3]);
self::assertSame(1, $calls[1][0]);
self::assertInstanceOf(Response::class, $calls[1][2]);
self::assertNull($calls[1][3]);
}
public function testBackoffCalculateDelay()
{
self::assertSame(0, RetryMiddleware::exponentialDelay(0));
self::assertSame(1000, RetryMiddleware::exponentialDelay(1));
self::assertSame(2000, RetryMiddleware::exponentialDelay(2));
self::assertSame(4000, RetryMiddleware::exponentialDelay(3));
self::assertSame(8000, RetryMiddleware::exponentialDelay(4));
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/UtilsTest.php | tests/UtilsTest.php | <?php
namespace GuzzleHttp\Test;
use GuzzleHttp;
use GuzzleHttp\Utils;
use PHPUnit\Framework\TestCase;
class UtilsTest extends TestCase
{
public static function noBodyProvider()
{
return [['get'], ['head'], ['delete']];
}
public static function typeProvider()
{
return [
['foo', 'string(3) "foo"'],
[true, 'bool(true)'],
[false, 'bool(false)'],
[10, 'int(10)'],
[1.0, 'float(1)'],
[new StrClass(), 'object(GuzzleHttp\Test\StrClass)'],
[['foo'], 'array(1)'],
];
}
/**
* @dataProvider typeProvider
*/
public function testDescribesType($input, $output)
{
/**
* Output may not match if Xdebug is loaded and overloading var_dump().
*
* @see https://xdebug.org/docs/display#overload_var_dump
*/
if (extension_loaded('xdebug')) {
$originalOverload = ini_get('xdebug.overload_var_dump');
ini_set('xdebug.overload_var_dump', 0);
}
try {
self::assertSame($output, Utils::describeType($input));
self::assertSame($output, GuzzleHttp\describe_type($input));
} finally {
if (extension_loaded('xdebug')) {
ini_set('xdebug.overload_var_dump', $originalOverload);
}
}
}
public function testParsesHeadersFromLines()
{
$lines = [
'Foo: bar',
'Foo: baz',
'Abc: 123',
'Def: a, b',
];
$expected = [
'Foo' => ['bar', 'baz'],
'Abc' => ['123'],
'Def' => ['a, b'],
];
self::assertSame($expected, Utils::headersFromLines($lines));
self::assertSame($expected, GuzzleHttp\headers_from_lines($lines));
}
public function testParsesHeadersFromLinesWithMultipleLines()
{
$lines = ['Foo: bar', 'Foo: baz', 'Foo: 123'];
$expected = ['Foo' => ['bar', 'baz', '123']];
self::assertSame($expected, Utils::headersFromLines($lines));
self::assertSame($expected, GuzzleHttp\headers_from_lines($lines));
}
public function testChooseHandler()
{
self::assertIsCallable(Utils::chooseHandler());
self::assertIsCallable(GuzzleHttp\choose_handler());
}
public function testDefaultUserAgent()
{
self::assertIsString(Utils::defaultUserAgent());
self::assertIsString(GuzzleHttp\default_user_agent());
}
public function testReturnsDebugResource()
{
self::assertIsResource(Utils::debugResource());
self::assertIsResource(GuzzleHttp\debug_resource());
}
public function testProvidesDefaultCaBundler()
{
self::assertFileExists(Utils::defaultCaBundle());
self::assertFileExists(GuzzleHttp\default_ca_bundle());
}
public function testNormalizeHeaderKeys()
{
$input = ['HelLo' => 'foo', 'WORld' => 'bar'];
$expected = ['hello' => 'HelLo', 'world' => 'WORld'];
self::assertSame($expected, Utils::normalizeHeaderKeys($input));
self::assertSame($expected, GuzzleHttp\normalize_header_keys($input));
}
public static function noProxyProvider()
{
return [
['mit.edu', ['.mit.edu'], false],
['foo.mit.edu', ['.mit.edu'], true],
['foo.mit.edu:123', ['.mit.edu'], true],
['mit.edu', ['mit.edu'], true],
['mit.edu', ['baz', 'mit.edu'], true],
['mit.edu', ['', '', 'mit.edu'], true],
['mit.edu', ['baz', '*'], true],
];
}
/**
* @dataProvider noproxyProvider
*/
public function testChecksNoProxyList($host, $list, $result)
{
self::assertSame($result, Utils::isHostInNoProxy($host, $list));
self::assertSame($result, \GuzzleHttp\is_host_in_noproxy($host, $list));
}
public function testEnsuresNoProxyCheckHostIsSet()
{
$this->expectException(\InvalidArgumentException::class);
Utils::isHostInNoProxy('', []);
}
public function testEnsuresNoProxyCheckHostIsSetLegacy()
{
$this->expectException(\InvalidArgumentException::class);
\GuzzleHttp\is_host_in_noproxy('', []);
}
public function testEncodesJson()
{
self::assertSame('true', Utils::jsonEncode(true));
self::assertSame('true', \GuzzleHttp\json_encode(true));
}
public function testEncodesJsonAndThrowsOnError()
{
$this->expectException(\InvalidArgumentException::class);
Utils::jsonEncode("\x99");
}
public function testEncodesJsonAndThrowsOnErrorLegacy()
{
$this->expectException(\InvalidArgumentException::class);
\GuzzleHttp\json_encode("\x99");
}
public function testDecodesJson()
{
self::assertTrue(Utils::jsonDecode('true'));
self::assertTrue(\GuzzleHttp\json_decode('true'));
}
public function testDecodesJsonAndThrowsOnError()
{
$this->expectException(\InvalidArgumentException::class);
Utils::jsonDecode('{{]]');
}
public function testDecodesJsonAndThrowsOnErrorLegacy()
{
$this->expectException(\InvalidArgumentException::class);
\GuzzleHttp\json_decode('{{]]');
}
}
final class StrClass
{
public function __toString()
{
return 'foo';
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/bootstrap.php | tests/bootstrap.php | <?php
namespace {
\setlocale(\LC_ALL, 'C');
\error_reporting(\E_ALL);
}
namespace GuzzleHttp\Test {
require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/Server.php';
use GuzzleHttp\Tests\Server;
Server::start();
\register_shutdown_function(static function () {
Server::stop();
});
}
// Override curl_setopt_array() and curl_multi_setopt() to get the last set curl options
namespace GuzzleHttp\Handler {
function curl_setopt_array($handle, array $options)
{
if (!empty($_SERVER['curl_test'])) {
$_SERVER['_curl'] = $options;
} else {
unset($_SERVER['_curl']);
}
return \curl_setopt_array($handle, $options);
}
function curl_multi_setopt($handle, $option, $value)
{
if (!empty($_SERVER['curl_test'])) {
$_SERVER['_curl_multi'][$option] = $value;
} else {
unset($_SERVER['_curl_multi']);
}
return \curl_multi_setopt($handle, $option, $value);
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/RedirectMiddlewareTest.php | tests/RedirectMiddlewareTest.php | <?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\TooManyRedirectsException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\RedirectMiddleware;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestInterface;
/**
* @covers \GuzzleHttp\RedirectMiddleware
*/
class RedirectMiddlewareTest extends TestCase
{
public function testIgnoresNonRedirects()
{
$response = new Response(200);
$stack = new HandlerStack(new MockHandler([$response]));
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com');
$promise = $handler($request, []);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testIgnoresWhenNoLocation()
{
$response = new Response(304);
$stack = new HandlerStack(new MockHandler([$response]));
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com');
$promise = $handler($request, []);
$response = $promise->wait();
self::assertSame(304, $response->getStatusCode());
}
public function testRedirectsWithAbsoluteUri()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
new Response(200),
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['max' => 2],
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('http://test.com', (string) $mock->getLastRequest()->getUri());
}
public function testRedirectsWithRelativeUri()
{
$mock = new MockHandler([
new Response(302, ['Location' => '/foo']),
new Response(200),
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['max' => 2],
]);
$response = $promise->wait();
self::assertSame(200, $response->getStatusCode());
self::assertSame('http://example.com/foo', (string) $mock->getLastRequest()->getUri());
}
public function testLimitsToMaxRedirects()
{
$mock = new MockHandler([
new Response(301, ['Location' => 'http://test.com']),
new Response(302, ['Location' => 'http://test.com']),
new Response(303, ['Location' => 'http://test.com']),
new Response(304, ['Location' => 'http://test.com']),
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com');
$promise = $handler($request, ['allow_redirects' => ['max' => 3]]);
$this->expectException(TooManyRedirectsException::class);
$this->expectExceptionMessage('Will not follow more than 3 redirects');
$promise->wait();
}
public function testTooManyRedirectsExceptionHasResponse()
{
$mock = new MockHandler([
new Response(301, ['Location' => 'http://test.com']),
new Response(302, ['Location' => 'http://test.com']),
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com');
$promise = $handler($request, ['allow_redirects' => ['max' => 1]]);
try {
$promise->wait();
self::fail();
} catch (TooManyRedirectsException $e) {
self::assertSame(302, $e->getResponse()->getStatusCode());
}
}
public function testEnsuresProtocolIsValid()
{
$mock = new MockHandler([
new Response(301, ['Location' => 'ftp://test.com']),
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com');
$this->expectException(BadResponseException::class);
$this->expectExceptionMessage('Redirect URI,');
$handler($request, ['allow_redirects' => ['max' => 3]])->wait();
}
public function testAddsRefererHeader()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
new Response(200),
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['max' => 2, 'referer' => true],
]);
$promise->wait();
self::assertSame(
'http://example.com?a=b',
$mock->getLastRequest()->getHeaderLine('Referer')
);
}
public function testAddsRefererHeaderButClearsUserInfo()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
new Response(200),
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://foo:bar@example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['max' => 2, 'referer' => true],
]);
$promise->wait();
self::assertSame(
'http://example.com?a=b',
$mock->getLastRequest()->getHeaderLine('Referer')
);
}
public function testAddsGuzzleRedirectHeader()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com']),
new Response(302, ['Location' => 'http://example.com/foo']),
new Response(302, ['Location' => 'http://example.com/bar']),
new Response(200),
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['track_redirects' => true],
]);
$response = $promise->wait(true);
self::assertSame(
[
'http://example.com',
'http://example.com/foo',
'http://example.com/bar',
],
$response->getHeader(RedirectMiddleware::HISTORY_HEADER)
);
}
public function testAddsGuzzleRedirectStatusHeader()
{
$mock = new MockHandler([
new Response(301, ['Location' => 'http://example.com']),
new Response(302, ['Location' => 'http://example.com/foo']),
new Response(301, ['Location' => 'http://example.com/bar']),
new Response(302, ['Location' => 'http://example.com/baz']),
new Response(200),
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['track_redirects' => true],
]);
$response = $promise->wait(true);
self::assertSame(
[
'301',
'302',
'301',
'302',
],
$response->getHeader(RedirectMiddleware::STATUS_HISTORY_HEADER)
);
}
public function testDoesNotAddRefererWhenGoingFromHttpsToHttp()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
new Response(200),
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'https://example.com?a=b');
$promise = $handler($request, [
'allow_redirects' => ['max' => 2, 'referer' => true],
]);
$promise->wait();
self::assertFalse($mock->getLastRequest()->hasHeader('Referer'));
}
public function testInvokesOnRedirectForRedirects()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
new Response(200),
]);
$stack = new HandlerStack($mock);
$stack->push(Middleware::redirect());
$handler = $stack->resolve();
$request = new Request('GET', 'http://example.com?a=b');
$call = false;
$promise = $handler($request, [
'allow_redirects' => [
'max' => 2,
'on_redirect' => static function ($request, $response, $uri) use (&$call) {
self::assertSame(302, $response->getStatusCode());
self::assertSame('GET', $request->getMethod());
self::assertSame('http://test.com', (string) $uri);
$call = true;
},
],
]);
$promise->wait();
self::assertTrue($call);
}
/**
* @testWith ["digest"]
* ["ntlm"]
*/
public function testRemoveCurlAuthorizationOptionsOnRedirectCrossHost($auth)
{
if (!defined('\CURLOPT_HTTPAUTH')) {
self::markTestSkipped('ext-curl is required for this test');
}
$mock = new MockHandler([
new Response(302, ['Location' => 'http://test.com']),
static function (RequestInterface $request, $options) {
self::assertFalse(
isset($options['curl'][\CURLOPT_HTTPAUTH]),
'curl options still contain CURLOPT_HTTPAUTH entry'
);
self::assertFalse(
isset($options['curl'][\CURLOPT_USERPWD]),
'curl options still contain CURLOPT_USERPWD entry'
);
return new Response(200);
},
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
}
/**
* @testWith ["digest"]
* ["ntlm"]
*/
public function testRemoveCurlAuthorizationOptionsOnRedirectCrossPort($auth)
{
if (!defined('\CURLOPT_HTTPAUTH')) {
self::markTestSkipped('ext-curl is required for this test');
}
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com:81/']),
static function (RequestInterface $request, $options) {
self::assertFalse(
isset($options['curl'][\CURLOPT_HTTPAUTH]),
'curl options still contain CURLOPT_HTTPAUTH entry'
);
self::assertFalse(
isset($options['curl'][\CURLOPT_USERPWD]),
'curl options still contain CURLOPT_USERPWD entry'
);
return new Response(200);
},
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
}
/**
* @testWith ["digest"]
* ["ntlm"]
*/
public function testRemoveCurlAuthorizationOptionsOnRedirectCrossScheme($auth)
{
if (!defined('\CURLOPT_HTTPAUTH')) {
self::markTestSkipped('ext-curl is required for this test');
}
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com?a=b']),
static function (RequestInterface $request, $options) {
self::assertFalse(
isset($options['curl'][\CURLOPT_HTTPAUTH]),
'curl options still contain CURLOPT_HTTPAUTH entry'
);
self::assertFalse(
isset($options['curl'][\CURLOPT_USERPWD]),
'curl options still contain CURLOPT_USERPWD entry'
);
return new Response(200);
},
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('https://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
}
/**
* @testWith ["digest"]
* ["ntlm"]
*/
public function testRemoveCurlAuthorizationOptionsOnRedirectCrossSchemeSamePort($auth)
{
if (!defined('\CURLOPT_HTTPAUTH')) {
self::markTestSkipped('ext-curl is required for this test');
}
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com:80?a=b']),
static function (RequestInterface $request, $options) {
self::assertFalse(
isset($options['curl'][\CURLOPT_HTTPAUTH]),
'curl options still contain CURLOPT_HTTPAUTH entry'
);
self::assertFalse(
isset($options['curl'][\CURLOPT_USERPWD]),
'curl options still contain CURLOPT_USERPWD entry'
);
return new Response(200);
},
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('https://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
}
/**
* @testWith ["digest"]
* ["ntlm"]
*/
public function testNotRemoveCurlAuthorizationOptionsOnRedirect($auth)
{
if (!defined('\CURLOPT_HTTPAUTH') || !defined('\CURLOPT_USERPWD')) {
self::markTestSkipped('ext-curl is required for this test');
}
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com/2']),
static function (RequestInterface $request, $options) {
self::assertTrue(
isset($options['curl'][\CURLOPT_HTTPAUTH]),
'curl options does not contain expected CURLOPT_HTTPAUTH entry'
);
self::assertTrue(
isset($options['curl'][\CURLOPT_USERPWD]),
'curl options does not contain expected CURLOPT_USERPWD entry'
);
return new Response(200);
},
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass', $auth]]);
}
public static function crossOriginRedirectProvider()
{
return [
['http://example.com/123', 'http://example.com/', false],
['http://example.com/123', 'http://example.com:80/', false],
['http://example.com:80/123', 'http://example.com/', false],
['http://example.com:80/123', 'http://example.com:80/', false],
['http://example.com/123', 'https://example.com/', true],
['http://example.com/123', 'http://www.example.com/', true],
['http://example.com/123', 'http://example.com:81/', true],
['http://example.com:80/123', 'http://example.com:81/', true],
['https://example.com/123', 'https://example.com/', false],
['https://example.com/123', 'https://example.com:443/', false],
['https://example.com:443/123', 'https://example.com/', false],
['https://example.com:443/123', 'https://example.com:443/', false],
['https://example.com/123', 'http://example.com/', true],
['https://example.com/123', 'https://www.example.com/', true],
['https://example.com/123', 'https://example.com:444/', true],
['https://example.com:443/123', 'https://example.com:444/', true],
];
}
/**
* @dataProvider crossOriginRedirectProvider
*/
public function testHeadersTreatmentOnRedirect($originalUri, $targetUri, $isCrossOrigin)
{
$mock = new MockHandler([
new Response(302, ['Location' => $targetUri]),
static function (RequestInterface $request) use ($isCrossOrigin) {
self::assertSame(!$isCrossOrigin, $request->hasHeader('Authorization'));
self::assertSame(!$isCrossOrigin, $request->hasHeader('Cookie'));
return new Response(200);
},
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get($originalUri, ['auth' => ['testuser', 'testpass'], 'headers' => ['Cookie' => 'foo=bar']]);
}
public function testNotRemoveAuthorizationHeaderOnRedirect()
{
$mock = new MockHandler([
new Response(302, ['Location' => 'http://example.com/2']),
static function (RequestInterface $request) {
self::assertTrue($request->hasHeader('Authorization'));
return new Response(200);
},
]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
$client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass']]);
}
/**
* Verifies how RedirectMiddleware::modifyRequest() modifies the method and body of a request issued when
* encountering a redirect response.
*
* @dataProvider modifyRequestFollowRequyestMethodAndBodyProvider
*
* @param string $expectedFollowRequestMethod
*/
public function testModifyRequestFollowRequestMethodAndBody(
RequestInterface $request,
$expectedFollowRequestMethod
) {
$redirectMiddleware = new RedirectMiddleware(static function () {
});
$options = [
'allow_redirects' => [
'protocols' => ['http', 'https'],
'strict' => false,
'referer' => null,
],
];
$modifiedRequest = $redirectMiddleware->modifyRequest($request, $options, new Response());
self::assertEquals($expectedFollowRequestMethod, $modifiedRequest->getMethod());
self::assertEquals(0, $modifiedRequest->getBody()->getSize());
}
/**
* @return array
*/
public static function modifyRequestFollowRequyestMethodAndBodyProvider()
{
return [
'DELETE' => [
'request' => new Request('DELETE', 'http://example.com/'),
'expectedFollowRequestMethod' => 'GET',
],
'GET' => [
'request' => new Request('GET', 'http://example.com/'),
'expectedFollowRequestMethod' => 'GET',
],
'HEAD' => [
'request' => new Request('HEAD', 'http://example.com/'),
'expectedFollowRequestMethod' => 'HEAD',
],
'OPTIONS' => [
'request' => new Request('OPTIONS', 'http://example.com/'),
'expectedFollowRequestMethod' => 'OPTIONS',
],
'PATCH' => [
'request' => new Request('PATCH', 'http://example.com/'),
'expectedFollowRequestMethod' => 'GET',
],
'POST' => [
'request' => new Request('POST', 'http://example.com/'),
'expectedFollowRequestMethod' => 'GET',
],
'PUT' => [
'request' => new Request('PUT', 'http://example.com/'),
'expectedFollowRequestMethod' => 'GET',
],
];
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/MiddlewareTest.php | tests/MiddlewareTest.php | <?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\BodySummarizer;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Cookie\SetCookie;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\MessageFormatter;
use GuzzleHttp\Middleware;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
class MiddlewareTest extends TestCase
{
public function testAddsCookiesToRequests()
{
$jar = new CookieJar();
$m = Middleware::cookies($jar);
$h = new MockHandler(
[
static function (RequestInterface $request) {
return new Response(200, [
'Set-Cookie' => (string) new SetCookie([
'Name' => 'name',
'Value' => 'value',
'Domain' => 'foo.com',
]),
]);
},
]
);
$f = $m($h);
$f(new Request('GET', 'http://foo.com'), ['cookies' => $jar])->wait();
self::assertCount(1, $jar);
}
public function testThrowsExceptionOnHttpClientError()
{
$m = Middleware::httpErrors();
$h = new MockHandler([new Response(400, [], str_repeat('a', 1000))]);
$f = $m($h);
$p = $f(new Request('GET', 'http://foo.com'), ['http_errors' => true]);
self::assertTrue(P\Is::pending($p));
$this->expectException(ClientException::class);
$this->expectExceptionMessage(\sprintf("Client error: `GET http://foo.com` resulted in a `400 Bad Request` response:\n%s (truncated...)", str_repeat('a', 120)));
$p->wait();
}
public function testThrowsExceptionOnHttpClientErrorLongBody()
{
$m = Middleware::httpErrors(new BodySummarizer(200));
$h = new MockHandler([new Response(404, [], str_repeat('b', 1000))]);
$f = $m($h);
$p = $f(new Request('GET', 'http://foo.com'), ['http_errors' => true]);
self::assertTrue(P\Is::pending($p));
$this->expectException(ClientException::class);
$this->expectExceptionMessage(\sprintf("Client error: `GET http://foo.com` resulted in a `404 Not Found` response:\n%s (truncated...)", str_repeat('b', 200)));
$p->wait();
}
public function testThrowsExceptionOnHttpServerError()
{
$m = Middleware::httpErrors();
$h = new MockHandler([new Response(500, [], 'Oh no!')]);
$f = $m($h);
$p = $f(new Request('GET', 'http://foo.com'), ['http_errors' => true]);
self::assertTrue(P\Is::pending($p));
$this->expectException(ServerException::class);
$this->expectExceptionMessage("GET http://foo.com` resulted in a `500 Internal Server Error` response:\nOh no!");
$p->wait();
}
/**
* @dataProvider getHistoryUseCases
*/
public function testTracksHistory($container)
{
$m = Middleware::history($container);
$h = new MockHandler([new Response(200), new Response(201)]);
$f = $m($h);
$p1 = $f(new Request('GET', 'http://foo.com'), ['headers' => ['foo' => 'bar']]);
$p2 = $f(new Request('HEAD', 'http://foo.com'), ['headers' => ['foo' => 'baz']]);
$p1->wait();
$p2->wait();
self::assertCount(2, $container);
self::assertSame(200, $container[0]['response']->getStatusCode());
self::assertSame(201, $container[1]['response']->getStatusCode());
self::assertSame('GET', $container[0]['request']->getMethod());
self::assertSame('HEAD', $container[1]['request']->getMethod());
self::assertSame('bar', $container[0]['options']['headers']['foo']);
self::assertSame('baz', $container[1]['options']['headers']['foo']);
}
/**
* As documented in Middleware::history parameter phpdoc.
*/
public function testNullContainerException()
{
$this->expectException(\InvalidArgumentException::class);
$nullContainer = null;
Middleware::history($nullContainer);
}
public static function getHistoryUseCases()
{
return [
[[]], // 1. Container is an array
[new \ArrayObject()], // 2. Container is an ArrayObject
];
}
public function testTracksHistoryForFailures()
{
$container = [];
$m = Middleware::history($container);
$request = new Request('GET', 'http://foo.com');
$h = new MockHandler([new RequestException('error', $request)]);
$f = $m($h);
$f($request, [])->wait(false);
self::assertCount(1, $container);
self::assertSame('GET', $container[0]['request']->getMethod());
self::assertInstanceOf(RequestException::class, $container[0]['error']);
}
public function testTapsBeforeAndAfter()
{
$calls = [];
$m = static function ($handler) use (&$calls) {
return static function ($request, $options) use ($handler, &$calls) {
$calls[] = '2';
return $handler($request, $options);
};
};
$m2 = Middleware::tap(
static function (RequestInterface $request, array $options) use (&$calls) {
$calls[] = '1';
},
static function (RequestInterface $request, array $options, PromiseInterface $p) use (&$calls) {
$calls[] = '3';
}
);
$h = new MockHandler([new Response()]);
$b = new HandlerStack($h);
$b->push($m2);
$b->push($m);
$comp = $b->resolve();
$p = $comp(new Request('GET', 'http://foo.com'), []);
self::assertSame('123', \implode('', $calls));
self::assertInstanceOf(PromiseInterface::class, $p);
self::assertSame(200, $p->wait()->getStatusCode());
}
public function testMapsRequest()
{
$h = new MockHandler([
static function (RequestInterface $request, array $options) {
self::assertSame('foo', $request->getHeaderLine('Bar'));
return new Response(200);
},
]);
$stack = new HandlerStack($h);
$stack->push(Middleware::mapRequest(static function (RequestInterface $request) {
return $request->withHeader('Bar', 'foo');
}));
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), []);
self::assertInstanceOf(PromiseInterface::class, $p);
}
public function testMapsResponse()
{
$h = new MockHandler([new Response(200)]);
$stack = new HandlerStack($h);
$stack->push(Middleware::mapResponse(static function (ResponseInterface $response) {
return $response->withHeader('Bar', 'foo');
}));
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), []);
$p->wait();
self::assertSame('foo', $p->wait()->getHeaderLine('Bar'));
}
public function testLogsRequestsAndResponses()
{
$h = new MockHandler([new Response(200)]);
$stack = new HandlerStack($h);
$logger = new TestLogger();
$formatter = new MessageFormatter();
$stack->push(Middleware::log($logger, $formatter));
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), []);
$p->wait();
self::assertCount(1, $logger->records);
self::assertStringContainsString('"PUT / HTTP/1.1" 200', $logger->records[0]['message']);
}
public function testLogsRequestsAndResponsesCustomLevel()
{
$h = new MockHandler([new Response(200)]);
$stack = new HandlerStack($h);
$logger = new TestLogger();
$formatter = new MessageFormatter();
$stack->push(Middleware::log($logger, $formatter, 'debug'));
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), []);
$p->wait();
self::assertCount(1, $logger->records);
self::assertStringContainsString('"PUT / HTTP/1.1" 200', $logger->records[0]['message']);
self::assertSame('debug', $logger->records[0]['level']);
}
public function testLogsRequestsAndErrors()
{
$h = new MockHandler([new Response(404)]);
$stack = new HandlerStack($h);
$logger = new TestLogger();
$formatter = new MessageFormatter('{code} {error}');
$stack->push(Middleware::log($logger, $formatter));
$stack->push(Middleware::httpErrors());
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), ['http_errors' => true]);
$p->wait(false);
self::assertCount(1, $logger->records);
self::assertStringContainsString('PUT http://www.google.com', $logger->records[0]['message']);
self::assertStringContainsString('404 Not Found', $logger->records[0]['message']);
}
public function testLogsWithStringError()
{
$h = new MockHandler([P\Create::rejectionFor('some problem')]);
$stack = new HandlerStack($h);
$logger = new TestLogger();
$formatter = new MessageFormatter('{error}');
$stack->push(Middleware::log($logger, $formatter));
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com'), []);
$p->wait(false);
self::assertCount(1, $logger->records);
self::assertStringContainsString('some problem', $logger->records[0]['message']);
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
guzzle/guzzle | https://github.com/guzzle/guzzle/blob/b51ac707cfa420b7bfd4e4d5e510ba8008e822b4/tests/PrepareBodyMiddlewareTest.php | tests/PrepareBodyMiddlewareTest.php | <?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\FnStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestInterface;
class PrepareBodyMiddlewareTest extends TestCase
{
public static function methodProvider()
{
$methods = ['GET', 'PUT', 'POST'];
$bodies = ['Test', ''];
foreach ($methods as $method) {
foreach ($bodies as $body) {
yield [$method, $body];
}
}
}
/**
* @dataProvider methodProvider
*/
public function testAddsContentLengthWhenMissingAndPossible($method, $body)
{
$h = new MockHandler([
static function (RequestInterface $request) use ($body) {
$length = \strlen($body);
if ($length > 0) {
self::assertEquals($length, $request->getHeaderLine('Content-Length'));
} else {
self::assertFalse($request->hasHeader('Content-Length'));
}
return new Response(200);
},
]);
$m = Middleware::prepareBody();
$stack = new HandlerStack($h);
$stack->push($m);
$comp = $stack->resolve();
$p = $comp(new Request($method, 'http://www.google.com', [], $body), []);
self::assertInstanceOf(PromiseInterface::class, $p);
$response = $p->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testAddsTransferEncodingWhenNoContentLength()
{
$body = FnStream::decorate(Psr7\Utils::streamFor('foo'), [
'getSize' => static function () {
return null;
},
]);
$h = new MockHandler([
static function (RequestInterface $request) {
self::assertFalse($request->hasHeader('Content-Length'));
self::assertSame('chunked', $request->getHeaderLine('Transfer-Encoding'));
return new Response(200);
},
]);
$m = Middleware::prepareBody();
$stack = new HandlerStack($h);
$stack->push($m);
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com', [], $body), []);
self::assertInstanceOf(PromiseInterface::class, $p);
$response = $p->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testAddsContentTypeWhenMissingAndPossible()
{
$bd = Psr7\Utils::streamFor(\fopen(__DIR__.'/../composer.json', 'r'));
$h = new MockHandler([
static function (RequestInterface $request) {
self::assertSame('application/json', $request->getHeaderLine('Content-Type'));
self::assertTrue($request->hasHeader('Content-Length'));
return new Response(200);
},
]);
$m = Middleware::prepareBody();
$stack = new HandlerStack($h);
$stack->push($m);
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com', [], $bd), []);
self::assertInstanceOf(PromiseInterface::class, $p);
$response = $p->wait();
self::assertSame(200, $response->getStatusCode());
}
public static function expectProvider()
{
return [
[true, ['100-Continue']],
[false, []],
[10, ['100-Continue']],
[500000, []],
];
}
/**
* @dataProvider expectProvider
*/
public function testAddsExpect($value, $result)
{
$bd = Psr7\Utils::streamFor(\fopen(__DIR__.'/../composer.json', 'r'));
$h = new MockHandler([
static function (RequestInterface $request) use ($result) {
self::assertSame($result, $request->getHeader('Expect'));
return new Response(200);
},
]);
$m = Middleware::prepareBody();
$stack = new HandlerStack($h);
$stack->push($m);
$comp = $stack->resolve();
$p = $comp(new Request('PUT', 'http://www.google.com', [], $bd), [
'expect' => $value,
]);
self::assertInstanceOf(PromiseInterface::class, $p);
$response = $p->wait();
self::assertSame(200, $response->getStatusCode());
}
public function testIgnoresIfExpectIsPresent()
{
$bd = Psr7\Utils::streamFor(\fopen(__DIR__.'/../composer.json', 'r'));
$h = new MockHandler([
static function (RequestInterface $request) {
self::assertSame(['Foo'], $request->getHeader('Expect'));
return new Response(200);
},
]);
$m = Middleware::prepareBody();
$stack = new HandlerStack($h);
$stack->push($m);
$comp = $stack->resolve();
$p = $comp(
new Request('PUT', 'http://www.google.com', ['Expect' => 'Foo'], $bd),
['expect' => true]
);
self::assertInstanceOf(PromiseInterface::class, $p);
$response = $p->wait();
self::assertSame(200, $response->getStatusCode());
}
}
| php | MIT | b51ac707cfa420b7bfd4e4d5e510ba8008e822b4 | 2026-01-04T15:02:34.279082Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.