save
This commit is contained in:
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
// autoload.php @generated by Composer
|
||||
|
||||
if (PHP_VERSION_ID < 50600) {
|
||||
if (!headers_sent()) {
|
||||
header('HTTP/1.1 500 Internal Server Error');
|
||||
}
|
||||
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
|
||||
if (!ini_get('display_errors')) {
|
||||
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
|
||||
fwrite(STDERR, $err);
|
||||
} elseif (!headers_sent()) {
|
||||
echo $err;
|
||||
}
|
||||
}
|
||||
trigger_error(
|
||||
$err,
|
||||
E_USER_ERROR
|
||||
);
|
||||
}
|
||||
|
||||
require_once __DIR__ . '/composer/autoload_real.php';
|
||||
|
||||
return ComposerAutoloaderInitb550e1c39f23f72dcd3480e7d01e9b56::getLoader();
|
||||
Vendored
+579
@@ -0,0 +1,579 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Composer.
|
||||
*
|
||||
* (c) Nils Adermann <naderman@naderman.de>
|
||||
* Jordi Boggiano <j.boggiano@seld.be>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Composer\Autoload;
|
||||
|
||||
/**
|
||||
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
|
||||
*
|
||||
* $loader = new \Composer\Autoload\ClassLoader();
|
||||
*
|
||||
* // register classes with namespaces
|
||||
* $loader->add('Symfony\Component', __DIR__.'/component');
|
||||
* $loader->add('Symfony', __DIR__.'/framework');
|
||||
*
|
||||
* // activate the autoloader
|
||||
* $loader->register();
|
||||
*
|
||||
* // to enable searching the include path (eg. for PEAR packages)
|
||||
* $loader->setUseIncludePath(true);
|
||||
*
|
||||
* In this example, if you try to use a class in the Symfony\Component
|
||||
* namespace or one of its children (Symfony\Component\Console for instance),
|
||||
* the autoloader will first look for the class under the component/
|
||||
* directory, and it will then fallback to the framework/ directory if not
|
||||
* found before giving up.
|
||||
*
|
||||
* This class is loosely based on the Symfony UniversalClassLoader.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
* @author Jordi Boggiano <j.boggiano@seld.be>
|
||||
* @see https://www.php-fig.org/psr/psr-0/
|
||||
* @see https://www.php-fig.org/psr/psr-4/
|
||||
*/
|
||||
class ClassLoader
|
||||
{
|
||||
/** @var \Closure(string):void */
|
||||
private static $includeFile;
|
||||
|
||||
/** @var string|null */
|
||||
private $vendorDir;
|
||||
|
||||
// PSR-4
|
||||
/**
|
||||
* @var array<string, array<string, int>>
|
||||
*/
|
||||
private $prefixLengthsPsr4 = array();
|
||||
/**
|
||||
* @var array<string, list<string>>
|
||||
*/
|
||||
private $prefixDirsPsr4 = array();
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
private $fallbackDirsPsr4 = array();
|
||||
|
||||
// PSR-0
|
||||
/**
|
||||
* List of PSR-0 prefixes
|
||||
*
|
||||
* Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2')))
|
||||
*
|
||||
* @var array<string, array<string, list<string>>>
|
||||
*/
|
||||
private $prefixesPsr0 = array();
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
private $fallbackDirsPsr0 = array();
|
||||
|
||||
/** @var bool */
|
||||
private $useIncludePath = false;
|
||||
|
||||
/**
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private $classMap = array();
|
||||
|
||||
/** @var bool */
|
||||
private $classMapAuthoritative = false;
|
||||
|
||||
/**
|
||||
* @var array<string, bool>
|
||||
*/
|
||||
private $missingClasses = array();
|
||||
|
||||
/** @var string|null */
|
||||
private $apcuPrefix;
|
||||
|
||||
/**
|
||||
* @var array<string, self>
|
||||
*/
|
||||
private static $registeredLoaders = array();
|
||||
|
||||
/**
|
||||
* @param string|null $vendorDir
|
||||
*/
|
||||
public function __construct($vendorDir = null)
|
||||
{
|
||||
$this->vendorDir = $vendorDir;
|
||||
self::initializeIncludeClosure();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, list<string>>
|
||||
*/
|
||||
public function getPrefixes()
|
||||
{
|
||||
if (!empty($this->prefixesPsr0)) {
|
||||
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
|
||||
}
|
||||
|
||||
return array();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, list<string>>
|
||||
*/
|
||||
public function getPrefixesPsr4()
|
||||
{
|
||||
return $this->prefixDirsPsr4;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function getFallbackDirs()
|
||||
{
|
||||
return $this->fallbackDirsPsr0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function getFallbackDirsPsr4()
|
||||
{
|
||||
return $this->fallbackDirsPsr4;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> Array of classname => path
|
||||
*/
|
||||
public function getClassMap()
|
||||
{
|
||||
return $this->classMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $classMap Class to filename map
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function addClassMap(array $classMap)
|
||||
{
|
||||
if ($this->classMap) {
|
||||
$this->classMap = array_merge($this->classMap, $classMap);
|
||||
} else {
|
||||
$this->classMap = $classMap;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a set of PSR-0 directories for a given prefix, either
|
||||
* appending or prepending to the ones previously set for this prefix.
|
||||
*
|
||||
* @param string $prefix The prefix
|
||||
* @param list<string>|string $paths The PSR-0 root directories
|
||||
* @param bool $prepend Whether to prepend the directories
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function add($prefix, $paths, $prepend = false)
|
||||
{
|
||||
$paths = (array) $paths;
|
||||
if (!$prefix) {
|
||||
if ($prepend) {
|
||||
$this->fallbackDirsPsr0 = array_merge(
|
||||
$paths,
|
||||
$this->fallbackDirsPsr0
|
||||
);
|
||||
} else {
|
||||
$this->fallbackDirsPsr0 = array_merge(
|
||||
$this->fallbackDirsPsr0,
|
||||
$paths
|
||||
);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$first = $prefix[0];
|
||||
if (!isset($this->prefixesPsr0[$first][$prefix])) {
|
||||
$this->prefixesPsr0[$first][$prefix] = $paths;
|
||||
|
||||
return;
|
||||
}
|
||||
if ($prepend) {
|
||||
$this->prefixesPsr0[$first][$prefix] = array_merge(
|
||||
$paths,
|
||||
$this->prefixesPsr0[$first][$prefix]
|
||||
);
|
||||
} else {
|
||||
$this->prefixesPsr0[$first][$prefix] = array_merge(
|
||||
$this->prefixesPsr0[$first][$prefix],
|
||||
$paths
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a set of PSR-4 directories for a given namespace, either
|
||||
* appending or prepending to the ones previously set for this namespace.
|
||||
*
|
||||
* @param string $prefix The prefix/namespace, with trailing '\\'
|
||||
* @param list<string>|string $paths The PSR-4 base directories
|
||||
* @param bool $prepend Whether to prepend the directories
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function addPsr4($prefix, $paths, $prepend = false)
|
||||
{
|
||||
$paths = (array) $paths;
|
||||
if (!$prefix) {
|
||||
// Register directories for the root namespace.
|
||||
if ($prepend) {
|
||||
$this->fallbackDirsPsr4 = array_merge(
|
||||
$paths,
|
||||
$this->fallbackDirsPsr4
|
||||
);
|
||||
} else {
|
||||
$this->fallbackDirsPsr4 = array_merge(
|
||||
$this->fallbackDirsPsr4,
|
||||
$paths
|
||||
);
|
||||
}
|
||||
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
|
||||
// Register directories for a new namespace.
|
||||
$length = strlen($prefix);
|
||||
if ('\\' !== $prefix[$length - 1]) {
|
||||
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
|
||||
}
|
||||
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
|
||||
$this->prefixDirsPsr4[$prefix] = $paths;
|
||||
} elseif ($prepend) {
|
||||
// Prepend directories for an already registered namespace.
|
||||
$this->prefixDirsPsr4[$prefix] = array_merge(
|
||||
$paths,
|
||||
$this->prefixDirsPsr4[$prefix]
|
||||
);
|
||||
} else {
|
||||
// Append directories for an already registered namespace.
|
||||
$this->prefixDirsPsr4[$prefix] = array_merge(
|
||||
$this->prefixDirsPsr4[$prefix],
|
||||
$paths
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a set of PSR-0 directories for a given prefix,
|
||||
* replacing any others previously set for this prefix.
|
||||
*
|
||||
* @param string $prefix The prefix
|
||||
* @param list<string>|string $paths The PSR-0 base directories
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function set($prefix, $paths)
|
||||
{
|
||||
if (!$prefix) {
|
||||
$this->fallbackDirsPsr0 = (array) $paths;
|
||||
} else {
|
||||
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a set of PSR-4 directories for a given namespace,
|
||||
* replacing any others previously set for this namespace.
|
||||
*
|
||||
* @param string $prefix The prefix/namespace, with trailing '\\'
|
||||
* @param list<string>|string $paths The PSR-4 base directories
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setPsr4($prefix, $paths)
|
||||
{
|
||||
if (!$prefix) {
|
||||
$this->fallbackDirsPsr4 = (array) $paths;
|
||||
} else {
|
||||
$length = strlen($prefix);
|
||||
if ('\\' !== $prefix[$length - 1]) {
|
||||
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
|
||||
}
|
||||
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
|
||||
$this->prefixDirsPsr4[$prefix] = (array) $paths;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns on searching the include path for class files.
|
||||
*
|
||||
* @param bool $useIncludePath
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setUseIncludePath($useIncludePath)
|
||||
{
|
||||
$this->useIncludePath = $useIncludePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Can be used to check if the autoloader uses the include path to check
|
||||
* for classes.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function getUseIncludePath()
|
||||
{
|
||||
return $this->useIncludePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns off searching the prefix and fallback directories for classes
|
||||
* that have not been registered with the class map.
|
||||
*
|
||||
* @param bool $classMapAuthoritative
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setClassMapAuthoritative($classMapAuthoritative)
|
||||
{
|
||||
$this->classMapAuthoritative = $classMapAuthoritative;
|
||||
}
|
||||
|
||||
/**
|
||||
* Should class lookup fail if not found in the current class map?
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isClassMapAuthoritative()
|
||||
{
|
||||
return $this->classMapAuthoritative;
|
||||
}
|
||||
|
||||
/**
|
||||
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
|
||||
*
|
||||
* @param string|null $apcuPrefix
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setApcuPrefix($apcuPrefix)
|
||||
{
|
||||
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The APCu prefix in use, or null if APCu caching is not enabled.
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public function getApcuPrefix()
|
||||
{
|
||||
return $this->apcuPrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers this instance as an autoloader.
|
||||
*
|
||||
* @param bool $prepend Whether to prepend the autoloader or not
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register($prepend = false)
|
||||
{
|
||||
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
|
||||
|
||||
if (null === $this->vendorDir) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($prepend) {
|
||||
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
|
||||
} else {
|
||||
unset(self::$registeredLoaders[$this->vendorDir]);
|
||||
self::$registeredLoaders[$this->vendorDir] = $this;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregisters this instance as an autoloader.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function unregister()
|
||||
{
|
||||
spl_autoload_unregister(array($this, 'loadClass'));
|
||||
|
||||
if (null !== $this->vendorDir) {
|
||||
unset(self::$registeredLoaders[$this->vendorDir]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the given class or interface.
|
||||
*
|
||||
* @param string $class The name of the class
|
||||
* @return true|null True if loaded, null otherwise
|
||||
*/
|
||||
public function loadClass($class)
|
||||
{
|
||||
if ($file = $this->findFile($class)) {
|
||||
$includeFile = self::$includeFile;
|
||||
$includeFile($file);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the path to the file where the class is defined.
|
||||
*
|
||||
* @param string $class The name of the class
|
||||
*
|
||||
* @return string|false The path if found, false otherwise
|
||||
*/
|
||||
public function findFile($class)
|
||||
{
|
||||
// class map lookup
|
||||
if (isset($this->classMap[$class])) {
|
||||
return $this->classMap[$class];
|
||||
}
|
||||
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
|
||||
return false;
|
||||
}
|
||||
if (null !== $this->apcuPrefix) {
|
||||
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
|
||||
if ($hit) {
|
||||
return $file;
|
||||
}
|
||||
}
|
||||
|
||||
$file = $this->findFileWithExtension($class, '.php');
|
||||
|
||||
// Search for Hack files if we are running on HHVM
|
||||
if (false === $file && defined('HHVM_VERSION')) {
|
||||
$file = $this->findFileWithExtension($class, '.hh');
|
||||
}
|
||||
|
||||
if (null !== $this->apcuPrefix) {
|
||||
apcu_add($this->apcuPrefix.$class, $file);
|
||||
}
|
||||
|
||||
if (false === $file) {
|
||||
// Remember that this class does not exist.
|
||||
$this->missingClasses[$class] = true;
|
||||
}
|
||||
|
||||
return $file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the currently registered loaders keyed by their corresponding vendor directories.
|
||||
*
|
||||
* @return array<string, self>
|
||||
*/
|
||||
public static function getRegisteredLoaders()
|
||||
{
|
||||
return self::$registeredLoaders;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $class
|
||||
* @param string $ext
|
||||
* @return string|false
|
||||
*/
|
||||
private function findFileWithExtension($class, $ext)
|
||||
{
|
||||
// PSR-4 lookup
|
||||
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
|
||||
|
||||
$first = $class[0];
|
||||
if (isset($this->prefixLengthsPsr4[$first])) {
|
||||
$subPath = $class;
|
||||
while (false !== $lastPos = strrpos($subPath, '\\')) {
|
||||
$subPath = substr($subPath, 0, $lastPos);
|
||||
$search = $subPath . '\\';
|
||||
if (isset($this->prefixDirsPsr4[$search])) {
|
||||
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
|
||||
foreach ($this->prefixDirsPsr4[$search] as $dir) {
|
||||
if (file_exists($file = $dir . $pathEnd)) {
|
||||
return $file;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PSR-4 fallback dirs
|
||||
foreach ($this->fallbackDirsPsr4 as $dir) {
|
||||
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
|
||||
return $file;
|
||||
}
|
||||
}
|
||||
|
||||
// PSR-0 lookup
|
||||
if (false !== $pos = strrpos($class, '\\')) {
|
||||
// namespaced class name
|
||||
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
|
||||
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
|
||||
} else {
|
||||
// PEAR-like class name
|
||||
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
|
||||
}
|
||||
|
||||
if (isset($this->prefixesPsr0[$first])) {
|
||||
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
|
||||
if (0 === strpos($class, $prefix)) {
|
||||
foreach ($dirs as $dir) {
|
||||
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
|
||||
return $file;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PSR-0 fallback dirs
|
||||
foreach ($this->fallbackDirsPsr0 as $dir) {
|
||||
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
|
||||
return $file;
|
||||
}
|
||||
}
|
||||
|
||||
// PSR-0 include paths.
|
||||
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
|
||||
return $file;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
private static function initializeIncludeClosure()
|
||||
{
|
||||
if (self::$includeFile !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope isolated include.
|
||||
*
|
||||
* Prevents access to $this/self from included files.
|
||||
*
|
||||
* @param string $file
|
||||
* @return void
|
||||
*/
|
||||
self::$includeFile = \Closure::bind(static function($file) {
|
||||
include $file;
|
||||
}, null, null);
|
||||
}
|
||||
}
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Composer.
|
||||
*
|
||||
* (c) Nils Adermann <naderman@naderman.de>
|
||||
* Jordi Boggiano <j.boggiano@seld.be>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Composer;
|
||||
|
||||
use Composer\Autoload\ClassLoader;
|
||||
use Composer\Semver\VersionParser;
|
||||
|
||||
/**
|
||||
* This class is copied in every Composer installed project and available to all
|
||||
*
|
||||
* See also https://getcomposer.org/doc/07-runtime.md#installed-versions
|
||||
*
|
||||
* To require its presence, you can require `composer-runtime-api ^2.0`
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class InstalledVersions
|
||||
{
|
||||
/**
|
||||
* @var mixed[]|null
|
||||
* @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null
|
||||
*/
|
||||
private static $installed;
|
||||
|
||||
/**
|
||||
* @var bool|null
|
||||
*/
|
||||
private static $canGetVendors;
|
||||
|
||||
/**
|
||||
* @var array[]
|
||||
* @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
|
||||
*/
|
||||
private static $installedByVendor = array();
|
||||
|
||||
/**
|
||||
* Returns a list of all package names which are present, either by being installed, replaced or provided
|
||||
*
|
||||
* @return string[]
|
||||
* @psalm-return list<string>
|
||||
*/
|
||||
public static function getInstalledPackages()
|
||||
{
|
||||
$packages = array();
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
$packages[] = array_keys($installed['versions']);
|
||||
}
|
||||
|
||||
if (1 === \count($packages)) {
|
||||
return $packages[0];
|
||||
}
|
||||
|
||||
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of all package names with a specific type e.g. 'library'
|
||||
*
|
||||
* @param string $type
|
||||
* @return string[]
|
||||
* @psalm-return list<string>
|
||||
*/
|
||||
public static function getInstalledPackagesByType($type)
|
||||
{
|
||||
$packagesByType = array();
|
||||
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
foreach ($installed['versions'] as $name => $package) {
|
||||
if (isset($package['type']) && $package['type'] === $type) {
|
||||
$packagesByType[] = $name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $packagesByType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given package is installed
|
||||
*
|
||||
* This also returns true if the package name is provided or replaced by another package
|
||||
*
|
||||
* @param string $packageName
|
||||
* @param bool $includeDevRequirements
|
||||
* @return bool
|
||||
*/
|
||||
public static function isInstalled($packageName, $includeDevRequirements = true)
|
||||
{
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
if (isset($installed['versions'][$packageName])) {
|
||||
return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given package satisfies a version constraint
|
||||
*
|
||||
* e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
|
||||
*
|
||||
* Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
|
||||
*
|
||||
* @param VersionParser $parser Install composer/semver to have access to this class and functionality
|
||||
* @param string $packageName
|
||||
* @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
|
||||
* @return bool
|
||||
*/
|
||||
public static function satisfies(VersionParser $parser, $packageName, $constraint)
|
||||
{
|
||||
$constraint = $parser->parseConstraints((string) $constraint);
|
||||
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
|
||||
|
||||
return $provided->matches($constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a version constraint representing all the range(s) which are installed for a given package
|
||||
*
|
||||
* It is easier to use this via isInstalled() with the $constraint argument if you need to check
|
||||
* whether a given version of a package is installed, and not just whether it exists
|
||||
*
|
||||
* @param string $packageName
|
||||
* @return string Version constraint usable with composer/semver
|
||||
*/
|
||||
public static function getVersionRanges($packageName)
|
||||
{
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
if (!isset($installed['versions'][$packageName])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$ranges = array();
|
||||
if (isset($installed['versions'][$packageName]['pretty_version'])) {
|
||||
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
|
||||
}
|
||||
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
|
||||
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
|
||||
}
|
||||
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
|
||||
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
|
||||
}
|
||||
if (array_key_exists('provided', $installed['versions'][$packageName])) {
|
||||
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
|
||||
}
|
||||
|
||||
return implode(' || ', $ranges);
|
||||
}
|
||||
|
||||
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $packageName
|
||||
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
|
||||
*/
|
||||
public static function getVersion($packageName)
|
||||
{
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
if (!isset($installed['versions'][$packageName])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isset($installed['versions'][$packageName]['version'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $installed['versions'][$packageName]['version'];
|
||||
}
|
||||
|
||||
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $packageName
|
||||
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
|
||||
*/
|
||||
public static function getPrettyVersion($packageName)
|
||||
{
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
if (!isset($installed['versions'][$packageName])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $installed['versions'][$packageName]['pretty_version'];
|
||||
}
|
||||
|
||||
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $packageName
|
||||
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
|
||||
*/
|
||||
public static function getReference($packageName)
|
||||
{
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
if (!isset($installed['versions'][$packageName])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isset($installed['versions'][$packageName]['reference'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $installed['versions'][$packageName]['reference'];
|
||||
}
|
||||
|
||||
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $packageName
|
||||
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
|
||||
*/
|
||||
public static function getInstallPath($packageName)
|
||||
{
|
||||
foreach (self::getInstalled() as $installed) {
|
||||
if (!isset($installed['versions'][$packageName])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
|
||||
}
|
||||
|
||||
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
* @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}
|
||||
*/
|
||||
public static function getRootPackage()
|
||||
{
|
||||
$installed = self::getInstalled();
|
||||
|
||||
return $installed[0]['root'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the raw installed.php data for custom implementations
|
||||
*
|
||||
* @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
|
||||
* @return array[]
|
||||
* @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
|
||||
*/
|
||||
public static function getRawData()
|
||||
{
|
||||
@trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);
|
||||
|
||||
if (null === self::$installed) {
|
||||
// only require the installed.php file if this file is loaded from its dumped location,
|
||||
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
|
||||
if (substr(__DIR__, -8, 1) !== 'C') {
|
||||
self::$installed = include __DIR__ . '/installed.php';
|
||||
} else {
|
||||
self::$installed = array();
|
||||
}
|
||||
}
|
||||
|
||||
return self::$installed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the raw data of all installed.php which are currently loaded for custom implementations
|
||||
*
|
||||
* @return array[]
|
||||
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
|
||||
*/
|
||||
public static function getAllRawData()
|
||||
{
|
||||
return self::getInstalled();
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets you reload the static array from another file
|
||||
*
|
||||
* This is only useful for complex integrations in which a project needs to use
|
||||
* this class but then also needs to execute another project's autoloader in process,
|
||||
* and wants to ensure both projects have access to their version of installed.php.
|
||||
*
|
||||
* A typical case would be PHPUnit, where it would need to make sure it reads all
|
||||
* the data it needs from this class, then call reload() with
|
||||
* `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
|
||||
* the project in which it runs can then also use this class safely, without
|
||||
* interference between PHPUnit's dependencies and the project's dependencies.
|
||||
*
|
||||
* @param array[] $data A vendor/composer/installed.php data set
|
||||
* @return void
|
||||
*
|
||||
* @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data
|
||||
*/
|
||||
public static function reload($data)
|
||||
{
|
||||
self::$installed = $data;
|
||||
self::$installedByVendor = array();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array[]
|
||||
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
|
||||
*/
|
||||
private static function getInstalled()
|
||||
{
|
||||
if (null === self::$canGetVendors) {
|
||||
self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
|
||||
}
|
||||
|
||||
$installed = array();
|
||||
|
||||
if (self::$canGetVendors) {
|
||||
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
|
||||
if (isset(self::$installedByVendor[$vendorDir])) {
|
||||
$installed[] = self::$installedByVendor[$vendorDir];
|
||||
} elseif (is_file($vendorDir.'/composer/installed.php')) {
|
||||
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
|
||||
$required = require $vendorDir.'/composer/installed.php';
|
||||
$installed[] = self::$installedByVendor[$vendorDir] = $required;
|
||||
if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
|
||||
self::$installed = $installed[count($installed) - 1];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (null === self::$installed) {
|
||||
// only require the installed.php file if this file is loaded from its dumped location,
|
||||
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
|
||||
if (substr(__DIR__, -8, 1) !== 'C') {
|
||||
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
|
||||
$required = require __DIR__ . '/installed.php';
|
||||
self::$installed = $required;
|
||||
} else {
|
||||
self::$installed = array();
|
||||
}
|
||||
}
|
||||
|
||||
if (self::$installed !== array()) {
|
||||
$installed[] = self::$installed;
|
||||
}
|
||||
|
||||
return $installed;
|
||||
}
|
||||
}
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
|
||||
Copyright (c) Nils Adermann, Jordi Boggiano
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is furnished
|
||||
to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
// autoload_classmap.php @generated by Composer
|
||||
|
||||
$vendorDir = dirname(__DIR__);
|
||||
$baseDir = dirname($vendorDir);
|
||||
|
||||
return array(
|
||||
'AllowDynamicProperties' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/AllowDynamicProperties.php',
|
||||
'Attribute' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
|
||||
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
|
||||
'Nette\\ArgumentOutOfRangeException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\DeprecatedException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\DirectoryNotFoundException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\FileNotFoundException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\HtmlStringable' => $vendorDir . '/nette/utils/src/HtmlStringable.php',
|
||||
'Nette\\IOException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\InvalidArgumentException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\InvalidStateException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\Iterators\\CachingIterator' => $vendorDir . '/nette/utils/src/Iterators/CachingIterator.php',
|
||||
'Nette\\Iterators\\Mapper' => $vendorDir . '/nette/utils/src/Iterators/Mapper.php',
|
||||
'Nette\\Localization\\ITranslator' => $vendorDir . '/nette/utils/src/compatibility.php',
|
||||
'Nette\\Localization\\Translator' => $vendorDir . '/nette/utils/src/Translator.php',
|
||||
'Nette\\MemberAccessException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\NotImplementedException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\NotSupportedException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\OutOfRangeException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\Schema\\Context' => $vendorDir . '/nette/schema/src/Schema/Context.php',
|
||||
'Nette\\Schema\\DynamicParameter' => $vendorDir . '/nette/schema/src/Schema/DynamicParameter.php',
|
||||
'Nette\\Schema\\Elements\\AnyOf' => $vendorDir . '/nette/schema/src/Schema/Elements/AnyOf.php',
|
||||
'Nette\\Schema\\Elements\\ArrayType' => $vendorDir . '/nette/schema/src/Schema/Elements/ArrayType.php',
|
||||
'Nette\\Schema\\Elements\\Base' => $vendorDir . '/nette/schema/src/Schema/Elements/Base.php',
|
||||
'Nette\\Schema\\Elements\\EnumType' => $vendorDir . '/nette/schema/src/Schema/Elements/EnumType.php',
|
||||
'Nette\\Schema\\Elements\\NumberType' => $vendorDir . '/nette/schema/src/Schema/Elements/NumberType.php',
|
||||
'Nette\\Schema\\Elements\\StringType' => $vendorDir . '/nette/schema/src/Schema/Elements/StringType.php',
|
||||
'Nette\\Schema\\Elements\\Structure' => $vendorDir . '/nette/schema/src/Schema/Elements/Structure.php',
|
||||
'Nette\\Schema\\Elements\\TupleType' => $vendorDir . '/nette/schema/src/Schema/Elements/TupleType.php',
|
||||
'Nette\\Schema\\Elements\\Type' => $vendorDir . '/nette/schema/src/Schema/Elements/Type.php',
|
||||
'Nette\\Schema\\Expect' => $vendorDir . '/nette/schema/src/Schema/Expect.php',
|
||||
'Nette\\Schema\\Helpers' => $vendorDir . '/nette/schema/src/Schema/Helpers.php',
|
||||
'Nette\\Schema\\JsonSchema' => $vendorDir . '/nette/schema/src/Schema/JsonSchema.php',
|
||||
'Nette\\Schema\\Kind' => $vendorDir . '/nette/schema/src/Schema/enums.php',
|
||||
'Nette\\Schema\\MergeMode' => $vendorDir . '/nette/schema/src/Schema/enums.php',
|
||||
'Nette\\Schema\\Message' => $vendorDir . '/nette/schema/src/Schema/Message.php',
|
||||
'Nette\\Schema\\Processor' => $vendorDir . '/nette/schema/src/Schema/Processor.php',
|
||||
'Nette\\Schema\\Schema' => $vendorDir . '/nette/schema/src/Schema/Schema.php',
|
||||
'Nette\\Schema\\TypeExpression' => $vendorDir . '/nette/schema/src/Schema/TypeExpression.php',
|
||||
'Nette\\Schema\\ValidationException' => $vendorDir . '/nette/schema/src/Schema/ValidationException.php',
|
||||
'Nette\\ShouldNotHappenException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\SmartObject' => $vendorDir . '/nette/utils/src/SmartObject.php',
|
||||
'Nette\\StaticClass' => $vendorDir . '/nette/utils/src/StaticClass.php',
|
||||
'Nette\\UnexpectedValueException' => $vendorDir . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\Utils\\ArrayHash' => $vendorDir . '/nette/utils/src/Utils/ArrayHash.php',
|
||||
'Nette\\Utils\\ArrayList' => $vendorDir . '/nette/utils/src/Utils/ArrayList.php',
|
||||
'Nette\\Utils\\Arrays' => $vendorDir . '/nette/utils/src/Utils/Arrays.php',
|
||||
'Nette\\Utils\\AssertionException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php',
|
||||
'Nette\\Utils\\Callback' => $vendorDir . '/nette/utils/src/Utils/Callback.php',
|
||||
'Nette\\Utils\\DateTime' => $vendorDir . '/nette/utils/src/Utils/DateTime.php',
|
||||
'Nette\\Utils\\DateTimeImmutable' => $vendorDir . '/nette/utils/src/Utils/DateTimeImmutable.php',
|
||||
'Nette\\Utils\\FileInfo' => $vendorDir . '/nette/utils/src/Utils/FileInfo.php',
|
||||
'Nette\\Utils\\FileSystem' => $vendorDir . '/nette/utils/src/Utils/FileSystem.php',
|
||||
'Nette\\Utils\\Finder' => $vendorDir . '/nette/utils/src/Utils/Finder.php',
|
||||
'Nette\\Utils\\Floats' => $vendorDir . '/nette/utils/src/Utils/Floats.php',
|
||||
'Nette\\Utils\\Helpers' => $vendorDir . '/nette/utils/src/Utils/Helpers.php',
|
||||
'Nette\\Utils\\Html' => $vendorDir . '/nette/utils/src/Utils/Html.php',
|
||||
'Nette\\Utils\\IHtmlString' => $vendorDir . '/nette/utils/src/compatibility.php',
|
||||
'Nette\\Utils\\Image' => $vendorDir . '/nette/utils/src/Utils/Image.php',
|
||||
'Nette\\Utils\\ImageColor' => $vendorDir . '/nette/utils/src/Utils/ImageColor.php',
|
||||
'Nette\\Utils\\ImageException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php',
|
||||
'Nette\\Utils\\ImageType' => $vendorDir . '/nette/utils/src/Utils/ImageType.php',
|
||||
'Nette\\Utils\\Iterables' => $vendorDir . '/nette/utils/src/Utils/Iterables.php',
|
||||
'Nette\\Utils\\Json' => $vendorDir . '/nette/utils/src/Utils/Json.php',
|
||||
'Nette\\Utils\\JsonException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php',
|
||||
'Nette\\Utils\\ObjectHelpers' => $vendorDir . '/nette/utils/src/Utils/ObjectHelpers.php',
|
||||
'Nette\\Utils\\Paginator' => $vendorDir . '/nette/utils/src/Utils/Paginator.php',
|
||||
'Nette\\Utils\\Process' => $vendorDir . '/nette/utils/src/Utils/Process.php',
|
||||
'Nette\\Utils\\ProcessFailedException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php',
|
||||
'Nette\\Utils\\ProcessTimeoutException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php',
|
||||
'Nette\\Utils\\Random' => $vendorDir . '/nette/utils/src/Utils/Random.php',
|
||||
'Nette\\Utils\\Reflection' => $vendorDir . '/nette/utils/src/Utils/Reflection.php',
|
||||
'Nette\\Utils\\ReflectionMethod' => $vendorDir . '/nette/utils/src/Utils/ReflectionMethod.php',
|
||||
'Nette\\Utils\\RegexpException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php',
|
||||
'Nette\\Utils\\Strings' => $vendorDir . '/nette/utils/src/Utils/Strings.php',
|
||||
'Nette\\Utils\\Type' => $vendorDir . '/nette/utils/src/Utils/Type.php',
|
||||
'Nette\\Utils\\UnknownImageFileException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php',
|
||||
'Nette\\Utils\\Validators' => $vendorDir . '/nette/utils/src/Utils/Validators.php',
|
||||
'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
|
||||
'Random\\BrokenRandomEngineError' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/BrokenRandomEngineError.php',
|
||||
'Random\\CryptoSafeEngine' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/CryptoSafeEngine.php',
|
||||
'Random\\Engine' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/Engine.php',
|
||||
'Random\\Engine\\Secure' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/Engine/Secure.php',
|
||||
'Random\\RandomError' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/RandomError.php',
|
||||
'Random\\RandomException' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/Random/RandomException.php',
|
||||
'SensitiveParameter' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/SensitiveParameter.php',
|
||||
'SensitiveParameterValue' => $vendorDir . '/symfony/polyfill-php82/Resources/stubs/SensitiveParameterValue.php',
|
||||
'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
|
||||
'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
|
||||
'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
|
||||
);
|
||||
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
// autoload_files.php @generated by Composer
|
||||
|
||||
$vendorDir = dirname(__DIR__);
|
||||
$baseDir = dirname($vendorDir);
|
||||
|
||||
return array(
|
||||
'6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php',
|
||||
'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php',
|
||||
'5897ea0ac4cccf14d323035e65887801' => $vendorDir . '/symfony/polyfill-php82/bootstrap.php',
|
||||
'253c157292f75eb38082b5acb06f3f01' => $vendorDir . '/nikic/fast-route/src/functions.php',
|
||||
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
|
||||
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
|
||||
'd2136ff22b54ac75cd96a40e0022218e' => $vendorDir . '/workerman/webman-framework/src/support/helpers.php',
|
||||
);
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
// autoload_namespaces.php @generated by Composer
|
||||
|
||||
$vendorDir = dirname(__DIR__);
|
||||
$baseDir = dirname($vendorDir);
|
||||
|
||||
return array(
|
||||
);
|
||||
Vendored
+41
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
// autoload_psr4.php @generated by Composer
|
||||
|
||||
$vendorDir = dirname(__DIR__);
|
||||
$baseDir = dirname($vendorDir);
|
||||
|
||||
return array(
|
||||
'support\\' => array($vendorDir . '/workerman/webman-framework/src/support'),
|
||||
'Workerman\\Coroutine\\' => array($vendorDir . '/workerman/coroutine/src'),
|
||||
'Workerman\\' => array($vendorDir . '/workerman/coroutine/src', $vendorDir . '/workerman/workerman/src'),
|
||||
'Webman\\' => array($vendorDir . '/workerman/webman-framework/src'),
|
||||
'Symfony\\Polyfill\\Php82\\' => array($vendorDir . '/symfony/polyfill-php82'),
|
||||
'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'),
|
||||
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
|
||||
'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'),
|
||||
'Support\\View\\' => array($vendorDir . '/workerman/webman-framework/src/support/view'),
|
||||
'Support\\Exception\\' => array($vendorDir . '/workerman/webman-framework/src/support/exception'),
|
||||
'Support\\Bootstrap\\' => array($vendorDir . '/workerman/webman-framework/src/support/bootstrap'),
|
||||
'Support\\' => array($vendorDir . '/workerman/webman-framework/src/support'),
|
||||
'Psr\\Log\\' => array($vendorDir . '/psr/log/src'),
|
||||
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src', $vendorDir . '/psr/http-factory/src'),
|
||||
'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'),
|
||||
'Psr\\EventDispatcher\\' => array($vendorDir . '/psr/event-dispatcher/src'),
|
||||
'Psr\\Container\\' => array($vendorDir . '/psr/container/src'),
|
||||
'PhpOption\\' => array($vendorDir . '/phpoption/phpoption/src/PhpOption'),
|
||||
'Nette\\' => array($vendorDir . '/nette/schema/src', $vendorDir . '/nette/utils/src'),
|
||||
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
|
||||
'League\\OAuth2\\Client\\' => array($vendorDir . '/league/oauth2-client/src'),
|
||||
'League\\Config\\' => array($vendorDir . '/league/config/src'),
|
||||
'League\\CommonMark\\' => array($vendorDir . '/league/commonmark/src'),
|
||||
'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'),
|
||||
'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'),
|
||||
'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'),
|
||||
'GrahamCampbell\\ResultType\\' => array($vendorDir . '/graham-campbell/result-type/src'),
|
||||
'Firebase\\JWT\\' => array($vendorDir . '/firebase/php-jwt/src'),
|
||||
'FastRoute\\' => array($vendorDir . '/nikic/fast-route/src'),
|
||||
'Dotenv\\' => array($vendorDir . '/vlucas/phpdotenv/src'),
|
||||
'Dflydev\\DotAccessData\\' => array($vendorDir . '/dflydev/dot-access-data/src'),
|
||||
'App\\' => array($baseDir . '/app'),
|
||||
);
|
||||
Vendored
+50
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
// autoload_real.php @generated by Composer
|
||||
|
||||
class ComposerAutoloaderInitb550e1c39f23f72dcd3480e7d01e9b56
|
||||
{
|
||||
private static $loader;
|
||||
|
||||
public static function loadClassLoader($class)
|
||||
{
|
||||
if ('Composer\Autoload\ClassLoader' === $class) {
|
||||
require __DIR__ . '/ClassLoader.php';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Composer\Autoload\ClassLoader
|
||||
*/
|
||||
public static function getLoader()
|
||||
{
|
||||
if (null !== self::$loader) {
|
||||
return self::$loader;
|
||||
}
|
||||
|
||||
require __DIR__ . '/platform_check.php';
|
||||
|
||||
spl_autoload_register(array('ComposerAutoloaderInitb550e1c39f23f72dcd3480e7d01e9b56', 'loadClassLoader'), true, true);
|
||||
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
|
||||
spl_autoload_unregister(array('ComposerAutoloaderInitb550e1c39f23f72dcd3480e7d01e9b56', 'loadClassLoader'));
|
||||
|
||||
require __DIR__ . '/autoload_static.php';
|
||||
call_user_func(\Composer\Autoload\ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56::getInitializer($loader));
|
||||
|
||||
$loader->register(true);
|
||||
|
||||
$filesToLoad = \Composer\Autoload\ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56::$files;
|
||||
$requireFile = \Closure::bind(static function ($fileIdentifier, $file) {
|
||||
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
|
||||
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
|
||||
|
||||
require $file;
|
||||
}
|
||||
}, null, null);
|
||||
foreach ($filesToLoad as $fileIdentifier => $file) {
|
||||
$requireFile($fileIdentifier, $file);
|
||||
}
|
||||
|
||||
return $loader;
|
||||
}
|
||||
}
|
||||
Vendored
+323
@@ -0,0 +1,323 @@
|
||||
<?php
|
||||
|
||||
// autoload_static.php @generated by Composer
|
||||
|
||||
namespace Composer\Autoload;
|
||||
|
||||
class ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56
|
||||
{
|
||||
public static $files = array (
|
||||
'6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php',
|
||||
'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php',
|
||||
'5897ea0ac4cccf14d323035e65887801' => __DIR__ . '/..' . '/symfony/polyfill-php82/bootstrap.php',
|
||||
'253c157292f75eb38082b5acb06f3f01' => __DIR__ . '/..' . '/nikic/fast-route/src/functions.php',
|
||||
'320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php',
|
||||
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
|
||||
'd2136ff22b54ac75cd96a40e0022218e' => __DIR__ . '/..' . '/workerman/webman-framework/src/support/helpers.php',
|
||||
);
|
||||
|
||||
public static $prefixLengthsPsr4 = array (
|
||||
's' =>
|
||||
array (
|
||||
'support\\' => 8,
|
||||
),
|
||||
'W' =>
|
||||
array (
|
||||
'Workerman\\Coroutine\\' => 20,
|
||||
'Workerman\\' => 10,
|
||||
'Webman\\' => 7,
|
||||
),
|
||||
'S' =>
|
||||
array (
|
||||
'Symfony\\Polyfill\\Php82\\' => 23,
|
||||
'Symfony\\Polyfill\\Php80\\' => 23,
|
||||
'Symfony\\Polyfill\\Mbstring\\' => 26,
|
||||
'Symfony\\Polyfill\\Ctype\\' => 23,
|
||||
'Support\\View\\' => 13,
|
||||
'Support\\Exception\\' => 18,
|
||||
'Support\\Bootstrap\\' => 18,
|
||||
'Support\\' => 8,
|
||||
),
|
||||
'P' =>
|
||||
array (
|
||||
'Psr\\Log\\' => 8,
|
||||
'Psr\\Http\\Message\\' => 17,
|
||||
'Psr\\Http\\Client\\' => 16,
|
||||
'Psr\\EventDispatcher\\' => 20,
|
||||
'Psr\\Container\\' => 14,
|
||||
'PhpOption\\' => 10,
|
||||
),
|
||||
'N' =>
|
||||
array (
|
||||
'Nette\\' => 6,
|
||||
),
|
||||
'M' =>
|
||||
array (
|
||||
'Monolog\\' => 8,
|
||||
),
|
||||
'L' =>
|
||||
array (
|
||||
'League\\OAuth2\\Client\\' => 21,
|
||||
'League\\Config\\' => 14,
|
||||
'League\\CommonMark\\' => 18,
|
||||
),
|
||||
'G' =>
|
||||
array (
|
||||
'GuzzleHttp\\Psr7\\' => 16,
|
||||
'GuzzleHttp\\Promise\\' => 19,
|
||||
'GuzzleHttp\\' => 11,
|
||||
'GrahamCampbell\\ResultType\\' => 26,
|
||||
),
|
||||
'F' =>
|
||||
array (
|
||||
'Firebase\\JWT\\' => 13,
|
||||
'FastRoute\\' => 10,
|
||||
),
|
||||
'D' =>
|
||||
array (
|
||||
'Dotenv\\' => 7,
|
||||
'Dflydev\\DotAccessData\\' => 22,
|
||||
),
|
||||
'A' =>
|
||||
array (
|
||||
'App\\' => 4,
|
||||
),
|
||||
);
|
||||
|
||||
public static $prefixDirsPsr4 = array (
|
||||
'support\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/workerman/webman-framework/src/support',
|
||||
),
|
||||
'Workerman\\Coroutine\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/workerman/coroutine/src',
|
||||
),
|
||||
'Workerman\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/workerman/coroutine/src',
|
||||
1 => __DIR__ . '/..' . '/workerman/workerman/src',
|
||||
),
|
||||
'Webman\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/workerman/webman-framework/src',
|
||||
),
|
||||
'Symfony\\Polyfill\\Php82\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/symfony/polyfill-php82',
|
||||
),
|
||||
'Symfony\\Polyfill\\Php80\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/symfony/polyfill-php80',
|
||||
),
|
||||
'Symfony\\Polyfill\\Mbstring\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring',
|
||||
),
|
||||
'Symfony\\Polyfill\\Ctype\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/symfony/polyfill-ctype',
|
||||
),
|
||||
'Support\\View\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/workerman/webman-framework/src/support/view',
|
||||
),
|
||||
'Support\\Exception\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/workerman/webman-framework/src/support/exception',
|
||||
),
|
||||
'Support\\Bootstrap\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/workerman/webman-framework/src/support/bootstrap',
|
||||
),
|
||||
'Support\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/workerman/webman-framework/src/support',
|
||||
),
|
||||
'Psr\\Log\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/psr/log/src',
|
||||
),
|
||||
'Psr\\Http\\Message\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/psr/http-message/src',
|
||||
1 => __DIR__ . '/..' . '/psr/http-factory/src',
|
||||
),
|
||||
'Psr\\Http\\Client\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/psr/http-client/src',
|
||||
),
|
||||
'Psr\\EventDispatcher\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/psr/event-dispatcher/src',
|
||||
),
|
||||
'Psr\\Container\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/psr/container/src',
|
||||
),
|
||||
'PhpOption\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/phpoption/phpoption/src/PhpOption',
|
||||
),
|
||||
'Nette\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/nette/schema/src',
|
||||
1 => __DIR__ . '/..' . '/nette/utils/src',
|
||||
),
|
||||
'Monolog\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/monolog/monolog/src/Monolog',
|
||||
),
|
||||
'League\\OAuth2\\Client\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/league/oauth2-client/src',
|
||||
),
|
||||
'League\\Config\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/league/config/src',
|
||||
),
|
||||
'League\\CommonMark\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/league/commonmark/src',
|
||||
),
|
||||
'GuzzleHttp\\Psr7\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src',
|
||||
),
|
||||
'GuzzleHttp\\Promise\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/guzzlehttp/promises/src',
|
||||
),
|
||||
'GuzzleHttp\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/guzzlehttp/guzzle/src',
|
||||
),
|
||||
'GrahamCampbell\\ResultType\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/graham-campbell/result-type/src',
|
||||
),
|
||||
'Firebase\\JWT\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/firebase/php-jwt/src',
|
||||
),
|
||||
'FastRoute\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/nikic/fast-route/src',
|
||||
),
|
||||
'Dotenv\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/vlucas/phpdotenv/src',
|
||||
),
|
||||
'Dflydev\\DotAccessData\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/dflydev/dot-access-data/src',
|
||||
),
|
||||
'App\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/../..' . '/app',
|
||||
),
|
||||
);
|
||||
|
||||
public static $classMap = array (
|
||||
'AllowDynamicProperties' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/AllowDynamicProperties.php',
|
||||
'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
|
||||
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
|
||||
'Nette\\ArgumentOutOfRangeException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\DeprecatedException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\DirectoryNotFoundException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\FileNotFoundException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\HtmlStringable' => __DIR__ . '/..' . '/nette/utils/src/HtmlStringable.php',
|
||||
'Nette\\IOException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\InvalidArgumentException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\InvalidStateException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\Iterators\\CachingIterator' => __DIR__ . '/..' . '/nette/utils/src/Iterators/CachingIterator.php',
|
||||
'Nette\\Iterators\\Mapper' => __DIR__ . '/..' . '/nette/utils/src/Iterators/Mapper.php',
|
||||
'Nette\\Localization\\ITranslator' => __DIR__ . '/..' . '/nette/utils/src/compatibility.php',
|
||||
'Nette\\Localization\\Translator' => __DIR__ . '/..' . '/nette/utils/src/Translator.php',
|
||||
'Nette\\MemberAccessException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\NotImplementedException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\NotSupportedException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\OutOfRangeException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\Schema\\Context' => __DIR__ . '/..' . '/nette/schema/src/Schema/Context.php',
|
||||
'Nette\\Schema\\DynamicParameter' => __DIR__ . '/..' . '/nette/schema/src/Schema/DynamicParameter.php',
|
||||
'Nette\\Schema\\Elements\\AnyOf' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/AnyOf.php',
|
||||
'Nette\\Schema\\Elements\\ArrayType' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/ArrayType.php',
|
||||
'Nette\\Schema\\Elements\\Base' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/Base.php',
|
||||
'Nette\\Schema\\Elements\\EnumType' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/EnumType.php',
|
||||
'Nette\\Schema\\Elements\\NumberType' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/NumberType.php',
|
||||
'Nette\\Schema\\Elements\\StringType' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/StringType.php',
|
||||
'Nette\\Schema\\Elements\\Structure' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/Structure.php',
|
||||
'Nette\\Schema\\Elements\\TupleType' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/TupleType.php',
|
||||
'Nette\\Schema\\Elements\\Type' => __DIR__ . '/..' . '/nette/schema/src/Schema/Elements/Type.php',
|
||||
'Nette\\Schema\\Expect' => __DIR__ . '/..' . '/nette/schema/src/Schema/Expect.php',
|
||||
'Nette\\Schema\\Helpers' => __DIR__ . '/..' . '/nette/schema/src/Schema/Helpers.php',
|
||||
'Nette\\Schema\\JsonSchema' => __DIR__ . '/..' . '/nette/schema/src/Schema/JsonSchema.php',
|
||||
'Nette\\Schema\\Kind' => __DIR__ . '/..' . '/nette/schema/src/Schema/enums.php',
|
||||
'Nette\\Schema\\MergeMode' => __DIR__ . '/..' . '/nette/schema/src/Schema/enums.php',
|
||||
'Nette\\Schema\\Message' => __DIR__ . '/..' . '/nette/schema/src/Schema/Message.php',
|
||||
'Nette\\Schema\\Processor' => __DIR__ . '/..' . '/nette/schema/src/Schema/Processor.php',
|
||||
'Nette\\Schema\\Schema' => __DIR__ . '/..' . '/nette/schema/src/Schema/Schema.php',
|
||||
'Nette\\Schema\\TypeExpression' => __DIR__ . '/..' . '/nette/schema/src/Schema/TypeExpression.php',
|
||||
'Nette\\Schema\\ValidationException' => __DIR__ . '/..' . '/nette/schema/src/Schema/ValidationException.php',
|
||||
'Nette\\ShouldNotHappenException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\SmartObject' => __DIR__ . '/..' . '/nette/utils/src/SmartObject.php',
|
||||
'Nette\\StaticClass' => __DIR__ . '/..' . '/nette/utils/src/StaticClass.php',
|
||||
'Nette\\UnexpectedValueException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php',
|
||||
'Nette\\Utils\\ArrayHash' => __DIR__ . '/..' . '/nette/utils/src/Utils/ArrayHash.php',
|
||||
'Nette\\Utils\\ArrayList' => __DIR__ . '/..' . '/nette/utils/src/Utils/ArrayList.php',
|
||||
'Nette\\Utils\\Arrays' => __DIR__ . '/..' . '/nette/utils/src/Utils/Arrays.php',
|
||||
'Nette\\Utils\\AssertionException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php',
|
||||
'Nette\\Utils\\Callback' => __DIR__ . '/..' . '/nette/utils/src/Utils/Callback.php',
|
||||
'Nette\\Utils\\DateTime' => __DIR__ . '/..' . '/nette/utils/src/Utils/DateTime.php',
|
||||
'Nette\\Utils\\DateTimeImmutable' => __DIR__ . '/..' . '/nette/utils/src/Utils/DateTimeImmutable.php',
|
||||
'Nette\\Utils\\FileInfo' => __DIR__ . '/..' . '/nette/utils/src/Utils/FileInfo.php',
|
||||
'Nette\\Utils\\FileSystem' => __DIR__ . '/..' . '/nette/utils/src/Utils/FileSystem.php',
|
||||
'Nette\\Utils\\Finder' => __DIR__ . '/..' . '/nette/utils/src/Utils/Finder.php',
|
||||
'Nette\\Utils\\Floats' => __DIR__ . '/..' . '/nette/utils/src/Utils/Floats.php',
|
||||
'Nette\\Utils\\Helpers' => __DIR__ . '/..' . '/nette/utils/src/Utils/Helpers.php',
|
||||
'Nette\\Utils\\Html' => __DIR__ . '/..' . '/nette/utils/src/Utils/Html.php',
|
||||
'Nette\\Utils\\IHtmlString' => __DIR__ . '/..' . '/nette/utils/src/compatibility.php',
|
||||
'Nette\\Utils\\Image' => __DIR__ . '/..' . '/nette/utils/src/Utils/Image.php',
|
||||
'Nette\\Utils\\ImageColor' => __DIR__ . '/..' . '/nette/utils/src/Utils/ImageColor.php',
|
||||
'Nette\\Utils\\ImageException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php',
|
||||
'Nette\\Utils\\ImageType' => __DIR__ . '/..' . '/nette/utils/src/Utils/ImageType.php',
|
||||
'Nette\\Utils\\Iterables' => __DIR__ . '/..' . '/nette/utils/src/Utils/Iterables.php',
|
||||
'Nette\\Utils\\Json' => __DIR__ . '/..' . '/nette/utils/src/Utils/Json.php',
|
||||
'Nette\\Utils\\JsonException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php',
|
||||
'Nette\\Utils\\ObjectHelpers' => __DIR__ . '/..' . '/nette/utils/src/Utils/ObjectHelpers.php',
|
||||
'Nette\\Utils\\Paginator' => __DIR__ . '/..' . '/nette/utils/src/Utils/Paginator.php',
|
||||
'Nette\\Utils\\Process' => __DIR__ . '/..' . '/nette/utils/src/Utils/Process.php',
|
||||
'Nette\\Utils\\ProcessFailedException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php',
|
||||
'Nette\\Utils\\ProcessTimeoutException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php',
|
||||
'Nette\\Utils\\Random' => __DIR__ . '/..' . '/nette/utils/src/Utils/Random.php',
|
||||
'Nette\\Utils\\Reflection' => __DIR__ . '/..' . '/nette/utils/src/Utils/Reflection.php',
|
||||
'Nette\\Utils\\ReflectionMethod' => __DIR__ . '/..' . '/nette/utils/src/Utils/ReflectionMethod.php',
|
||||
'Nette\\Utils\\RegexpException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php',
|
||||
'Nette\\Utils\\Strings' => __DIR__ . '/..' . '/nette/utils/src/Utils/Strings.php',
|
||||
'Nette\\Utils\\Type' => __DIR__ . '/..' . '/nette/utils/src/Utils/Type.php',
|
||||
'Nette\\Utils\\UnknownImageFileException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php',
|
||||
'Nette\\Utils\\Validators' => __DIR__ . '/..' . '/nette/utils/src/Utils/Validators.php',
|
||||
'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
|
||||
'Random\\BrokenRandomEngineError' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/BrokenRandomEngineError.php',
|
||||
'Random\\CryptoSafeEngine' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/CryptoSafeEngine.php',
|
||||
'Random\\Engine' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/Engine.php',
|
||||
'Random\\Engine\\Secure' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/Engine/Secure.php',
|
||||
'Random\\RandomError' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/RandomError.php',
|
||||
'Random\\RandomException' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/Random/RandomException.php',
|
||||
'SensitiveParameter' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/SensitiveParameter.php',
|
||||
'SensitiveParameterValue' => __DIR__ . '/..' . '/symfony/polyfill-php82/Resources/stubs/SensitiveParameterValue.php',
|
||||
'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
|
||||
'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
|
||||
'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
|
||||
);
|
||||
|
||||
public static function getInitializer(ClassLoader $loader)
|
||||
{
|
||||
return \Closure::bind(function () use ($loader) {
|
||||
$loader->prefixLengthsPsr4 = ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56::$prefixLengthsPsr4;
|
||||
$loader->prefixDirsPsr4 = ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56::$prefixDirsPsr4;
|
||||
$loader->classMap = ComposerStaticInitb550e1c39f23f72dcd3480e7d01e9b56::$classMap;
|
||||
|
||||
}, null, ClassLoader::class);
|
||||
}
|
||||
}
|
||||
Vendored
+2266
File diff suppressed because it is too large
Load Diff
Vendored
+308
@@ -0,0 +1,308 @@
|
||||
<?php return array(
|
||||
'root' => array(
|
||||
'name' => 'laysense/laysite',
|
||||
'pretty_version' => 'dev-main',
|
||||
'version' => 'dev-main',
|
||||
'reference' => '89f363186becd5bb733f30901af79903f47c9627',
|
||||
'type' => 'project',
|
||||
'install_path' => __DIR__ . '/../../',
|
||||
'aliases' => array(),
|
||||
'dev' => true,
|
||||
),
|
||||
'versions' => array(
|
||||
'dflydev/dot-access-data' => array(
|
||||
'pretty_version' => 'v3.0.3',
|
||||
'version' => '3.0.3.0',
|
||||
'reference' => 'a23a2bf4f31d3518f3ecb38660c95715dfead60f',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../dflydev/dot-access-data',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'firebase/php-jwt' => array(
|
||||
'pretty_version' => 'v7.2.2',
|
||||
'version' => '7.2.2.0',
|
||||
'reference' => '99efeb17d6def8c0295777f2d45b07ff4fdb4e40',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../firebase/php-jwt',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'graham-campbell/result-type' => array(
|
||||
'pretty_version' => 'v1.2.0',
|
||||
'version' => '1.2.0.0',
|
||||
'reference' => 'adccca3324eece92ca35463648c12b9e6293c05b',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../graham-campbell/result-type',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'guzzlehttp/guzzle' => array(
|
||||
'pretty_version' => '8.5.5',
|
||||
'version' => '8.5.5.0',
|
||||
'reference' => 'd1a26e6ce24268e740af501de8748d1c945e6f4b',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../guzzlehttp/guzzle',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'guzzlehttp/promises' => array(
|
||||
'pretty_version' => '3.2.0',
|
||||
'version' => '3.2.0.0',
|
||||
'reference' => 'a201cc78db93065f891278f86eaeaa1c97c5a158',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../guzzlehttp/promises',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'guzzlehttp/psr7' => array(
|
||||
'pretty_version' => '3.6.0',
|
||||
'version' => '3.6.0.0',
|
||||
'reference' => '1fa0f8319c046b7dec80030460254283d851388e',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../guzzlehttp/psr7',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'laysense/laysite' => array(
|
||||
'pretty_version' => 'dev-main',
|
||||
'version' => 'dev-main',
|
||||
'reference' => '89f363186becd5bb733f30901af79903f47c9627',
|
||||
'type' => 'project',
|
||||
'install_path' => __DIR__ . '/../../',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'league/commonmark' => array(
|
||||
'pretty_version' => '2.10.7',
|
||||
'version' => '2.10.7.0',
|
||||
'reference' => '8eb53e906fd60c67038d22f1f1cab420ed58b8be',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../league/commonmark',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'league/config' => array(
|
||||
'pretty_version' => 'v1.2.0',
|
||||
'version' => '1.2.0.0',
|
||||
'reference' => '754b3604fb2984c71f4af4a9cbe7b57f346ec1f3',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../league/config',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'league/oauth2-client' => array(
|
||||
'pretty_version' => '2.10.0',
|
||||
'version' => '2.10.0.0',
|
||||
'reference' => '25d240c6804f975909f8cdd131345949d8642535',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../league/oauth2-client',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'monolog/monolog' => array(
|
||||
'pretty_version' => '3.13.0',
|
||||
'version' => '3.13.0.0',
|
||||
'reference' => '1f5f55bb4a9a230ff6d8a4ceccea31d10b0142ac',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../monolog/monolog',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'nette/schema' => array(
|
||||
'pretty_version' => 'v1.4.0',
|
||||
'version' => '1.4.0.0',
|
||||
'reference' => 'af9fa8a86bfca9b02b10346220db26e62ef942ec',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../nette/schema',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'nette/utils' => array(
|
||||
'pretty_version' => 'v4.1.6',
|
||||
'version' => '4.1.6.0',
|
||||
'reference' => '6bf24518accf32cf845bca305e0b92078700fd01',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../nette/utils',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'nikic/fast-route' => array(
|
||||
'pretty_version' => '1.3.1',
|
||||
'version' => '1.3.1.0',
|
||||
'reference' => '7476684f39bb9124b3be69ed3d84b66723920298',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../nikic/fast-route',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'phpoption/phpoption' => array(
|
||||
'pretty_version' => '1.10.0',
|
||||
'version' => '1.10.0.0',
|
||||
'reference' => '67b192b6a42ec03944b972d6e633ddec78ad2c6d',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../phpoption/phpoption',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'psr/container' => array(
|
||||
'pretty_version' => '2.0.2',
|
||||
'version' => '2.0.2.0',
|
||||
'reference' => 'c71ecc56dfe541dbd90c5360474fbc405f8d5963',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../psr/container',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'psr/event-dispatcher' => array(
|
||||
'pretty_version' => '1.0.0',
|
||||
'version' => '1.0.0.0',
|
||||
'reference' => 'dbefd12671e8a14ec7f180cab83036ed26714bb0',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../psr/event-dispatcher',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'psr/http-client' => array(
|
||||
'pretty_version' => '1.0.3',
|
||||
'version' => '1.0.3.0',
|
||||
'reference' => 'bb5906edc1c324c9a05aa0873d40117941e5fa90',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../psr/http-client',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'psr/http-client-implementation' => array(
|
||||
'dev_requirement' => false,
|
||||
'provided' => array(
|
||||
0 => '1.0',
|
||||
),
|
||||
),
|
||||
'psr/http-factory' => array(
|
||||
'pretty_version' => '1.1.0',
|
||||
'version' => '1.1.0.0',
|
||||
'reference' => '2b4765fddfe3b508ac62f829e852b1501d3f6e8a',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../psr/http-factory',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'psr/http-factory-implementation' => array(
|
||||
'dev_requirement' => false,
|
||||
'provided' => array(
|
||||
0 => '1.1',
|
||||
),
|
||||
),
|
||||
'psr/http-message' => array(
|
||||
'pretty_version' => '2.0',
|
||||
'version' => '2.0.0.0',
|
||||
'reference' => '402d35bcb92c70c026d1a6a9883f06b2ead23d71',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../psr/http-message',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'psr/http-message-implementation' => array(
|
||||
'dev_requirement' => false,
|
||||
'provided' => array(
|
||||
0 => '2.0',
|
||||
),
|
||||
),
|
||||
'psr/log' => array(
|
||||
'pretty_version' => '3.0.2',
|
||||
'version' => '3.0.2.0',
|
||||
'reference' => 'f16e1d5863e37f8d8c2a01719f5b34baa2b714d3',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../psr/log',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'psr/log-implementation' => array(
|
||||
'dev_requirement' => false,
|
||||
'provided' => array(
|
||||
0 => '3.0.0',
|
||||
),
|
||||
),
|
||||
'symfony/deprecation-contracts' => array(
|
||||
'pretty_version' => 'v3.8.1',
|
||||
'version' => '3.8.1.0',
|
||||
'reference' => 'feb1edf4e546af3b85c5caebe8359a20db230ca3',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../symfony/deprecation-contracts',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'symfony/polyfill-ctype' => array(
|
||||
'pretty_version' => 'v1.37.0',
|
||||
'version' => '1.37.0.0',
|
||||
'reference' => '141046a8f9477948ff284fa65be2095baafb94f2',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../symfony/polyfill-ctype',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'symfony/polyfill-mbstring' => array(
|
||||
'pretty_version' => 'v1.43.3',
|
||||
'version' => '1.43.3.0',
|
||||
'reference' => '122889ed24dc000165bcbfd77ec412f15cbdfc6a',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../symfony/polyfill-mbstring',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'symfony/polyfill-php80' => array(
|
||||
'pretty_version' => 'v1.43.0',
|
||||
'version' => '1.43.0.0',
|
||||
'reference' => '9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../symfony/polyfill-php80',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'symfony/polyfill-php82' => array(
|
||||
'pretty_version' => 'v1.43.0',
|
||||
'version' => '1.43.0.0',
|
||||
'reference' => '843bbe8b2a7934307b749751eede0f111f5d1cfc',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../symfony/polyfill-php82',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'vlucas/phpdotenv' => array(
|
||||
'pretty_version' => 'v5.8.1',
|
||||
'version' => '5.8.1.0',
|
||||
'reference' => 'ba37876e98122ca15151247ce1187d20ee8bf4e0',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../vlucas/phpdotenv',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'workerman/coroutine' => array(
|
||||
'pretty_version' => 'v1.1.7',
|
||||
'version' => '1.1.7.0',
|
||||
'reference' => '68a905d50f7ec1efcedc1ec317a75dcc3dea3f0f',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../workerman/coroutine',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'workerman/webman-framework' => array(
|
||||
'pretty_version' => 'v2.2.5',
|
||||
'version' => '2.2.5.0',
|
||||
'reference' => '263ef955d8ba6a0cb6fbc1bd0912589ed67c0c8d',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../workerman/webman-framework',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'workerman/workerman' => array(
|
||||
'pretty_version' => 'v5.2.4',
|
||||
'version' => '5.2.4.0',
|
||||
'reference' => '4c817dec82c9ea223879b019600db58f62199abc',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../workerman/workerman',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
),
|
||||
);
|
||||
Vendored
+26
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
// platform_check.php @generated by Composer
|
||||
|
||||
$issues = array();
|
||||
|
||||
if (!(PHP_VERSION_ID >= 80200)) {
|
||||
$issues[] = 'Your Composer dependencies require a PHP version ">= 8.2.0". You are running ' . PHP_VERSION . '.';
|
||||
}
|
||||
|
||||
if ($issues) {
|
||||
if (!headers_sent()) {
|
||||
header('HTTP/1.1 500 Internal Server Error');
|
||||
}
|
||||
if (!ini_get('display_errors')) {
|
||||
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
|
||||
fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
|
||||
} elseif (!headers_sent()) {
|
||||
echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
|
||||
}
|
||||
}
|
||||
trigger_error(
|
||||
'Composer detected issues in your platform: ' . implode(' ', $issues),
|
||||
E_USER_ERROR
|
||||
);
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [3.0.3] - 2024-07-08
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed PHP 8.4 deprecation notices (#47)
|
||||
|
||||
## [3.0.2] - 2022-10-27
|
||||
|
||||
### Fixed
|
||||
|
||||
- Added missing return types to docblocks (#44, #45)
|
||||
|
||||
## [3.0.1] - 2021-08-13
|
||||
|
||||
### Added
|
||||
|
||||
- Adds ReturnTypeWillChange to suppress PHP 8.1 warnings (#40)
|
||||
|
||||
## [3.0.0] - 2021-01-01
|
||||
|
||||
### Added
|
||||
- Added support for both `.` and `/`-delimited key paths (#24)
|
||||
- Added parameter and return types to everything; enabled strict type checks (#18)
|
||||
- Added new exception classes to better identify certain types of errors (#20)
|
||||
- `Data` now implements `ArrayAccess` (#17)
|
||||
- Added ability to merge non-associative array values (#31, #32)
|
||||
|
||||
### Changed
|
||||
- All thrown exceptions are now instances or subclasses of `DataException` (#20)
|
||||
- Calling `get()` on a missing key path without providing a default will throw a `MissingPathException` instead of returning `null` (#29)
|
||||
- Bumped supported PHP versions to 7.1 - 8.x (#18)
|
||||
|
||||
### Fixed
|
||||
- Fixed incorrect merging of array values into string values (#32)
|
||||
- Fixed `get()` method behaving as if keys with `null` values didn't exist
|
||||
|
||||
## [2.0.0] - 2017-12-21
|
||||
|
||||
### Changed
|
||||
- Bumped supported PHP versions to 7.0 - 7.4 (#12)
|
||||
- Switched to PSR-4 autoloading
|
||||
|
||||
## [1.1.0] - 2017-01-20
|
||||
|
||||
### Added
|
||||
- Added new `has()` method to check for the existence of the given key (#4, #7)
|
||||
|
||||
## [1.0.1] - 2015-08-12
|
||||
|
||||
### Added
|
||||
- Added new optional `$default` parameter to the `get()` method (#2)
|
||||
|
||||
## [1.0.0] - 2012-07-17
|
||||
|
||||
**Initial release!**
|
||||
|
||||
[Unreleased]: https://github.com/dflydev/dflydev-dot-access-data/compare/v3.0.3...main
|
||||
[3.0.3]: https://github.com/dflydev/dflydev-dot-access-data/compare/v3.0.2...v3.0.3
|
||||
[3.0.2]: https://github.com/dflydev/dflydev-dot-access-data/compare/v3.0.1...v3.0.2
|
||||
[3.0.1]: https://github.com/dflydev/dflydev-dot-access-data/compare/v3.0.0...v3.0.1
|
||||
[3.0.0]: https://github.com/dflydev/dflydev-dot-access-data/compare/v2.0.0...v3.0.0
|
||||
[2.0.0]: https://github.com/dflydev/dflydev-dot-access-data/compare/v1.1.0...v2.0.0
|
||||
[1.1.0]: https://github.com/dflydev/dflydev-dot-access-data/compare/v1.0.1...v1.1.0
|
||||
[1.0.1]: https://github.com/dflydev/dflydev-dot-access-data/compare/v1.0.0...v1.0.1
|
||||
[1.0.0]: https://github.com/dflydev/dflydev-dot-access-data/releases/tag/v1.0.0
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
Copyright (c) 2012 Dragonfly Development Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is furnished
|
||||
to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
Dot Access Data
|
||||
===============
|
||||
|
||||
[](https://packagist.org/packages/dflydev/dot-access-data)
|
||||
[](https://packagist.org/packages/dflydev/dot-access-data)
|
||||
[](LICENSE)
|
||||
[](https://github.com/dflydev/dflydev-dot-access-data/actions?query=workflow%3ATests+branch%3Amain)
|
||||
[](https://scrutinizer-ci.com/g/dflydev/dflydev-dot-access-data/code-structure/)
|
||||
[](https://scrutinizer-ci.com/g/dflydev/dflydev-dot-access-data)
|
||||
|
||||
Given a deep data structure, access data by dot notation.
|
||||
|
||||
|
||||
Requirements
|
||||
------------
|
||||
|
||||
* PHP (7.1+)
|
||||
|
||||
> For PHP (5.3+) please refer to version `1.0`.
|
||||
|
||||
|
||||
Usage
|
||||
-----
|
||||
|
||||
Abstract example:
|
||||
|
||||
```php
|
||||
use Dflydev\DotAccessData\Data;
|
||||
|
||||
$data = new Data;
|
||||
|
||||
$data->set('a.b.c', 'C');
|
||||
$data->set('a.b.d', 'D1');
|
||||
$data->append('a.b.d', 'D2');
|
||||
$data->set('a.b.e', ['E0', 'E1', 'E2']);
|
||||
|
||||
// C
|
||||
$data->get('a.b.c');
|
||||
|
||||
// ['D1', 'D2']
|
||||
$data->get('a.b.d');
|
||||
|
||||
// ['E0', 'E1', 'E2']
|
||||
$data->get('a.b.e');
|
||||
|
||||
// true
|
||||
$data->has('a.b.c');
|
||||
|
||||
// false
|
||||
$data->has('a.b.d.j');
|
||||
|
||||
|
||||
// 'some-default-value'
|
||||
$data->get('some.path.that.does.not.exist', 'some-default-value');
|
||||
|
||||
// throws a MissingPathException because no default was given
|
||||
$data->get('some.path.that.does.not.exist');
|
||||
```
|
||||
|
||||
A more concrete example:
|
||||
|
||||
```php
|
||||
use Dflydev\DotAccessData\Data;
|
||||
|
||||
$data = new Data([
|
||||
'hosts' => [
|
||||
'hewey' => [
|
||||
'username' => 'hman',
|
||||
'password' => 'HPASS',
|
||||
'roles' => ['web'],
|
||||
],
|
||||
'dewey' => [
|
||||
'username' => 'dman',
|
||||
'password' => 'D---S',
|
||||
'roles' => ['web', 'db'],
|
||||
'nick' => 'dewey dman',
|
||||
],
|
||||
'lewey' => [
|
||||
'username' => 'lman',
|
||||
'password' => 'LP@$$',
|
||||
'roles' => ['db'],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
// hman
|
||||
$username = $data->get('hosts.hewey.username');
|
||||
// HPASS
|
||||
$password = $data->get('hosts.hewey.password');
|
||||
// ['web']
|
||||
$roles = $data->get('hosts.hewey.roles');
|
||||
// dewey dman
|
||||
$nick = $data->get('hosts.dewey.nick');
|
||||
// Unknown
|
||||
$nick = $data->get('hosts.lewey.nick', 'Unknown');
|
||||
|
||||
// DataInterface instance
|
||||
$dewey = $data->getData('hosts.dewey');
|
||||
// dman
|
||||
$username = $dewey->get('username');
|
||||
// D---S
|
||||
$password = $dewey->get('password');
|
||||
// ['web', 'db']
|
||||
$roles = $dewey->get('roles');
|
||||
|
||||
// No more lewey
|
||||
$data->remove('hosts.lewey');
|
||||
|
||||
// Add DB to hewey's roles
|
||||
$data->append('hosts.hewey.roles', 'db');
|
||||
|
||||
$data->set('hosts.april', [
|
||||
'username' => 'aman',
|
||||
'password' => '@---S',
|
||||
'roles' => ['web'],
|
||||
]);
|
||||
|
||||
// Check if a key exists (true to this case)
|
||||
$hasKey = $data->has('hosts.dewey.username');
|
||||
```
|
||||
|
||||
`Data` may be used as an array, since it implements `ArrayAccess` interface:
|
||||
|
||||
```php
|
||||
// Get
|
||||
$data->get('name') === $data['name']; // true
|
||||
|
||||
$data['name'] = 'Dewey';
|
||||
// is equivalent to
|
||||
$data->set($name, 'Dewey');
|
||||
|
||||
isset($data['name']) === $data->has('name');
|
||||
|
||||
// Remove key
|
||||
unset($data['name']);
|
||||
```
|
||||
|
||||
`/` can also be used as a path delimiter:
|
||||
|
||||
```php
|
||||
$data->set('a/b/c', 'd');
|
||||
echo $data->get('a/b/c'); // "d"
|
||||
|
||||
$data->get('a/b/c') === $data->get('a.b.c'); // true
|
||||
```
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
This library is licensed under the MIT License - see the LICENSE file
|
||||
for details.
|
||||
|
||||
|
||||
Community
|
||||
---------
|
||||
|
||||
If you have questions or want to help out, join us in the
|
||||
[#dflydev](irc://irc.freenode.net/#dflydev) channel on irc.freenode.net.
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"name": "dflydev/dot-access-data",
|
||||
"type": "library",
|
||||
"description": "Given a deep data structure, access data by dot notation.",
|
||||
"homepage": "https://github.com/dflydev/dflydev-dot-access-data",
|
||||
"keywords": ["dot", "access", "data", "notation"],
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Dragonfly Development Inc.",
|
||||
"email": "info@dflydev.com",
|
||||
"homepage": "http://dflydev.com"
|
||||
},
|
||||
{
|
||||
"name": "Beau Simensen",
|
||||
"email": "beau@dflydev.com",
|
||||
"homepage": "http://beausimensen.com"
|
||||
},
|
||||
{
|
||||
"name": "Carlos Frutos",
|
||||
"email": "carlos@kiwing.it",
|
||||
"homepage": "https://github.com/cfrutos"
|
||||
},
|
||||
{
|
||||
"name": "Colin O'Dell",
|
||||
"email": "colinodell@gmail.com",
|
||||
"homepage": "https://www.colinodell.com"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^7.1 || ^8.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpstan/phpstan": "^0.12.42",
|
||||
"phpunit/phpunit": "^7.5 || ^8.5 || ^9.3",
|
||||
"scrutinizer/ocular": "1.6.0",
|
||||
"squizlabs/php_codesniffer": "^3.5",
|
||||
"vimeo/psalm": "^4.0.0"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Dflydev\\DotAccessData\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"Dflydev\\DotAccessData\\": "tests/"
|
||||
}
|
||||
},
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-main": "3.x-dev"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"phpcs": "phpcs",
|
||||
"phpstan": "phpstan analyse",
|
||||
"phpunit": "phpunit --no-coverage",
|
||||
"psalm": "psalm",
|
||||
"test": [
|
||||
"@phpcs",
|
||||
"@phpstan",
|
||||
"@psalm",
|
||||
"@phpunit"
|
||||
]
|
||||
}
|
||||
}
|
||||
+286
@@ -0,0 +1,286 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* This file is a part of dflydev/dot-access-data.
|
||||
*
|
||||
* (c) Dragonfly Development Inc.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Dflydev\DotAccessData;
|
||||
|
||||
use ArrayAccess;
|
||||
use Dflydev\DotAccessData\Exception\DataException;
|
||||
use Dflydev\DotAccessData\Exception\InvalidPathException;
|
||||
use Dflydev\DotAccessData\Exception\MissingPathException;
|
||||
|
||||
/**
|
||||
* @implements ArrayAccess<string, mixed>
|
||||
*/
|
||||
class Data implements DataInterface, ArrayAccess
|
||||
{
|
||||
private const DELIMITERS = ['.', '/'];
|
||||
|
||||
/**
|
||||
* Internal representation of data data
|
||||
*
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
protected $data;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public function __construct(array $data = [])
|
||||
{
|
||||
$this->data = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function append(string $key, $value = null): void
|
||||
{
|
||||
$currentValue =& $this->data;
|
||||
$keyPath = self::keyToPathArray($key);
|
||||
|
||||
$endKey = array_pop($keyPath);
|
||||
foreach ($keyPath as $currentKey) {
|
||||
if (! isset($currentValue[$currentKey])) {
|
||||
$currentValue[$currentKey] = [];
|
||||
}
|
||||
$currentValue =& $currentValue[$currentKey];
|
||||
}
|
||||
|
||||
if (!isset($currentValue[$endKey])) {
|
||||
$currentValue[$endKey] = [];
|
||||
}
|
||||
|
||||
if (!is_array($currentValue[$endKey])) {
|
||||
// Promote this key to an array.
|
||||
// TODO: Is this really what we want to do?
|
||||
$currentValue[$endKey] = [$currentValue[$endKey]];
|
||||
}
|
||||
|
||||
$currentValue[$endKey][] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function set(string $key, $value = null): void
|
||||
{
|
||||
$currentValue =& $this->data;
|
||||
$keyPath = self::keyToPathArray($key);
|
||||
|
||||
$endKey = array_pop($keyPath);
|
||||
foreach ($keyPath as $currentKey) {
|
||||
if (!isset($currentValue[$currentKey])) {
|
||||
$currentValue[$currentKey] = [];
|
||||
}
|
||||
if (!is_array($currentValue[$currentKey])) {
|
||||
throw new DataException(sprintf('Key path "%s" within "%s" cannot be indexed into (is not an array)', $currentKey, self::formatPath($key)));
|
||||
}
|
||||
$currentValue =& $currentValue[$currentKey];
|
||||
}
|
||||
$currentValue[$endKey] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function remove(string $key): void
|
||||
{
|
||||
$currentValue =& $this->data;
|
||||
$keyPath = self::keyToPathArray($key);
|
||||
|
||||
$endKey = array_pop($keyPath);
|
||||
foreach ($keyPath as $currentKey) {
|
||||
if (!isset($currentValue[$currentKey])) {
|
||||
return;
|
||||
}
|
||||
$currentValue =& $currentValue[$currentKey];
|
||||
}
|
||||
unset($currentValue[$endKey]);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @psalm-mutation-free
|
||||
*/
|
||||
public function get(string $key, $default = null)
|
||||
{
|
||||
/** @psalm-suppress ImpureFunctionCall */
|
||||
$hasDefault = \func_num_args() > 1;
|
||||
|
||||
$currentValue = $this->data;
|
||||
$keyPath = self::keyToPathArray($key);
|
||||
|
||||
foreach ($keyPath as $currentKey) {
|
||||
if (!is_array($currentValue) || !array_key_exists($currentKey, $currentValue)) {
|
||||
if ($hasDefault) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
throw new MissingPathException($key, sprintf('No data exists at the given path: "%s"', self::formatPath($keyPath)));
|
||||
}
|
||||
|
||||
$currentValue = $currentValue[$currentKey];
|
||||
}
|
||||
|
||||
return $currentValue === null ? $default : $currentValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @psalm-mutation-free
|
||||
*/
|
||||
public function has(string $key): bool
|
||||
{
|
||||
$currentValue = $this->data;
|
||||
|
||||
foreach (self::keyToPathArray($key) as $currentKey) {
|
||||
if (
|
||||
!is_array($currentValue) ||
|
||||
!array_key_exists($currentKey, $currentValue)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
$currentValue = $currentValue[$currentKey];
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @psalm-mutation-free
|
||||
*/
|
||||
public function getData(string $key): DataInterface
|
||||
{
|
||||
$value = $this->get($key);
|
||||
if (is_array($value) && Util::isAssoc($value)) {
|
||||
return new Data($value);
|
||||
}
|
||||
|
||||
throw new DataException(sprintf('Value at "%s" could not be represented as a DataInterface', self::formatPath($key)));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function import(array $data, int $mode = self::REPLACE): void
|
||||
{
|
||||
$this->data = Util::mergeAssocArray($this->data, $data, $mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function importData(DataInterface $data, int $mode = self::REPLACE): void
|
||||
{
|
||||
$this->import($data->export(), $mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @psalm-mutation-free
|
||||
*/
|
||||
public function export(): array
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function offsetExists($key)
|
||||
{
|
||||
return $this->has($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function offsetGet($key)
|
||||
{
|
||||
return $this->get($key, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function offsetSet($key, $value)
|
||||
{
|
||||
$this->set($key, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function offsetUnset($key)
|
||||
{
|
||||
$this->remove($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $path
|
||||
*
|
||||
* @return string[]
|
||||
*
|
||||
* @psalm-return non-empty-list<string>
|
||||
*
|
||||
* @psalm-pure
|
||||
*/
|
||||
protected static function keyToPathArray(string $path): array
|
||||
{
|
||||
if (\strlen($path) === 0) {
|
||||
throw new InvalidPathException('Path cannot be an empty string');
|
||||
}
|
||||
|
||||
$path = \str_replace(self::DELIMITERS, '.', $path);
|
||||
|
||||
return \explode('.', $path);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|string[] $path
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @psalm-pure
|
||||
*/
|
||||
protected static function formatPath($path): string
|
||||
{
|
||||
if (is_string($path)) {
|
||||
$path = self::keyToPathArray($path);
|
||||
}
|
||||
|
||||
return implode(' » ', $path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* This file is a part of dflydev/dot-access-data.
|
||||
*
|
||||
* (c) Dragonfly Development Inc.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Dflydev\DotAccessData;
|
||||
|
||||
use Dflydev\DotAccessData\Exception\DataException;
|
||||
use Dflydev\DotAccessData\Exception\InvalidPathException;
|
||||
|
||||
interface DataInterface
|
||||
{
|
||||
public const PRESERVE = 0;
|
||||
public const REPLACE = 1;
|
||||
public const MERGE = 2;
|
||||
|
||||
/**
|
||||
* Append a value to a key (assumes key refers to an array value)
|
||||
*
|
||||
* If the key does not yet exist it will be created.
|
||||
* If the key references a non-array it's existing contents will be added into a new array before appending the new value.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
*
|
||||
* @throws InvalidPathException if the given key is empty
|
||||
*/
|
||||
public function append(string $key, $value = null): void;
|
||||
|
||||
/**
|
||||
* Set a value for a key
|
||||
*
|
||||
* If the key does not yet exist it will be created.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
*
|
||||
* @throws InvalidPathException if the given key is empty
|
||||
* @throws DataException if the given key does not target an array
|
||||
*/
|
||||
public function set(string $key, $value = null): void;
|
||||
|
||||
/**
|
||||
* Remove a key
|
||||
*
|
||||
* No exception will be thrown if the key does not exist
|
||||
*
|
||||
* @param string $key
|
||||
*
|
||||
* @throws InvalidPathException if the given key is empty
|
||||
*/
|
||||
public function remove(string $key): void;
|
||||
|
||||
/**
|
||||
* Get the raw value for a key
|
||||
*
|
||||
* If the key does not exist, an optional default value can be returned instead.
|
||||
* If no default is provided then an exception will be thrown instead.
|
||||
*
|
||||
* @param string $key
|
||||
* @param mixed $default
|
||||
*
|
||||
* @return mixed
|
||||
*
|
||||
* @throws InvalidPathException if the given key is empty
|
||||
* @throws InvalidPathException if the given key does not exist and no default value was given
|
||||
*
|
||||
* @psalm-mutation-free
|
||||
*/
|
||||
public function get(string $key, $default = null);
|
||||
|
||||
/**
|
||||
* Check if the key exists
|
||||
*
|
||||
* @param string $key
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @throws InvalidPathException if the given key is empty
|
||||
*
|
||||
* @psalm-mutation-free
|
||||
*/
|
||||
public function has(string $key): bool;
|
||||
|
||||
/**
|
||||
* Get a data instance for a key
|
||||
*
|
||||
* @param string $key
|
||||
*
|
||||
* @return DataInterface
|
||||
*
|
||||
* @throws InvalidPathException if the given key is empty
|
||||
* @throws DataException if the given key does not reference an array
|
||||
*
|
||||
* @psalm-mutation-free
|
||||
*/
|
||||
public function getData(string $key): DataInterface;
|
||||
|
||||
/**
|
||||
* Import data into existing data
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @param self::PRESERVE|self::REPLACE|self::MERGE $mode
|
||||
*/
|
||||
public function import(array $data, int $mode = self::REPLACE): void;
|
||||
|
||||
/**
|
||||
* Import data from an external data into existing data
|
||||
*
|
||||
* @param DataInterface $data
|
||||
* @param self::PRESERVE|self::REPLACE|self::MERGE $mode
|
||||
*/
|
||||
public function importData(DataInterface $data, int $mode = self::REPLACE): void;
|
||||
|
||||
/**
|
||||
* Export data as raw data
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*
|
||||
* @psalm-mutation-free
|
||||
*/
|
||||
public function export(): array;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* This file is a part of dflydev/dot-access-data.
|
||||
*
|
||||
* (c) Dragonfly Development Inc.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Dflydev\DotAccessData\Exception;
|
||||
|
||||
/**
|
||||
* Base runtime exception type thrown by this library
|
||||
*/
|
||||
class DataException extends \RuntimeException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* This file is a part of dflydev/dot-access-data.
|
||||
*
|
||||
* (c) Dragonfly Development Inc.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Dflydev\DotAccessData\Exception;
|
||||
|
||||
/**
|
||||
* Thrown when trying to access an invalid path in the data array
|
||||
*/
|
||||
class InvalidPathException extends DataException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* This file is a part of dflydev/dot-access-data.
|
||||
*
|
||||
* (c) Dragonfly Development Inc.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Dflydev\DotAccessData\Exception;
|
||||
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Thrown when trying to access a path that does not exist
|
||||
*/
|
||||
class MissingPathException extends DataException
|
||||
{
|
||||
/** @var string */
|
||||
protected $path;
|
||||
|
||||
public function __construct(string $path, string $message = '', int $code = 0, ?Throwable $previous = null)
|
||||
{
|
||||
$this->path = $path;
|
||||
|
||||
parent::__construct($message, $code, $previous);
|
||||
}
|
||||
|
||||
public function getPath(): string
|
||||
{
|
||||
return $this->path;
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* This file is a part of dflydev/dot-access-data.
|
||||
*
|
||||
* (c) Dragonfly Development Inc.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Dflydev\DotAccessData;
|
||||
|
||||
class Util
|
||||
{
|
||||
/**
|
||||
* Test if array is an associative array
|
||||
*
|
||||
* Note that this function will return true if an array is empty. Meaning
|
||||
* empty arrays will be treated as if they are associative arrays.
|
||||
*
|
||||
* @param array<mixed> $arr
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @psalm-pure
|
||||
*/
|
||||
public static function isAssoc(array $arr): bool
|
||||
{
|
||||
return !count($arr) || count(array_filter(array_keys($arr), 'is_string')) == count($arr);
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge contents from one associtative array to another
|
||||
*
|
||||
* @param mixed $to
|
||||
* @param mixed $from
|
||||
* @param DataInterface::PRESERVE|DataInterface::REPLACE|DataInterface::MERGE $mode
|
||||
*
|
||||
* @return mixed
|
||||
*
|
||||
* @psalm-pure
|
||||
*/
|
||||
public static function mergeAssocArray($to, $from, int $mode = DataInterface::REPLACE)
|
||||
{
|
||||
if ($mode === DataInterface::MERGE && self::isList($to) && self::isList($from)) {
|
||||
return array_merge($to, $from);
|
||||
}
|
||||
|
||||
if (is_array($from) && is_array($to)) {
|
||||
foreach ($from as $k => $v) {
|
||||
if (!isset($to[$k])) {
|
||||
$to[$k] = $v;
|
||||
} else {
|
||||
$to[$k] = self::mergeAssocArray($to[$k], $v, $mode);
|
||||
}
|
||||
}
|
||||
|
||||
return $to;
|
||||
}
|
||||
|
||||
return $mode === DataInterface::PRESERVE ? $to : $from;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @psalm-pure
|
||||
*/
|
||||
private static function isList($value): bool
|
||||
{
|
||||
return is_array($value) && array_values($value) === $value;
|
||||
}
|
||||
}
|
||||
Vendored
+272
@@ -0,0 +1,272 @@
|
||||
# Changelog
|
||||
|
||||
## [7.1.1](https://github.com/googleapis/php-jwt/compare/v7.1.0...v7.1.1) (2026-09-02)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Limit the number of segments a JWT can be exploded into ([#639](https://github.com/googleapis/php-jwt/issues/639)) ([93d248c](https://github.com/googleapis/php-jwt/commit/93d248c650aea615d74a5ffa20c91c7a818e9b8d))
|
||||
|
||||
## [7.1.0](https://github.com/googleapis/php-jwt/compare/v7.0.5...v7.1.0) (2026-06-11)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Add support for PS256 ([#637](https://github.com/googleapis/php-jwt/issues/637)) ([aa0b447](https://github.com/googleapis/php-jwt/commit/aa0b4472c137255545b177a1840891304eac55f1))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Skip parsing valid unsupported curves ([#638](https://github.com/googleapis/php-jwt/issues/638)) ([8a6c2a7](https://github.com/googleapis/php-jwt/commit/8a6c2a75d7f45e781c93d618939f8a045fe69f53))
|
||||
* Update homepage URL in composer.json ([#635](https://github.com/googleapis/php-jwt/issues/635)) ([f7ae571](https://github.com/googleapis/php-jwt/commit/f7ae571efe255aed89c8f8d0f2cb7f71c5835664))
|
||||
* Validate numeric type of iat, nbf and exp claims in encode ([#634](https://github.com/googleapis/php-jwt/issues/634)) ([958e422](https://github.com/googleapis/php-jwt/commit/958e422961e874843a7fcc339e55a0101a66201d))
|
||||
|
||||
## [7.0.5](https://github.com/firebase/php-jwt/compare/v7.0.4...v7.0.5) (2026-03-31)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* RSA from JWK sometimes returns empty Instance ([#628](https://github.com/firebase/php-jwt/issues/628)) ([b4c78aa](https://github.com/firebase/php-jwt/commit/b4c78aa731664122198ad36c0033aa29e807397a))
|
||||
|
||||
## [7.0.4](https://github.com/firebase/php-jwt/compare/v7.0.3...v7.0.4) (2026-03-27)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* readme examples, add tests for all examples ([#626](https://github.com/firebase/php-jwt/issues/626)) ([510a00c](https://github.com/firebase/php-jwt/commit/510a00c0e6353bc7d68412fab67e57a13954cb46))
|
||||
* use urlsafeB64Decode everywhere ([#627](https://github.com/firebase/php-jwt/issues/627)) ([b889495](https://github.com/firebase/php-jwt/commit/b889495c83ddc3f3885ca3f0b65b41b1cb37a3b1))
|
||||
|
||||
## [7.0.3](https://github.com/firebase/php-jwt/compare/v7.0.2...v7.0.3) (2026-02-18)
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* add environment for Release Please job ([#619](https://github.com/firebase/php-jwt/issues/619)) ([300fd02](https://github.com/firebase/php-jwt/commit/300fd02c883f096c9067df652dbd23f62cb5e2a7))
|
||||
|
||||
## [7.0.2](https://github.com/firebase/php-jwt/compare/v7.0.1...v7.0.2) (2025-12-16)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add key length validation for ec keys ([#615](https://github.com/firebase/php-jwt/issues/615)) ([7044f9a](https://github.com/firebase/php-jwt/commit/7044f9ae7e7d175d28cca71714feb236f1c0e252))
|
||||
|
||||
## [7.0.0](https://github.com/firebase/php-jwt/compare/v6.11.1...v7.0.0) (2025-12-15)
|
||||
|
||||
|
||||
### ⚠️ ⚠️ ⚠️ Security Fixes ⚠️ ⚠️ ⚠️
|
||||
* add key size validation ([#613](https://github.com/firebase/php-jwt/issues/613)) ([6b80341](https://github.com/firebase/php-jwt/commit/6b80341bf57838ea2d011487917337901cd71576))
|
||||
**NOTE**: This fix will cause keys with a size below the minimally allowed size to break.
|
||||
|
||||
### Features
|
||||
|
||||
* add SensitiveParameter attribute to security-critical parameters ([#603](https://github.com/firebase/php-jwt/issues/603)) ([4dbfac0](https://github.com/firebase/php-jwt/commit/4dbfac0260eeb0e9e643063c99998e3219cc539b))
|
||||
* store timestamp in `ExpiredException` ([#604](https://github.com/firebase/php-jwt/issues/604)) ([f174826](https://github.com/firebase/php-jwt/commit/f1748260d218a856b6a0c23715ac7fae1d7ca95b))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* validate iat and nbf on payload ([#568](https://github.com/firebase/php-jwt/issues/568)) ([953b2c8](https://github.com/firebase/php-jwt/commit/953b2c88bb445b7e3bb82a5141928f13d7343afd))
|
||||
|
||||
## [6.11.1](https://github.com/firebase/php-jwt/compare/v6.11.0...v6.11.1) (2025-04-09)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* update error text for consistency ([#528](https://github.com/firebase/php-jwt/issues/528)) ([c11113a](https://github.com/firebase/php-jwt/commit/c11113afa13265e016a669e75494b9203b8a7775))
|
||||
|
||||
## [6.11.0](https://github.com/firebase/php-jwt/compare/v6.10.2...v6.11.0) (2025-01-23)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* support octet typed JWK ([#587](https://github.com/firebase/php-jwt/issues/587)) ([7cb8a26](https://github.com/firebase/php-jwt/commit/7cb8a265fa81edf2fa6ef8098f5bc5ae573c33ad))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* refactor constructor Key to use PHP 8.0 syntax ([#577](https://github.com/firebase/php-jwt/issues/577)) ([29fa2ce](https://github.com/firebase/php-jwt/commit/29fa2ce9e0582cd397711eec1e80c05ce20fabca))
|
||||
|
||||
## [6.10.2](https://github.com/firebase/php-jwt/compare/v6.10.1...v6.10.2) (2024-11-24)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Mitigate PHP8.4 deprecation warnings ([#570](https://github.com/firebase/php-jwt/issues/570)) ([76808fa](https://github.com/firebase/php-jwt/commit/76808fa227f3811aa5cdb3bf81233714b799a5b5))
|
||||
* support php 8.4 ([#583](https://github.com/firebase/php-jwt/issues/583)) ([e3d68b0](https://github.com/firebase/php-jwt/commit/e3d68b044421339443c74199edd020e03fb1887e))
|
||||
|
||||
## [6.10.1](https://github.com/firebase/php-jwt/compare/v6.10.0...v6.10.1) (2024-05-18)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* ensure ratelimit expiry is set every time ([#556](https://github.com/firebase/php-jwt/issues/556)) ([09cb208](https://github.com/firebase/php-jwt/commit/09cb2081c2c3bc0f61e2f2a5fbea5741f7498648))
|
||||
* ratelimit cache expiration ([#550](https://github.com/firebase/php-jwt/issues/550)) ([dda7250](https://github.com/firebase/php-jwt/commit/dda725033585ece30ff8cae8937320d7e9f18bae))
|
||||
|
||||
## [6.10.0](https://github.com/firebase/php-jwt/compare/v6.9.0...v6.10.0) (2023-11-28)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* allow typ header override ([#546](https://github.com/firebase/php-jwt/issues/546)) ([79cb30b](https://github.com/firebase/php-jwt/commit/79cb30b729a22931b2fbd6b53f20629a83031ba9))
|
||||
|
||||
## [6.9.0](https://github.com/firebase/php-jwt/compare/v6.8.1...v6.9.0) (2023-10-04)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add payload to jwt exception ([#521](https://github.com/firebase/php-jwt/issues/521)) ([175edf9](https://github.com/firebase/php-jwt/commit/175edf958bb61922ec135b2333acf5622f2238a2))
|
||||
|
||||
## [6.8.1](https://github.com/firebase/php-jwt/compare/v6.8.0...v6.8.1) (2023-07-14)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* accept float claims but round down to ignore them ([#492](https://github.com/firebase/php-jwt/issues/492)) ([3936842](https://github.com/firebase/php-jwt/commit/39368423beeaacb3002afa7dcb75baebf204fe7e))
|
||||
* different BeforeValidException messages for nbf and iat ([#526](https://github.com/firebase/php-jwt/issues/526)) ([0a53cf2](https://github.com/firebase/php-jwt/commit/0a53cf2986e45c2bcbf1a269f313ebf56a154ee4))
|
||||
|
||||
## [6.8.0](https://github.com/firebase/php-jwt/compare/v6.7.0...v6.8.0) (2023-06-14)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add support for P-384 curve ([#515](https://github.com/firebase/php-jwt/issues/515)) ([5de4323](https://github.com/firebase/php-jwt/commit/5de4323f4baf4d70bca8663bd87682a69c656c3d))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* handle invalid http responses ([#508](https://github.com/firebase/php-jwt/issues/508)) ([91c39c7](https://github.com/firebase/php-jwt/commit/91c39c72b22fc3e1191e574089552c1f2041c718))
|
||||
|
||||
## [6.7.0](https://github.com/firebase/php-jwt/compare/v6.6.0...v6.7.0) (2023-06-14)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add ed25519 support to JWK (public keys) ([#452](https://github.com/firebase/php-jwt/issues/452)) ([e53979a](https://github.com/firebase/php-jwt/commit/e53979abae927de916a75b9d239cfda8ce32be2a))
|
||||
|
||||
## [6.6.0](https://github.com/firebase/php-jwt/compare/v6.5.0...v6.6.0) (2023-06-13)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* allow get headers when decoding token ([#442](https://github.com/firebase/php-jwt/issues/442)) ([fb85f47](https://github.com/firebase/php-jwt/commit/fb85f47cfaeffdd94faf8defdf07164abcdad6c3))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* only check iat if nbf is not used ([#493](https://github.com/firebase/php-jwt/issues/493)) ([398ccd2](https://github.com/firebase/php-jwt/commit/398ccd25ea12fa84b9e4f1085d5ff448c21ec797))
|
||||
|
||||
## [6.5.0](https://github.com/firebase/php-jwt/compare/v6.4.0...v6.5.0) (2023-05-12)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* allow KID of '0' ([#505](https://github.com/firebase/php-jwt/issues/505)) ([9dc46a9](https://github.com/firebase/php-jwt/commit/9dc46a9c3e5801294249cfd2554c5363c9f9326a))
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* drop support for PHP 7.3 ([#495](https://github.com/firebase/php-jwt/issues/495))
|
||||
|
||||
## [6.4.0](https://github.com/firebase/php-jwt/compare/v6.3.2...v6.4.0) (2023-02-08)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add support for W3C ES256K ([#462](https://github.com/firebase/php-jwt/issues/462)) ([213924f](https://github.com/firebase/php-jwt/commit/213924f51936291fbbca99158b11bd4ae56c2c95))
|
||||
* improve caching by only decoding jwks when necessary ([#486](https://github.com/firebase/php-jwt/issues/486)) ([78d3ed1](https://github.com/firebase/php-jwt/commit/78d3ed1073553f7d0bbffa6c2010009a0d483d5c))
|
||||
|
||||
## [6.3.2](https://github.com/firebase/php-jwt/compare/v6.3.1...v6.3.2) (2022-11-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* check kid before using as array index ([bad1b04](https://github.com/firebase/php-jwt/commit/bad1b040d0c736bbf86814c6b5ae614f517cf7bd))
|
||||
|
||||
## [6.3.1](https://github.com/firebase/php-jwt/compare/v6.3.0...v6.3.1) (2022-11-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* casing of GET for PSR compat ([#451](https://github.com/firebase/php-jwt/issues/451)) ([60b52b7](https://github.com/firebase/php-jwt/commit/60b52b71978790eafcf3b95cfbd83db0439e8d22))
|
||||
* string interpolation format for php 8.2 ([#446](https://github.com/firebase/php-jwt/issues/446)) ([2e07d8a](https://github.com/firebase/php-jwt/commit/2e07d8a1524d12b69b110ad649f17461d068b8f2))
|
||||
|
||||
## 6.3.0 / 2022-07-15
|
||||
|
||||
- Added ES256 support to JWK parsing ([#399](https://github.com/firebase/php-jwt/pull/399))
|
||||
- Fixed potential caching error in `CachedKeySet` by caching jwks as strings ([#435](https://github.com/firebase/php-jwt/pull/435))
|
||||
|
||||
## 6.2.0 / 2022-05-14
|
||||
|
||||
- Added `CachedKeySet` ([#397](https://github.com/firebase/php-jwt/pull/397))
|
||||
- Added `$defaultAlg` parameter to `JWT::parseKey` and `JWT::parseKeySet` ([#426](https://github.com/firebase/php-jwt/pull/426)).
|
||||
|
||||
## 6.1.0 / 2022-03-23
|
||||
|
||||
- Drop support for PHP 5.3, 5.4, 5.5, 5.6, and 7.0
|
||||
- Add parameter typing and return types where possible
|
||||
|
||||
## 6.0.0 / 2022-01-24
|
||||
|
||||
- **Backwards-Compatibility Breaking Changes**: See the [Release Notes](https://github.com/firebase/php-jwt/releases/tag/v6.0.0) for more information.
|
||||
- New Key object to prevent key/algorithm type confusion (#365)
|
||||
- Add JWK support (#273)
|
||||
- Add ES256 support (#256)
|
||||
- Add ES384 support (#324)
|
||||
- Add Ed25519 support (#343)
|
||||
|
||||
## 5.0.0 / 2017-06-26
|
||||
- Support RS384 and RS512.
|
||||
See [#117](https://github.com/firebase/php-jwt/pull/117). Thanks [@joostfaassen](https://github.com/joostfaassen)!
|
||||
- Add an example for RS256 openssl.
|
||||
See [#125](https://github.com/firebase/php-jwt/pull/125). Thanks [@akeeman](https://github.com/akeeman)!
|
||||
- Detect invalid Base64 encoding in signature.
|
||||
See [#162](https://github.com/firebase/php-jwt/pull/162). Thanks [@psignoret](https://github.com/psignoret)!
|
||||
- Update `JWT::verify` to handle OpenSSL errors.
|
||||
See [#159](https://github.com/firebase/php-jwt/pull/159). Thanks [@bshaffer](https://github.com/bshaffer)!
|
||||
- Add `array` type hinting to `decode` method
|
||||
See [#101](https://github.com/firebase/php-jwt/pull/101). Thanks [@hywak](https://github.com/hywak)!
|
||||
- Add all JSON error types.
|
||||
See [#110](https://github.com/firebase/php-jwt/pull/110). Thanks [@gbalduzzi](https://github.com/gbalduzzi)!
|
||||
- Bugfix 'kid' not in given key list.
|
||||
See [#129](https://github.com/firebase/php-jwt/pull/129). Thanks [@stampycode](https://github.com/stampycode)!
|
||||
- Miscellaneous cleanup, documentation and test fixes.
|
||||
See [#107](https://github.com/firebase/php-jwt/pull/107), [#115](https://github.com/firebase/php-jwt/pull/115),
|
||||
[#160](https://github.com/firebase/php-jwt/pull/160), [#161](https://github.com/firebase/php-jwt/pull/161), and
|
||||
[#165](https://github.com/firebase/php-jwt/pull/165). Thanks [@akeeman](https://github.com/akeeman),
|
||||
[@chinedufn](https://github.com/chinedufn), and [@bshaffer](https://github.com/bshaffer)!
|
||||
|
||||
## 4.0.0 / 2016-07-17
|
||||
- Add support for late static binding. See [#88](https://github.com/firebase/php-jwt/pull/88) for details. Thanks to [@chappy84](https://github.com/chappy84)!
|
||||
- Use static `$timestamp` instead of `time()` to improve unit testing. See [#93](https://github.com/firebase/php-jwt/pull/93) for details. Thanks to [@josephmcdermott](https://github.com/josephmcdermott)!
|
||||
- Fixes to exceptions classes. See [#81](https://github.com/firebase/php-jwt/pull/81) for details. Thanks to [@Maks3w](https://github.com/Maks3w)!
|
||||
- Fixes to PHPDoc. See [#76](https://github.com/firebase/php-jwt/pull/76) for details. Thanks to [@akeeman](https://github.com/akeeman)!
|
||||
|
||||
## 3.0.0 / 2015-07-22
|
||||
- Minimum PHP version updated from `5.2.0` to `5.3.0`.
|
||||
- Add `\Firebase\JWT` namespace. See
|
||||
[#59](https://github.com/firebase/php-jwt/pull/59) for details. Thanks to
|
||||
[@Dashron](https://github.com/Dashron)!
|
||||
- Require a non-empty key to decode and verify a JWT. See
|
||||
[#60](https://github.com/firebase/php-jwt/pull/60) for details. Thanks to
|
||||
[@sjones608](https://github.com/sjones608)!
|
||||
- Cleaner documentation blocks in the code. See
|
||||
[#62](https://github.com/firebase/php-jwt/pull/62) for details. Thanks to
|
||||
[@johanderuijter](https://github.com/johanderuijter)!
|
||||
|
||||
## 2.2.0 / 2015-06-22
|
||||
- Add support for adding custom, optional JWT headers to `JWT::encode()`. See
|
||||
[#53](https://github.com/firebase/php-jwt/pull/53/files) for details. Thanks to
|
||||
[@mcocaro](https://github.com/mcocaro)!
|
||||
|
||||
## 2.1.0 / 2015-05-20
|
||||
- Add support for adding a leeway to `JWT:decode()` that accounts for clock skew
|
||||
between signing and verifying entities. Thanks to [@lcabral](https://github.com/lcabral)!
|
||||
- Add support for passing an object implementing the `ArrayAccess` interface for
|
||||
`$keys` argument in `JWT::decode()`. Thanks to [@aztech-dev](https://github.com/aztech-dev)!
|
||||
|
||||
## 2.0.0 / 2015-04-01
|
||||
- **Note**: It is strongly recommended that you update to > v2.0.0 to address
|
||||
known security vulnerabilities in prior versions when both symmetric and
|
||||
asymmetric keys are used together.
|
||||
- Update signature for `JWT::decode(...)` to require an array of supported
|
||||
algorithms to use when verifying token signatures.
|
||||
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
Copyright (c) 2011, Neuman Vong
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials provided
|
||||
with the distribution.
|
||||
|
||||
* Neither the name of the copyright holder nor the names of other
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
Vendored
+469
@@ -0,0 +1,469 @@
|
||||

|
||||
[](https://packagist.org/packages/firebase/php-jwt)
|
||||
[](https://packagist.org/packages/firebase/php-jwt)
|
||||
[](https://packagist.org/packages/firebase/php-jwt)
|
||||
|
||||
PHP-JWT
|
||||
=======
|
||||
A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519).
|
||||
|
||||
Supported Specifications
|
||||
------------------------
|
||||
|
||||
- [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519) — JSON Web Token (JWT)
|
||||
- [RFC 7515](https://datatracker.ietf.org/doc/html/rfc7515) — JSON Web Signature (JWS)
|
||||
- [RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517) — JSON Web Key (JWK)
|
||||
- [RFC 7518](https://datatracker.ietf.org/doc/html/rfc7518) — JSON Web Algorithms (JWA) (`HS256`, `HS384`, `HS512`, `RS256`, `RS384`, `RS512`, `ES256`, `ES384`, `PS256`)
|
||||
- [RFC 8037](https://datatracker.ietf.org/doc/html/rfc8037) — CFRG Elliptic Curve Diffie-Hellman (ECDH) and Signatures in JOSE (`EdDSA` / `Ed25519` and `OKP` JWKs)
|
||||
- [RFC 8812](https://datatracker.ietf.org/doc/html/rfc8812) — CBOR Object Signing and Encryption (COSE) and JSON Object Signing and Encryption (JOSE) Registrations for Web Authentication (WebAuthn) Algorithms (`ES256K` / `secp256k1`)
|
||||
|
||||
> **Note:** This library only supports signed JWTs (JWS, [RFC 7515](https://datatracker.ietf.org/doc/html/rfc7515)). Encrypted JWTs (JWE, [RFC 7516](https://datatracker.ietf.org/doc/html/rfc7516)) are not supported.
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
Use composer to manage your dependencies and download PHP-JWT:
|
||||
|
||||
```bash
|
||||
composer require firebase/php-jwt
|
||||
```
|
||||
|
||||
Optionally, install the `paragonie/sodium_compat` package from composer if your
|
||||
php env does not have libsodium installed:
|
||||
|
||||
```bash
|
||||
composer require paragonie/sodium_compat
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
|
||||
$key = 'example_key_of_sufficient_length';
|
||||
$payload = [
|
||||
'iss' => 'example.org',
|
||||
'aud' => 'example.com',
|
||||
'iat' => 1356999524,
|
||||
'nbf' => 1357000000
|
||||
];
|
||||
|
||||
/**
|
||||
* IMPORTANT:
|
||||
* You must specify supported algorithms for your application. See
|
||||
* https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
|
||||
* for a list of spec-compliant algorithms.
|
||||
*/
|
||||
$jwt = JWT::encode($payload, $key, 'HS256');
|
||||
$decoded = JWT::decode($jwt, new Key($key, 'HS256'));
|
||||
print_r($decoded);
|
||||
|
||||
// Pass a stdClass in as the third parameter to get the decoded header values
|
||||
$headers = new stdClass();
|
||||
$decoded = JWT::decode($jwt, new Key($key, 'HS256'), $headers);
|
||||
print_r($headers);
|
||||
|
||||
/*
|
||||
NOTE: This will now be an object instead of an associative array. To get
|
||||
an associative array, you will need to cast it as such:
|
||||
*/
|
||||
|
||||
$decoded_array = (array) $decoded;
|
||||
|
||||
/**
|
||||
* You can add a leeway to account for when there is a clock skew times between
|
||||
* the signing and verifying servers. It is recommended that this leeway should
|
||||
* not be bigger than a few minutes.
|
||||
*
|
||||
* Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
|
||||
*/
|
||||
JWT::$leeway = 60; // $leeway in seconds
|
||||
$decoded = JWT::decode($jwt, new Key($key, 'HS256'));
|
||||
```
|
||||
|
||||
## Example encode/decode headers
|
||||
|
||||
Decoding the JWT headers without verifying the JWT first is NOT recommended, and is not supported by
|
||||
this library. This is because without verifying the JWT, the header values could have been tampered with.
|
||||
Any value pulled from an unverified header should be treated as if it could be any string sent in from an
|
||||
attacker. If this is something you still want to do in your application for whatever reason, it's possible to
|
||||
decode the header values manually simply by calling `json_decode` and `base64_decode` on the JWT
|
||||
header part:
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
|
||||
$key = 'example_key_of_sufficient_length';
|
||||
$payload = [
|
||||
'iss' => 'example.org',
|
||||
'aud' => 'example.com',
|
||||
'iat' => 1356999524,
|
||||
'nbf' => 1357000000
|
||||
];
|
||||
|
||||
$headers = [
|
||||
'x-forwarded-for' => 'www.google.com'
|
||||
];
|
||||
|
||||
// Encode headers in the JWT string
|
||||
$jwt = JWT::encode($payload, $key, 'HS256', null, $headers);
|
||||
|
||||
// Decode headers from the JWT string WITHOUT validation
|
||||
// **IMPORTANT**: This operation is vulnerable to attacks, as the JWT has not yet been verified.
|
||||
// These headers could be any value sent by an attacker.
|
||||
list($headersB64, $payloadB64, $sig) = explode('.', $jwt);
|
||||
$decoded = json_decode(base64_decode($headersB64), true);
|
||||
|
||||
print_r($decoded);
|
||||
```
|
||||
|
||||
## Example with RS256 (openssl)
|
||||
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
|
||||
$privateKey = <<<EOD
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEowIBAAKCAQEAuzWHNM5f+amCjQztc5QTfJfzCC5J4nuW+L/aOxZ4f8J3Frew
|
||||
M2c/dufrnmedsApb0By7WhaHlcqCh/ScAPyJhzkPYLae7bTVro3hok0zDITR8F6S
|
||||
JGL42JAEUk+ILkPI+DONM0+3vzk6Kvfe548tu4czCuqU8BGVOlnp6IqBHhAswNMM
|
||||
78pos/2z0CjPM4tbeXqSTTbNkXRboxjU29vSopcT51koWOgiTf3C7nJUoMWZHZI5
|
||||
HqnIhPAG9yv8HAgNk6CMk2CadVHDo4IxjxTzTTqo1SCSH2pooJl9O8at6kkRYsrZ
|
||||
WwsKlOFE2LUce7ObnXsYihStBUDoeBQlGG/BwQIDAQABAoIBAFtGaOqNKGwggn9k
|
||||
6yzr6GhZ6Wt2rh1Xpq8XUz514UBhPxD7dFRLpbzCrLVpzY80LbmVGJ9+1pJozyWc
|
||||
VKeCeUdNwbqkr240Oe7GTFmGjDoxU+5/HX/SJYPpC8JZ9oqgEA87iz+WQX9hVoP2
|
||||
oF6EB4ckDvXmk8FMwVZW2l2/kd5mrEVbDaXKxhvUDf52iVD+sGIlTif7mBgR99/b
|
||||
c3qiCnxCMmfYUnT2eh7Vv2LhCR/G9S6C3R4lA71rEyiU3KgsGfg0d82/XWXbegJW
|
||||
h3QbWNtQLxTuIvLq5aAryV3PfaHlPgdgK0ft6ocU2de2FagFka3nfVEyC7IUsNTK
|
||||
bq6nhAECgYEA7d/0DPOIaItl/8BWKyCuAHMss47j0wlGbBSHdJIiS55akMvnAG0M
|
||||
39y22Qqfzh1at9kBFeYeFIIU82ZLF3xOcE3z6pJZ4Dyvx4BYdXH77odo9uVK9s1l
|
||||
3T3BlMcqd1hvZLMS7dviyH79jZo4CXSHiKzc7pQ2YfK5eKxKqONeXuECgYEAyXlG
|
||||
vonaus/YTb1IBei9HwaccnQ/1HRn6MvfDjb7JJDIBhNClGPt6xRlzBbSZ73c2QEC
|
||||
6Fu9h36K/HZ2qcLd2bXiNyhIV7b6tVKk+0Psoj0dL9EbhsD1OsmE1nTPyAc9XZbb
|
||||
OPYxy+dpBCUA8/1U9+uiFoCa7mIbWcSQ+39gHuECgYAz82pQfct30aH4JiBrkNqP
|
||||
nJfRq05UY70uk5k1u0ikLTRoVS/hJu/d4E1Kv4hBMqYCavFSwAwnvHUo51lVCr/y
|
||||
xQOVYlsgnwBg2MX4+GjmIkqpSVCC8D7j/73MaWb746OIYZervQ8dbKahi2HbpsiG
|
||||
8AHcVSA/agxZr38qvWV54QKBgCD5TlDE8x18AuTGQ9FjxAAd7uD0kbXNz2vUYg9L
|
||||
hFL5tyL3aAAtUrUUw4xhd9IuysRhW/53dU+FsG2dXdJu6CxHjlyEpUJl2iZu/j15
|
||||
YnMzGWHIEX8+eWRDsw/+Ujtko/B7TinGcWPz3cYl4EAOiCeDUyXnqnO1btCEUU44
|
||||
DJ1BAoGBAJuPD27ErTSVtId90+M4zFPNibFP50KprVdc8CR37BE7r8vuGgNYXmnI
|
||||
RLnGP9p3pVgFCktORuYS2J/6t84I3+A17nEoB4xvhTLeAinAW/uTQOUmNicOP4Ek
|
||||
2MsLL2kHgL8bLTmvXV4FX+PXphrDKg1XxzOYn0otuoqdAQrkK4og
|
||||
-----END RSA PRIVATE KEY-----
|
||||
EOD;
|
||||
|
||||
$publicKey = <<<EOD
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzWHNM5f+amCjQztc5QT
|
||||
fJfzCC5J4nuW+L/aOxZ4f8J3FrewM2c/dufrnmedsApb0By7WhaHlcqCh/ScAPyJ
|
||||
hzkPYLae7bTVro3hok0zDITR8F6SJGL42JAEUk+ILkPI+DONM0+3vzk6Kvfe548t
|
||||
u4czCuqU8BGVOlnp6IqBHhAswNMM78pos/2z0CjPM4tbeXqSTTbNkXRboxjU29vS
|
||||
opcT51koWOgiTf3C7nJUoMWZHZI5HqnIhPAG9yv8HAgNk6CMk2CadVHDo4IxjxTz
|
||||
TTqo1SCSH2pooJl9O8at6kkRYsrZWwsKlOFE2LUce7ObnXsYihStBUDoeBQlGG/B
|
||||
wQIDAQAB
|
||||
-----END PUBLIC KEY-----
|
||||
EOD;
|
||||
|
||||
$payload = [
|
||||
'iss' => 'example.org',
|
||||
'aud' => 'example.com',
|
||||
'iat' => 1356999524,
|
||||
'nbf' => 1357000000
|
||||
];
|
||||
|
||||
$jwt = JWT::encode($payload, $privateKey, 'RS256');
|
||||
echo "Encode:\n" . print_r($jwt, true) . "\n";
|
||||
|
||||
$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256'));
|
||||
|
||||
/*
|
||||
NOTE: This will now be an object instead of an associative array. To get
|
||||
an associative array, you will need to cast it as such:
|
||||
*/
|
||||
|
||||
$decoded_array = (array) $decoded;
|
||||
echo "Decode:\n" . print_r($decoded_array, true) . "\n";
|
||||
```
|
||||
|
||||
## Example with a passphrase
|
||||
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
|
||||
// Your passphrase
|
||||
$passphrase = '[YOUR_PASSPHRASE]';
|
||||
|
||||
// Your private key file with passphrase
|
||||
// Can be generated with "ssh-keygen -t rsa -m pem"
|
||||
$privateKeyFile = '/path/to/key-with-passphrase.pem';
|
||||
|
||||
/** @var OpenSSLAsymmetricKey $privateKey */
|
||||
$privateKey = openssl_pkey_get_private(
|
||||
file_get_contents($privateKeyFile),
|
||||
$passphrase
|
||||
);
|
||||
|
||||
$payload = [
|
||||
'iss' => 'example.org',
|
||||
'aud' => 'example.com',
|
||||
'iat' => 1356999524,
|
||||
'nbf' => 1357000000
|
||||
];
|
||||
|
||||
$jwt = JWT::encode($payload, $privateKey, 'RS256');
|
||||
echo "Encode:\n" . print_r($jwt, true) . "\n";
|
||||
|
||||
// Get public key from the private key, or pull from from a file.
|
||||
$publicKey = openssl_pkey_get_details($privateKey)['key'];
|
||||
|
||||
$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256'));
|
||||
echo "Decode:\n" . print_r((array) $decoded, true) . "\n";
|
||||
```
|
||||
|
||||
## Example with EdDSA (libsodium and Ed25519 signature)
|
||||
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
|
||||
// Public and private keys are expected to be Base64 encoded. The last
|
||||
// non-empty line is used so that keys can be generated with
|
||||
// sodium_crypto_sign_keypair(). The secret keys generated by other tools may
|
||||
// need to be adjusted to match the input expected by libsodium.
|
||||
|
||||
$keyPair = sodium_crypto_sign_keypair();
|
||||
|
||||
$privateKey = base64_encode(sodium_crypto_sign_secretkey($keyPair));
|
||||
|
||||
$publicKey = base64_encode(sodium_crypto_sign_publickey($keyPair));
|
||||
|
||||
$payload = [
|
||||
'iss' => 'example.org',
|
||||
'aud' => 'example.com',
|
||||
'iat' => 1356999524,
|
||||
'nbf' => 1357000000
|
||||
];
|
||||
|
||||
$jwt = JWT::encode($payload, $privateKey, 'EdDSA');
|
||||
echo "Encode:\n" . print_r($jwt, true) . "\n";
|
||||
|
||||
$decoded = JWT::decode($jwt, new Key($publicKey, 'EdDSA'));
|
||||
echo "Decode:\n" . print_r((array) $decoded, true) . "\n";
|
||||
```
|
||||
|
||||
## Example with multiple keys
|
||||
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
|
||||
// Example RSA keys from previous example
|
||||
// $privateRsKey = '...';
|
||||
// $publicRsKey = '...';
|
||||
|
||||
// Example EdDSA keys from previous example
|
||||
// $privateEcKey = '...';
|
||||
// $publicEcKey = '...';
|
||||
|
||||
$payload = [
|
||||
'iss' => 'example.org',
|
||||
'aud' => 'example.com',
|
||||
'iat' => 1356999524,
|
||||
'nbf' => 1357000000
|
||||
];
|
||||
|
||||
$jwt1 = JWT::encode($payload, $privateRsKey, 'RS256', 'kid1');
|
||||
$jwt2 = JWT::encode($payload, $privateEcKey, 'EdDSA', 'kid2');
|
||||
echo "Encode 1:\n" . print_r($jwt1, true) . "\n";
|
||||
echo "Encode 2:\n" . print_r($jwt2, true) . "\n";
|
||||
|
||||
$keys = [
|
||||
'kid1' => new Key($publicRsKey, 'RS256'),
|
||||
'kid2' => new Key($publicEcKey, 'EdDSA'),
|
||||
];
|
||||
|
||||
$decoded1 = JWT::decode($jwt1, $keys);
|
||||
$decoded2 = JWT::decode($jwt2, $keys);
|
||||
|
||||
echo "Decode 1:\n" . print_r((array) $decoded1, true) . "\n";
|
||||
echo "Decode 2:\n" . print_r((array) $decoded2, true) . "\n";
|
||||
```
|
||||
|
||||
## Example with PS256
|
||||
|
||||
### Note
|
||||
PHP's OpenSSL extension does not support RSASSA-PSS signatures (PS256) by default, so we provide support via a soft dependency on the [phpseclib/phpseclib](https://github.com/phpseclib/phpseclib) library. It is necessary to install this library in your project if you plan to use PS256.
|
||||
```bash
|
||||
composer install phpseclib/phpseclib:^3.0
|
||||
```
|
||||
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
|
||||
$privateRsKey = '-----BEGIN RSA PRIVATE KEY----- ...';
|
||||
$publicKey = '-----BEGIN PUBLIC KEY----- ...';
|
||||
|
||||
$payload = [
|
||||
'iss' => 'example.org',
|
||||
'aud' => 'example.com',
|
||||
'iat' => 1356999524,
|
||||
'nbf' => 1357000000
|
||||
];
|
||||
|
||||
/**
|
||||
* PS256 support requires phpseclib/phpseclib
|
||||
*/
|
||||
$jwt = JWT::encode($payload, $privateRsKey, 'PS256', 'keyid');
|
||||
echo "Encode:\n" . print_r($jwt, true) . "\n";
|
||||
|
||||
$decoded = JWT::decode($jwt, new Key($publicKey, 'PS256'));
|
||||
echo "Decode:\n" . print_r((array) $decoded, true) . "\n";
|
||||
```
|
||||
|
||||
## Using JWKs
|
||||
|
||||
```php
|
||||
use Firebase\JWT\JWK;
|
||||
use Firebase\JWT\JWT;
|
||||
|
||||
// Set of keys. The "keys" key is required. For example, the JSON response to
|
||||
// this endpoint: https://www.gstatic.com/iap/verify/public_key-jwk
|
||||
$jwks = ['keys' => []];
|
||||
|
||||
// JWK::parseKeySet($jwks) returns an associative array of **kid** to Firebase\JWT\Key
|
||||
// objects. Pass this as the second parameter to JWT::decode.
|
||||
$decoded = JWT::decode($jwt, JWK::parseKeySet($jwks));
|
||||
print_r($decoded);
|
||||
```
|
||||
|
||||
## Using Cached Key Sets
|
||||
|
||||
The `CachedKeySet` class can be used to fetch and cache JWKS (JSON Web Key Sets) from a public URI.
|
||||
This has the following advantages:
|
||||
|
||||
1. The results are cached for performance.
|
||||
2. If an unrecognized key is requested, the cache is refreshed, to accomodate for key rotation.
|
||||
3. If rate limiting is enabled, the JWKS URI will not make more than 10 requests a second.
|
||||
|
||||
```php
|
||||
use Firebase\JWT\CachedKeySet;
|
||||
use Firebase\JWT\JWT;
|
||||
|
||||
// The URI for the JWKS you wish to cache the results from
|
||||
$jwksUri = 'https://www.gstatic.com/iap/verify/public_key-jwk';
|
||||
|
||||
// Create an HTTP client (can be any PSR-7 compatible HTTP client)
|
||||
$httpClient = new GuzzleHttp\Client();
|
||||
|
||||
// Create an HTTP request factory (can be any PSR-17 compatible HTTP request factory)
|
||||
$httpFactory = new GuzzleHttp\Psr7\HttpFactory();
|
||||
|
||||
// Create a cache item pool (can be any PSR-6 compatible cache item pool)
|
||||
$cacheItemPool = Phpfastcache\CacheManager::getInstance('files');
|
||||
|
||||
$keySet = new CachedKeySet(
|
||||
$jwksUri,
|
||||
$httpClient,
|
||||
$httpFactory,
|
||||
$cacheItemPool,
|
||||
null, // $expiresAfter int seconds to set the JWKS to expire
|
||||
true // $rateLimit true to enable rate limit of 10 RPS on lookup of invalid keys
|
||||
);
|
||||
|
||||
$jwt = 'eyJhbGci...'; // Some JWT signed by a key from the $jwkUri above
|
||||
$decoded = JWT::decode($jwt, $keySet);
|
||||
```
|
||||
|
||||
Miscellaneous
|
||||
-------------
|
||||
|
||||
#### Exception Handling
|
||||
|
||||
When a call to `JWT::decode` is invalid, it will throw one of the following exceptions:
|
||||
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\SignatureInvalidException;
|
||||
use Firebase\JWT\BeforeValidException;
|
||||
use Firebase\JWT\ExpiredException;
|
||||
use DomainException;
|
||||
use InvalidArgumentException;
|
||||
use UnexpectedValueException;
|
||||
|
||||
try {
|
||||
$decoded = JWT::decode($jwt, $keys);
|
||||
} catch (InvalidArgumentException $e) {
|
||||
// provided key/key-array is empty or malformed.
|
||||
} catch (DomainException $e) {
|
||||
// provided algorithm is unsupported OR
|
||||
// provided key is invalid OR
|
||||
// unknown error thrown in openSSL or libsodium OR
|
||||
// libsodium is required but not available.
|
||||
} catch (SignatureInvalidException $e) {
|
||||
// provided JWT signature verification failed.
|
||||
} catch (BeforeValidException $e) {
|
||||
// provided JWT is trying to be used before "nbf" claim OR
|
||||
// provided JWT is trying to be used before "iat" claim.
|
||||
} catch (ExpiredException $e) {
|
||||
// provided JWT is trying to be used after "exp" claim.
|
||||
} catch (UnexpectedValueException $e) {
|
||||
// provided JWT is malformed OR
|
||||
// provided JWT is missing an algorithm / using an unsupported algorithm OR
|
||||
// provided JWT algorithm does not match provided key OR
|
||||
// provided key ID in key/key-array is empty or invalid.
|
||||
}
|
||||
```
|
||||
|
||||
All exceptions in the `Firebase\JWT` namespace extend `UnexpectedValueException`, and can be simplified
|
||||
like this:
|
||||
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
use UnexpectedValueException;
|
||||
try {
|
||||
$decoded = JWT::decode($jwt, $keys);
|
||||
} catch (LogicException $e) {
|
||||
// errors having to do with environmental setup or malformed JWT Keys
|
||||
} catch (UnexpectedValueException $e) {
|
||||
// errors having to do with JWT signature and claims
|
||||
}
|
||||
```
|
||||
|
||||
#### Casting to array
|
||||
|
||||
The return value of `JWT::decode` is the generic PHP object `stdClass`. If you'd like to handle with arrays
|
||||
instead, you can do the following:
|
||||
|
||||
```php
|
||||
// return type is stdClass
|
||||
$decoded = JWT::decode($jwt, $keys);
|
||||
|
||||
// cast to array
|
||||
$decoded = json_decode(json_encode($decoded), true);
|
||||
```
|
||||
|
||||
Tests
|
||||
-----
|
||||
Run the tests using phpunit:
|
||||
|
||||
```bash
|
||||
$ composer update
|
||||
$ vendor/bin/phpunit -c phpunit.xml.dist
|
||||
PHPUnit 3.7.10 by Sebastian Bergmann.
|
||||
.....
|
||||
Time: 0 seconds, Memory: 2.50Mb
|
||||
OK (5 tests, 5 assertions)
|
||||
```
|
||||
|
||||
New Lines in private keys
|
||||
-----
|
||||
|
||||
If your private key contains `\n` characters, be sure to wrap it in double quotes `""`
|
||||
and not single quotes `''` in order to properly interpret the escaped characters.
|
||||
|
||||
License
|
||||
-------
|
||||
[3-Clause BSD](http://opensource.org/licenses/BSD-3-Clause).
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
7.2.2
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"name": "firebase/php-jwt",
|
||||
"description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
|
||||
"homepage": "https://github.com/googleapis/php-jwt",
|
||||
"keywords": [
|
||||
"php",
|
||||
"jwt"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Neuman Vong",
|
||||
"email": "neuman+pear@twilio.com",
|
||||
"role": "Developer"
|
||||
},
|
||||
{
|
||||
"name": "Anant Narayanan",
|
||||
"email": "anant@php.net",
|
||||
"role": "Developer"
|
||||
}
|
||||
],
|
||||
"license": "BSD-3-Clause",
|
||||
"require": {
|
||||
"php": "^8.0"
|
||||
},
|
||||
"suggest": {
|
||||
"paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present",
|
||||
"ext-sodium": "Support EdDSA (Ed25519) signatures",
|
||||
"phpseclib/phpseclib": "Support PS256 (RSASSA-PSS) signatures"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Firebase\\JWT\\": "src"
|
||||
}
|
||||
},
|
||||
"require-dev": {
|
||||
"guzzlehttp/guzzle": "^7.4||^8.0",
|
||||
"phpspec/prophecy-phpunit": "^2.2",
|
||||
"phpunit/phpunit": "^9.5",
|
||||
"psr/cache": "^2.0||^3.0",
|
||||
"psr/http-client": "^1.0",
|
||||
"psr/http-factory": "^1.0",
|
||||
"phpfastcache/phpfastcache": "^9.2",
|
||||
"phpseclib/phpseclib": "~3.0"
|
||||
},
|
||||
"extra": {
|
||||
"component": {
|
||||
"id": "jwt",
|
||||
"target": "googleapis/php-jwt.git",
|
||||
"path": "Jwt",
|
||||
"entry": "README.md"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Firebase\JWT;
|
||||
|
||||
class BeforeValidException extends \UnexpectedValueException implements JWTExceptionWithPayloadInterface
|
||||
{
|
||||
private object $payload;
|
||||
|
||||
public function setPayload(object $payload): void
|
||||
{
|
||||
$this->payload = $payload;
|
||||
}
|
||||
|
||||
public function getPayload(): object
|
||||
{
|
||||
return $this->payload;
|
||||
}
|
||||
}
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
<?php
|
||||
|
||||
namespace Firebase\JWT;
|
||||
|
||||
use ArrayAccess;
|
||||
use InvalidArgumentException;
|
||||
use LogicException;
|
||||
use OutOfBoundsException;
|
||||
use Psr\Cache\CacheItemInterface;
|
||||
use Psr\Cache\CacheItemPoolInterface;
|
||||
use Psr\Http\Client\ClientInterface;
|
||||
use Psr\Http\Message\RequestFactoryInterface;
|
||||
use RuntimeException;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* @implements ArrayAccess<string, Key>
|
||||
*/
|
||||
class CachedKeySet implements ArrayAccess
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $jwksUri;
|
||||
/**
|
||||
* @var ClientInterface
|
||||
*/
|
||||
private $httpClient;
|
||||
/**
|
||||
* @var RequestFactoryInterface
|
||||
*/
|
||||
private $httpFactory;
|
||||
/**
|
||||
* @var CacheItemPoolInterface
|
||||
*/
|
||||
private $cache;
|
||||
/**
|
||||
* @var ?int
|
||||
*/
|
||||
private $expiresAfter;
|
||||
/**
|
||||
* @var ?CacheItemInterface
|
||||
*/
|
||||
private $cacheItem;
|
||||
/**
|
||||
* @var array<string, array<mixed>>
|
||||
*/
|
||||
private $keySet;
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $cacheKey;
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $cacheKeyPrefix = 'jwks';
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
private $maxKeyLength = 64;
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
private $rateLimit;
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $rateLimitCacheKey;
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
private $maxCallsPerMinute = 10;
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
private $defaultAlg;
|
||||
|
||||
public function __construct(
|
||||
string $jwksUri,
|
||||
ClientInterface $httpClient,
|
||||
RequestFactoryInterface $httpFactory,
|
||||
CacheItemPoolInterface $cache,
|
||||
?int $expiresAfter = null,
|
||||
bool $rateLimit = false,
|
||||
?string $defaultAlg = null
|
||||
) {
|
||||
$this->jwksUri = $jwksUri;
|
||||
$this->httpClient = $httpClient;
|
||||
$this->httpFactory = $httpFactory;
|
||||
$this->cache = $cache;
|
||||
$this->expiresAfter = $expiresAfter;
|
||||
$this->rateLimit = $rateLimit;
|
||||
$this->defaultAlg = $defaultAlg;
|
||||
$this->setCacheKeys();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $keyId
|
||||
* @return Key
|
||||
*/
|
||||
public function offsetGet($keyId): Key
|
||||
{
|
||||
if (!$this->keyIdExists($keyId)) {
|
||||
throw new OutOfBoundsException('Key ID not found');
|
||||
}
|
||||
return JWK::parseKey($this->keySet[$keyId], $this->defaultAlg);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $keyId
|
||||
* @return bool
|
||||
*/
|
||||
public function offsetExists($keyId): bool
|
||||
{
|
||||
return $this->keyIdExists($keyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $offset
|
||||
* @param Key $value
|
||||
*/
|
||||
public function offsetSet($offset, $value): void
|
||||
{
|
||||
throw new LogicException('Method not implemented');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $offset
|
||||
*/
|
||||
public function offsetUnset($offset): void
|
||||
{
|
||||
throw new LogicException('Method not implemented');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<mixed>
|
||||
*/
|
||||
private function formatJwksForCache(string $jwks): array
|
||||
{
|
||||
$jwks = json_decode($jwks, true);
|
||||
|
||||
if (!isset($jwks['keys'])) {
|
||||
throw new UnexpectedValueException('"keys" member must exist in the JWK Set');
|
||||
}
|
||||
|
||||
if (empty($jwks['keys'])) {
|
||||
throw new InvalidArgumentException('JWK Set did not contain any keys');
|
||||
}
|
||||
|
||||
$keys = [];
|
||||
foreach ($jwks['keys'] as $k => $v) {
|
||||
$kid = isset($v['kid']) ? $v['kid'] : $k;
|
||||
$keys[(string) $kid] = $v;
|
||||
}
|
||||
|
||||
return $keys;
|
||||
}
|
||||
|
||||
private function keyIdExists(string $keyId): bool
|
||||
{
|
||||
if (null === $this->keySet) {
|
||||
$item = $this->getCacheItem();
|
||||
// Try to load keys from cache
|
||||
if ($item->isHit()) {
|
||||
// item found! retrieve it
|
||||
$this->keySet = $item->get();
|
||||
// If the cached item is a string, the JWKS response was cached (previous behavior).
|
||||
// Parse this into expected format array<kid, jwk> instead.
|
||||
if (\is_string($this->keySet)) {
|
||||
$this->keySet = $this->formatJwksForCache($this->keySet);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($this->keySet[$keyId])) {
|
||||
if ($this->rateLimitExceeded()) {
|
||||
return false;
|
||||
}
|
||||
$request = $this->httpFactory->createRequest('GET', $this->jwksUri);
|
||||
$jwksResponse = $this->httpClient->sendRequest($request);
|
||||
if ($jwksResponse->getStatusCode() !== 200) {
|
||||
throw new UnexpectedValueException(
|
||||
\sprintf(
|
||||
'HTTP Error: %d %s for URI "%s"',
|
||||
$jwksResponse->getStatusCode(),
|
||||
$jwksResponse->getReasonPhrase(),
|
||||
$this->jwksUri,
|
||||
),
|
||||
$jwksResponse->getStatusCode()
|
||||
);
|
||||
}
|
||||
$this->keySet = $this->formatJwksForCache((string) $jwksResponse->getBody());
|
||||
|
||||
if (!isset($this->keySet[$keyId])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$item = $this->getCacheItem();
|
||||
$item->set($this->keySet);
|
||||
if ($this->expiresAfter) {
|
||||
$item->expiresAfter($this->expiresAfter);
|
||||
}
|
||||
$this->cache->save($item);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function rateLimitExceeded(): bool
|
||||
{
|
||||
if (!$this->rateLimit) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$cacheItem = $this->cache->getItem($this->rateLimitCacheKey);
|
||||
|
||||
$cacheItemData = [];
|
||||
if ($cacheItem->isHit() && \is_array($data = $cacheItem->get())) {
|
||||
$cacheItemData = $data;
|
||||
}
|
||||
|
||||
$callsPerMinute = $cacheItemData['callsPerMinute'] ?? 0;
|
||||
$expiry = $cacheItemData['expiry'] ?? new \DateTime('+60 seconds', new \DateTimeZone('UTC'));
|
||||
|
||||
if (++$callsPerMinute > $this->maxCallsPerMinute) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$cacheItem->set(['expiry' => $expiry, 'callsPerMinute' => $callsPerMinute]);
|
||||
$cacheItem->expiresAt($expiry);
|
||||
$this->cache->save($cacheItem);
|
||||
return false;
|
||||
}
|
||||
|
||||
private function getCacheItem(): CacheItemInterface
|
||||
{
|
||||
if (\is_null($this->cacheItem)) {
|
||||
$this->cacheItem = $this->cache->getItem($this->cacheKey);
|
||||
}
|
||||
|
||||
return $this->cacheItem;
|
||||
}
|
||||
|
||||
private function setCacheKeys(): void
|
||||
{
|
||||
if (empty($this->jwksUri)) {
|
||||
throw new RuntimeException('JWKS URI is empty');
|
||||
}
|
||||
|
||||
// ensure we do not have illegal characters
|
||||
$key = preg_replace('|[^a-zA-Z0-9_\.!]|', '', $this->jwksUri);
|
||||
|
||||
// add prefix
|
||||
$key = $this->cacheKeyPrefix . $key;
|
||||
|
||||
// Hash keys if they exceed $maxKeyLength of 64
|
||||
if (\strlen($key) > $this->maxKeyLength) {
|
||||
$key = substr(hash('sha256', $key), 0, $this->maxKeyLength);
|
||||
}
|
||||
|
||||
$this->cacheKey = $key;
|
||||
|
||||
if ($this->rateLimit) {
|
||||
// add prefix
|
||||
$rateLimitKey = $this->cacheKeyPrefix . 'ratelimit' . $key;
|
||||
|
||||
// Hash keys if they exceed $maxKeyLength of 64
|
||||
if (\strlen($rateLimitKey) > $this->maxKeyLength) {
|
||||
$rateLimitKey = substr(hash('sha256', $rateLimitKey), 0, $this->maxKeyLength);
|
||||
}
|
||||
|
||||
$this->rateLimitCacheKey = $rateLimitKey;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace Firebase\JWT;
|
||||
|
||||
class ExpiredException extends \UnexpectedValueException implements JWTExceptionWithPayloadInterface
|
||||
{
|
||||
private object $payload;
|
||||
|
||||
private ?int $timestamp = null;
|
||||
|
||||
public function setPayload(object $payload): void
|
||||
{
|
||||
$this->payload = $payload;
|
||||
}
|
||||
|
||||
public function getPayload(): object
|
||||
{
|
||||
return $this->payload;
|
||||
}
|
||||
|
||||
public function setTimestamp(int $timestamp): void
|
||||
{
|
||||
$this->timestamp = $timestamp;
|
||||
}
|
||||
|
||||
public function getTimestamp(): ?int
|
||||
{
|
||||
return $this->timestamp;
|
||||
}
|
||||
}
|
||||
Vendored
+376
@@ -0,0 +1,376 @@
|
||||
<?php
|
||||
|
||||
namespace Firebase\JWT;
|
||||
|
||||
use DomainException;
|
||||
use InvalidArgumentException;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* JSON Web Key implementation, based on this spec:
|
||||
* https://tools.ietf.org/html/draft-ietf-jose-json-web-key-41
|
||||
*
|
||||
* PHP version 5
|
||||
*
|
||||
* @category Authentication
|
||||
* @package Authentication_JWT
|
||||
* @author Bui Sy Nguyen <nguyenbs@gmail.com>
|
||||
* @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
|
||||
* @link https://github.com/firebase/php-jwt
|
||||
*/
|
||||
class JWK
|
||||
{
|
||||
private const OID = '1.2.840.10045.2.1';
|
||||
private const ASN1_OBJECT_IDENTIFIER = 0x06;
|
||||
private const ASN1_SEQUENCE = 0x10; // also defined in JWT
|
||||
private const ASN1_BIT_STRING = 0x03;
|
||||
private const EC_CURVES = [
|
||||
'P-256' => '1.2.840.10045.3.1.7', // Len: 64
|
||||
'secp256k1' => '1.3.132.0.10', // Len: 64
|
||||
'P-384' => '1.3.132.0.34', // Len: 96
|
||||
// 'P-521' => '1.3.132.0.35', // Len: 132 (not supported)
|
||||
];
|
||||
|
||||
// Known standard curves from the IANA JOSE registry which are not supported
|
||||
private const KNOWN_UNSUPPORTED_EC_CURVES = [
|
||||
'P-521', // RFC 7518
|
||||
'Ed25519', // RFC 8037
|
||||
'Ed448', // RFC 8037
|
||||
'X25519', // RFC 8037
|
||||
'X448' // RFC 8037
|
||||
];
|
||||
|
||||
// For keys with "kty" equal to "OKP" (Octet Key Pair), the "crv" parameter must contain the key subtype.
|
||||
// This library supports the following subtypes:
|
||||
private const OKP_SUBTYPES = [
|
||||
'Ed25519' => true, // RFC 8037
|
||||
];
|
||||
|
||||
/**
|
||||
* Parse a set of JWK keys
|
||||
*
|
||||
* @param array<mixed> $jwks The JSON Web Key Set as an associative array
|
||||
* @param string $defaultAlg The algorithm for the Key object if "alg" is not set in the
|
||||
* JSON Web Key Set
|
||||
*
|
||||
* @return array<string, Key> An associative array of key IDs (kid) to Key objects
|
||||
*
|
||||
* @throws InvalidArgumentException Provided JWK Set is empty
|
||||
* @throws UnexpectedValueException Provided JWK Set was invalid
|
||||
* @throws DomainException OpenSSL failure
|
||||
*
|
||||
* @uses parseKey
|
||||
*/
|
||||
public static function parseKeySet(#[\SensitiveParameter] array $jwks, ?string $defaultAlg = null): array
|
||||
{
|
||||
$keys = [];
|
||||
|
||||
if (!isset($jwks['keys'])) {
|
||||
throw new UnexpectedValueException('"keys" member must exist in the JWK Set');
|
||||
}
|
||||
|
||||
if (empty($jwks['keys'])) {
|
||||
throw new InvalidArgumentException('JWK Set did not contain any keys');
|
||||
}
|
||||
|
||||
foreach ($jwks['keys'] as $k => $v) {
|
||||
$kid = isset($v['kid']) ? $v['kid'] : $k;
|
||||
if ($key = self::parseKey($v, $defaultAlg)) {
|
||||
$keys[(string) $kid] = $key;
|
||||
}
|
||||
}
|
||||
|
||||
if (0 === \count($keys)) {
|
||||
throw new UnexpectedValueException('No supported algorithms found in JWK Set');
|
||||
}
|
||||
|
||||
return $keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a JWK key
|
||||
*
|
||||
* @param array<mixed> $jwk An individual JWK
|
||||
* @param string $defaultAlg The algorithm for the Key object if "alg" is not set in the
|
||||
* JSON Web Key Set
|
||||
*
|
||||
* @return Key The key object for the JWK
|
||||
*
|
||||
* @throws InvalidArgumentException Provided JWK is empty
|
||||
* @throws UnexpectedValueException Provided JWK was invalid
|
||||
* @throws DomainException OpenSSL failure
|
||||
*
|
||||
* @uses createPemFromModulusAndExponent
|
||||
*/
|
||||
public static function parseKey(#[\SensitiveParameter] array $jwk, ?string $defaultAlg = null): ?Key
|
||||
{
|
||||
if (empty($jwk)) {
|
||||
throw new InvalidArgumentException('JWK must not be empty');
|
||||
}
|
||||
|
||||
if (!isset($jwk['kty'])) {
|
||||
throw new UnexpectedValueException('JWK must contain a "kty" parameter');
|
||||
}
|
||||
|
||||
if (!isset($jwk['alg'])) {
|
||||
if (\is_null($defaultAlg)) {
|
||||
// The "alg" parameter is optional in a KTY, but an algorithm is required
|
||||
// for parsing in this library. Use the $defaultAlg parameter when parsing the
|
||||
// key set in order to prevent this error.
|
||||
// @see https://datatracker.ietf.org/doc/html/rfc7517#section-4.4
|
||||
throw new UnexpectedValueException('JWK must contain an "alg" parameter');
|
||||
}
|
||||
$jwk['alg'] = $defaultAlg;
|
||||
}
|
||||
|
||||
switch ($jwk['kty']) {
|
||||
case 'RSA':
|
||||
if (!empty($jwk['d'])) {
|
||||
throw new UnexpectedValueException('RSA private keys are not supported');
|
||||
}
|
||||
if (!isset($jwk['n']) || !isset($jwk['e'])) {
|
||||
throw new UnexpectedValueException('RSA keys must contain values for both "n" and "e"');
|
||||
}
|
||||
|
||||
$pem = self::createPemFromModulusAndExponent($jwk['n'], $jwk['e']);
|
||||
$publicKey = \openssl_pkey_get_public($pem);
|
||||
if (false === $publicKey) {
|
||||
throw new DomainException(
|
||||
'OpenSSL error: ' . \openssl_error_string()
|
||||
);
|
||||
}
|
||||
return new Key($publicKey, $jwk['alg']);
|
||||
case 'EC':
|
||||
if (isset($jwk['d'])) {
|
||||
// The key is actually a private key
|
||||
throw new UnexpectedValueException('Key data must be for a public key');
|
||||
}
|
||||
|
||||
if (empty($jwk['crv'])) {
|
||||
throw new UnexpectedValueException('crv not set');
|
||||
}
|
||||
|
||||
if (!isset(self::EC_CURVES[$jwk['crv']])) {
|
||||
if (!\in_array($jwk['crv'], self::KNOWN_UNSUPPORTED_EC_CURVES)) {
|
||||
throw new DomainException('Unrecognised EC curve');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (empty($jwk['x']) || empty($jwk['y'])) {
|
||||
throw new UnexpectedValueException('x and y not set');
|
||||
}
|
||||
|
||||
$publicKey = self::createPemFromCrvAndXYCoordinates($jwk['crv'], $jwk['x'], $jwk['y']);
|
||||
return new Key($publicKey, $jwk['alg']);
|
||||
case 'OKP':
|
||||
if (isset($jwk['d'])) {
|
||||
// The key is actually a private key
|
||||
throw new UnexpectedValueException('Key data must be for a public key');
|
||||
}
|
||||
|
||||
if (!isset($jwk['crv'])) {
|
||||
throw new UnexpectedValueException('crv not set');
|
||||
}
|
||||
|
||||
if (empty(self::OKP_SUBTYPES[$jwk['crv']])) {
|
||||
throw new DomainException('Unrecognised or unsupported OKP key subtype');
|
||||
}
|
||||
|
||||
if (empty($jwk['x'])) {
|
||||
throw new UnexpectedValueException('x not set');
|
||||
}
|
||||
|
||||
// This library works internally with EdDSA keys (Ed25519) encoded in standard base64.
|
||||
$publicKey = JWT::convertBase64urlToBase64($jwk['x']);
|
||||
return new Key($publicKey, $jwk['alg']);
|
||||
case 'oct':
|
||||
if (!isset($jwk['k'])) {
|
||||
throw new UnexpectedValueException('k not set');
|
||||
}
|
||||
|
||||
return new Key(JWT::urlsafeB64Decode($jwk['k']), $jwk['alg']);
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the EC JWK values to pem format.
|
||||
*
|
||||
* @param string $crv The EC curve (only P-256 & P-384 is supported)
|
||||
* @param string $x The EC x-coordinate
|
||||
* @param string $y The EC y-coordinate
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private static function createPemFromCrvAndXYCoordinates(string $crv, string $x, string $y): string
|
||||
{
|
||||
$pem =
|
||||
self::encodeDER(
|
||||
self::ASN1_SEQUENCE,
|
||||
self::encodeDER(
|
||||
self::ASN1_SEQUENCE,
|
||||
self::encodeDER(
|
||||
self::ASN1_OBJECT_IDENTIFIER,
|
||||
self::encodeOID(self::OID)
|
||||
)
|
||||
. self::encodeDER(
|
||||
self::ASN1_OBJECT_IDENTIFIER,
|
||||
self::encodeOID(self::EC_CURVES[$crv])
|
||||
)
|
||||
) .
|
||||
self::encodeDER(
|
||||
self::ASN1_BIT_STRING,
|
||||
\chr(0x00) . \chr(0x04)
|
||||
. JWT::urlsafeB64Decode($x)
|
||||
. JWT::urlsafeB64Decode($y)
|
||||
)
|
||||
);
|
||||
|
||||
return \sprintf(
|
||||
"-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n",
|
||||
wordwrap(base64_encode($pem), 64, "\n", true)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a public key represented in PEM format from RSA modulus and exponent information
|
||||
*
|
||||
* @param string $n The RSA modulus encoded in Base64
|
||||
* @param string $e The RSA exponent encoded in Base64
|
||||
*
|
||||
* @return string The RSA public key represented in PEM format
|
||||
*
|
||||
* @uses encodeLength
|
||||
*/
|
||||
private static function createPemFromModulusAndExponent(
|
||||
string $n,
|
||||
string $e
|
||||
): string {
|
||||
$mod = JWT::urlsafeB64Decode($n);
|
||||
$exp = JWT::urlsafeB64Decode($e);
|
||||
// Correct encoding for ASN1, as ints are represented as unsigned in jwk
|
||||
// but signed in ASN1. Prepending null byte makes it unsigned.
|
||||
if (\strlen($mod) > 0 && \ord($mod[0]) >= 128) {
|
||||
$mod = \chr(0) . $mod;
|
||||
}
|
||||
if (\strlen($exp) > 0 && \ord($exp[0]) >= 128) {
|
||||
$exp = \chr(0) . $exp;
|
||||
}
|
||||
|
||||
$modulus = \pack('Ca*a*', 2, self::encodeLength(\strlen($mod)), $mod);
|
||||
$publicExponent = \pack('Ca*a*', 2, self::encodeLength(\strlen($exp)), $exp);
|
||||
|
||||
$rsaPublicKey = \pack(
|
||||
'Ca*a*a*',
|
||||
48,
|
||||
self::encodeLength(\strlen($modulus) + \strlen($publicExponent)),
|
||||
$modulus,
|
||||
$publicExponent
|
||||
);
|
||||
|
||||
// sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
|
||||
$rsaOID = \pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
|
||||
$rsaPublicKey = \chr(0) . $rsaPublicKey;
|
||||
$rsaPublicKey = \chr(3) . self::encodeLength(\strlen($rsaPublicKey)) . $rsaPublicKey;
|
||||
|
||||
$rsaPublicKey = \pack(
|
||||
'Ca*a*',
|
||||
48,
|
||||
self::encodeLength(\strlen($rsaOID . $rsaPublicKey)),
|
||||
$rsaOID . $rsaPublicKey
|
||||
);
|
||||
|
||||
return "-----BEGIN PUBLIC KEY-----\r\n" .
|
||||
\chunk_split(\base64_encode($rsaPublicKey), 64) .
|
||||
'-----END PUBLIC KEY-----';
|
||||
}
|
||||
|
||||
/**
|
||||
* DER-encode the length
|
||||
*
|
||||
* DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
|
||||
* {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3}
|
||||
* for more information.
|
||||
*
|
||||
* @param int $length
|
||||
* @return string
|
||||
*/
|
||||
private static function encodeLength(int $length): string
|
||||
{
|
||||
if ($length <= 0x7F) {
|
||||
return \chr($length);
|
||||
}
|
||||
|
||||
$temp = \ltrim(\pack('N', $length), \chr(0));
|
||||
|
||||
return \pack('Ca*', 0x80 | \strlen($temp), $temp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes a value into a DER object.
|
||||
* Also defined in Firebase\JWT\JWT
|
||||
*
|
||||
* @param int $type DER tag
|
||||
* @param string $value the value to encode
|
||||
* @return string the encoded object
|
||||
*/
|
||||
private static function encodeDER(int $type, string $value): string
|
||||
{
|
||||
$tag_header = 0;
|
||||
if ($type === self::ASN1_SEQUENCE) {
|
||||
$tag_header |= 0x20;
|
||||
}
|
||||
|
||||
// Type
|
||||
$der = \chr($tag_header | $type);
|
||||
|
||||
// Length
|
||||
$der .= \chr(\strlen($value));
|
||||
|
||||
return $der . $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes a string into a DER-encoded OID.
|
||||
*
|
||||
* @param string $oid the OID string
|
||||
* @return string the binary DER-encoded OID
|
||||
*/
|
||||
private static function encodeOID(string $oid): string
|
||||
{
|
||||
$octets = explode('.', $oid);
|
||||
|
||||
// Get the first octet
|
||||
$first = (int) array_shift($octets);
|
||||
$second = (int) array_shift($octets);
|
||||
$oid = \chr($first * 40 + $second);
|
||||
|
||||
// Iterate over subsequent octets
|
||||
foreach ($octets as $octet) {
|
||||
if ($octet == 0) {
|
||||
$oid .= \chr(0x00);
|
||||
continue;
|
||||
}
|
||||
$bin = '';
|
||||
|
||||
while ($octet) {
|
||||
$bin .= \chr(0x80 | ($octet & 0x7f));
|
||||
$octet >>= 7;
|
||||
}
|
||||
$bin[0] = $bin[0] & \chr(0x7f);
|
||||
|
||||
// Convert to big endian if necessary
|
||||
if (pack('V', 65534) == pack('L', 65534)) {
|
||||
$oid .= strrev($bin);
|
||||
} else {
|
||||
$oid .= $bin;
|
||||
}
|
||||
}
|
||||
|
||||
return $oid;
|
||||
}
|
||||
}
|
||||
Vendored
+835
@@ -0,0 +1,835 @@
|
||||
<?php
|
||||
|
||||
namespace Firebase\JWT;
|
||||
|
||||
use ArrayAccess;
|
||||
use DateTime;
|
||||
use DomainException;
|
||||
use Exception;
|
||||
use InvalidArgumentException;
|
||||
use OpenSSLAsymmetricKey;
|
||||
use OpenSSLCertificate;
|
||||
use stdClass;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* JSON Web Token implementation, based on this spec:
|
||||
* https://tools.ietf.org/html/rfc7519
|
||||
*
|
||||
* PHP version 5
|
||||
*
|
||||
* @category Authentication
|
||||
* @package Authentication_JWT
|
||||
* @author Neuman Vong <neuman@twilio.com>
|
||||
* @author Anant Narayanan <anant@php.net>
|
||||
* @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
|
||||
* @link https://github.com/firebase/php-jwt
|
||||
*/
|
||||
class JWT
|
||||
{
|
||||
private const ASN1_INTEGER = 0x02;
|
||||
private const ASN1_SEQUENCE = 0x10;
|
||||
private const ASN1_BIT_STRING = 0x03;
|
||||
|
||||
private const RSA_KEY_MIN_LENGTH = 2048;
|
||||
|
||||
/**
|
||||
* When checking nbf, iat or expiration times,
|
||||
* we want to provide some extra leeway time to
|
||||
* account for clock skew.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public static $leeway = 0;
|
||||
|
||||
/**
|
||||
* Allow the current timestamp to be specified.
|
||||
* Useful for fixing a value within unit testing.
|
||||
* Will default to PHP time() value if null.
|
||||
*
|
||||
* @var ?int
|
||||
*/
|
||||
public static $timestamp = null;
|
||||
|
||||
/**
|
||||
* @var array<string, string[]>
|
||||
*/
|
||||
public static $supported_algs = [
|
||||
'ES384' => ['openssl', 'SHA384'],
|
||||
'ES256' => ['openssl', 'SHA256'],
|
||||
'ES256K' => ['openssl', 'SHA256'],
|
||||
'HS256' => ['hash_hmac', 'SHA256'],
|
||||
'HS384' => ['hash_hmac', 'SHA384'],
|
||||
'HS512' => ['hash_hmac', 'SHA512'],
|
||||
'RS256' => ['openssl', 'SHA256'],
|
||||
'RS384' => ['openssl', 'SHA384'],
|
||||
'RS512' => ['openssl', 'SHA512'],
|
||||
'PS256' => ['openssl', 'SHA256'],
|
||||
'EdDSA' => ['sodium_crypto', 'EdDSA']
|
||||
];
|
||||
|
||||
/**
|
||||
* Decodes a JWT string into a PHP object.
|
||||
*
|
||||
* @param string $jwt The JWT
|
||||
* @param Key|ArrayAccess<string,Key>|array<string,Key> $keyOrKeyArray The Key or associative array of key IDs
|
||||
* (kid) to Key objects.
|
||||
* If the algorithm used is asymmetric, this is
|
||||
* the public key.
|
||||
* Each Key object contains an algorithm and
|
||||
* matching key.
|
||||
* Supported algorithms are 'ES384','ES256',
|
||||
* 'HS256', 'HS384', 'HS512', 'RS256', 'RS384'
|
||||
* and 'RS512'.
|
||||
* @param stdClass $headers Optional. Populates stdClass with headers.
|
||||
*
|
||||
* @return stdClass The JWT's payload as a PHP object
|
||||
*
|
||||
* @throws InvalidArgumentException Provided key/key-array was empty or malformed
|
||||
* @throws DomainException Provided JWT is malformed
|
||||
* @throws UnexpectedValueException Provided JWT was invalid
|
||||
* @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
|
||||
* @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
|
||||
* @throws BeforeValidException Provided JWT is trying to be used before it's
|
||||
* been created as defined by 'iat'
|
||||
* @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
|
||||
*
|
||||
* @uses jsonDecode
|
||||
* @uses urlsafeB64Decode
|
||||
*/
|
||||
public static function decode(
|
||||
string $jwt,
|
||||
#[\SensitiveParameter] $keyOrKeyArray,
|
||||
?stdClass &$headers = null
|
||||
): stdClass {
|
||||
// Validate JWT
|
||||
$timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp;
|
||||
|
||||
if (empty($keyOrKeyArray)) {
|
||||
throw new InvalidArgumentException('Key may not be empty');
|
||||
}
|
||||
$tks = \explode('.', $jwt, 4);
|
||||
if (\count($tks) !== 3) {
|
||||
throw new UnexpectedValueException('Wrong number of segments');
|
||||
}
|
||||
list($headb64, $bodyb64, $cryptob64) = $tks;
|
||||
$headerRaw = static::urlsafeB64Decode($headb64);
|
||||
if (null === ($header = static::jsonDecode($headerRaw))) {
|
||||
throw new UnexpectedValueException('Invalid header encoding');
|
||||
}
|
||||
if ($headers !== null) {
|
||||
$headers = $header;
|
||||
}
|
||||
$payloadRaw = static::urlsafeB64Decode($bodyb64);
|
||||
if (null === ($payload = static::jsonDecode($payloadRaw))) {
|
||||
throw new UnexpectedValueException('Invalid claims encoding');
|
||||
}
|
||||
if (\is_array($payload)) {
|
||||
// prevent PHP Fatal Error in edge-cases when payload is empty array
|
||||
$payload = (object) $payload;
|
||||
}
|
||||
if (!$payload instanceof stdClass) {
|
||||
throw new UnexpectedValueException('Payload must be a JSON object');
|
||||
}
|
||||
if (isset($payload->iat) && !\is_numeric($payload->iat)) {
|
||||
throw new UnexpectedValueException('Payload iat must be a number');
|
||||
}
|
||||
if (isset($payload->nbf) && !\is_numeric($payload->nbf)) {
|
||||
throw new UnexpectedValueException('Payload nbf must be a number');
|
||||
}
|
||||
if (isset($payload->exp) && !\is_numeric($payload->exp)) {
|
||||
throw new UnexpectedValueException('Payload exp must be a number');
|
||||
}
|
||||
|
||||
$sig = static::urlsafeB64Decode($cryptob64);
|
||||
if (empty($header->alg)) {
|
||||
throw new UnexpectedValueException('Empty algorithm');
|
||||
}
|
||||
if (empty(static::$supported_algs[$header->alg])) {
|
||||
throw new UnexpectedValueException('Algorithm not supported');
|
||||
}
|
||||
|
||||
$key = self::getKey($keyOrKeyArray, property_exists($header, 'kid') ? $header->kid : null);
|
||||
|
||||
// Check the algorithm
|
||||
if (!self::constantTimeEquals($key->getAlgorithm(), $header->alg)) {
|
||||
// See issue #351
|
||||
throw new UnexpectedValueException('Incorrect key for this algorithm');
|
||||
}
|
||||
if (\in_array($header->alg, ['ES256', 'ES256K', 'ES384'], true)) {
|
||||
// OpenSSL expects an ASN.1 DER sequence for ES256/ES256K/ES384 signatures
|
||||
$sig = self::signatureToDER($sig);
|
||||
}
|
||||
if (!self::verify("{$headb64}.{$bodyb64}", $sig, $key->getKeyMaterial(), $header->alg)) {
|
||||
throw new SignatureInvalidException('Signature verification failed');
|
||||
}
|
||||
|
||||
// Check the nbf if it is defined. This is the time that the
|
||||
// token can actually be used. If it's not yet that time, abort.
|
||||
if (isset($payload->nbf) && floor($payload->nbf) > ($timestamp + static::$leeway)) {
|
||||
$ex = new BeforeValidException(
|
||||
'Cannot handle token with nbf prior to ' . \date(DateTime::ATOM, (int) floor($payload->nbf))
|
||||
);
|
||||
$ex->setPayload($payload);
|
||||
throw $ex;
|
||||
}
|
||||
|
||||
// Check that this token has been created before 'now'. This prevents
|
||||
// using tokens that have been created for later use (and haven't
|
||||
// correctly used the nbf claim).
|
||||
if (!isset($payload->nbf) && isset($payload->iat) && floor($payload->iat) > ($timestamp + static::$leeway)) {
|
||||
$ex = new BeforeValidException(
|
||||
'Cannot handle token with iat prior to ' . \date(DateTime::ATOM, (int) floor($payload->iat))
|
||||
);
|
||||
$ex->setPayload($payload);
|
||||
throw $ex;
|
||||
}
|
||||
|
||||
// Check if this token has expired.
|
||||
if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {
|
||||
$ex = new ExpiredException('Expired token');
|
||||
$ex->setPayload($payload);
|
||||
$ex->setTimestamp($timestamp);
|
||||
throw $ex;
|
||||
}
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts and signs a PHP array into a JWT string.
|
||||
*
|
||||
* @param array<mixed> $payload PHP array
|
||||
* @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key.
|
||||
* @param string $alg Supported algorithms are 'ES384','ES256', 'ES256K', 'HS256',
|
||||
* 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
|
||||
* @param string $keyId
|
||||
* @param array<string, string|string[]> $head An array with header elements to attach
|
||||
*
|
||||
* @return string A signed JWT
|
||||
*
|
||||
* @uses jsonEncode
|
||||
* @uses urlsafeB64Encode
|
||||
*/
|
||||
public static function encode(
|
||||
array $payload,
|
||||
#[\SensitiveParameter] $key,
|
||||
string $alg,
|
||||
?string $keyId = null,
|
||||
?array $head = null
|
||||
): string {
|
||||
$header = ['typ' => 'JWT'];
|
||||
if (isset($head)) {
|
||||
$header = \array_merge($header, $head);
|
||||
}
|
||||
$header['alg'] = $alg;
|
||||
if ($keyId !== null) {
|
||||
$header['kid'] = $keyId;
|
||||
}
|
||||
if (isset($payload['nbf']) && !\is_numeric($payload['nbf'])) {
|
||||
throw new UnexpectedValueException('Payload nbf must be a number');
|
||||
}
|
||||
if (isset($payload['iat']) && !\is_numeric($payload['iat'])) {
|
||||
throw new UnexpectedValueException('Payload iat must be a number');
|
||||
}
|
||||
if (isset($payload['exp']) && !\is_numeric($payload['exp'])) {
|
||||
throw new UnexpectedValueException('Payload exp must be a number');
|
||||
}
|
||||
$segments = [];
|
||||
$segments[] = static::urlsafeB64Encode((string) static::jsonEncode($header));
|
||||
$segments[] = static::urlsafeB64Encode((string) static::jsonEncode($payload));
|
||||
$signing_input = \implode('.', $segments);
|
||||
|
||||
$signature = static::sign($signing_input, $key, $alg);
|
||||
$segments[] = static::urlsafeB64Encode($signature);
|
||||
|
||||
return \implode('.', $segments);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign a string with a given key and algorithm.
|
||||
*
|
||||
* @param string $msg The message to sign
|
||||
* @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key.
|
||||
* @param string $alg Supported algorithms are 'EdDSA', 'ES384', 'ES256', 'ES256K', 'HS256',
|
||||
* 'HS384', 'HS512', 'RS256', 'RS384', 'PS256' and 'RS512'
|
||||
*
|
||||
* @return string An encrypted message
|
||||
*
|
||||
* @throws DomainException Unsupported algorithm or bad key was specified
|
||||
*/
|
||||
public static function sign(
|
||||
string $msg,
|
||||
#[\SensitiveParameter] $key,
|
||||
string $alg
|
||||
): string {
|
||||
if (empty(static::$supported_algs[$alg])) {
|
||||
throw new DomainException('Algorithm not supported');
|
||||
}
|
||||
list($function, $algorithm) = static::$supported_algs[$alg];
|
||||
switch ($function) {
|
||||
case 'hash_hmac':
|
||||
if (!\is_string($key)) {
|
||||
throw new InvalidArgumentException('key must be a string when using hmac');
|
||||
}
|
||||
self::validateHmacKeyLength($key, $algorithm);
|
||||
return \hash_hmac($algorithm, $msg, $key, true);
|
||||
case 'openssl':
|
||||
if ($alg === 'PS256') {
|
||||
return self::signPS256($key, $msg);
|
||||
}
|
||||
$signature = '';
|
||||
if (!$key = openssl_pkey_get_private($key)) {
|
||||
throw new DomainException('OpenSSL unable to validate key');
|
||||
}
|
||||
if (str_starts_with($alg, 'RS')) {
|
||||
self::validateRsaKeyLength($key);
|
||||
} elseif (str_starts_with($alg, 'ES')) {
|
||||
self::validateEcKeyLength($key, $alg);
|
||||
}
|
||||
$success = \openssl_sign($msg, $signature, $key, $algorithm);
|
||||
if (!$success) {
|
||||
throw new DomainException('OpenSSL unable to sign data');
|
||||
}
|
||||
if ($alg === 'ES256' || $alg === 'ES256K') {
|
||||
$signature = self::signatureFromDER($signature, 256);
|
||||
} elseif ($alg === 'ES384') {
|
||||
$signature = self::signatureFromDER($signature, 384);
|
||||
}
|
||||
return $signature;
|
||||
case 'sodium_crypto':
|
||||
try {
|
||||
return sodium_crypto_sign_detached($msg, self::validateEdDSAKey($key));
|
||||
} catch (Exception $e) {
|
||||
throw new DomainException($e->getMessage(), 0, $e);
|
||||
}
|
||||
}
|
||||
|
||||
throw new DomainException('Algorithm not supported');
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a signature with the message, key and method. Not all methods
|
||||
* are symmetric, so we must have a separate verify and sign method.
|
||||
*
|
||||
* @param string $msg The original message (header and body)
|
||||
* @param string $signature The original signature
|
||||
* @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial For Ed*, ES*, HS*, a string key works.
|
||||
* for RS*, must be an instance of OpenSSLAsymmetricKey
|
||||
* @param string $alg The algorithm
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @throws DomainException Invalid Algorithm, bad key, or OpenSSL failure
|
||||
*/
|
||||
private static function verify(
|
||||
string $msg,
|
||||
string $signature,
|
||||
#[\SensitiveParameter] $keyMaterial,
|
||||
string $alg
|
||||
): bool {
|
||||
if (empty(static::$supported_algs[$alg])) {
|
||||
throw new DomainException('Algorithm not supported');
|
||||
}
|
||||
|
||||
list($function, $algorithm) = static::$supported_algs[$alg];
|
||||
switch ($function) {
|
||||
case 'openssl':
|
||||
if ($alg === 'PS256') {
|
||||
return self::verifyPS256($keyMaterial, $msg, $signature);
|
||||
}
|
||||
if (!$key = openssl_pkey_get_public($keyMaterial)) {
|
||||
throw new DomainException('OpenSSL unable to validate key');
|
||||
}
|
||||
if (str_starts_with($alg, 'RS')) {
|
||||
self::validateRsaKeyLength($key);
|
||||
} elseif (str_starts_with($alg, 'ES')) {
|
||||
self::validateEcKeyLength($key, $alg);
|
||||
}
|
||||
$success = \openssl_verify($msg, $signature, $keyMaterial, $algorithm);
|
||||
if ($success === 1) {
|
||||
return true;
|
||||
}
|
||||
if ($success === 0) {
|
||||
return false;
|
||||
}
|
||||
// returns 1 on success, 0 on failure, -1 on error.
|
||||
throw new DomainException(
|
||||
'OpenSSL error: ' . \openssl_error_string()
|
||||
);
|
||||
case 'sodium_crypto':
|
||||
try {
|
||||
$key = self::validateEdDSAKey($keyMaterial);
|
||||
if (\strlen($signature) === 0) {
|
||||
throw new DomainException('Signature cannot be empty string');
|
||||
}
|
||||
return sodium_crypto_sign_verify_detached($signature, $msg, $key);
|
||||
} catch (Exception $e) {
|
||||
throw new DomainException($e->getMessage(), 0, $e);
|
||||
}
|
||||
case 'hash_hmac':
|
||||
default:
|
||||
if (!\is_string($keyMaterial)) {
|
||||
throw new InvalidArgumentException('key must be a string when using hmac');
|
||||
}
|
||||
self::validateHmacKeyLength($keyMaterial, $algorithm);
|
||||
$hash = \hash_hmac($algorithm, $msg, $keyMaterial, true);
|
||||
return self::constantTimeEquals($hash, $signature);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a JSON string into a PHP object.
|
||||
*
|
||||
* @param string $input JSON string
|
||||
*
|
||||
* @return mixed The decoded JSON string
|
||||
*
|
||||
* @throws DomainException Provided string was invalid JSON
|
||||
*/
|
||||
public static function jsonDecode(string $input)
|
||||
{
|
||||
$obj = \json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
|
||||
|
||||
if ($errno = \json_last_error()) {
|
||||
self::handleJsonError($errno);
|
||||
} elseif ($obj === null && $input !== 'null') {
|
||||
throw new DomainException('Null result with non-null input');
|
||||
}
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode a PHP array into a JSON string.
|
||||
*
|
||||
* @param array<mixed> $input A PHP array
|
||||
*
|
||||
* @return string JSON representation of the PHP array
|
||||
*
|
||||
* @throws DomainException Provided object could not be encoded to valid JSON
|
||||
*/
|
||||
public static function jsonEncode(array $input): string
|
||||
{
|
||||
$json = \json_encode($input, \JSON_UNESCAPED_SLASHES);
|
||||
if ($errno = \json_last_error()) {
|
||||
self::handleJsonError($errno);
|
||||
} elseif ($json === 'null') {
|
||||
throw new DomainException('Null result with non-null input');
|
||||
}
|
||||
if ($json === false) {
|
||||
throw new DomainException('Provided object could not be encoded to valid JSON');
|
||||
}
|
||||
return $json;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a string with URL-safe Base64.
|
||||
*
|
||||
* @param string $input A Base64 encoded string
|
||||
*
|
||||
* @return string A decoded string
|
||||
*
|
||||
* @throws InvalidArgumentException invalid base64 characters
|
||||
*/
|
||||
public static function urlsafeB64Decode(string $input): string
|
||||
{
|
||||
return \base64_decode(self::convertBase64UrlToBase64($input));
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a string in the base64url (URL-safe Base64) encoding to standard base64.
|
||||
*
|
||||
* @param string $input A Base64 encoded string with URL-safe characters (-_ and no padding)
|
||||
*
|
||||
* @return string A Base64 encoded string with standard characters (+/) and padding (=), when
|
||||
* needed.
|
||||
*
|
||||
* @see https://www.rfc-editor.org/rfc/rfc4648
|
||||
*/
|
||||
public static function convertBase64UrlToBase64(string $input): string
|
||||
{
|
||||
$remainder = \strlen($input) % 4;
|
||||
if ($remainder) {
|
||||
$padlen = 4 - $remainder;
|
||||
$input .= \str_repeat('=', $padlen);
|
||||
}
|
||||
return \strtr($input, '-_', '+/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode a string with URL-safe Base64.
|
||||
*
|
||||
* @param string $input The string you want encoded
|
||||
*
|
||||
* @return string The base64 encode of what you passed in
|
||||
*/
|
||||
public static function urlsafeB64Encode(string $input): string
|
||||
{
|
||||
return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if an algorithm has been provided for each Key
|
||||
*
|
||||
* @param Key|ArrayAccess<string,Key>|array<string,Key> $keyOrKeyArray
|
||||
* @param string|null $kid
|
||||
*
|
||||
* @throws UnexpectedValueException
|
||||
*
|
||||
* @return Key
|
||||
*/
|
||||
private static function getKey(
|
||||
#[\SensitiveParameter] $keyOrKeyArray,
|
||||
?string $kid
|
||||
): Key {
|
||||
if ($keyOrKeyArray instanceof Key) {
|
||||
return $keyOrKeyArray;
|
||||
}
|
||||
|
||||
if (empty($kid) && $kid !== '0') {
|
||||
throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');
|
||||
}
|
||||
|
||||
if ($keyOrKeyArray instanceof CachedKeySet) {
|
||||
// Skip "isset" check, as this will automatically refresh if not set
|
||||
return $keyOrKeyArray[$kid];
|
||||
}
|
||||
|
||||
if (!isset($keyOrKeyArray[$kid])) {
|
||||
throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key');
|
||||
}
|
||||
|
||||
return $keyOrKeyArray[$kid];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $left The string of known length to compare against
|
||||
* @param string $right The user-supplied string
|
||||
* @return bool
|
||||
*/
|
||||
public static function constantTimeEquals(string $left, string $right): bool
|
||||
{
|
||||
if (\function_exists('hash_equals')) {
|
||||
return \hash_equals($left, $right);
|
||||
}
|
||||
$len = \min(self::safeStrlen($left), self::safeStrlen($right));
|
||||
|
||||
$status = 0;
|
||||
for ($i = 0; $i < $len; $i++) {
|
||||
$status |= (\ord($left[$i]) ^ \ord($right[$i]));
|
||||
}
|
||||
$status |= (self::safeStrlen($left) ^ self::safeStrlen($right));
|
||||
|
||||
return ($status === 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to create a JSON error.
|
||||
*
|
||||
* @param int $errno An error number from json_last_error()
|
||||
*
|
||||
* @throws DomainException
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function handleJsonError(int $errno): void
|
||||
{
|
||||
$messages = [
|
||||
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
|
||||
JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
|
||||
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
|
||||
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
|
||||
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3
|
||||
];
|
||||
throw new DomainException(
|
||||
isset($messages[$errno])
|
||||
? $messages[$errno]
|
||||
: 'Unknown JSON error: ' . $errno
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of bytes in cryptographic strings.
|
||||
*
|
||||
* @param string $str
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
private static function safeStrlen(string $str): int
|
||||
{
|
||||
if (\function_exists('mb_strlen')) {
|
||||
return \mb_strlen($str, '8bit');
|
||||
}
|
||||
return \strlen($str);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an ECDSA signature to an ASN.1 DER sequence
|
||||
*
|
||||
* @param string $sig The ECDSA signature to convert
|
||||
* @return string The encoded DER object
|
||||
*/
|
||||
private static function signatureToDER(string $sig): string
|
||||
{
|
||||
// Separate the signature into r-value and s-value
|
||||
$length = max(1, (int) (\strlen($sig) / 2));
|
||||
list($r, $s) = \str_split($sig, $length);
|
||||
|
||||
// Trim leading zeros
|
||||
$r = \ltrim($r, "\x00");
|
||||
$s = \ltrim($s, "\x00");
|
||||
|
||||
// Convert r-value and s-value from unsigned big-endian integers to
|
||||
// signed two's complement
|
||||
if (\ord($r[0]) > 0x7f) {
|
||||
$r = "\x00" . $r;
|
||||
}
|
||||
if (\ord($s[0]) > 0x7f) {
|
||||
$s = "\x00" . $s;
|
||||
}
|
||||
|
||||
return self::encodeDER(
|
||||
self::ASN1_SEQUENCE,
|
||||
self::encodeDER(self::ASN1_INTEGER, $r) .
|
||||
self::encodeDER(self::ASN1_INTEGER, $s)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes a value into a DER object.
|
||||
*
|
||||
* @param int $type DER tag
|
||||
* @param string $value the value to encode
|
||||
*
|
||||
* @return string the encoded object
|
||||
*/
|
||||
private static function encodeDER(int $type, string $value): string
|
||||
{
|
||||
$tag_header = 0;
|
||||
if ($type === self::ASN1_SEQUENCE) {
|
||||
$tag_header |= 0x20;
|
||||
}
|
||||
|
||||
// Type
|
||||
$der = \chr($tag_header | $type);
|
||||
|
||||
// Length
|
||||
$der .= \chr(\strlen($value));
|
||||
|
||||
return $der . $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes signature from a DER object.
|
||||
*
|
||||
* @param string $der binary signature in DER format
|
||||
* @param int $keySize the number of bits in the key
|
||||
*
|
||||
* @return string the signature
|
||||
*/
|
||||
private static function signatureFromDER(string $der, int $keySize): string
|
||||
{
|
||||
// OpenSSL returns the ECDSA signatures as a binary ASN.1 DER SEQUENCE
|
||||
list($offset, $_) = self::readDER($der);
|
||||
list($offset, $r) = self::readDER($der, $offset);
|
||||
list($offset, $s) = self::readDER($der, $offset);
|
||||
|
||||
// Convert r-value and s-value from signed two's compliment to unsigned
|
||||
// big-endian integers
|
||||
$r = \ltrim($r, "\x00");
|
||||
$s = \ltrim($s, "\x00");
|
||||
|
||||
// Pad out r and s so that they are $keySize bits long
|
||||
$r = \str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT);
|
||||
$s = \str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT);
|
||||
|
||||
return $r . $s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads binary DER-encoded data and decodes into a single object
|
||||
*
|
||||
* @param string $der the binary data in DER format
|
||||
* @param int $offset the offset of the data stream containing the object
|
||||
* to decode
|
||||
*
|
||||
* @return array{int, string|null} the new offset and the decoded object
|
||||
*/
|
||||
private static function readDER(string $der, int $offset = 0): array
|
||||
{
|
||||
$pos = $offset;
|
||||
$size = \strlen($der);
|
||||
$constructed = (\ord($der[$pos]) >> 5) & 0x01;
|
||||
$type = \ord($der[$pos++]) & 0x1f;
|
||||
|
||||
// Length
|
||||
$len = \ord($der[$pos++]);
|
||||
if ($len & 0x80) {
|
||||
$n = $len & 0x1f;
|
||||
$len = 0;
|
||||
while ($n-- && $pos < $size) {
|
||||
$len = ($len << 8) | \ord($der[$pos++]);
|
||||
}
|
||||
}
|
||||
|
||||
// Value
|
||||
if ($type === self::ASN1_BIT_STRING) {
|
||||
$pos++; // Skip the first contents octet (padding indicator)
|
||||
$data = \substr($der, $pos, $len - 1);
|
||||
$pos += $len - 1;
|
||||
} elseif (!$constructed) {
|
||||
$data = \substr($der, $pos, $len);
|
||||
$pos += $len;
|
||||
} else {
|
||||
$data = null;
|
||||
}
|
||||
|
||||
return [$pos, $data];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate HMAC key length
|
||||
*
|
||||
* @param string $key HMAC key material
|
||||
* @param string $algorithm The algorithm
|
||||
*
|
||||
* @throws DomainException Provided key is too short
|
||||
*/
|
||||
private static function validateHmacKeyLength(string $key, string $algorithm): void
|
||||
{
|
||||
$keyLength = \strlen($key) * 8;
|
||||
$minKeyLength = (int) \str_replace('SHA', '', $algorithm);
|
||||
if ($keyLength < $minKeyLength) {
|
||||
throw new DomainException('Provided key is too short');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate RSA key length
|
||||
*
|
||||
* @param OpenSSLAsymmetricKey $key RSA key material
|
||||
* @throws DomainException Provided key is too short
|
||||
*/
|
||||
private static function validateRsaKeyLength(#[\SensitiveParameter] OpenSSLAsymmetricKey $key): void
|
||||
{
|
||||
if (!$keyDetails = openssl_pkey_get_details($key)) {
|
||||
throw new DomainException('Unable to validate key');
|
||||
}
|
||||
if ($keyDetails['bits'] < self::RSA_KEY_MIN_LENGTH) {
|
||||
throw new DomainException('Provided key is too short');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate RSA key length
|
||||
*
|
||||
* @param OpenSSLAsymmetricKey $key RSA key material
|
||||
* @param string $algorithm The algorithm
|
||||
* @throws DomainException Provided key is too short
|
||||
*/
|
||||
private static function validateEcKeyLength(
|
||||
#[\SensitiveParameter] OpenSSLAsymmetricKey $key,
|
||||
string $algorithm
|
||||
): void {
|
||||
if (!$keyDetails = openssl_pkey_get_details($key)) {
|
||||
throw new DomainException('Unable to validate key');
|
||||
}
|
||||
$minKeyLength = (int) \str_replace('ES', '', $algorithm);
|
||||
if ($keyDetails['bits'] < $minKeyLength) {
|
||||
throw new DomainException('Provided key is too short');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial
|
||||
* @return non-empty-string
|
||||
*/
|
||||
private static function validateEdDSAKey(#[\SensitiveParameter] $keyMaterial): string
|
||||
{
|
||||
if (!\function_exists('sodium_crypto_sign_verify_detached')) {
|
||||
throw new DomainException('libsodium is not available');
|
||||
}
|
||||
if (!\is_string($keyMaterial)) {
|
||||
throw new InvalidArgumentException('key must be a string when using EdDSA');
|
||||
}
|
||||
// The last non-empty line is used as the key.
|
||||
$lines = array_filter(explode("\n", $keyMaterial));
|
||||
$key = self::urlsafeB64Decode((string) end($lines));
|
||||
if (\strlen($key) === 0) {
|
||||
throw new DomainException('Key cannot be empty string');
|
||||
}
|
||||
return $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs a message with a PS256 algorithm
|
||||
*
|
||||
* @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $key
|
||||
* @param string $message
|
||||
* @throws DomainException Provided key is invalid
|
||||
*/
|
||||
private static function signPS256(
|
||||
#[\SensitiveParameter] string|OpenSSLAsymmetricKey|OpenSSLCertificate $key,
|
||||
string $message
|
||||
): string {
|
||||
if (!class_exists('\phpseclib3\Crypt\RSA')) {
|
||||
throw new DomainException('phpseclib/phpseclib is required for PS256 support');
|
||||
}
|
||||
|
||||
if ($key instanceof OpenSSLCertificate) {
|
||||
throw new DomainException('Cannot sign with an X.509 certificate. A private key is required.');
|
||||
}
|
||||
|
||||
if ($key instanceof OpenSSLAsymmetricKey) {
|
||||
if (!openssl_pkey_export($key, $pem)) {
|
||||
throw new DomainException('OpenSSL unable to export the AsymmetricKey');
|
||||
}
|
||||
$key = $pem;
|
||||
}
|
||||
|
||||
/** @var \phpseclib3\Crypt\RSA\PrivateKey $rsa */
|
||||
$rsa = \phpseclib3\Crypt\PublicKeyLoader::load($key);
|
||||
|
||||
return $rsa->withPadding(\phpseclib3\Crypt\RSA::SIGNATURE_PSS)
|
||||
->withHash('sha256')
|
||||
->sign($message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a PS256 algorithm signature.
|
||||
*
|
||||
* @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $key
|
||||
* @param string $message
|
||||
* @param string $signature
|
||||
* @throws DomainException Provided key is invalid
|
||||
*/
|
||||
private static function verifyPS256(
|
||||
#[\SensitiveParameter] string|OpenSSLAsymmetricKey|OpenSSLCertificate $key,
|
||||
string $message,
|
||||
string $signature
|
||||
): bool {
|
||||
if (!class_exists('\phpseclib3\Crypt\RSA')) {
|
||||
throw new DomainException('phpseclib/phpseclib is required for PS256 support');
|
||||
}
|
||||
|
||||
if ($key instanceof OpenSSLAsymmetricKey) {
|
||||
$details = openssl_pkey_get_details($key);
|
||||
if (!$details || !isset($details['key'])) {
|
||||
throw new DomainException('OpenSSL unable to extract public key');
|
||||
}
|
||||
$key = $details['key'];
|
||||
} elseif ($key instanceof OpenSSLCertificate) {
|
||||
if (!openssl_x509_export($key, $pem)) {
|
||||
throw new DomainException('OpenSSL unable to export certificate');
|
||||
}
|
||||
$key = $pem;
|
||||
}
|
||||
|
||||
/** @var \phpseclib3\Crypt\RSA\PublicKey $rsa */
|
||||
$rsa = \phpseclib3\Crypt\PublicKeyLoader::load($key);
|
||||
|
||||
return $rsa->withPadding(\phpseclib3\Crypt\RSA::SIGNATURE_PSS)
|
||||
->withHash('sha256')
|
||||
->verify($message, $signature);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
namespace Firebase\JWT;
|
||||
|
||||
interface JWTExceptionWithPayloadInterface
|
||||
{
|
||||
/**
|
||||
* Get the payload that caused this exception.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function getPayload(): object;
|
||||
|
||||
/**
|
||||
* Get the payload that caused this exception.
|
||||
*
|
||||
* @param object $payload
|
||||
* @return void
|
||||
*/
|
||||
public function setPayload(object $payload): void;
|
||||
}
|
||||
Vendored
+53
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace Firebase\JWT;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use OpenSSLAsymmetricKey;
|
||||
use OpenSSLCertificate;
|
||||
use TypeError;
|
||||
|
||||
class Key
|
||||
{
|
||||
/**
|
||||
* @param string|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial
|
||||
* @param string $algorithm
|
||||
*/
|
||||
public function __construct(
|
||||
#[\SensitiveParameter] private $keyMaterial,
|
||||
private string $algorithm
|
||||
) {
|
||||
if (!\is_string($keyMaterial)
|
||||
&& !$keyMaterial instanceof OpenSSLAsymmetricKey
|
||||
&& !$keyMaterial instanceof OpenSSLCertificate
|
||||
) {
|
||||
throw new TypeError('Key material must be a string, OpenSSLCertificate, or OpenSSLAsymmetricKey');
|
||||
}
|
||||
|
||||
if (empty($keyMaterial)) {
|
||||
throw new InvalidArgumentException('Key material must not be empty');
|
||||
}
|
||||
|
||||
if (empty($algorithm)) {
|
||||
throw new InvalidArgumentException('Algorithm must not be empty');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the algorithm valid for this key
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getAlgorithm(): string
|
||||
{
|
||||
return $this->algorithm;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|OpenSSLAsymmetricKey|OpenSSLCertificate
|
||||
*/
|
||||
public function getKeyMaterial()
|
||||
{
|
||||
return $this->keyMaterial;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace Firebase\JWT;
|
||||
|
||||
class SignatureInvalidException extends \UnexpectedValueException
|
||||
{
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2020-2026 Graham Campbell <hello@gjcampbell.co.uk>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "graham-campbell/result-type",
|
||||
"description": "An Implementation Of The Result Type",
|
||||
"keywords": ["result", "result-type", "Result", "Result Type", "Result-Type", "Graham Campbell", "GrahamCampbell"],
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Graham Campbell",
|
||||
"email": "hello@gjcampbell.co.uk",
|
||||
"homepage": "https://github.com/GrahamCampbell"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^7.2.5 || ^8.0",
|
||||
"phpoption/phpoption": "^1.10"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^8.5.52 || ^9.6.34 || ^10.5.63 || ^11.5.55 || ^12.5.14"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"GrahamCampbell\\ResultType\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"GrahamCampbell\\Tests\\ResultType\\": "tests/"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"preferred-install": "dist"
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* This file is part of Result Type.
|
||||
*
|
||||
* (c) Graham Campbell <hello@gjcampbell.co.uk>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace GrahamCampbell\ResultType;
|
||||
|
||||
use PhpOption\None;
|
||||
use PhpOption\Some;
|
||||
|
||||
/**
|
||||
* @template-covariant E
|
||||
*
|
||||
* @extends \GrahamCampbell\ResultType\Result<never,E>
|
||||
*/
|
||||
final class Error extends Result
|
||||
{
|
||||
/**
|
||||
* @var E
|
||||
*/
|
||||
private $value;
|
||||
|
||||
/**
|
||||
* Internal constructor for an error value.
|
||||
*
|
||||
* @param E $value
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function __construct($value)
|
||||
{
|
||||
$this->value = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new error value.
|
||||
*
|
||||
* @template F
|
||||
*
|
||||
* @param F $value
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Error<F>
|
||||
*/
|
||||
public static function create($value)
|
||||
{
|
||||
return new self($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the success option value.
|
||||
*
|
||||
* @return \PhpOption\Option<never>
|
||||
*/
|
||||
public function success()
|
||||
{
|
||||
return None::create();
|
||||
}
|
||||
|
||||
/**
|
||||
* Map over the success value.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param callable(never):S $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Error<E>
|
||||
*/
|
||||
public function map(callable $f)
|
||||
{
|
||||
return self::create($this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flat map over the success value.
|
||||
*
|
||||
* @template S
|
||||
* @template F
|
||||
*
|
||||
* @param callable(never):\GrahamCampbell\ResultType\Result<S,F> $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Error<E>
|
||||
*/
|
||||
public function flatMap(callable $f)
|
||||
{
|
||||
return self::create($this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the error option value.
|
||||
*
|
||||
* @return \PhpOption\Option<E>
|
||||
*/
|
||||
public function error()
|
||||
{
|
||||
return Some::create($this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Map over the error value.
|
||||
*
|
||||
* @template F
|
||||
*
|
||||
* @param callable(E):F $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Error<F>
|
||||
*/
|
||||
public function mapError(callable $f)
|
||||
{
|
||||
return self::create($f($this->value));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* This file is part of Result Type.
|
||||
*
|
||||
* (c) Graham Campbell <hello@gjcampbell.co.uk>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace GrahamCampbell\ResultType;
|
||||
|
||||
/**
|
||||
* @template-covariant T
|
||||
* @template-covariant E
|
||||
*/
|
||||
abstract class Result
|
||||
{
|
||||
/**
|
||||
* Get the success option value.
|
||||
*
|
||||
* @return \PhpOption\Option<T>
|
||||
*/
|
||||
abstract public function success();
|
||||
|
||||
/**
|
||||
* Map over the success value.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param callable(T):S $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Result<S,E>
|
||||
*/
|
||||
abstract public function map(callable $f);
|
||||
|
||||
/**
|
||||
* Flat map over the success value.
|
||||
*
|
||||
* @template S
|
||||
* @template F
|
||||
*
|
||||
* @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Result<S,E|F>
|
||||
*/
|
||||
abstract public function flatMap(callable $f);
|
||||
|
||||
/**
|
||||
* Get the error option value.
|
||||
*
|
||||
* @return \PhpOption\Option<E>
|
||||
*/
|
||||
abstract public function error();
|
||||
|
||||
/**
|
||||
* Map over the error value.
|
||||
*
|
||||
* @template F
|
||||
*
|
||||
* @param callable(E):F $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Result<T,F>
|
||||
*/
|
||||
abstract public function mapError(callable $f);
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* This file is part of Result Type.
|
||||
*
|
||||
* (c) Graham Campbell <hello@gjcampbell.co.uk>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace GrahamCampbell\ResultType;
|
||||
|
||||
use PhpOption\None;
|
||||
use PhpOption\Some;
|
||||
|
||||
/**
|
||||
* @template-covariant T
|
||||
*
|
||||
* @extends \GrahamCampbell\ResultType\Result<T,never>
|
||||
*/
|
||||
final class Success extends Result
|
||||
{
|
||||
/**
|
||||
* @var T
|
||||
*/
|
||||
private $value;
|
||||
|
||||
/**
|
||||
* Internal constructor for a success value.
|
||||
*
|
||||
* @param T $value
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function __construct($value)
|
||||
{
|
||||
$this->value = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new success value.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param S $value
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Success<S>
|
||||
*/
|
||||
public static function create($value)
|
||||
{
|
||||
return new self($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the success option value.
|
||||
*
|
||||
* @return \PhpOption\Option<T>
|
||||
*/
|
||||
public function success()
|
||||
{
|
||||
return Some::create($this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Map over the success value.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param callable(T):S $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Success<S>
|
||||
*/
|
||||
public function map(callable $f)
|
||||
{
|
||||
return self::create($f($this->value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Flat map over the success value.
|
||||
*
|
||||
* @template S
|
||||
* @template F
|
||||
*
|
||||
* @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Result<S,F>
|
||||
*/
|
||||
public function flatMap(callable $f)
|
||||
{
|
||||
return $f($this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the error option value.
|
||||
*
|
||||
* @return \PhpOption\Option<never>
|
||||
*/
|
||||
public function error()
|
||||
{
|
||||
return None::create();
|
||||
}
|
||||
|
||||
/**
|
||||
* Map over the error value.
|
||||
*
|
||||
* @template F
|
||||
*
|
||||
* @param callable(never):F $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Success<T>
|
||||
*/
|
||||
public function mapError(callable $f)
|
||||
{
|
||||
return self::create($this->value);
|
||||
}
|
||||
}
|
||||
Vendored
+76
@@ -0,0 +1,76 @@
|
||||
# Agent Guidelines
|
||||
|
||||
## Code and tooling
|
||||
|
||||
- All code must remain compatible with PHP 7.4. Run PHPStan and PHP-CS-Fixer
|
||||
only under a PHP 7.4.x runtime; never run either tool under any other PHP
|
||||
major.minor version.
|
||||
- Use fully qualified `#[\SensitiveParameter]` on concrete executable
|
||||
parameters when their established role normally carries a secret,
|
||||
credential-bearing aggregate, or confidential Guzzle-owned container, and
|
||||
the active frame can throw or invoke throwing code.
|
||||
- Repeat the attribute on every qualifying owned caller, callee, concrete trait
|
||||
method, and closure parameter. Do not add it to interfaces, abstract-only
|
||||
declarations, pure/no-realistic-throw helpers, assignment-only sites,
|
||||
arbitrary generic payloads, or completed non-recoverable derivatives.
|
||||
- For PHP 7.4 compatibility, put `#[\SensitiveParameter]` on its own line and
|
||||
the parameter on the following line, expand the complete parameter list, and
|
||||
never add a comma after the final parameter. Native trace redaction starts on
|
||||
PHP 8.2 and does not redact logs, messages, properties, wire traffic, captured
|
||||
variables, return values, or the separate backtrace `$this`/`object`.
|
||||
- Always pass an explicit character list to `trim()`, `ltrim()`, and `rtrim()`;
|
||||
never rely on the default characters.
|
||||
- Handle `preg_*` engine failures: when the result is used as data, test for
|
||||
`false` or `null` and throw a `\RuntimeException` including
|
||||
`preg_last_error_msg()`; boolean validation guards must compare strictly, such
|
||||
as `=== 1`, so an engine failure can only ever fail closed. Diagnostic
|
||||
escaping is the narrow exception: use a deterministic bytewise fallback rather
|
||||
than throwing, so it cannot obscure the original exception.
|
||||
- Anchor validation patterns to the true end of input with the `D` modifier or
|
||||
`\z`; a bare `$` accepts a trailing newline.
|
||||
- Never embed raw control bytes in exception messages and other diagnostics;
|
||||
escape or redact the offending value first.
|
||||
- Helper classes that expose only public static methods are `final` and have a
|
||||
private constructor.
|
||||
- Resist native PHP serialization when a class holds live state (streams,
|
||||
resources, handles, callbacks, credentials) or when magic methods such as
|
||||
`__destruct()` have side effects that untrusted unserialized data could
|
||||
redirect, as with the file and session write fixes in Guzzle's persisting
|
||||
cookie jars. Plain data holders, such as Guzzle's in-memory cookie jar, remain
|
||||
serializable.
|
||||
- To resist, `__serialize()` and `__unserialize()` both throw
|
||||
`\LogicException(static::class.' should never be serialized')` and its
|
||||
unserialized counterpart, usually via the `@internal` `NonSerializableTrait`.
|
||||
Where a `__destruct()` has such a side effect, it is enabled only by the
|
||||
constructor and disabled in `__wakeup()` and `__unserialize()` before
|
||||
throwing, so the protection holds even if the exception is swallowed.
|
||||
- In general, numeric inputs should not accept non-finite floats. In situations
|
||||
where they are accepted and we need to cast to a string, we should branch on
|
||||
`\is_finite($value)`, using `(string) $value` for the finite case and
|
||||
`\is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF')` otherwise.
|
||||
- Never call `strtolower()`, `strtoupper()`, `strcasecmp()`, `stripos()`, or
|
||||
other locale-sensitive case functions; use the locale-independent
|
||||
`GuzzleHttp\Psr7\Utils::asciiToLower()`, `asciiToUpper()`,
|
||||
`caselessEquals()`, and `caselessContains()` helpers instead.
|
||||
- Changes in behavior need a `CHANGELOG.md` entry in the unreleased section of
|
||||
the target branch and an `UPGRADING.md` note when the behavior differs between
|
||||
major versions.
|
||||
|
||||
## Contributor references
|
||||
|
||||
- Read the [exception guidelines](docs/contributing/exception-guidelines.md)
|
||||
before deciding which exception a change should throw.
|
||||
- Read the
|
||||
[cURL connection reuse reference](docs/contributing/curl-connection-reuse.md)
|
||||
before working on the cURL handlers or connection reuse and sharing behavior.
|
||||
|
||||
## Documentation
|
||||
|
||||
- Wrap markdown prose and PHPDoc text to 80 columns using greedy wrapping. Never
|
||||
split a markdown link or an inline code span across a line break; a line that
|
||||
cannot be broken may exceed the limit. Avoid em dashes.
|
||||
- Keep PHPDoc and the corresponding `docs/` pages in sync: shared prose is
|
||||
deliberately word-for-word identical, including boilerplate copied verbatim
|
||||
between related functions, so apply the same edit to every copy. Only
|
||||
formatting and linking may differ, such as a docs link becoming a PHPDoc
|
||||
`@see` tag; the wording must never drift.
|
||||
+2403
File diff suppressed because it is too large
Load Diff
Vendored
+1
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
Vendored
+27
@@ -0,0 +1,27 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2011 Michael Dowling <mtdowling@gmail.com>
|
||||
Copyright (c) 2012 Jeremy Lindblom <jeremeamia@gmail.com>
|
||||
Copyright (c) 2014 Graham Campbell <hello@gjcampbell.co.uk>
|
||||
Copyright (c) 2015 Márk Sági-Kazár <mark.sagikazar@gmail.com>
|
||||
Copyright (c) 2015 Tobias Schultze <webmaster@tubo-world.de>
|
||||
Copyright (c) 2016 Tobias Nyholm <tobias.nyholm@gmail.com>
|
||||
Copyright (c) 2016 George Mponos <gmponos@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
Vendored
+95
@@ -0,0 +1,95 @@
|
||||

|
||||
|
||||
# Guzzle, PHP HTTP Client
|
||||
|
||||
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and
|
||||
trivial to integrate with web services.
|
||||
|
||||
- Simple interface for building query strings, POST requests, streaming large
|
||||
uploads, streaming large downloads, using HTTP cookies, uploading JSON data,
|
||||
etc...
|
||||
- Can send both synchronous and asynchronous requests using the same interface.
|
||||
- Uses PSR-7 interfaces for requests, responses, and streams. This allows you
|
||||
to utilize other PSR-7 compatible libraries with Guzzle.
|
||||
- Supports PSR-18, allowing interoperability with other PSR-18 HTTP clients.
|
||||
- Abstracts away the underlying HTTP transport, allowing you to write
|
||||
environment and transport agnostic code; i.e., no hard dependency on cURL,
|
||||
PHP streams, sockets, or non-blocking event loops.
|
||||
- Middleware system allows you to augment and compose client behavior.
|
||||
|
||||
## Installation
|
||||
|
||||
The recommended way to install Guzzle is through
|
||||
[Composer](https://getcomposer.org/).
|
||||
|
||||
```bash
|
||||
composer require guzzlehttp/guzzle
|
||||
```
|
||||
|
||||
## Version Guidance
|
||||
|
||||
| Version | Status | PHP Version |
|
||||
|---------|--------------|--------------|
|
||||
| 8.5 | Latest | >=7.4,<8.7 |
|
||||
| 7.16 | Maintenance | >=7.2.5,<8.7 |
|
||||
| 6.5 | End of Life | >=5.5,<8.0 |
|
||||
|
||||
## Quick Start
|
||||
|
||||
```php
|
||||
$client = new \GuzzleHttp\Client();
|
||||
$response = $client->request('GET', 'https://api.example.com/users/123');
|
||||
|
||||
echo $response->getStatusCode(); // 200
|
||||
echo $response->getHeaderLine('content-type'); // 'application/json'
|
||||
echo $response->getBody(); // '{"id": 123, "name": "Ada"}'
|
||||
```
|
||||
|
||||
For more examples, see the [Quick Start](docs/quick-start.md).
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Quick Start](docs/quick-start.md)
|
||||
- [Overview](docs/overview.md)
|
||||
- [Request Options](docs/request-options.md)
|
||||
- [Uploading Data](docs/uploading-data.md)
|
||||
- [Cookies](docs/cookies.md)
|
||||
- [Exceptions](docs/exceptions.md)
|
||||
- [Guzzle and PSR-7](docs/guzzle-and-psr-7.md)
|
||||
- [Handlers](docs/handlers.md)
|
||||
- [Middleware](docs/middleware.md)
|
||||
- [Testing Guzzle Clients](docs/testing-guzzle-clients.md)
|
||||
- [FAQ](docs/faq.md)
|
||||
- [Package Ecosystem](docs/package-ecosystem.md)
|
||||
- [Upgrade Guide](UPGRADING.md)
|
||||
- [Changelog](CHANGELOG.md)
|
||||
|
||||
We use GitHub issues only to discuss bugs and new features. For support, use
|
||||
[Stack Overflow](https://stackoverflow.com/questions/tagged/guzzle), the
|
||||
[#guzzle](https://app.slack.com/client/T0D2S9JCT/CE6UAAKL4) channel on
|
||||
[PHP-HTTP Slack](https://slack.httplug.io/), or
|
||||
[Gitter](https://gitter.im/guzzle/guzzle).
|
||||
|
||||
## Security
|
||||
|
||||
If you discover a security vulnerability within this package, please send an
|
||||
email to security@tidelift.com. All security vulnerabilities will be promptly
|
||||
addressed by the security maintainers listed in the
|
||||
[Security Policy](https://github.com/guzzle/guzzle/security/policy). Please do
|
||||
not disclose security-related issues publicly until a fix has been announced.
|
||||
|
||||
## License
|
||||
|
||||
Guzzle is made available under the MIT License (MIT). Please see
|
||||
[License File](LICENSE) for more information.
|
||||
|
||||
## For Enterprise
|
||||
|
||||
Available as part of the Tidelift Subscription
|
||||
|
||||
The maintainers of Guzzle and thousands of other packages are working with
|
||||
Tidelift to deliver commercial support and maintenance for the open source
|
||||
dependencies you use to build your applications. Save time, reduce risk, and
|
||||
improve code health, while paying the maintainers of the exact dependencies you
|
||||
use.
|
||||
[Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-guzzle?utm_source=packagist-guzzlehttp-guzzle&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
|
||||
+2785
File diff suppressed because it is too large
Load Diff
+132
@@ -0,0 +1,132 @@
|
||||
{
|
||||
"name": "guzzlehttp/guzzle",
|
||||
"description": "Guzzle is a PHP HTTP client library",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"framework",
|
||||
"http",
|
||||
"rest",
|
||||
"web service",
|
||||
"curl",
|
||||
"client",
|
||||
"HTTP client",
|
||||
"PSR-7",
|
||||
"PSR-18"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Graham Campbell",
|
||||
"email": "hello@gjcampbell.co.uk",
|
||||
"homepage": "https://github.com/GrahamCampbell"
|
||||
},
|
||||
{
|
||||
"name": "Michael Dowling",
|
||||
"email": "mtdowling@gmail.com",
|
||||
"homepage": "https://github.com/mtdowling"
|
||||
},
|
||||
{
|
||||
"name": "Jeremy Lindblom",
|
||||
"email": "jeremeamia@gmail.com",
|
||||
"homepage": "https://github.com/jeremeamia"
|
||||
},
|
||||
{
|
||||
"name": "George Mponos",
|
||||
"email": "gmponos@gmail.com",
|
||||
"homepage": "https://github.com/gmponos"
|
||||
},
|
||||
{
|
||||
"name": "Tobias Nyholm",
|
||||
"email": "tobias.nyholm@gmail.com",
|
||||
"homepage": "https://github.com/Nyholm"
|
||||
},
|
||||
{
|
||||
"name": "Márk Sági-Kazár",
|
||||
"email": "mark.sagikazar@gmail.com",
|
||||
"homepage": "https://github.com/sagikazarmark"
|
||||
},
|
||||
{
|
||||
"name": "Tobias Schultze",
|
||||
"email": "webmaster@tubo-world.de",
|
||||
"homepage": "https://github.com/Tobion"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^7.4 || ^8.0",
|
||||
"ext-json": "*",
|
||||
"guzzlehttp/promises": "^3.1.1",
|
||||
"guzzlehttp/psr7": "^3.5.1",
|
||||
"psr/http-client": "^1.0",
|
||||
"psr/http-factory": "^1.0",
|
||||
"symfony/deprecation-contracts": "^2.5 || ^3.0",
|
||||
"symfony/polyfill-php80": "^1.25",
|
||||
"symfony/polyfill-php82": "^1.27"
|
||||
},
|
||||
"require-dev": {
|
||||
"ext-curl": "*",
|
||||
"bamarni/composer-bin-plugin": "^1.8.2",
|
||||
"guzzle/client-integration-tests": "4.0.1",
|
||||
"guzzlehttp/test-server": "^1.1",
|
||||
"php-http/message-factory": "^1.1",
|
||||
"phpunit/phpunit": "^9.6.34",
|
||||
"psr/log": "^1.1 || ^2.0 || ^3.0"
|
||||
},
|
||||
"provide": {
|
||||
"psr/http-client-implementation": "1.0"
|
||||
},
|
||||
"suggest": {
|
||||
"ext-curl": "Required for CURL handler support",
|
||||
"ext-intl": "Required for Internationalized Domain Name (IDN) support",
|
||||
"psr/log": "Required for using the Log middleware"
|
||||
},
|
||||
"repositories": [
|
||||
{
|
||||
"type": "package",
|
||||
"package": {
|
||||
"name": "guzzle/client-integration-tests",
|
||||
"version": "v4.0.1",
|
||||
"require": {
|
||||
"guzzlehttp/psr7": "^3.5.1",
|
||||
"php": "^7.4 || ^8.0",
|
||||
"php-http/message": "^1.0 || ^2.0",
|
||||
"phpunit/phpunit": "^9.6.34",
|
||||
"th3n3rd/cartesian-product": "^0.3"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Http\\Client\\Tests\\": "src/"
|
||||
}
|
||||
},
|
||||
"bin": [
|
||||
"bin/http_test_server"
|
||||
],
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://codeload.github.com/guzzle/client-integration-tests/zip/e54cb9d94e3aa5e125dcd7d01bec22db202444ac"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\Tests\\": "tests/"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"allow-plugins": {
|
||||
"bamarni/composer-bin-plugin": true
|
||||
},
|
||||
"preferred-install": "dist",
|
||||
"sort-packages": true
|
||||
},
|
||||
"extra": {
|
||||
"bamarni-bin": {
|
||||
"bin-links": true,
|
||||
"forward-command": false
|
||||
}
|
||||
}
|
||||
}
|
||||
+515
@@ -0,0 +1,515 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Auth;
|
||||
|
||||
use GuzzleHttp\Psr7;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class DigestAuth
|
||||
{
|
||||
/**
|
||||
* @var array<string, array{hash: string, sess: bool, rank: int, header: string}>
|
||||
*/
|
||||
private const ALGORITHMS = [
|
||||
'MD5' => ['hash' => 'md5', 'sess' => false, 'rank' => 10, 'header' => 'MD5'],
|
||||
'MD5-SESS' => ['hash' => 'md5', 'sess' => true, 'rank' => 11, 'header' => 'MD5-sess'],
|
||||
'SHA-256' => ['hash' => 'sha256', 'sess' => false, 'rank' => 20, 'header' => 'SHA-256'],
|
||||
'SHA-256-SESS' => ['hash' => 'sha256', 'sess' => true, 'rank' => 21, 'header' => 'SHA-256-sess'],
|
||||
'SHA-512-256' => ['hash' => 'sha512/256', 'sess' => false, 'rank' => 30, 'header' => 'SHA-512-256'],
|
||||
'SHA-512-256-SESS' => ['hash' => 'sha512/256', 'sess' => true, 'rank' => 31, 'header' => 'SHA-512-256-sess'],
|
||||
];
|
||||
|
||||
/**
|
||||
* @var array<string, true>
|
||||
*/
|
||||
private const DIGEST_CHALLENGE_PARAMETER_NAMES = [
|
||||
'realm' => true,
|
||||
'domain' => true,
|
||||
'nonce' => true,
|
||||
'opaque' => true,
|
||||
'stale' => true,
|
||||
'algorithm' => true,
|
||||
'qop' => true,
|
||||
'charset' => true,
|
||||
'userhash' => true,
|
||||
];
|
||||
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
public static function selectChallenge(
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
): ?DigestChallenge {
|
||||
$selected = null;
|
||||
|
||||
foreach ($response->getHeader('WWW-Authenticate') as $header) {
|
||||
foreach (self::parseAuthenticateHeader($header) as $challenge) {
|
||||
if ($challenge['scheme'] !== 'digest' || $challenge['invalid']) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$digest = self::createChallenge($challenge['params']);
|
||||
if ($digest === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($selected === null || $digest->algorithm['rank'] > $selected->algorithm['rank']) {
|
||||
$selected = $digest;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $selected;
|
||||
}
|
||||
|
||||
public static function authorizationHeader(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
DigestChallenge $challenge,
|
||||
string $username,
|
||||
#[\SensitiveParameter]
|
||||
string $password,
|
||||
string $cnonce,
|
||||
string $nc = '00000001'
|
||||
): ?string {
|
||||
if ($challenge->algorithm['sess'] && $challenge->qop === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$uri = $request->getRequestTarget();
|
||||
if ($uri === '') {
|
||||
$uri = '/';
|
||||
}
|
||||
|
||||
foreach ([$username, $challenge->realm, $challenge->nonce, $uri, $cnonce] as $value) {
|
||||
if (!self::isHeaderSafe($value)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if ($challenge->opaque !== null && !self::isHeaderSafe($challenge->opaque)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($challenge->qop !== null && !self::isNonceCount($nc)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$hash = $challenge->algorithm['hash'];
|
||||
$ha1 = \hash($hash, $username.':'.$challenge->realm.':'.$password);
|
||||
|
||||
if ($challenge->algorithm['sess']) {
|
||||
$ha1 = \hash($hash, $ha1.':'.$challenge->nonce.':'.$cnonce);
|
||||
}
|
||||
|
||||
$ha2 = \hash($hash, $request->getMethod().':'.$uri);
|
||||
$response = $challenge->qop === null
|
||||
? \hash($hash, $ha1.':'.$challenge->nonce.':'.$ha2)
|
||||
: \hash($hash, $ha1.':'.$challenge->nonce.':'.$nc.':'.$cnonce.':'.$challenge->qop.':'.$ha2);
|
||||
|
||||
if ($challenge->userhash) {
|
||||
$headerUsername = \hash($hash, $username.':'.$challenge->realm);
|
||||
if ($headerUsername === false) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
$headerUsername = $username;
|
||||
}
|
||||
|
||||
$parts = [
|
||||
'username='.self::quote($headerUsername),
|
||||
'realm='.self::quote($challenge->realm),
|
||||
'nonce='.self::quote($challenge->nonce),
|
||||
'uri='.self::quote($uri),
|
||||
'response='.self::quote($response),
|
||||
'algorithm='.$challenge->algorithm['header'],
|
||||
];
|
||||
|
||||
if ($challenge->opaque !== null) {
|
||||
$parts[] = 'opaque='.self::quote($challenge->opaque);
|
||||
}
|
||||
|
||||
if ($challenge->qop !== null) {
|
||||
$parts[] = 'qop='.$challenge->qop;
|
||||
$parts[] = 'nc='.$nc;
|
||||
$parts[] = 'cnonce='.self::quote($cnonce);
|
||||
}
|
||||
|
||||
if ($challenge->userhash) {
|
||||
$parts[] = 'userhash=true';
|
||||
}
|
||||
|
||||
return 'Digest '.\implode(', ', $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{scheme: string, params: array<string, string>, invalid: bool}>
|
||||
*/
|
||||
public static function parseAuthenticateHeader(string $header): array
|
||||
{
|
||||
$length = \strlen($header);
|
||||
$offset = 0;
|
||||
$challenges = [];
|
||||
|
||||
while (true) {
|
||||
self::skipSeparators($header, $offset, $length);
|
||||
if ($offset >= $length) {
|
||||
break;
|
||||
}
|
||||
|
||||
$scheme = self::readToken($header, $offset, $length);
|
||||
if ($scheme === null) {
|
||||
break;
|
||||
}
|
||||
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
|
||||
if (self::skipToken68Challenge($header, $offset, $length)) {
|
||||
$challenges[] = [
|
||||
'scheme' => Psr7\Utils::asciiToLower($scheme),
|
||||
'params' => [],
|
||||
'invalid' => false,
|
||||
];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$params = [];
|
||||
$invalid = false;
|
||||
|
||||
while ($offset < $length) {
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
|
||||
if ($offset < $length && $header[$offset] === ',') {
|
||||
if (self::commaStartsNextChallenge($header, $offset + 1, $length)) {
|
||||
if (Psr7\Utils::caselessEquals($scheme, 'Digest')
|
||||
&& self::commaStartsKnownDigestParameterWithoutValue($header, $offset + 1, $length)
|
||||
) {
|
||||
$invalid = true;
|
||||
break;
|
||||
}
|
||||
|
||||
++$offset;
|
||||
break;
|
||||
}
|
||||
|
||||
++$offset;
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = self::readToken($header, $offset, $length);
|
||||
if ($name === null) {
|
||||
if ($offset < $length) {
|
||||
$invalid = true;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
if ($offset >= $length || $header[$offset] !== '=') {
|
||||
$invalid = true;
|
||||
break;
|
||||
}
|
||||
|
||||
++$offset;
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
|
||||
$value = self::readValue($header, $offset, $length);
|
||||
if ($value === null) {
|
||||
$invalid = true;
|
||||
break;
|
||||
}
|
||||
|
||||
$lowerName = Psr7\Utils::asciiToLower($name);
|
||||
if (\array_key_exists($lowerName, $params)) {
|
||||
$invalid = true;
|
||||
}
|
||||
|
||||
$params[$lowerName] = $value;
|
||||
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
if ($offset >= $length) {
|
||||
break;
|
||||
}
|
||||
|
||||
if ($header[$offset] !== ',') {
|
||||
$invalid = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$challenges[] = [
|
||||
'scheme' => Psr7\Utils::asciiToLower($scheme),
|
||||
'params' => $params,
|
||||
'invalid' => $invalid,
|
||||
];
|
||||
}
|
||||
|
||||
return $challenges;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $params
|
||||
*/
|
||||
private static function createChallenge(array $params): ?DigestChallenge
|
||||
{
|
||||
if (!isset($params['nonce']) || $params['nonce'] === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isset($params['charset']) && !Psr7\Utils::caselessEquals($params['charset'], 'UTF-8')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$algorithm = self::algorithm($params['algorithm'] ?? null);
|
||||
if ($algorithm === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$qop = self::selectQop($params['qop'] ?? null);
|
||||
if ($qop === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($algorithm['sess'] && $qop === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$challenge = new DigestChallenge();
|
||||
$challenge->algorithm = $algorithm;
|
||||
$challenge->realm = $params['realm'] ?? '';
|
||||
$challenge->nonce = $params['nonce'];
|
||||
$challenge->opaque = $params['opaque'] ?? null;
|
||||
if (isset($params['domain'])) {
|
||||
$domainAreas = \preg_split('/[ \t]+/', $params['domain']);
|
||||
|
||||
if ($domainAreas === false) {
|
||||
throw new \RuntimeException('Unable to split the Digest domain list: '.\preg_last_error_msg());
|
||||
}
|
||||
|
||||
$challenge->domain = \array_values(\array_filter($domainAreas));
|
||||
} else {
|
||||
$challenge->domain = [];
|
||||
}
|
||||
$challenge->qop = $qop;
|
||||
$challenge->stale = isset($params['stale']) && Psr7\Utils::caselessEquals($params['stale'], 'true');
|
||||
$challenge->userhash = isset($params['userhash']) && Psr7\Utils::caselessEquals($params['userhash'], 'true');
|
||||
|
||||
return $challenge;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{name: string, hash: string, sess: bool, rank: int, header: string}|null
|
||||
*/
|
||||
private static function algorithm(?string $algorithm): ?array
|
||||
{
|
||||
$name = Psr7\Utils::asciiToUpper($algorithm ?? 'MD5');
|
||||
|
||||
if (!isset(self::ALGORITHMS[$name])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$mapped = self::ALGORITHMS[$name];
|
||||
if (!\in_array($mapped['hash'], \hash_algos(), true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['name' => $name] + $mapped;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|false|null
|
||||
*/
|
||||
private static function selectQop(?string $qop)
|
||||
{
|
||||
if ($qop === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$tokens = \array_map(
|
||||
static function (string $token): string {
|
||||
return Psr7\Utils::asciiToLower(\trim($token, " \t"));
|
||||
},
|
||||
\explode(',', $qop)
|
||||
);
|
||||
|
||||
return \in_array('auth', $tokens, true) ? 'auth' : false;
|
||||
}
|
||||
|
||||
private static function quote(string $value): string
|
||||
{
|
||||
return '"'.\strtr($value, [
|
||||
'\\' => '\\\\',
|
||||
'"' => '\\"',
|
||||
]).'"';
|
||||
}
|
||||
|
||||
private static function isHeaderSafe(string $value): bool
|
||||
{
|
||||
return \preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/D', $value) === 1;
|
||||
}
|
||||
|
||||
private static function isNonceCount(string $nc): bool
|
||||
{
|
||||
// Nonce counts start at one.
|
||||
return $nc !== '00000000' && \preg_match('/^[0-9a-f]{8}$/D', $nc) === 1;
|
||||
}
|
||||
|
||||
private static function commaStartsNextChallenge(string $header, int $offset, int $length): bool
|
||||
{
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
$nextOffset = $offset;
|
||||
$token = self::readToken($header, $nextOffset, $length);
|
||||
if ($token === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
self::skipWhitespace($header, $nextOffset, $length);
|
||||
|
||||
return $nextOffset >= $length || $header[$nextOffset] !== '=';
|
||||
}
|
||||
|
||||
private static function commaStartsKnownDigestParameterWithoutValue(string $header, int $offset, int $length): bool
|
||||
{
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
$name = self::readToken($header, $offset, $length);
|
||||
if ($name === null || !isset(self::DIGEST_CHALLENGE_PARAMETER_NAMES[Psr7\Utils::asciiToLower($name)])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
|
||||
return $offset >= $length || $header[$offset] !== '=';
|
||||
}
|
||||
|
||||
private static function skipToken68Challenge(string $header, int &$offset, int $length): bool
|
||||
{
|
||||
$cursor = $offset;
|
||||
$hasValue = false;
|
||||
while ($cursor < $length && self::isToken68Char($header[$cursor])) {
|
||||
$hasValue = true;
|
||||
++$cursor;
|
||||
}
|
||||
|
||||
while ($cursor < $length && $header[$cursor] === '=') {
|
||||
++$cursor;
|
||||
}
|
||||
|
||||
if (!$hasValue) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$after = $cursor;
|
||||
self::skipWhitespace($header, $after, $length);
|
||||
|
||||
if ($after < $length && $header[$after] !== ',') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$offset = $after;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static function skipSeparators(string $header, int &$offset, int $length): void
|
||||
{
|
||||
while ($offset < $length) {
|
||||
$char = $header[$offset];
|
||||
if ($char !== ',' && !self::isWhitespace($char)) {
|
||||
return;
|
||||
}
|
||||
|
||||
++$offset;
|
||||
}
|
||||
}
|
||||
|
||||
private static function skipWhitespace(string $header, int &$offset, int $length): void
|
||||
{
|
||||
while ($offset < $length && self::isWhitespace($header[$offset])) {
|
||||
++$offset;
|
||||
}
|
||||
}
|
||||
|
||||
private static function isWhitespace(string $char): bool
|
||||
{
|
||||
return $char === ' ' || $char === "\t";
|
||||
}
|
||||
|
||||
private static function readToken(string $header, int &$offset, int $length): ?string
|
||||
{
|
||||
$start = $offset;
|
||||
while ($offset < $length && self::isTokenChar($header[$offset])) {
|
||||
++$offset;
|
||||
}
|
||||
|
||||
if ($offset === $start) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$token = \substr($header, $start, $offset - $start);
|
||||
|
||||
return $token === false ? null : $token;
|
||||
}
|
||||
|
||||
private static function isTokenChar(string $char): bool
|
||||
{
|
||||
return \strspn($char, "!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") === 1;
|
||||
}
|
||||
|
||||
private static function isToken68Char(string $char): bool
|
||||
{
|
||||
return \strspn($char, '-._~+/0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') === 1;
|
||||
}
|
||||
|
||||
private static function readValue(string $header, int &$offset, int $length): ?string
|
||||
{
|
||||
if ($offset >= $length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($header[$offset] === '"') {
|
||||
return self::readQuotedString($header, $offset, $length);
|
||||
}
|
||||
|
||||
return self::readToken($header, $offset, $length);
|
||||
}
|
||||
|
||||
private static function readQuotedString(string $header, int &$offset, int $length): ?string
|
||||
{
|
||||
++$offset;
|
||||
$value = '';
|
||||
$escaped = false;
|
||||
|
||||
while ($offset < $length) {
|
||||
$char = $header[$offset++];
|
||||
|
||||
if ($escaped) {
|
||||
$value .= $char;
|
||||
$escaped = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($char === '\\') {
|
||||
$escaped = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($char === '"') {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$value .= $char;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Auth;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class DigestChallenge
|
||||
{
|
||||
/** @var array{name: string, hash: string, sess: bool, rank: int, header: string} */
|
||||
public array $algorithm;
|
||||
|
||||
public string $realm = '';
|
||||
|
||||
public string $nonce;
|
||||
|
||||
public ?string $opaque = null;
|
||||
|
||||
/** @var list<string> */
|
||||
public array $domain = [];
|
||||
|
||||
public ?string $qop = null;
|
||||
|
||||
public bool $stale = false;
|
||||
|
||||
public bool $userhash = false;
|
||||
}
|
||||
+846
@@ -0,0 +1,846 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Auth\DigestAuth;
|
||||
use GuzzleHttp\Auth\DigestChallenge;
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\Exception\ResponseException;
|
||||
use GuzzleHttp\Promise as P;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\Psr7\HttpFactory;
|
||||
use GuzzleHttp\Psr7\LazyOpenStream;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\StreamFactoryInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
/**
|
||||
* Applies built-in Basic authentication and handles Digest authentication
|
||||
* challenges.
|
||||
*/
|
||||
final class AuthMiddleware
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
private const DIGEST_MAX_RETRIES = 2;
|
||||
|
||||
private const CHALLENGE_CACHE_LIMIT = 32;
|
||||
|
||||
/**
|
||||
* Request option carrying nonce counts already spent during a Digest
|
||||
* handshake, so stale retries advance instead of repeating a count.
|
||||
*/
|
||||
private const DIGEST_NONCE_COUNTS_OPTION = '__guzzle_digest_nonce_counts';
|
||||
|
||||
/**
|
||||
* Headers that describe the request payload. A probe with an empty body
|
||||
* must not carry them.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
private const DIGEST_PROBE_PAYLOAD_HEADERS = [
|
||||
'Transfer-Encoding',
|
||||
'Expect',
|
||||
'Trailer',
|
||||
'Content-Range',
|
||||
'Content-Encoding',
|
||||
'Content-MD5',
|
||||
'Digest',
|
||||
'Content-Digest',
|
||||
'Repr-Digest',
|
||||
];
|
||||
|
||||
/**
|
||||
* @var callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private $nextHandler;
|
||||
|
||||
/**
|
||||
* @var callable(): string
|
||||
*/
|
||||
private $cnonceGenerator;
|
||||
|
||||
private bool $reuseChallenges;
|
||||
|
||||
private ?string $credentialHashSecret = null;
|
||||
|
||||
/**
|
||||
* @var array<string, array{challenge: DigestChallenge, credentials: string, nextNc: int}>
|
||||
*/
|
||||
private array $digestChallenges = [];
|
||||
|
||||
/**
|
||||
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $nextHandler
|
||||
* @param (callable(): string)|null $cnonceGenerator
|
||||
*/
|
||||
public function __construct(callable $nextHandler, ?callable $cnonceGenerator = null, bool $reuseChallenges = true)
|
||||
{
|
||||
$this->nextHandler = $nextHandler;
|
||||
$this->cnonceGenerator = $cnonceGenerator ?? static function (): string {
|
||||
return \bin2hex(\random_bytes(16));
|
||||
};
|
||||
$this->reuseChallenges = $reuseChallenges;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
public function __invoke(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
): PromiseInterface {
|
||||
$auth = $options['auth'] ?? null;
|
||||
if ($auth === null || $auth === false || $auth === [] || \is_string($auth)) {
|
||||
return ($this->nextHandler)($request, $options);
|
||||
}
|
||||
|
||||
$normalizedAuth = self::normalizeAuth($auth);
|
||||
if ($normalizedAuth === null) {
|
||||
return ($this->nextHandler)($request, $options);
|
||||
}
|
||||
|
||||
[$username, $password, $type] = $normalizedAuth;
|
||||
|
||||
if ($type === 'basic') {
|
||||
return $this->sendBasic($request, $options, $username, $password);
|
||||
}
|
||||
|
||||
return $this->sendDigest($request, $options, $username, $password);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $auth
|
||||
*
|
||||
* @return array{0: string, 1: string, 2: 'basic'|'digest'}|null
|
||||
*/
|
||||
private static function normalizeAuth(
|
||||
#[\SensitiveParameter]
|
||||
array $auth
|
||||
): ?array {
|
||||
$type = 'basic';
|
||||
if (\array_key_exists(2, $auth) && $auth[2] !== null) {
|
||||
if (!\is_string($auth[2])) {
|
||||
throw new InvalidArgumentException('auth type must be a string');
|
||||
}
|
||||
|
||||
$type = Psr7\Utils::asciiToLower($auth[2]);
|
||||
}
|
||||
|
||||
if (!\in_array($type, ['basic', 'digest'], true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!\array_key_exists(0, $auth) || !\array_key_exists(1, $auth)) {
|
||||
throw new InvalidArgumentException('auth must contain username and password strings');
|
||||
}
|
||||
|
||||
if (!\is_string($auth[0]) || !\is_string($auth[1])) {
|
||||
throw new InvalidArgumentException('auth must contain username and password strings');
|
||||
}
|
||||
|
||||
return [$auth[0], $auth[1], $type];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private function sendBasic(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
string $username,
|
||||
#[\SensitiveParameter]
|
||||
string $password
|
||||
): PromiseInterface {
|
||||
if (\strpos($username, ':') !== false) {
|
||||
throw new InvalidArgumentException('Basic authentication username must not contain a colon');
|
||||
}
|
||||
|
||||
if (\preg_match('/[\x00-\x1F\x7F]/', $username.$password) !== 0) {
|
||||
throw new InvalidArgumentException('Basic authentication credentials must not contain ASCII control characters');
|
||||
}
|
||||
|
||||
unset($options['auth']);
|
||||
|
||||
return ($this->nextHandler)(
|
||||
$request->withHeader('Authorization', 'Basic '.\base64_encode($username.':'.$password)),
|
||||
$options
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private function sendDigest(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
string $username,
|
||||
#[\SensitiveParameter]
|
||||
string $password
|
||||
): PromiseInterface {
|
||||
$preemptive = $this->reuseChallenges
|
||||
? $this->preemptiveDigestRequest($request, $username, $password)
|
||||
: null;
|
||||
|
||||
if ($preemptive !== null) {
|
||||
$preemptiveOptions = self::withTemporarySink($options);
|
||||
unset($preemptiveOptions['auth']);
|
||||
|
||||
return ($this->nextHandler)($preemptive, $preemptiveOptions)->then(
|
||||
function (
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
) use ($request, $options, $preemptiveOptions, $username, $password) {
|
||||
// Clear on 4xx/5xx other than 401 so non-conformant stale-nonce
|
||||
// errors cannot poison the cache indefinitely.
|
||||
$status = $response->getStatusCode();
|
||||
if ($status >= 400 && $status !== 401) {
|
||||
$this->clearDigestChallenge($request);
|
||||
}
|
||||
|
||||
return $this->handleDigestResponse($request, $options, $preemptiveOptions, $response, $username, $password, false);
|
||||
},
|
||||
function (
|
||||
#[\SensitiveParameter]
|
||||
$reason
|
||||
) use ($request, $preemptiveOptions) {
|
||||
return $this->handleDigestRejection($request, $preemptiveOptions, $reason, true);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
$probeOptions = self::withTemporarySink($options);
|
||||
unset($probeOptions['auth']);
|
||||
|
||||
[$probeRequest, $bodyWithheld] = self::probeRequest($request, $options);
|
||||
|
||||
if ($bodyWithheld) {
|
||||
// The probe has no payload, so prepare_body must not add Expect
|
||||
// if a custom empty stream has unknown size.
|
||||
$probeOptions[RequestOptions::EXPECT] = false;
|
||||
}
|
||||
|
||||
return ($this->nextHandler)($probeRequest, $probeOptions)->then(
|
||||
function (
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
) use ($request, $options, $probeOptions, $username, $password, $bodyWithheld) {
|
||||
return $this->handleDigestResponse($request, $options, $probeOptions, $response, $username, $password, $bodyWithheld);
|
||||
},
|
||||
function (
|
||||
#[\SensitiveParameter]
|
||||
$reason
|
||||
) use ($request, $probeOptions) {
|
||||
return $this->handleDigestRejection($request, $probeOptions, $reason, false);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private function preemptiveDigestRequest(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
string $username,
|
||||
#[\SensitiveParameter]
|
||||
string $password
|
||||
): ?RequestInterface {
|
||||
try {
|
||||
if ($request->getBody()->getSize() !== 0) {
|
||||
return null;
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$key = self::digestCacheKey($request);
|
||||
if ($key === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$entry = $this->digestChallenges[$key] ?? null;
|
||||
if ($entry === null
|
||||
|| $entry['credentials'] !== $this->digestCredentialKey($username, $password)
|
||||
|| !self::challengeCoversRequest($entry['challenge'], $request)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$authorization = DigestAuth::authorizationHeader(
|
||||
$request,
|
||||
$entry['challenge'],
|
||||
$username,
|
||||
$password,
|
||||
($this->cnonceGenerator)(),
|
||||
\sprintf('%08x', $entry['nextNc'])
|
||||
);
|
||||
|
||||
if ($authorization === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
++$this->digestChallenges[$key]['nextNc'];
|
||||
|
||||
return $request->withHeader('Authorization', $authorization);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the unauthenticated probe request for a Digest handshake.
|
||||
*
|
||||
* @return array{0: RequestInterface, 1: bool}
|
||||
*/
|
||||
private static function probeRequest(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
): array {
|
||||
$probe = $request->withoutHeader('Authorization');
|
||||
|
||||
try {
|
||||
$size = $probe->getBody()->getSize();
|
||||
} catch (\Exception $e) {
|
||||
$size = null;
|
||||
}
|
||||
|
||||
if ($size === 0) {
|
||||
return [$probe, false];
|
||||
}
|
||||
|
||||
$streamFactory = self::requireStreamFactory(
|
||||
$options[RequestOptions::STREAM_FACTORY] ?? new HttpFactory()
|
||||
);
|
||||
|
||||
$probe = $probe->withBody($streamFactory->createStream(''))
|
||||
->withHeader('Content-Length', '0');
|
||||
|
||||
foreach (self::DIGEST_PROBE_PAYLOAD_HEADERS as $header) {
|
||||
$probe = $probe->withoutHeader($header);
|
||||
}
|
||||
|
||||
return [$probe, true];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ResponseInterface|PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private function handleDigestResponse(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
#[\SensitiveParameter]
|
||||
array $probeOptions,
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response,
|
||||
string $username,
|
||||
#[\SensitiveParameter]
|
||||
string $password,
|
||||
bool $bodyWithheld
|
||||
) {
|
||||
$status = $response->getStatusCode();
|
||||
|
||||
$previousEntry = null;
|
||||
if ($this->reuseChallenges && $status === 401) {
|
||||
$key = self::digestCacheKey($request);
|
||||
$previousEntry = $key !== null ? ($this->digestChallenges[$key] ?? null) : null;
|
||||
$this->clearDigestChallenge($request);
|
||||
}
|
||||
|
||||
if ($status !== 401) {
|
||||
if ($this->reuseChallenges && $response->hasHeader('Authentication-Info')) {
|
||||
$this->clearDigestChallenge($request);
|
||||
}
|
||||
|
||||
$response = self::restoreOriginalSink($request, $response, $probeOptions);
|
||||
|
||||
if ($bodyWithheld && $status !== 407 && !self::isRedirectLikeResponse($response)) {
|
||||
throw new ResponseException(
|
||||
'Digest authentication failed because the server did not issue a challenge; the request was probed without its body',
|
||||
$request,
|
||||
$response
|
||||
);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
$challenge = DigestAuth::selectChallenge($response);
|
||||
if ($challenge === null) {
|
||||
return self::restoreOriginalSink($request, $response, $probeOptions);
|
||||
}
|
||||
|
||||
$retries = $options['__guzzle_digest_retries'] ?? 0;
|
||||
if (!\is_int($retries)) {
|
||||
$retries = 0;
|
||||
}
|
||||
|
||||
if (($retries > 0 && !$challenge->stale) || $retries >= self::DIGEST_MAX_RETRIES) {
|
||||
return self::restoreOriginalSink($request, $response, $probeOptions);
|
||||
}
|
||||
|
||||
try {
|
||||
self::rewindBodyForRetry($request, $bodyWithheld);
|
||||
} catch (\Exception $e) {
|
||||
$response = self::restoreOriginalSink($request, $response, $probeOptions);
|
||||
|
||||
throw new ResponseException(
|
||||
'Digest authentication failed because the request body could not be rewound',
|
||||
$request,
|
||||
$response,
|
||||
$e
|
||||
);
|
||||
}
|
||||
|
||||
$nonceCounts = self::digestNonceCountsFromOptions($options);
|
||||
|
||||
if ($previousEntry !== null
|
||||
&& $previousEntry['credentials'] === $this->digestCredentialKey($username, $password)
|
||||
) {
|
||||
self::rememberDigestNonceCount($nonceCounts, $previousEntry['challenge'], $previousEntry['nextNc']);
|
||||
}
|
||||
|
||||
$nc = $challenge->qop === null ? 1 : ($nonceCounts[self::digestNonceCountKey($challenge)] ?? 1);
|
||||
|
||||
$authorization = DigestAuth::authorizationHeader(
|
||||
$request,
|
||||
$challenge,
|
||||
$username,
|
||||
$password,
|
||||
($this->cnonceGenerator)(),
|
||||
\sprintf('%08x', $nc)
|
||||
);
|
||||
|
||||
if ($authorization === null) {
|
||||
return self::restoreOriginalSink($request, $response, $probeOptions);
|
||||
}
|
||||
|
||||
$response->getBody()->close();
|
||||
|
||||
self::rememberDigestNonceCount($nonceCounts, $challenge, $nc + 1);
|
||||
|
||||
$retryOptions = $options;
|
||||
$retryOptions['__guzzle_digest_retries'] = $retries + 1;
|
||||
$retryOptions[self::DIGEST_NONCE_COUNTS_OPTION] = $nonceCounts;
|
||||
$downstreamOptions = $retryOptions;
|
||||
// The nonce-count map only carries handshake state into the retry
|
||||
// recursion; downstream handlers must not observe it.
|
||||
unset($downstreamOptions[self::DIGEST_NONCE_COUNTS_OPTION]);
|
||||
// The caller's delay applies once, before the first Digest leg, not
|
||||
// before each handshake retry.
|
||||
unset($downstreamOptions[RequestOptions::DELAY]);
|
||||
$downstreamOptions = self::withTemporarySink($downstreamOptions);
|
||||
unset($downstreamOptions['auth']);
|
||||
|
||||
$retryRequest = $request->withHeader('Authorization', $authorization);
|
||||
|
||||
return ($this->nextHandler)($retryRequest, $downstreamOptions)->then(
|
||||
function (
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $retryResponse
|
||||
) use ($retryRequest, $retryOptions, $downstreamOptions, $username, $password, $challenge, $nc) {
|
||||
if ($this->reuseChallenges && self::isCacheableDigestSuccess($retryResponse)) {
|
||||
$this->storeDigestChallenge($retryRequest, $challenge, $username, $password, $nc + 1);
|
||||
}
|
||||
|
||||
return $this->handleDigestResponse($retryRequest, $retryOptions, $downstreamOptions, $retryResponse, $username, $password, false);
|
||||
},
|
||||
function (
|
||||
#[\SensitiveParameter]
|
||||
$reason
|
||||
) use ($retryRequest, $downstreamOptions) {
|
||||
return $this->handleDigestRejection($retryRequest, $downstreamOptions, $reason, false);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private static function isCacheableDigestSuccess(ResponseInterface $response): bool
|
||||
{
|
||||
$status = $response->getStatusCode();
|
||||
|
||||
return $status >= 200 && $status < 400 && !$response->hasHeader('Authentication-Info');
|
||||
}
|
||||
|
||||
private function storeDigestChallenge(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
DigestChallenge $challenge,
|
||||
string $username,
|
||||
#[\SensitiveParameter]
|
||||
string $password,
|
||||
int $nextNc
|
||||
): void {
|
||||
$key = self::digestCacheKey($request);
|
||||
if ($key === null || $challenge->qop === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
unset($this->digestChallenges[$key]);
|
||||
|
||||
if (\count($this->digestChallenges) >= self::CHALLENGE_CACHE_LIMIT) {
|
||||
\array_shift($this->digestChallenges);
|
||||
}
|
||||
|
||||
$this->digestChallenges[$key] = [
|
||||
'challenge' => $challenge,
|
||||
'credentials' => $this->digestCredentialKey($username, $password),
|
||||
'nextNc' => $nextNc,
|
||||
];
|
||||
}
|
||||
|
||||
private function clearDigestChallenge(RequestInterface $request): void
|
||||
{
|
||||
$key = self::digestCacheKey($request);
|
||||
if ($key !== null) {
|
||||
unset($this->digestChallenges[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $options
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
private static function digestNonceCountsFromOptions(array $options): array
|
||||
{
|
||||
$counts = $options[self::DIGEST_NONCE_COUNTS_OPTION] ?? [];
|
||||
if (!\is_array($counts)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$normalized = [];
|
||||
foreach ($counts as $key => $nextNc) {
|
||||
if (\is_string($key) && \is_int($nextNc) && $nextNc > 0 && $nextNc < \PHP_INT_MAX) {
|
||||
$normalized[$key] = $nextNc;
|
||||
}
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
private static function digestNonceCountKey(DigestChallenge $challenge): string
|
||||
{
|
||||
return \implode("\0", [
|
||||
$challenge->realm,
|
||||
$challenge->nonce,
|
||||
$challenge->qop ?? '',
|
||||
$challenge->algorithm['header'],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, int> $counts
|
||||
*/
|
||||
private static function rememberDigestNonceCount(array &$counts, DigestChallenge $challenge, int $nextNc): void
|
||||
{
|
||||
if ($challenge->qop === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$key = self::digestNonceCountKey($challenge);
|
||||
$counts[$key] = \max($counts[$key] ?? 1, $nextNc);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $reason
|
||||
*
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private function handleDigestRejection(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
#[\SensitiveParameter]
|
||||
$reason,
|
||||
bool $preemptive
|
||||
): PromiseInterface {
|
||||
if ($this->reuseChallenges && $reason instanceof ResponseException) {
|
||||
$response = $reason->getResponse();
|
||||
|
||||
if ($response->getStatusCode() === 401
|
||||
|| $response->hasHeader('Authentication-Info')
|
||||
|| ($preemptive && $response->getStatusCode() >= 400)
|
||||
) {
|
||||
$this->clearDigestChallenge($request);
|
||||
}
|
||||
}
|
||||
|
||||
return self::restoreOriginalSinkOnRejection($options, $reason);
|
||||
}
|
||||
|
||||
private static function digestCacheKey(RequestInterface $request): ?string
|
||||
{
|
||||
$uri = $request->getUri();
|
||||
$scheme = Psr7\Utils::asciiToLower($uri->getScheme());
|
||||
$host = HostIdentity::canonicalHost($uri->getHost());
|
||||
|
||||
if (($scheme !== 'http' && $scheme !== 'https') || $host === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$port = $uri->getPort() ?? ($scheme === 'https' ? 443 : 80);
|
||||
|
||||
return $scheme.'://'.$host.':'.$port.'|'.HostIdentity::canonicalHostHeader($request->getHeaderLine('Host'));
|
||||
}
|
||||
|
||||
private function digestCredentialKey(
|
||||
string $username,
|
||||
#[\SensitiveParameter]
|
||||
string $password
|
||||
): string {
|
||||
if ($this->credentialHashSecret === null) {
|
||||
$this->credentialHashSecret = \random_bytes(32);
|
||||
}
|
||||
|
||||
return \hash_hmac('sha256', $username."\0".$password, $this->credentialHashSecret);
|
||||
}
|
||||
|
||||
private static function challengeCoversRequest(DigestChallenge $challenge, RequestInterface $request): bool
|
||||
{
|
||||
if ($challenge->domain === []) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$target = $request->getRequestTarget();
|
||||
foreach ($challenge->domain as $space) {
|
||||
$prefix = self::protectionSpacePath($space, $request);
|
||||
if ($prefix !== null && \str_starts_with($target, $prefix)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function protectionSpacePath(string $space, RequestInterface $request): ?string
|
||||
{
|
||||
if ($space === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($space[0] === '/') {
|
||||
return $space;
|
||||
}
|
||||
|
||||
try {
|
||||
// A server must not be able to raise the psr7 host deprecation.
|
||||
$uri = (new Psr7\ErrorScope(\E_USER_DEPRECATED))->run(static function () use ($space): Psr7\Uri {
|
||||
return new Psr7\Uri($space);
|
||||
});
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (Psr7\UriComparator::isCrossOrigin($uri, self::effectiveRequestUri($request))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$path = $uri->getPath();
|
||||
$prefix = $path === '' ? '/' : $path;
|
||||
|
||||
if ($uri->getQuery() !== '') {
|
||||
$prefix .= '?'.$uri->getQuery();
|
||||
}
|
||||
|
||||
return $prefix;
|
||||
}
|
||||
|
||||
private static function effectiveRequestUri(RequestInterface $request): UriInterface
|
||||
{
|
||||
$uri = $request->getUri();
|
||||
$host = $request->getHeaderLine('Host');
|
||||
if ($host === '' || Psr7\Utils::caselessEquals($host, $uri->getHost())) {
|
||||
return $uri;
|
||||
}
|
||||
|
||||
try {
|
||||
$authority = new Psr7\Uri('//'.$host);
|
||||
if ($authority->getHost() === '') {
|
||||
return $uri;
|
||||
}
|
||||
|
||||
return $uri->withHost($authority->getHost())->withPort($authority->getPort());
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return $uri;
|
||||
}
|
||||
}
|
||||
|
||||
private static function isRedirectLikeResponse(ResponseInterface $response): bool
|
||||
{
|
||||
return $response->hasHeader('Location')
|
||||
&& \in_array($response->getStatusCode(), [301, 302, 303, 307, 308], true);
|
||||
}
|
||||
|
||||
private static function rewindBodyForRetry(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
bool $bodyWithheld
|
||||
): void {
|
||||
$body = $request->getBody();
|
||||
|
||||
if (!$bodyWithheld) {
|
||||
try {
|
||||
if ($body->getSize() === 0) {
|
||||
return;
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
// Fall through to the standard rewind path.
|
||||
}
|
||||
|
||||
Psr7\Message::rewindBody($request);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($body->isSeekable()) {
|
||||
$body->rewind();
|
||||
}
|
||||
}
|
||||
|
||||
private static function withTemporarySink(
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
): array {
|
||||
// The 'stream' option is deliberately not checked here: the cURL
|
||||
// handlers do not support streaming and write each leg to the sink,
|
||||
// so a configured sink always needs challenge-body protection.
|
||||
if (!isset($options[RequestOptions::SINK])) {
|
||||
return $options;
|
||||
}
|
||||
|
||||
$streamFactory = self::requireStreamFactory(
|
||||
$options[RequestOptions::STREAM_FACTORY] ?? new HttpFactory()
|
||||
);
|
||||
|
||||
$options['__guzzle_auth_original_sink'] = $options[RequestOptions::SINK];
|
||||
$options[RequestOptions::SINK] = $streamFactory->createStreamFromResource(
|
||||
Psr7\Utils::tryFopen('php://temp', 'w+')
|
||||
);
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
private static function restoreOriginalSink(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
): ResponseInterface {
|
||||
if (!\array_key_exists('__guzzle_auth_original_sink', $options)) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
try {
|
||||
$source = $response->getBody();
|
||||
if ($source->isSeekable()) {
|
||||
$source->rewind();
|
||||
}
|
||||
|
||||
$target = self::streamForOriginalSink($options['__guzzle_auth_original_sink']);
|
||||
|
||||
Psr7\Utils::copyToStream($source, $target);
|
||||
|
||||
if ($target->isSeekable()) {
|
||||
$target->rewind();
|
||||
}
|
||||
|
||||
return $response->withBody($target);
|
||||
} catch (\Exception $e) {
|
||||
throw new ResponseException(
|
||||
$e->getMessage() !== '' ? $e->getMessage() : 'Failed to write the response body',
|
||||
$request,
|
||||
$response,
|
||||
$e
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $reason
|
||||
*
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private static function restoreOriginalSinkOnRejection(
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
#[\SensitiveParameter]
|
||||
$reason
|
||||
): PromiseInterface {
|
||||
if (!$reason instanceof ResponseException || !\array_key_exists('__guzzle_auth_original_sink', $options)) {
|
||||
/** @var PromiseInterface<ResponseInterface, mixed> */
|
||||
return P\Create::rejectionFor($reason);
|
||||
}
|
||||
|
||||
try {
|
||||
$response = self::restoreOriginalSink($reason->getRequest(), $reason->getResponse(), $options);
|
||||
|
||||
/** @var PromiseInterface<ResponseInterface, mixed> */
|
||||
return P\Create::rejectionFor($reason->withResponse($response));
|
||||
} catch (\Throwable $e) {
|
||||
/** @var PromiseInterface<ResponseInterface, mixed> */
|
||||
return P\Create::rejectionFor($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $sink
|
||||
*/
|
||||
private static function streamForOriginalSink($sink): StreamInterface
|
||||
{
|
||||
if (\is_string($sink)) {
|
||||
return new LazyOpenStream($sink, 'w+');
|
||||
}
|
||||
|
||||
if (\is_resource($sink)) {
|
||||
return self::streamForResourceSink(Psr7\Utils::streamFor($sink));
|
||||
}
|
||||
|
||||
if (!$sink instanceof StreamInterface) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'sink must be a resource, string, or %s',
|
||||
StreamInterface::class
|
||||
));
|
||||
}
|
||||
|
||||
return Psr7\Utils::streamFor($sink);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decorates a caller-owned sink stream so that closing the response body
|
||||
* detaches Guzzle's wrapper without closing the original PHP resource.
|
||||
*/
|
||||
private static function streamForResourceSink(StreamInterface $stream): StreamInterface
|
||||
{
|
||||
return Psr7\FnStream::decorate($stream, [
|
||||
'close' => static function () use ($stream): void {
|
||||
$stream->detach();
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $factory
|
||||
*/
|
||||
private static function requireStreamFactory($factory): StreamFactoryInterface
|
||||
{
|
||||
if (!$factory instanceof StreamFactoryInterface) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'%s must be an instance of %s',
|
||||
RequestOptions::STREAM_FACTORY,
|
||||
StreamFactoryInterface::class
|
||||
));
|
||||
}
|
||||
|
||||
return $factory;
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use Psr\Http\Message\MessageInterface;
|
||||
|
||||
final class BodySummarizer implements BodySummarizerInterface
|
||||
{
|
||||
private ?int $truncateAt;
|
||||
|
||||
public function __construct(?int $truncateAt = null)
|
||||
{
|
||||
$this->truncateAt = $truncateAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a summarized message body.
|
||||
*/
|
||||
public function summarize(MessageInterface $message): ?string
|
||||
{
|
||||
try {
|
||||
return Psr7\Message::bodySummary($message, $this->truncateAt);
|
||||
} catch (\Exception $e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use Psr\Http\Message\MessageInterface;
|
||||
|
||||
interface BodySummarizerInterface
|
||||
{
|
||||
/**
|
||||
* Returns a summarized message body.
|
||||
*/
|
||||
public function summarize(MessageInterface $message): ?string;
|
||||
}
|
||||
+1716
File diff suppressed because it is too large
Load Diff
+370
@@ -0,0 +1,370 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Cookie\CookieJarInterface;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use Psr\Http\Message\RequestFactoryInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseFactoryInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\StreamFactoryInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
use Psr\Http\Message\UriFactoryInterface;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
/**
|
||||
* Client interface for sending HTTP requests.
|
||||
*/
|
||||
interface ClientInterface
|
||||
{
|
||||
/**
|
||||
* The Guzzle major version.
|
||||
*/
|
||||
public const MAJOR_VERSION = 8;
|
||||
|
||||
/**
|
||||
* Send an HTTP request.
|
||||
*
|
||||
* @param RequestInterface $request Request to send
|
||||
* @param array{
|
||||
* base_uri?: string|UriInterface,
|
||||
* allow_redirects?: bool|array{
|
||||
* max?: int,
|
||||
* strict?: bool,
|
||||
* referer?: bool,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
|
||||
* track_redirects?: bool
|
||||
* },
|
||||
* auth?: array{
|
||||
* 0: string,
|
||||
* 1: string,
|
||||
* 2?: string|null
|
||||
* }|string|false|null,
|
||||
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||
* cert?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* cert_type?: string,
|
||||
* connect_timeout?: int|float,
|
||||
* cookies?: false|CookieJarInterface,
|
||||
* crypto_method?: int,
|
||||
* crypto_method_max?: int,
|
||||
* debug?: bool|resource,
|
||||
* decode_content?: bool|string,
|
||||
* delay?: int|float,
|
||||
* expect?: bool|int,
|
||||
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||
* force_ip_resolve?: string,
|
||||
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||
* http_errors?: bool,
|
||||
* idn_conversion?: bool|int|null,
|
||||
* json?: mixed,
|
||||
* multipart?: array<array-key, array{
|
||||
* name: string|int,
|
||||
* contents: mixed,
|
||||
* headers?: array<array-key, string>,
|
||||
* filename?: string
|
||||
* }>,
|
||||
* multiplex?: string,
|
||||
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
|
||||
* on_stats?: callable(TransferStats): mixed,
|
||||
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
|
||||
* progress?: callable(int, int, int, int): mixed,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* proxy?: string|array{
|
||||
* http?: string|null,
|
||||
* https?: string|null,
|
||||
* no?: string|array<array-key, string>|null
|
||||
* },
|
||||
* query?: array<array-key, mixed>|string,
|
||||
* read_timeout?: int|float,
|
||||
* retries?: int,
|
||||
* request_factory?: RequestFactoryInterface,
|
||||
* response_factory?: ResponseFactoryInterface,
|
||||
* sink?: resource|string|StreamInterface,
|
||||
* ssl_key?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* ssl_key_type?: string,
|
||||
* stream?: bool,
|
||||
* stream_factory?: StreamFactoryInterface,
|
||||
* stream_context?: array<array-key, mixed>,
|
||||
* synchronous?: bool,
|
||||
* timeout?: int|float,
|
||||
* uri_factory?: UriFactoryInterface,
|
||||
* verify?: bool|string,
|
||||
* version?: string|int|float,
|
||||
* curl?: array<int|string, mixed>,
|
||||
* ...
|
||||
* } $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{
|
||||
* base_uri?: string|UriInterface,
|
||||
* allow_redirects?: bool|array{
|
||||
* max?: int,
|
||||
* strict?: bool,
|
||||
* referer?: bool,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
|
||||
* track_redirects?: bool
|
||||
* },
|
||||
* auth?: array{
|
||||
* 0: string,
|
||||
* 1: string,
|
||||
* 2?: string|null
|
||||
* }|string|false|null,
|
||||
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||
* cert?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* cert_type?: string,
|
||||
* connect_timeout?: int|float,
|
||||
* cookies?: false|CookieJarInterface,
|
||||
* crypto_method?: int,
|
||||
* crypto_method_max?: int,
|
||||
* debug?: bool|resource,
|
||||
* decode_content?: bool|string,
|
||||
* delay?: int|float,
|
||||
* expect?: bool|int,
|
||||
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||
* force_ip_resolve?: string,
|
||||
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||
* http_errors?: bool,
|
||||
* idn_conversion?: bool|int|null,
|
||||
* json?: mixed,
|
||||
* multipart?: array<array-key, array{
|
||||
* name: string|int,
|
||||
* contents: mixed,
|
||||
* headers?: array<array-key, string>,
|
||||
* filename?: string
|
||||
* }>,
|
||||
* multiplex?: string,
|
||||
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
|
||||
* on_stats?: callable(TransferStats): mixed,
|
||||
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
|
||||
* progress?: callable(int, int, int, int): mixed,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* proxy?: string|array{
|
||||
* http?: string|null,
|
||||
* https?: string|null,
|
||||
* no?: string|array<array-key, string>|null
|
||||
* },
|
||||
* query?: array<array-key, mixed>|string,
|
||||
* read_timeout?: int|float,
|
||||
* retries?: int,
|
||||
* request_factory?: RequestFactoryInterface,
|
||||
* response_factory?: ResponseFactoryInterface,
|
||||
* sink?: resource|string|StreamInterface,
|
||||
* ssl_key?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* ssl_key_type?: string,
|
||||
* stream?: bool,
|
||||
* stream_factory?: StreamFactoryInterface,
|
||||
* stream_context?: array<array-key, mixed>,
|
||||
* synchronous?: bool,
|
||||
* timeout?: int|float,
|
||||
* uri_factory?: UriFactoryInterface,
|
||||
* verify?: bool|string,
|
||||
* version?: string|int|float,
|
||||
* curl?: array<int|string, mixed>,
|
||||
* ...
|
||||
* } $options Request options to apply to the given request and to the transfer.
|
||||
*
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
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{
|
||||
* base_uri?: string|UriInterface,
|
||||
* allow_redirects?: bool|array{
|
||||
* max?: int,
|
||||
* strict?: bool,
|
||||
* referer?: bool,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
|
||||
* track_redirects?: bool
|
||||
* },
|
||||
* auth?: array{
|
||||
* 0: string,
|
||||
* 1: string,
|
||||
* 2?: string|null
|
||||
* }|string|false|null,
|
||||
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||
* cert?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* cert_type?: string,
|
||||
* connect_timeout?: int|float,
|
||||
* cookies?: false|CookieJarInterface,
|
||||
* crypto_method?: int,
|
||||
* crypto_method_max?: int,
|
||||
* debug?: bool|resource,
|
||||
* decode_content?: bool|string,
|
||||
* delay?: int|float,
|
||||
* expect?: bool|int,
|
||||
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||
* force_ip_resolve?: string,
|
||||
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||
* http_errors?: bool,
|
||||
* idn_conversion?: bool|int|null,
|
||||
* json?: mixed,
|
||||
* multipart?: array<array-key, array{
|
||||
* name: string|int,
|
||||
* contents: mixed,
|
||||
* headers?: array<array-key, string>,
|
||||
* filename?: string
|
||||
* }>,
|
||||
* multiplex?: string,
|
||||
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
|
||||
* on_stats?: callable(TransferStats): mixed,
|
||||
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
|
||||
* progress?: callable(int, int, int, int): mixed,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* proxy?: string|array{
|
||||
* http?: string|null,
|
||||
* https?: string|null,
|
||||
* no?: string|array<array-key, string>|null
|
||||
* },
|
||||
* query?: array<array-key, mixed>|string,
|
||||
* read_timeout?: int|float,
|
||||
* retries?: int,
|
||||
* request_factory?: RequestFactoryInterface,
|
||||
* response_factory?: ResponseFactoryInterface,
|
||||
* sink?: resource|string|StreamInterface,
|
||||
* ssl_key?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* ssl_key_type?: string,
|
||||
* stream?: bool,
|
||||
* stream_factory?: StreamFactoryInterface,
|
||||
* stream_context?: array<array-key, mixed>,
|
||||
* synchronous?: bool,
|
||||
* timeout?: int|float,
|
||||
* uri_factory?: UriFactoryInterface,
|
||||
* verify?: bool|string,
|
||||
* version?: string|int|float,
|
||||
* curl?: array<int|string, mixed>,
|
||||
* ...
|
||||
* } $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.
|
||||
*
|
||||
* @param string $method HTTP method
|
||||
* @param string|UriInterface $uri URI object or string.
|
||||
* @param array{
|
||||
* base_uri?: string|UriInterface,
|
||||
* allow_redirects?: bool|array{
|
||||
* max?: int,
|
||||
* strict?: bool,
|
||||
* referer?: bool,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
|
||||
* track_redirects?: bool
|
||||
* },
|
||||
* auth?: array{
|
||||
* 0: string,
|
||||
* 1: string,
|
||||
* 2?: string|null
|
||||
* }|string|false|null,
|
||||
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||
* cert?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* cert_type?: string,
|
||||
* connect_timeout?: int|float,
|
||||
* cookies?: false|CookieJarInterface,
|
||||
* crypto_method?: int,
|
||||
* crypto_method_max?: int,
|
||||
* debug?: bool|resource,
|
||||
* decode_content?: bool|string,
|
||||
* delay?: int|float,
|
||||
* expect?: bool|int,
|
||||
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||
* force_ip_resolve?: string,
|
||||
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||
* http_errors?: bool,
|
||||
* idn_conversion?: bool|int|null,
|
||||
* json?: mixed,
|
||||
* multipart?: array<array-key, array{
|
||||
* name: string|int,
|
||||
* contents: mixed,
|
||||
* headers?: array<array-key, string>,
|
||||
* filename?: string
|
||||
* }>,
|
||||
* multiplex?: string,
|
||||
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
|
||||
* on_stats?: callable(TransferStats): mixed,
|
||||
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
|
||||
* progress?: callable(int, int, int, int): mixed,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* proxy?: string|array{
|
||||
* http?: string|null,
|
||||
* https?: string|null,
|
||||
* no?: string|array<array-key, string>|null
|
||||
* },
|
||||
* query?: array<array-key, mixed>|string,
|
||||
* read_timeout?: int|float,
|
||||
* retries?: int,
|
||||
* request_factory?: RequestFactoryInterface,
|
||||
* response_factory?: ResponseFactoryInterface,
|
||||
* sink?: resource|string|StreamInterface,
|
||||
* ssl_key?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* ssl_key_type?: string,
|
||||
* stream?: bool,
|
||||
* stream_factory?: StreamFactoryInterface,
|
||||
* stream_context?: array<array-key, mixed>,
|
||||
* synchronous?: bool,
|
||||
* timeout?: int|float,
|
||||
* uri_factory?: UriFactoryInterface,
|
||||
* verify?: bool|string,
|
||||
* version?: string|int|float,
|
||||
* curl?: array<int|string, mixed>,
|
||||
* ...
|
||||
* } $options Request options to apply.
|
||||
*
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
public function requestAsync(string $method, $uri, array $options = []): PromiseInterface;
|
||||
}
|
||||
+1315
File diff suppressed because it is too large
Load Diff
+452
@@ -0,0 +1,452 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Cookie;
|
||||
|
||||
use GuzzleHttp\HostIdentity;
|
||||
use GuzzleHttp\Psr7;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Cookie jar that stores cookies as an array
|
||||
*/
|
||||
class CookieJar implements CookieJarInterface
|
||||
{
|
||||
private const MAX_SET_COOKIE_FIELD_LENGTH = 8190;
|
||||
private const MAX_SET_COOKIE_FIELDS = 50;
|
||||
private const MAX_REQUEST_COOKIES = 150;
|
||||
private const MAX_COOKIE_HEADER_LENGTH = 8190;
|
||||
|
||||
/**
|
||||
* @var SetCookie[] Loaded cookie data
|
||||
*/
|
||||
private array $cookies = [];
|
||||
|
||||
private bool $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,
|
||||
#[\SensitiveParameter]
|
||||
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(
|
||||
#[\SensitiveParameter]
|
||||
array $cookies,
|
||||
string $domain
|
||||
): self {
|
||||
$cookieJar = new self();
|
||||
foreach ($cookies as $name => $value) {
|
||||
if (!\is_scalar($value) && !(\is_object($value) && \method_exists($value, '__toString'))) {
|
||||
throw new \InvalidArgumentException('Cookie value must be scalar or stringable');
|
||||
}
|
||||
|
||||
$cookieJar->setCookie(new SetCookie([
|
||||
'Domain' => $domain,
|
||||
'Name' => (string) $name,
|
||||
'Value' => (string) $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() === $name) {
|
||||
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 === null) {
|
||||
$this->cookies = [];
|
||||
|
||||
return;
|
||||
} elseif ($path === null) {
|
||||
$this->cookies = \array_filter(
|
||||
$this->cookies,
|
||||
static function (SetCookie $cookie) use ($domain): bool {
|
||||
return $cookie->getDomain() === null || !$cookie->matchesDomain($domain);
|
||||
}
|
||||
);
|
||||
} elseif ($name === null) {
|
||||
$this->cookies = \array_filter(
|
||||
$this->cookies,
|
||||
static function (SetCookie $cookie) use ($path, $domain): bool {
|
||||
return !($cookie->getDomain() !== null
|
||||
&& $cookie->matchesPath($path)
|
||||
&& $cookie->matchesDomain($domain));
|
||||
}
|
||||
);
|
||||
} else {
|
||||
$this->cookies = \array_filter(
|
||||
$this->cookies,
|
||||
static function (SetCookie $cookie) use ($path, $domain, $name): bool {
|
||||
return !($cookie->getDomain() !== null
|
||||
&& $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(
|
||||
#[\SensitiveParameter]
|
||||
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;
|
||||
}
|
||||
|
||||
$maxAge = $cookie->getMaxAge();
|
||||
if (($maxAge !== null && $maxAge <= 0) || $cookie->isExpired()) {
|
||||
if ($cookie->getDomain() !== null) {
|
||||
$this->removeCookie($cookie);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Resolve conflicts with previously set cookies
|
||||
$replaced = false;
|
||||
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->getHostOnly() !== $cookie->getHostOnly()
|
||||
|| $c->getName() !== $cookie->getName()
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// An expired cookie is gone, so it must not lend its position
|
||||
if ($c->isExpired()) {
|
||||
unset($this->cookies[$i]);
|
||||
continue;
|
||||
}
|
||||
|
||||
// A stored cookie can be mutated into a duplicate, so drop later matches
|
||||
if ($replaced) {
|
||||
unset($this->cookies[$i]);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Replace the old cookie in place when its value, expiry or flags
|
||||
// changed, so it keeps its position among the other cookies
|
||||
if ($cookie->getValue() !== $c->getValue()
|
||||
|| $cookie->getExpires() !== $c->getExpires()
|
||||
|| $cookie->getDiscard() !== $c->getDiscard()
|
||||
|| $cookie->getSecure() !== $c->getSecure()
|
||||
|| $cookie->getHttpOnly() !== $c->getHttpOnly()
|
||||
) {
|
||||
$this->cookies[$i] = $cookie;
|
||||
$replaced = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// The cookie exists, so no need to continue
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$replaced) {
|
||||
$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(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
): void {
|
||||
if ($cookieHeader = $response->getHeader('Set-Cookie')) {
|
||||
$uri = $request->getUri();
|
||||
$requestHost = HostIdentity::canonicalHost($uri->getHost());
|
||||
$secure = $uri->getScheme() === 'https';
|
||||
$accepted = 0;
|
||||
|
||||
foreach ($cookieHeader as $cookie) {
|
||||
if (\strlen($cookie) > self::MAX_SET_COOKIE_FIELD_LENGTH) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$sc = SetCookie::fromString($cookie);
|
||||
$domain = $sc->getDomain();
|
||||
if ($domain === null || $domain === '') {
|
||||
$sc->setDomain($requestHost);
|
||||
$sc->setHostOnly(true);
|
||||
} else {
|
||||
$sc->setHostOnly(false);
|
||||
}
|
||||
if (0 !== \strpos($sc->getPath(), '/')) {
|
||||
$sc->setPath($this->getCookiePathFromRequest($request));
|
||||
}
|
||||
if (!$sc->matchesDomain($requestHost)) {
|
||||
continue;
|
||||
}
|
||||
if (!$secure && ($sc->getSecure() || $this->overlaysSecureCookie($sc))) {
|
||||
continue;
|
||||
}
|
||||
$prefixName = Psr7\Utils::asciiToLower((string) $sc->getName());
|
||||
if (\str_starts_with($prefixName, '__secure-') && !$sc->getSecure()) {
|
||||
continue;
|
||||
}
|
||||
if (\str_starts_with($prefixName, '__host-') && (!$sc->getSecure() || !$sc->getHostOnly() || $sc->getPath() !== '/' || !self::hasPathAttribute($cookie))) {
|
||||
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.
|
||||
if ($this->setCookie($sc) && ++$accepted === self::MAX_SET_COOKIE_FIELDS) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function overlaysSecureCookie(SetCookie $cookie): bool
|
||||
{
|
||||
foreach ($this->cookies as $stored) {
|
||||
if (self::isSecureCookieOverlay($cookie, $stored)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function isSecureCookieOverlay(SetCookie $cookie, SetCookie $stored): bool
|
||||
{
|
||||
if ($stored->getName() !== $cookie->getName() || !$stored->getSecure() || $stored->isExpired()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$domain = $cookie->getDomain();
|
||||
$storedDomain = $stored->getDomain();
|
||||
if ($domain === null || $storedDomain === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!HostIdentity::cookieDomainMatches($storedDomain, $domain) && !HostIdentity::cookieDomainMatches($domain, $storedDomain)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $stored->matchesPath($cookie->getPath());
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors SetCookie::fromString()'s splitting because parsed cookies cannot
|
||||
* distinguish an absent Path attribute from a defaulted path.
|
||||
*/
|
||||
private static function hasPathAttribute(string $header): bool
|
||||
{
|
||||
$parts = \explode(';', $header);
|
||||
\array_shift($parts);
|
||||
|
||||
foreach ($parts as $part) {
|
||||
$separator = \strpos($part, '=');
|
||||
if ($separator !== false && Psr7\Utils::caselessEquals(\trim(\substr($part, 0, $separator), " \t"), 'Path')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request
|
||||
): RequestInterface {
|
||||
$values = [];
|
||||
$count = 0;
|
||||
$headerLength = 8;
|
||||
$uri = $request->getUri();
|
||||
$scheme = $uri->getScheme();
|
||||
$host = HostIdentity::canonicalHost($uri->getHost());
|
||||
$path = $uri->getPath() ?: '/';
|
||||
|
||||
foreach ($this->cookies as $cookie) {
|
||||
if ($cookie->getDomain() !== null
|
||||
&& $cookie->matchesPath($path)
|
||||
&& $cookie->matchesDomain($host)
|
||||
&& !$cookie->isExpired()
|
||||
&& (!$cookie->getSecure() || $scheme === 'https')
|
||||
) {
|
||||
$name = (string) $cookie->getName();
|
||||
$value = (string) $cookie->getValue();
|
||||
$separatorLength = $values === [] ? 0 : 2;
|
||||
$valueLength = \strlen($name) + 1 + \strlen($value);
|
||||
if ($headerLength + $separatorLength + $valueLength > self::MAX_COOKIE_HEADER_LENGTH) {
|
||||
break;
|
||||
}
|
||||
|
||||
$values[\strlen($cookie->getPath())][] = $name.'='.$value;
|
||||
$headerLength += $separatorLength + $valueLength;
|
||||
if (++$count === self::MAX_REQUEST_COOKIES) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Longer paths first, then creation order, as in RFC 6265 section 5.4,
|
||||
// sorted after the limits so later cookies cannot crowd out older ones
|
||||
\krsort($values);
|
||||
|
||||
return $values
|
||||
? $request->withHeader('Cookie', \implode('; ', \array_merge(...$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 === '') && $cookie->getDomain() !== null) {
|
||||
$this->removeCookie($cookie);
|
||||
}
|
||||
}
|
||||
|
||||
private function removeCookie(SetCookie $cookie): void
|
||||
{
|
||||
$this->cookies = \array_filter(
|
||||
$this->cookies,
|
||||
static function (SetCookie $stored) use ($cookie): bool {
|
||||
return !($stored->getName() === $cookie->getName()
|
||||
&& $stored->getPath() === $cookie->getPath()
|
||||
&& $stored->getDomain() === $cookie->getDomain()
|
||||
&& $stored->getHostOnly() === $cookie->getHostOnly());
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Cookie;
|
||||
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7\DiagnosticValue;
|
||||
|
||||
/**
|
||||
* Persists non-session cookies using a JSON formatted file
|
||||
*/
|
||||
class FileCookieJar extends CookieJar
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* @var string filename
|
||||
*/
|
||||
private string $filename;
|
||||
|
||||
/**
|
||||
* @var bool Control whether to persist session cookies or not.
|
||||
*/
|
||||
private bool $storeSessionCookies;
|
||||
|
||||
/**
|
||||
* @var bool Whether to save the cookie jar on destruction.
|
||||
*
|
||||
* Disabled by __wakeup() to prevent FileCookieJar from being used as a
|
||||
* PHP object injection file-write gadget when an application unserializes
|
||||
* attacker-controlled data.
|
||||
*/
|
||||
private bool $autoSave = false;
|
||||
|
||||
/**
|
||||
* 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 loaded or is invalid
|
||||
*/
|
||||
public function __construct(string $cookieFile, bool $storeSessionCookies = false)
|
||||
{
|
||||
parent::__construct();
|
||||
$this->filename = $cookieFile;
|
||||
$this->storeSessionCookies = $storeSessionCookies;
|
||||
|
||||
if (\file_exists($cookieFile)) {
|
||||
$this->load($cookieFile);
|
||||
}
|
||||
|
||||
$this->autoSave = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the file when shutting down
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
if ($this->autoSave) {
|
||||
$this->save($this->filename);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable automatic persistence after unserialization.
|
||||
*/
|
||||
public function __wakeup(): void
|
||||
{
|
||||
$this->autoSave = false;
|
||||
}
|
||||
|
||||
public function __unserialize(array $data): void
|
||||
{
|
||||
$this->autoSave = false;
|
||||
|
||||
throw new \LogicException(static::class.' should never be unserialized');
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the cookies to a file.
|
||||
*
|
||||
* @param string $filename File to save
|
||||
*
|
||||
* @throws \RuntimeException if the cookie data cannot be encoded or the
|
||||
* file cannot be written
|
||||
*/
|
||||
public function save(string $filename): void
|
||||
{
|
||||
$json = [];
|
||||
/** @var SetCookie $cookie */
|
||||
foreach ($this as $cookie) {
|
||||
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
|
||||
$data = $cookie->toArray();
|
||||
$data['HostOnly'] = $cookie->getHostOnly();
|
||||
$json[] = $data;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$jsonStr = \json_encode($json, \JSON_HEX_TAG | \JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $e) {
|
||||
throw new \RuntimeException('Unable to encode cookie data', 0, $e);
|
||||
}
|
||||
|
||||
if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) {
|
||||
throw new \RuntimeException(\sprintf('Unable to save file %s', DiagnosticValue::escape($filename)));
|
||||
}
|
||||
|
||||
// Best-effort: restrict the cookie file to the owner so persisted
|
||||
// cookies are not world-readable.
|
||||
@\chmod($filename, 0600);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load cookies from a JSON formatted file.
|
||||
*
|
||||
* Old cookies are kept unless overwritten by newly loaded ones.
|
||||
* Cookie records are constructed before any are passed to setCookie().
|
||||
*
|
||||
* @param string $filename Cookie file to load.
|
||||
*
|
||||
* @throws \RuntimeException if the file cannot be loaded or is invalid
|
||||
*/
|
||||
public function load(string $filename): void
|
||||
{
|
||||
$json = \file_get_contents($filename);
|
||||
if (false === $json) {
|
||||
throw new \RuntimeException(\sprintf('Unable to load file %s', DiagnosticValue::escape($filename)));
|
||||
}
|
||||
if ($json === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$message = \sprintf('Invalid cookie file: %s', DiagnosticValue::escape($filename));
|
||||
|
||||
try {
|
||||
$data = \json_decode($json, true, 512, \JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $e) {
|
||||
throw new \RuntimeException($message, 0, $e);
|
||||
}
|
||||
|
||||
// Associative decoding turns JSON objects into arrays, so inspect the root syntax too.
|
||||
if (!\is_array($data) || \substr($json, \strspn($json, " \t\n\r"), 1) !== '[') {
|
||||
throw new \RuntimeException($message);
|
||||
}
|
||||
|
||||
$cookies = [];
|
||||
foreach ($data as $cookie) {
|
||||
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
|
||||
throw new \RuntimeException($message);
|
||||
}
|
||||
|
||||
try {
|
||||
$cookies[] = new SetCookie($cookie);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
throw new \RuntimeException($message, 0, $e);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($cookies as $cookie) {
|
||||
$this->setCookie($cookie);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Cookie;
|
||||
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* Persists cookies in the client session
|
||||
*/
|
||||
class SessionCookieJar extends CookieJar
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* @var string session key
|
||||
*/
|
||||
private string $sessionKey;
|
||||
|
||||
/**
|
||||
* @var bool Control whether to persist session cookies or not.
|
||||
*/
|
||||
private bool $storeSessionCookies;
|
||||
|
||||
/**
|
||||
* @var bool Whether to save the cookie jar on destruction.
|
||||
*
|
||||
* Disabled by __wakeup() to prevent SessionCookieJar from being used as a
|
||||
* PHP object injection $_SESSION-write gadget when an application
|
||||
* unserializes attacker-controlled data.
|
||||
*/
|
||||
private bool $autoSave = false;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* @throws \RuntimeException if the session contains invalid cookie data
|
||||
*/
|
||||
public function __construct(string $sessionKey, bool $storeSessionCookies = false)
|
||||
{
|
||||
parent::__construct();
|
||||
$this->sessionKey = $sessionKey;
|
||||
$this->storeSessionCookies = $storeSessionCookies;
|
||||
$this->load();
|
||||
$this->autoSave = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves cookies to session when shutting down
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
if ($this->autoSave) {
|
||||
$this->save();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable automatic persistence after unserialization.
|
||||
*/
|
||||
public function __wakeup(): void
|
||||
{
|
||||
$this->autoSave = false;
|
||||
}
|
||||
|
||||
public function __unserialize(array $data): void
|
||||
{
|
||||
$this->autoSave = false;
|
||||
|
||||
throw new \LogicException(static::class.' should never be unserialized');
|
||||
}
|
||||
|
||||
/**
|
||||
* Save cookies to the client session.
|
||||
*
|
||||
* @throws \RuntimeException if the cookie data cannot be encoded
|
||||
*/
|
||||
public function save(): void
|
||||
{
|
||||
$json = [];
|
||||
/** @var SetCookie $cookie */
|
||||
foreach ($this as $cookie) {
|
||||
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
|
||||
$data = $cookie->toArray();
|
||||
$data['HostOnly'] = $cookie->getHostOnly();
|
||||
$json[] = $data;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$json = \json_encode($json, \JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $e) {
|
||||
throw new \RuntimeException('Unable to encode cookie data', 0, $e);
|
||||
}
|
||||
|
||||
$_SESSION[$this->sessionKey] = $json;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load cookies from the client session.
|
||||
*
|
||||
* @throws \RuntimeException if the session contains invalid cookie data
|
||||
*/
|
||||
protected function load(): void
|
||||
{
|
||||
if (!isset($_SESSION[$this->sessionKey])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$message = 'Invalid cookie data';
|
||||
$json = $_SESSION[$this->sessionKey];
|
||||
if (!\is_string($json)) {
|
||||
throw new \RuntimeException($message);
|
||||
}
|
||||
|
||||
try {
|
||||
$data = \json_decode($json, true, 512, \JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $e) {
|
||||
throw new \RuntimeException($message, 0, $e);
|
||||
}
|
||||
|
||||
// Associative decoding turns JSON objects into arrays, so inspect the root syntax too.
|
||||
if (!\is_array($data) || \substr($json, \strspn($json, " \t\n\r"), 1) !== '[') {
|
||||
throw new \RuntimeException($message);
|
||||
}
|
||||
|
||||
$cookies = [];
|
||||
foreach ($data as $cookie) {
|
||||
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
|
||||
throw new \RuntimeException($message);
|
||||
}
|
||||
|
||||
try {
|
||||
$cookies[] = new SetCookie($cookie);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
throw new \RuntimeException($message, 0, $e);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($cookies as $cookie) {
|
||||
$this->setCookie($cookie);
|
||||
}
|
||||
}
|
||||
}
|
||||
+601
@@ -0,0 +1,601 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Cookie;
|
||||
|
||||
use GuzzleHttp\HostIdentity;
|
||||
use GuzzleHttp\Psr7;
|
||||
|
||||
/**
|
||||
* Set-Cookie object
|
||||
*/
|
||||
class SetCookie
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private const DEFAULTS = [
|
||||
'Name' => null,
|
||||
'Value' => null,
|
||||
'Domain' => null,
|
||||
'Path' => '/',
|
||||
'Max-Age' => null,
|
||||
'Expires' => null,
|
||||
'Secure' => false,
|
||||
'Discard' => false,
|
||||
'HttpOnly' => false,
|
||||
];
|
||||
|
||||
/**
|
||||
* @var array Cookie data
|
||||
*/
|
||||
private array $data;
|
||||
|
||||
/**
|
||||
* @var bool Whether this cookie was set without a Domain attribute.
|
||||
*/
|
||||
private bool $hostOnly = false;
|
||||
|
||||
/**
|
||||
* Create a new SetCookie object from a string.
|
||||
*
|
||||
* @param string $cookie Set-Cookie header string
|
||||
*/
|
||||
public static function fromString(
|
||||
#[\SensitiveParameter]
|
||||
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(static function (string $piece): string {
|
||||
return \trim($piece, " \t");
|
||||
}, \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], " \t");
|
||||
$value = isset($cookieParts[1])
|
||||
? \trim($cookieParts[1], " \t")
|
||||
: 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 (Psr7\Utils::caselessEquals($search, $key)) {
|
||||
if ($search === 'Max-Age') {
|
||||
if (\is_string($value) && \preg_match('/^[+-]?[0-9]+$/D', $value) === 1) {
|
||||
$maxAge = self::parseNumericInteger($value);
|
||||
if ($maxAge !== null) {
|
||||
$data[$search] = $maxAge;
|
||||
}
|
||||
}
|
||||
} elseif ($search === 'Secure' || $search === 'Discard' || $search === 'HttpOnly') {
|
||||
if ($value) {
|
||||
$data[$search] = true;
|
||||
}
|
||||
} elseif (\is_string($value)) {
|
||||
$data[$search] = $value;
|
||||
}
|
||||
continue 2;
|
||||
}
|
||||
}
|
||||
if (Psr7\Utils::caselessEquals('HostOnly', $key)) {
|
||||
continue;
|
||||
}
|
||||
$data[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
// Max-Age takes precedence over Expires, RFC 6265 section 5.3
|
||||
if ($data['Max-Age'] !== null) {
|
||||
$data['Expires'] = null;
|
||||
}
|
||||
|
||||
return new self($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data Array of cookie data provided by a Cookie parser
|
||||
*/
|
||||
public function __construct(
|
||||
#[\SensitiveParameter]
|
||||
array $data = []
|
||||
) {
|
||||
$this->data = self::DEFAULTS;
|
||||
self::validateFieldTypes($data);
|
||||
|
||||
if (\array_key_exists('HostOnly', $data)) {
|
||||
$this->setHostOnly($data['HostOnly']);
|
||||
unset($data['HostOnly']);
|
||||
}
|
||||
|
||||
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];
|
||||
}
|
||||
|
||||
// Derive Expires from Max-Age unless the data already carries one
|
||||
$maxAge = $this->getMaxAge();
|
||||
if ($maxAge !== null && $this->getExpires() === null) {
|
||||
$this->setExpires(self::maxAgeToExpires($maxAge, \time()));
|
||||
}
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
$str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; ';
|
||||
foreach ($this->data as $k => $v) {
|
||||
if ($k === 'Domain' && $this->getHostOnly()) {
|
||||
continue;
|
||||
}
|
||||
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
|
||||
{
|
||||
$data = $this->data;
|
||||
if ($this->getHostOnly()) {
|
||||
$data['HostOnly'] = true;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the cookie name.
|
||||
*/
|
||||
public function getName(): ?string
|
||||
{
|
||||
return $this->data['Name'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the cookie name.
|
||||
*
|
||||
* @param string $name Cookie name
|
||||
*/
|
||||
public function setName(string $name): void
|
||||
{
|
||||
$this->data['Name'] = $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the cookie value.
|
||||
*/
|
||||
public function getValue(): ?string
|
||||
{
|
||||
return $this->data['Value'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the cookie value.
|
||||
*
|
||||
* @param string $value Cookie value
|
||||
*/
|
||||
public function setValue(string $value): void
|
||||
{
|
||||
$this->data['Value'] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the domain.
|
||||
*/
|
||||
public function getDomain(): ?string
|
||||
{
|
||||
return $this->data['Domain'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the domain of the cookie.
|
||||
*
|
||||
* @param string|null $domain Domain of the cookie
|
||||
*/
|
||||
public function setDomain(?string $domain): void
|
||||
{
|
||||
$this->data['Domain'] = null === $domain ? null : self::normalizeDomain($domain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether this cookie is scoped to the origin host only.
|
||||
*/
|
||||
public function getHostOnly(): bool
|
||||
{
|
||||
return $this->hostOnly;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether this cookie is scoped to the origin host only.
|
||||
*
|
||||
* @param bool $hostOnly Set to true for host-only cookies
|
||||
*/
|
||||
public function setHostOnly(bool $hostOnly): void
|
||||
{
|
||||
$this->hostOnly = $hostOnly;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path.
|
||||
*/
|
||||
public function getPath(): string
|
||||
{
|
||||
return $this->data['Path'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the path of the cookie.
|
||||
*
|
||||
* @param string $path Path of the cookie
|
||||
*/
|
||||
public function setPath(string $path): void
|
||||
{
|
||||
$this->data['Path'] = $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maximum lifetime of the cookie in seconds.
|
||||
*/
|
||||
public function getMaxAge(): ?int
|
||||
{
|
||||
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(?int $maxAge): void
|
||||
{
|
||||
$this->data['Max-Age'] = $maxAge;
|
||||
}
|
||||
|
||||
/**
|
||||
* The UNIX timestamp when the cookie Expires.
|
||||
*/
|
||||
public function getExpires(): ?int
|
||||
{
|
||||
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) {
|
||||
// TODO: Move this to the parameter definition in 9.0.
|
||||
throw new \TypeError(__METHOD__.'(): Argument #1 ($timestamp) must be of type int|string|null');
|
||||
}
|
||||
|
||||
if ($timestamp === null) {
|
||||
$this->data['Expires'] = null;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (\is_string($timestamp)) {
|
||||
if (\is_numeric($timestamp)) {
|
||||
$this->data['Expires'] = self::parseNumericInteger($timestamp);
|
||||
|
||||
return;
|
||||
}
|
||||
} elseif (\is_int($timestamp)) {
|
||||
$this->data['Expires'] = $timestamp;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$expires = \strtotime($timestamp);
|
||||
$this->data['Expires'] = $expires === false ? null : $expires;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether or not this is a secure cookie.
|
||||
*/
|
||||
public function getSecure(): bool
|
||||
{
|
||||
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(bool $secure): void
|
||||
{
|
||||
$this->data['Secure'] = $secure;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether or not this is a session cookie.
|
||||
*/
|
||||
public function getDiscard(): bool
|
||||
{
|
||||
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(bool $discard): void
|
||||
{
|
||||
$this->data['Discard'] = $discard;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether or not this is an HTTP only cookie.
|
||||
*/
|
||||
public function getHttpOnly(): bool
|
||||
{
|
||||
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(bool $httpOnly): void
|
||||
{
|
||||
$this->data['HttpOnly'] = $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 || $cookieDomain === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->getHostOnly()) {
|
||||
return HostIdentity::canonicalCookieDomain($domain) === HostIdentity::canonicalCookieDomain($cookieDomain);
|
||||
}
|
||||
|
||||
return HostIdentity::cookieDomainMatches($domain, $cookieDomain);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 string|true Returns true if valid or an error message if invalid
|
||||
*/
|
||||
public function validate()
|
||||
{
|
||||
$name = $this->getName();
|
||||
if ($name === null || $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) !== 0) {
|
||||
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 may be omitted. "0" is not a valid
|
||||
// internet domain, but may be used as server name in a private network.
|
||||
$domain = $this->getDomain();
|
||||
if ($domain === '' || ($domain !== null && \ltrim(\trim($domain, " \n\r\t\0\x0B"), '.') === '')) {
|
||||
return 'The cookie domain must not be empty';
|
||||
}
|
||||
|
||||
if ($this->getHostOnly() && $domain === null) {
|
||||
return 'Host-only cookies must have a domain';
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static function normalizeDomain(string $domain): string
|
||||
{
|
||||
$domain = Psr7\Utils::asciiToLower($domain);
|
||||
|
||||
// Treat trailing-dot domains as host-only, but keep pure-dot domains invalid.
|
||||
if ($domain !== '' && \substr($domain, -1) === '.' && \trim($domain, '.') !== '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($domain !== '' && $domain !== '.' && $domain[0] === '.') {
|
||||
$domain = \substr_replace($domain, '', 0, 1);
|
||||
}
|
||||
|
||||
return HostIdentity::canonicalCookieDomain($domain);
|
||||
}
|
||||
|
||||
private static function maxAgeToExpires(int $maxAge, int $now): int
|
||||
{
|
||||
if ($maxAge <= 0) {
|
||||
return $now - 1;
|
||||
}
|
||||
|
||||
// Clamp absurd Max-Age values so addition cannot promote to float
|
||||
if ($maxAge > \PHP_INT_MAX - $now) {
|
||||
return \PHP_INT_MAX;
|
||||
}
|
||||
|
||||
return $now + $maxAge;
|
||||
}
|
||||
|
||||
private static function parseNumericInteger(string $value): ?int
|
||||
{
|
||||
if (!\is_numeric($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (\preg_match('/^[+-]?[0-9]+$/D', $value) === 1) {
|
||||
$negative = $value[0] === '-';
|
||||
$digits = \ltrim($value, '+-');
|
||||
$digits = \ltrim($digits, '0');
|
||||
$digits = $digits === '' ? '0' : $digits;
|
||||
$limit = $negative ? \substr((string) \PHP_INT_MIN, 1) : (string) \PHP_INT_MAX;
|
||||
|
||||
if (\strlen($digits) > \strlen($limit) || (\strlen($digits) === \strlen($limit) && \strcmp($digits, $limit) > 0)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) ($negative ? '-'.$digits : $digits);
|
||||
}
|
||||
|
||||
$number = (float) $value;
|
||||
if (!\is_finite($number) || $number < \PHP_INT_MIN || $number > \PHP_INT_MAX) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (\PHP_INT_SIZE === 8 && ($number <= (float) \PHP_INT_MIN || $number >= (float) \PHP_INT_MAX)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) $number;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed[] $data
|
||||
*/
|
||||
private static function validateFieldTypes(
|
||||
#[\SensitiveParameter]
|
||||
array $data
|
||||
): void {
|
||||
foreach (['Name', 'Value', 'Domain', 'Path'] as $field) {
|
||||
if (isset($data[$field]) && !\is_string($data[$field])) {
|
||||
throw new \InvalidArgumentException(\sprintf('Cookie field "%s" must be a string', $field));
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($data['Max-Age']) && !\is_int($data['Max-Age'])) {
|
||||
throw new \InvalidArgumentException('Cookie field "Max-Age" must be an integer');
|
||||
}
|
||||
|
||||
if (isset($data['Expires']) && !\is_int($data['Expires']) && !\is_string($data['Expires'])) {
|
||||
throw new \InvalidArgumentException('Cookie field "Expires" must be an integer or string');
|
||||
}
|
||||
|
||||
foreach (['Secure', 'Discard', 'HttpOnly'] as $field) {
|
||||
if (isset($data[$field]) && !\is_bool($data[$field])) {
|
||||
throw new \InvalidArgumentException(\sprintf('Cookie field "%s" must be a boolean', $field));
|
||||
}
|
||||
}
|
||||
|
||||
if (\array_key_exists('HostOnly', $data) && !\is_bool($data['HostOnly'])) {
|
||||
throw new \InvalidArgumentException('Cookie field "HostOnly" must be a boolean');
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
/**
|
||||
* Reads configuration from the process environment.
|
||||
*
|
||||
* Intentionally separate from Handler\ProxyEnv, which has different
|
||||
* lookup semantics.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class Env
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
public static function get(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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown for HTTP responses with 4xx or 5xx status codes.
|
||||
*/
|
||||
class BadResponseException extends ResponseException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown for HTTP responses with 4xx status codes.
|
||||
*/
|
||||
class ClientException extends BadResponseException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when connection establishment fails.
|
||||
*/
|
||||
class ConnectException extends NetworkException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when connection establishment exceeds the time limit.
|
||||
*/
|
||||
class ConnectTimeoutException extends ConnectException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
use Psr\Http\Client\ClientExceptionInterface;
|
||||
|
||||
interface GuzzleException extends ClientExceptionInterface
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when a handler is closed before a transfer completes.
|
||||
*/
|
||||
class HandlerClosedException extends TransferException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when an invalid argument is supplied to Guzzle.
|
||||
*/
|
||||
final class InvalidArgumentException extends \InvalidArgumentException implements GuzzleException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
use Psr\Http\Client\NetworkExceptionInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
* Base exception for transfer failures without a response.
|
||||
*/
|
||||
class NetworkException extends TransferException implements NetworkExceptionInterface
|
||||
{
|
||||
public function __construct(
|
||||
string $message,
|
||||
RequestInterface $request,
|
||||
?\Throwable $previous = null
|
||||
) {
|
||||
parent::__construct($message, $request, 0, $previous);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when a transfer times out before response headers are
|
||||
* received.
|
||||
*/
|
||||
class NetworkTimeoutException extends NetworkException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
use GuzzleHttp\BodySummarizer;
|
||||
use GuzzleHttp\BodySummarizerInterface;
|
||||
use GuzzleHttp\Psr7\DiagnosticValue;
|
||||
use Psr\Http\Client\RequestExceptionInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Base exception for request failures associated with a request.
|
||||
*/
|
||||
class RequestException extends TransferException implements RequestExceptionInterface
|
||||
{
|
||||
public function __construct(
|
||||
string $message,
|
||||
RequestInterface $request,
|
||||
int $code = 0,
|
||||
?\Throwable $previous = null
|
||||
) {
|
||||
parent::__construct($message, $request, $code, $previous);
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory method to create a new exception with a normalized error message
|
||||
*
|
||||
* @param RequestInterface $request Request sent
|
||||
* @param ResponseInterface|null $response Response received, if any
|
||||
* @param \Throwable|null $previous Previous exception
|
||||
* @param BodySummarizerInterface|null $bodySummarizer Optional body summarizer
|
||||
*/
|
||||
public static function create(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
?ResponseInterface $response = null,
|
||||
#[\SensitiveParameter]
|
||||
?\Throwable $previous = null,
|
||||
?BodySummarizerInterface $bodySummarizer = null
|
||||
): self {
|
||||
if (!$response) {
|
||||
return new self(
|
||||
'Error completing request',
|
||||
$request,
|
||||
0,
|
||||
$previous
|
||||
);
|
||||
}
|
||||
|
||||
$level = (int) \floor($response->getStatusCode() / 100);
|
||||
if ($level === 4) {
|
||||
$label = 'Client error';
|
||||
} elseif ($level === 5) {
|
||||
$label = 'Server error';
|
||||
} else {
|
||||
$label = 'Unsuccessful request';
|
||||
}
|
||||
|
||||
$uri = \GuzzleHttp\Psr7\UriRedactor::redactUriForMessage($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,
|
||||
DiagnosticValue::escape($request->getMethod()),
|
||||
$uri,
|
||||
$response->getStatusCode(),
|
||||
DiagnosticValue::escape($response->getReasonPhrase())
|
||||
);
|
||||
|
||||
$summary = ($bodySummarizer ?? new BodySummarizer())->summarize($response);
|
||||
|
||||
if ($summary !== null) {
|
||||
$message .= \sprintf(': %s', DiagnosticValue::escape($summary));
|
||||
}
|
||||
|
||||
if ($level === 4) {
|
||||
return new ClientException($message, $request, $response, $previous);
|
||||
}
|
||||
|
||||
if ($level === 5) {
|
||||
return new ServerException($message, $request, $response, $previous);
|
||||
}
|
||||
|
||||
return new ResponseException($message, $request, $response, $previous);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Exception thrown when a request fails after response headers are received.
|
||||
*/
|
||||
class ResponseException extends RequestException
|
||||
{
|
||||
private ResponseInterface $response;
|
||||
|
||||
final public function __construct(
|
||||
string $message,
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response,
|
||||
#[\SensitiveParameter]
|
||||
?\Throwable $previous = null
|
||||
) {
|
||||
parent::__construct($message, $request, $response->getStatusCode(), $previous);
|
||||
$this->response = $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a new exception instance with an updated response.
|
||||
*
|
||||
* @param \Throwable|null $previous Previous exception, or the current
|
||||
* previous exception when omitted.
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
public function withResponse(
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response,
|
||||
#[\SensitiveParameter]
|
||||
?\Throwable $previous = null
|
||||
): self {
|
||||
if ($response->getStatusCode() !== $this->response->getStatusCode()) {
|
||||
throw new InvalidArgumentException('Cannot replace response with a different status code.');
|
||||
}
|
||||
|
||||
return new static(
|
||||
$this->getMessage(),
|
||||
$this->getRequest(),
|
||||
$response,
|
||||
$previous ?? $this->getPrevious()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the associated response.
|
||||
*/
|
||||
public function getResponse(): ResponseInterface
|
||||
{
|
||||
return $this->response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when a transfer times out after response headers are
|
||||
* received.
|
||||
*/
|
||||
class ResponseTimeoutException extends ResponseTransferException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when a response transfer fails after response headers are
|
||||
* received.
|
||||
*/
|
||||
class ResponseTransferException extends ResponseException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown for HTTP responses with 5xx status codes.
|
||||
*/
|
||||
class ServerException extends BadResponseException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when redirect middleware reaches the redirect limit.
|
||||
*/
|
||||
class TooManyRedirectsException extends ResponseException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
* Base exception for transfer failures.
|
||||
*/
|
||||
class TransferException extends \RuntimeException implements GuzzleException
|
||||
{
|
||||
private RequestInterface $request;
|
||||
|
||||
public function __construct(
|
||||
string $message,
|
||||
RequestInterface $request,
|
||||
int $code = 0,
|
||||
?\Throwable $previous = null
|
||||
) {
|
||||
parent::__construct($message, $code, $previous);
|
||||
$this->request = $request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the request that caused the exception.
|
||||
*/
|
||||
public function getRequest(): RequestInterface
|
||||
{
|
||||
return $this->request;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7\StreamDecoratorTrait;
|
||||
use GuzzleHttp\Psr7\StreamWrapper;
|
||||
use GuzzleHttp\Psr7\Utils;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Decodes the chunked transfer coding of a response body read from the
|
||||
* unfiltered transport stream, with the framing rules libcurl applies.
|
||||
*
|
||||
* Each read returns the decoded bytes that are already available, waiting on
|
||||
* the transport only when there are none, so the transport's idle timeout
|
||||
* governs every wait. The body ends as soon as the last chunk and trailer
|
||||
* section have been decoded, without another transport read. A body that ends
|
||||
* early or has malformed framing fails the read once the bytes decoded before
|
||||
* the fault have been returned, and every later read fails the same way.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class ChunkedBodyStream implements StreamInterface
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
use StreamDecoratorTrait;
|
||||
|
||||
private const READ_SIZE = 8192;
|
||||
|
||||
private const MAX_SIZE_DIGITS = 17;
|
||||
|
||||
// libcurl's trailer line and header section limits.
|
||||
private const MAX_TRAILER_LINE_LENGTH = 4093;
|
||||
|
||||
private const MAX_TRAILER_SECTION_LENGTH = 307200;
|
||||
|
||||
private const SIZE = 0;
|
||||
|
||||
private const SIZE_LINE = 1;
|
||||
|
||||
private const DATA = 2;
|
||||
|
||||
private const DATA_END = 3;
|
||||
|
||||
private const TRAILER = 4;
|
||||
|
||||
private const TRAILER_CR = 5;
|
||||
|
||||
private const FINAL_CR = 6;
|
||||
|
||||
private const DONE = 7;
|
||||
|
||||
private StreamInterface $stream;
|
||||
|
||||
private string $buffer = '';
|
||||
|
||||
private int $offset = 0;
|
||||
|
||||
private int $state = self::SIZE;
|
||||
|
||||
private string $digits = '';
|
||||
|
||||
private int $remaining = 0;
|
||||
|
||||
private string $line = '';
|
||||
|
||||
private int $trailerLength = 0;
|
||||
|
||||
private int $position = 0;
|
||||
|
||||
private ?\RuntimeException $failure = null;
|
||||
|
||||
private bool $detachable = true;
|
||||
|
||||
public function __construct(StreamInterface $stream)
|
||||
{
|
||||
$this->stream = $stream;
|
||||
}
|
||||
|
||||
public function __clone()
|
||||
{
|
||||
// A clone shares the transport, so detaching it would break this body.
|
||||
$this->detachable = false;
|
||||
}
|
||||
|
||||
public function read(int $length): string
|
||||
{
|
||||
if ($this->failure !== null) {
|
||||
throw $this->failure;
|
||||
}
|
||||
if ($length < 0) {
|
||||
throw new \RuntimeException('Length parameter cannot be negative');
|
||||
}
|
||||
|
||||
do {
|
||||
$data = $this->decode($length);
|
||||
} while ($data === '' && $length > 0 && !$this->eof() && $this->fill());
|
||||
|
||||
$this->position = TransferByteCounter::add(
|
||||
$this->position,
|
||||
\strlen($data),
|
||||
'Response body exceeds the maximum integer size supported on this platform'
|
||||
);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function eof(): bool
|
||||
{
|
||||
return $this->state === self::DONE;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getMetadata(?string $key = null)
|
||||
{
|
||||
// A failed body has not timed out, whatever a stale flag on the
|
||||
// transport says, so callers report the failure itself.
|
||||
if ($this->failure !== null && $key === 'timed_out') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$metadata = $this->stream->getMetadata($key);
|
||||
if ($this->failure !== null && $key === null && \is_array($metadata)) {
|
||||
$metadata['timed_out'] = false;
|
||||
}
|
||||
|
||||
return $metadata;
|
||||
}
|
||||
|
||||
public function tell(): int
|
||||
{
|
||||
return $this->position;
|
||||
}
|
||||
|
||||
public function getSize(): ?int
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function isSeekable(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function seek(int $offset, int $whence = \SEEK_SET): void
|
||||
{
|
||||
throw new \RuntimeException('Cannot seek a chunked response body');
|
||||
}
|
||||
|
||||
public function isWritable(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function write(string $string): int
|
||||
{
|
||||
throw new \RuntimeException('Cannot write to a chunked response body');
|
||||
}
|
||||
|
||||
public function close(): void
|
||||
{
|
||||
$this->buffer = '';
|
||||
$this->offset = 0;
|
||||
$this->detachable = false;
|
||||
$this->stream->close();
|
||||
}
|
||||
|
||||
public function detach()
|
||||
{
|
||||
if (!$this->detachable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($this->state === self::DONE) {
|
||||
return $this->stream->detach();
|
||||
}
|
||||
|
||||
if ($this->buffer === '' && $this->failure === null) {
|
||||
$resource = $this->stream->detach();
|
||||
if (\is_resource($resource)) {
|
||||
// Nothing has been decoded yet, so PHP's filter can take over.
|
||||
\stream_filter_append($resource, 'dechunk', \STREAM_FILTER_READ);
|
||||
}
|
||||
|
||||
return $resource;
|
||||
}
|
||||
|
||||
// PHP's filter cannot resume part way through a chunk, so hand the
|
||||
// decoder over to a resource that keeps decoding the rest of the body.
|
||||
$decoder = clone $this;
|
||||
$this->buffer = '';
|
||||
$this->offset = 0;
|
||||
$this->detachable = false;
|
||||
$this->stream = Utils::streamFor('');
|
||||
$this->stream->detach();
|
||||
|
||||
return StreamWrapper::getResource($decoder);
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends what the transport has available to the buffer, waiting for at
|
||||
* least one byte.
|
||||
*/
|
||||
private function fill(): bool
|
||||
{
|
||||
$data = $this->stream->read(self::READ_SIZE);
|
||||
if ($data === '') {
|
||||
if (!$this->stream->eof()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->failure = new \RuntimeException('Response body ended before the chunked body was complete');
|
||||
|
||||
throw $this->failure;
|
||||
}
|
||||
|
||||
$this->buffer = \substr($this->buffer, $this->offset).$data;
|
||||
$this->offset = 0;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes up to $length bytes from the buffer, and any framing after them,
|
||||
* so the end of the body is noticed without another transport read.
|
||||
*/
|
||||
private function decode(int $length): string
|
||||
{
|
||||
$data = '';
|
||||
|
||||
try {
|
||||
while ($this->offset < \strlen($this->buffer) && $this->state !== self::DONE) {
|
||||
if ($this->state === self::DATA) {
|
||||
$take = \min($this->remaining, $length - \strlen($data), \strlen($this->buffer) - $this->offset);
|
||||
if ($take === 0) {
|
||||
break;
|
||||
}
|
||||
$data .= \substr($this->buffer, $this->offset, $take);
|
||||
$this->offset += $take;
|
||||
$this->remaining -= $take;
|
||||
if ($this->remaining === 0) {
|
||||
$this->state = self::DATA_END;
|
||||
}
|
||||
} elseif ($this->state === self::SIZE) {
|
||||
$chunks = $this->digits === '' ? $this->decodeChunks($length - \strlen($data)) : null;
|
||||
if ($chunks === null) {
|
||||
$this->decodeSize();
|
||||
} else {
|
||||
$data .= $chunks;
|
||||
}
|
||||
} elseif ($this->state === self::SIZE_LINE) {
|
||||
$this->skipSizeLine();
|
||||
} elseif ($this->state === self::DATA_END) {
|
||||
$this->decodeDataEnd();
|
||||
} else {
|
||||
$this->decodeTrailer();
|
||||
}
|
||||
}
|
||||
} catch (\RuntimeException $e) {
|
||||
$this->failure = $e;
|
||||
if ($data === '') {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes buffered chunks in bulk, up to $length bytes, and leaves the
|
||||
* state machine at the first chunk that needs more care. Returns null when
|
||||
* it consumes nothing.
|
||||
*/
|
||||
private function decodeChunks(int $length): ?string
|
||||
{
|
||||
$buffer = $this->buffer;
|
||||
$end = \strlen($buffer);
|
||||
$offset = $this->offset;
|
||||
$data = '';
|
||||
|
||||
while (true) {
|
||||
// Up to seven digits keep the size an int on every platform.
|
||||
$digits = \strspn($buffer, '0123456789abcdefABCDEF', $offset, 8);
|
||||
if ($digits === 0 || $digits === 8) {
|
||||
break;
|
||||
}
|
||||
$lineEnd = \strpos($buffer, "\n", $offset + $digits);
|
||||
if ($lineEnd === false) {
|
||||
break;
|
||||
}
|
||||
|
||||
$size = (int) \hexdec(\substr($buffer, $offset, $digits));
|
||||
$offset = $lineEnd + 1;
|
||||
if ($size === 0) {
|
||||
$this->state = self::TRAILER;
|
||||
break;
|
||||
}
|
||||
if ($size > $length || $offset + $size > $end) {
|
||||
$this->remaining = $size;
|
||||
$this->state = self::DATA;
|
||||
break;
|
||||
}
|
||||
|
||||
$data .= \substr($buffer, $offset, $size);
|
||||
$length -= $size;
|
||||
$offset += $size;
|
||||
if ($offset + 1 < $end && $buffer[$offset] === "\r" && $buffer[$offset + 1] === "\n") {
|
||||
$offset += 2;
|
||||
} elseif ($offset < $end && $buffer[$offset] === "\n") {
|
||||
++$offset;
|
||||
} else {
|
||||
$this->state = self::DATA_END;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($offset === $this->offset) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->offset = $offset;
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function decodeSize(): void
|
||||
{
|
||||
$count = \strspn($this->buffer, '0123456789abcdefABCDEF', $this->offset);
|
||||
$this->digits .= \substr($this->buffer, $this->offset, $count);
|
||||
$this->offset += $count;
|
||||
if (\strlen($this->digits) > self::MAX_SIZE_DIGITS) {
|
||||
throw new \RuntimeException('Invalid chunked response body: invalid chunk size');
|
||||
}
|
||||
if ($this->offset === \strlen($this->buffer)) {
|
||||
return;
|
||||
}
|
||||
if ($this->digits === '') {
|
||||
throw new \RuntimeException('Invalid chunked response body: invalid chunk size');
|
||||
}
|
||||
|
||||
$significant = \ltrim($this->digits, '0');
|
||||
if (\strlen($significant) > 16 || (\strlen($significant) === 16 && $significant[0] > '7')) {
|
||||
throw new \RuntimeException('Invalid chunked response body: invalid chunk size');
|
||||
}
|
||||
|
||||
$size = \hexdec($this->digits);
|
||||
if (!\is_int($size)) {
|
||||
throw new \OverflowException('Chunk size exceeds the maximum integer size supported on this platform');
|
||||
}
|
||||
|
||||
$this->digits = '';
|
||||
$this->remaining = $size;
|
||||
$this->state = self::SIZE_LINE;
|
||||
}
|
||||
|
||||
private function skipSizeLine(): void
|
||||
{
|
||||
// Chunk extensions, and anything else up to the line feed, are ignored
|
||||
// the way libcurl ignores them.
|
||||
$end = \strpos($this->buffer, "\n", $this->offset);
|
||||
if ($end === false) {
|
||||
$this->offset = \strlen($this->buffer);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->offset = $end + 1;
|
||||
$this->state = $this->remaining === 0 ? self::TRAILER : self::DATA;
|
||||
}
|
||||
|
||||
private function decodeDataEnd(): void
|
||||
{
|
||||
$this->offset += \strspn($this->buffer, "\r", $this->offset);
|
||||
if ($this->offset === \strlen($this->buffer)) {
|
||||
return;
|
||||
}
|
||||
if ($this->buffer[$this->offset] !== "\n") {
|
||||
throw new \RuntimeException('Invalid chunked response body: missing CRLF after chunk data');
|
||||
}
|
||||
|
||||
++$this->offset;
|
||||
$this->state = self::SIZE;
|
||||
}
|
||||
|
||||
private function decodeTrailer(): void
|
||||
{
|
||||
if ($this->state !== self::TRAILER) {
|
||||
if ($this->buffer[$this->offset] !== "\n") {
|
||||
throw new \RuntimeException('Invalid chunked response body: invalid trailer section');
|
||||
}
|
||||
|
||||
++$this->offset;
|
||||
$this->state = $this->state === self::FINAL_CR ? self::DONE : self::TRAILER;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$count = \strcspn($this->buffer, "\r\n", $this->offset);
|
||||
$this->line .= \substr($this->buffer, $this->offset, $count);
|
||||
$this->offset += $count;
|
||||
$this->trailerLength += $count;
|
||||
if (\strlen($this->line) > self::MAX_TRAILER_LINE_LENGTH || $this->trailerLength > self::MAX_TRAILER_SECTION_LENGTH) {
|
||||
throw new \RuntimeException('Invalid chunked response body: invalid trailer section');
|
||||
}
|
||||
if ($this->offset === \strlen($this->buffer)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$carriageReturn = $this->buffer[$this->offset] === "\r";
|
||||
++$this->offset;
|
||||
if ($this->line === '') {
|
||||
$this->state = $carriageReturn ? self::FINAL_CR : self::DONE;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (\strpos($this->line, "\0") !== false || \strpos($this->line, ':') === false) {
|
||||
throw new \RuntimeException('Invalid chunked response body: invalid trailer section');
|
||||
}
|
||||
|
||||
$this->line = '';
|
||||
if ($carriageReturn) {
|
||||
$this->state = self::TRAILER_CR;
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class Clock
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current monotonic clock reading in seconds.
|
||||
*/
|
||||
public static function now(): float
|
||||
{
|
||||
return \hrtime(true) / 1e9;
|
||||
}
|
||||
|
||||
public static function sleep(int $microseconds): void
|
||||
{
|
||||
while ($microseconds > 0) {
|
||||
$slice = \min($microseconds, 0xFFFFFFFF);
|
||||
\usleep($slice);
|
||||
$microseconds -= $slice;
|
||||
}
|
||||
}
|
||||
}
|
||||
+3179
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
interface CurlFactoryInterface
|
||||
{
|
||||
/**
|
||||
* Creates a cURL handle resource.
|
||||
*
|
||||
* Implementations must return an EasyHandle whose public state properties,
|
||||
* including the request and sink, contain values compatible with Guzzle's
|
||||
* cURL handlers.
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\Psr7\DiagnosticValue;
|
||||
use GuzzleHttp\TransportSharing;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* 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
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
private const KNOWN_CONSTRUCTOR_OPTIONS = [
|
||||
'handle_factory' => true,
|
||||
'max_idle_handles' => true,
|
||||
'transport_sharing' => true,
|
||||
];
|
||||
|
||||
private CurlFactoryInterface $factory;
|
||||
|
||||
private bool $ownsFactory;
|
||||
|
||||
private bool $closed = false;
|
||||
|
||||
private ?CurlShareHandleState $shareHandleState;
|
||||
|
||||
/**
|
||||
* Accepts an associative array of options:
|
||||
*
|
||||
* - handle_factory: Optional curl factory used to create cURL handles.
|
||||
* - max_idle_handles: Optional maximum number of idle cURL easy handles.
|
||||
* Zero disables retention; null or omission keeps the default of 3.
|
||||
* - transport_sharing: Optional transport sharing mode.
|
||||
*
|
||||
* @param array{handle_factory?: ?CurlFactoryInterface, max_idle_handles?: mixed, transport_sharing?: mixed} $options Array of options to use with the handler
|
||||
*/
|
||||
public function __construct(array $options = [])
|
||||
{
|
||||
foreach ($options as $name => $_) {
|
||||
if (!isset(self::KNOWN_CONSTRUCTOR_OPTIONS[$name])) {
|
||||
throw new InvalidArgumentException(\sprintf('Invalid CurlHandler constructor option "%s".', DiagnosticValue::escape((string) $name)));
|
||||
}
|
||||
}
|
||||
|
||||
CurlShareHandleState::assertNoRequiredSharingCustomFactoryConflict($options, 'CurlHandler');
|
||||
$transportSharing = $options['transport_sharing'] ?? null;
|
||||
$sharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing');
|
||||
|
||||
$maxIdleHandles = $options['max_idle_handles'] ?? 3;
|
||||
if (!\is_int($maxIdleHandles) || $maxIdleHandles < 0) {
|
||||
throw new InvalidArgumentException('max_idle_handles must be a non-negative integer.');
|
||||
}
|
||||
|
||||
if (\array_key_exists('handle_factory', $options) && $options['handle_factory'] !== null) {
|
||||
if (isset($options['max_idle_handles'])) {
|
||||
throw new InvalidArgumentException('The "max_idle_handles" CurlHandler option cannot be combined with a custom "handle_factory". Configure idle handle retention on the factory instead.');
|
||||
}
|
||||
|
||||
$this->shareHandleState = null;
|
||||
$this->factory = $options['handle_factory'];
|
||||
$this->ownsFactory = false;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->shareHandleState = $sharingMode !== TransportSharing::NONE
|
||||
? CurlShareHandleState::fromOption($transportSharing)
|
||||
: null;
|
||||
|
||||
$this->factory = $this->shareHandleState !== null
|
||||
? new CurlFactory($maxIdleHandles, $this->shareHandleState->mode, $this->shareHandleState)
|
||||
: new CurlFactory($maxIdleHandles);
|
||||
|
||||
$this->ownsFactory = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
public function __invoke(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
): PromiseInterface {
|
||||
$this->assertOpen();
|
||||
HostValidator::assertRequestHost($request);
|
||||
|
||||
if (isset($options['delay'])) {
|
||||
Clock::sleep((int) ($options['delay'] * 1000));
|
||||
}
|
||||
|
||||
// A Multiplexing::NONE request option holds unconditionally here:
|
||||
// the transfer runs alone during the blocking curl_exec(), and even
|
||||
// under persistent transport sharing an in-use connection cannot be
|
||||
// joined from another multi handle, so it never shares its
|
||||
// connection with a concurrent transfer.
|
||||
$easy = $this->factory->create($request, $options);
|
||||
|
||||
\curl_exec($easy->handle);
|
||||
$easy->errno = \curl_errno($easy->handle);
|
||||
|
||||
return CurlFactory::finish($this, $easy, $this->factory);
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes native cURL resources owned by this handler.
|
||||
*
|
||||
* After closing, the handler is terminal and must not be reused.
|
||||
*/
|
||||
public function close(): void
|
||||
{
|
||||
$this->doClose(true);
|
||||
}
|
||||
|
||||
public function __destruct()
|
||||
{
|
||||
try {
|
||||
$this->doClose(false);
|
||||
} catch (\Throwable $e) {
|
||||
// Destructors must not throw.
|
||||
}
|
||||
}
|
||||
|
||||
public function __unserialize(array $data): void
|
||||
{
|
||||
$this->closed = true;
|
||||
|
||||
throw new \LogicException(static::class.' should never be unserialized');
|
||||
}
|
||||
|
||||
private function assertOpen(): void
|
||||
{
|
||||
if ($this->closed) {
|
||||
// Programmer misuse (reusing a closed handler), not a transfer failure;
|
||||
// intentionally a LogicException outside the GuzzleException hierarchy.
|
||||
throw new \BadMethodCallException('Cannot use the cURL handler after it has been closed.');
|
||||
}
|
||||
}
|
||||
|
||||
private function doClose(bool $explicit): void
|
||||
{
|
||||
if ($this->closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->closed = true;
|
||||
|
||||
try {
|
||||
if ($this->ownsFactory && $this->factory instanceof CurlFactory) {
|
||||
$this->factory->close();
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
if ($explicit) {
|
||||
throw $e;
|
||||
}
|
||||
} finally {
|
||||
$this->shareHandleState = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,276 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\TransportSharing;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class CurlShareHandleState
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* @var resource|\CurlShareHandle|\CurlSharePersistentHandle|null
|
||||
*/
|
||||
public $handle;
|
||||
|
||||
public string $mode;
|
||||
|
||||
/**
|
||||
* @param resource|\CurlShareHandle|\CurlSharePersistentHandle|null $handle
|
||||
*/
|
||||
private function __construct(string $mode, $handle)
|
||||
{
|
||||
$this->mode = $mode;
|
||||
$this->handle = $handle;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $sharing
|
||||
*/
|
||||
public static function fromOption($sharing): ?self
|
||||
{
|
||||
if ($sharing instanceof self) {
|
||||
return $sharing;
|
||||
}
|
||||
|
||||
$mode = self::normalizeMode($sharing, 'transport_sharing');
|
||||
if ($mode === TransportSharing::NONE) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($mode === TransportSharing::HANDLER_PREFER) {
|
||||
return self::createHandlerShareOrNull($mode);
|
||||
}
|
||||
|
||||
if ($mode === TransportSharing::HANDLER_REQUIRE) {
|
||||
return self::createHandlerShare($mode);
|
||||
}
|
||||
|
||||
if ($mode === TransportSharing::PERSISTENT_PREFER) {
|
||||
return self::createPersistentShareOrFallback();
|
||||
}
|
||||
|
||||
return self::createPersistentShare($mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $sharing
|
||||
*/
|
||||
public static function normalizeMode($sharing, string $option): string
|
||||
{
|
||||
if ($sharing instanceof self) {
|
||||
return $sharing->mode;
|
||||
}
|
||||
|
||||
if ($sharing === null || $sharing === TransportSharing::NONE) {
|
||||
return TransportSharing::NONE;
|
||||
}
|
||||
|
||||
if (
|
||||
$sharing === TransportSharing::HANDLER_PREFER
|
||||
|| $sharing === TransportSharing::HANDLER_REQUIRE
|
||||
|| $sharing === TransportSharing::PERSISTENT_PREFER
|
||||
|| $sharing === TransportSharing::PERSISTENT_REQUIRE
|
||||
) {
|
||||
return $sharing;
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'The "%s" option must be null or a GuzzleHttp\\TransportSharing::* constant; received %s.',
|
||||
$option,
|
||||
\get_debug_type($sharing)
|
||||
));
|
||||
}
|
||||
|
||||
public static function assertNoRequiredSharingCustomFactoryConflict(array $options, string $handlerName): void
|
||||
{
|
||||
if (!\array_key_exists('handle_factory', $options) || $options['handle_factory'] === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$mode = self::normalizeMode($options['transport_sharing'] ?? null, 'transport_sharing');
|
||||
if (!\in_array($mode, [TransportSharing::HANDLER_REQUIRE, TransportSharing::PERSISTENT_REQUIRE], true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'The "transport_sharing" %s option cannot require sharing with a custom "handle_factory" because Guzzle cannot ensure that the custom factory applies CURLOPT_SHARE.',
|
||||
$handlerName
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether cURL can share both the DNS and SSL session cache state that
|
||||
* required handler-lifetime sharing needs, checked without configuring a
|
||||
* share handle so default handler selection can fall back to the stream
|
||||
* handler instead.
|
||||
*/
|
||||
public static function supportsHandlerRequireShare(): bool
|
||||
{
|
||||
return CurlVersion::supportsHandlerSharing()
|
||||
&& CurlVersion::supportsSslSessionSharing()
|
||||
&& \function_exists('curl_share_init')
|
||||
&& \function_exists('curl_share_setopt')
|
||||
&& \defined('CURLOPT_SHARE')
|
||||
&& \defined('CURLSHOPT_SHARE')
|
||||
&& \defined('CURL_LOCK_DATA_DNS')
|
||||
&& \defined('CURL_LOCK_DATA_SSL_SESSION');
|
||||
}
|
||||
|
||||
private static function createHandlerShareOrNull(string $mode): ?self
|
||||
{
|
||||
try {
|
||||
return self::createHandlerShare($mode);
|
||||
} catch (\Throwable $e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static function createHandlerShare(string $mode): self
|
||||
{
|
||||
if (!\function_exists('curl_share_init') || !\function_exists('curl_share_setopt')) {
|
||||
throw new InvalidArgumentException('The "transport_sharing" option requires cURL share support.');
|
||||
}
|
||||
|
||||
self::requireCurlConstant('CURLOPT_SHARE');
|
||||
$shareOption = self::requireCurlConstant('CURLSHOPT_SHARE');
|
||||
$locks = self::handlerLocks($mode);
|
||||
$handle = curl_share_init();
|
||||
|
||||
try {
|
||||
foreach ($locks as $lock) {
|
||||
try {
|
||||
$success = curl_share_setopt($handle, $shareOption, $lock);
|
||||
} catch (\Throwable $e) {
|
||||
throw new InvalidArgumentException('Unable to configure cURL share handle: '.$e->getMessage(), 0, $e);
|
||||
}
|
||||
|
||||
if (!$success) {
|
||||
throw new InvalidArgumentException(\sprintf('Unable to configure cURL share handle with lock data %d.', $lock));
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
self::closeHandlerShareHandleOnPhp7($handle);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return new self($mode, $handle);
|
||||
}
|
||||
|
||||
private static function createPersistentShareOrFallback(): ?self
|
||||
{
|
||||
if (self::supportsPersistentShare()) {
|
||||
try {
|
||||
return self::createPersistentShare(TransportSharing::PERSISTENT_PREFER);
|
||||
} catch (\Throwable $e) {
|
||||
// Fall back to handler-lifetime best effort below.
|
||||
}
|
||||
}
|
||||
|
||||
return self::createHandlerShareOrNull(TransportSharing::HANDLER_PREFER);
|
||||
}
|
||||
|
||||
private static function createPersistentShare(string $mode): self
|
||||
{
|
||||
CurlVersion::ensureConnectionSharingSupported();
|
||||
CurlVersion::ensureSslSessionSharingSupported();
|
||||
|
||||
if (!self::supportsPersistentShare()) {
|
||||
throw new InvalidArgumentException('The "transport_sharing" option requires persistent cURL share handle support.');
|
||||
}
|
||||
|
||||
self::requireCurlConstant('CURLOPT_SHARE');
|
||||
|
||||
try {
|
||||
$handle = curl_share_init_persistent(self::persistentLocks());
|
||||
} catch (\Throwable $e) {
|
||||
throw new InvalidArgumentException(
|
||||
'Unable to create persistent cURL share handle: '.$e->getMessage(),
|
||||
0,
|
||||
$e
|
||||
);
|
||||
}
|
||||
|
||||
return new self($mode, $handle);
|
||||
}
|
||||
|
||||
private static function supportsPersistentShare(): bool
|
||||
{
|
||||
return CurlVersion::supportsConnectionSharing()
|
||||
&& CurlVersion::supportsSslSessionSharing()
|
||||
&& \function_exists('curl_share_init_persistent')
|
||||
&& \class_exists('CurlSharePersistentHandle')
|
||||
&& \defined('CURL_LOCK_DATA_DNS')
|
||||
&& \defined('CURL_LOCK_DATA_CONNECT')
|
||||
&& \defined('CURL_LOCK_DATA_SSL_SESSION');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int[]
|
||||
*/
|
||||
private static function handlerLocks(string $mode): array
|
||||
{
|
||||
CurlVersion::ensureHandlerSharingSupported();
|
||||
|
||||
if ($mode === TransportSharing::HANDLER_REQUIRE) {
|
||||
CurlVersion::ensureSslSessionSharingSupported();
|
||||
}
|
||||
|
||||
$locks = [
|
||||
self::requireCurlConstant('CURL_LOCK_DATA_DNS'),
|
||||
];
|
||||
|
||||
if (CurlVersion::supportsSslSessionSharing()) {
|
||||
$locks[] = self::requireCurlConstant('CURL_LOCK_DATA_SSL_SESSION');
|
||||
}
|
||||
|
||||
return $locks;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int[]
|
||||
*/
|
||||
private static function persistentLocks(): array
|
||||
{
|
||||
return [
|
||||
self::requireCurlConstant('CURL_LOCK_DATA_DNS'),
|
||||
self::requireCurlConstant('CURL_LOCK_DATA_CONNECT'),
|
||||
self::requireCurlConstant('CURL_LOCK_DATA_SSL_SESSION'),
|
||||
];
|
||||
}
|
||||
|
||||
private static function requireCurlConstant(string $constant): int
|
||||
{
|
||||
if (!\defined($constant)) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'The "transport_sharing" option requires %s, but it is not available in the installed PHP cURL extension.',
|
||||
$constant
|
||||
));
|
||||
}
|
||||
|
||||
$value = \constant($constant);
|
||||
if (!\is_int($value)) {
|
||||
throw new InvalidArgumentException(\sprintf('The cURL constant %s must resolve to an integer.', $constant));
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param resource|\CurlShareHandle $handle
|
||||
*/
|
||||
private static function closeHandlerShareHandleOnPhp7($handle): void
|
||||
{
|
||||
if (\PHP_VERSION_ID < 80000 && \is_resource($handle)) {
|
||||
curl_share_close($handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\ConnectException;
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class CurlVersion
|
||||
{
|
||||
private const MIN_VERSION = '7.34.0';
|
||||
|
||||
private const TLS_13_VERSION = '7.52.0';
|
||||
|
||||
// CURLOPT_PIPEWAIT exists since libcurl 7.43.0, and multi handles have
|
||||
// multiplexed by default since 7.62.0 - but a 7.65.0-7.65.1 regression
|
||||
// dropped that default, which 7.65.2 restored, so 7.65.2 is the floor at
|
||||
// which PIPEWAIT is reliably effective.
|
||||
private const MULTIPLEX_VERSION = '7.65.2';
|
||||
|
||||
// libcurl's connection matcher refuses to hand a transfer wanting
|
||||
// HTTP/1.x a pooled connection that already negotiated HTTP/2 or newer
|
||||
// from 7.77.0: ConnectionExists() in lib/url.c gained the check between
|
||||
// the 7.76.0 and 7.77.0 releases. The HTTP/2 branch of the check
|
||||
// regressed to a debug log in 8.11.0 (curl commit 433d730) and was
|
||||
// restored in 8.13.0 via the negotiation mask (curl commit db72b8d), so
|
||||
// 8.11.0 through 8.12.1 are vulnerable again.
|
||||
private const HTTP_VERSION_REUSE_MATCH_VERSION = '7.77.0';
|
||||
|
||||
private const HTTP_VERSION_REUSE_MATCH_REGRESSION = '8.11.0';
|
||||
|
||||
private const HTTP_VERSION_REUSE_MATCH_RESTORED = '8.13.0';
|
||||
|
||||
// CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE restricts the ALPN offer to h2 only
|
||||
// since libcurl 8.10.0, and connection reuse matching stopped handing
|
||||
// lower-version connections to prior-knowledge transfers in 8.14.0; below
|
||||
// that, a required HTTP/2 request could silently be sent over a reused
|
||||
// HTTP/1.1 connection.
|
||||
private const REQUIRED_HTTP2_MULTIPLEX_VERSION = '8.14.0';
|
||||
|
||||
// Version-aware connection reuse matching arrived in libcurl 8.13.0 with
|
||||
// an HTTP/3-only mask for CURL_HTTP_VERSION_3ONLY transfers; below that,
|
||||
// a required HTTP/3 request could silently ride a reused HTTP/2
|
||||
// connection.
|
||||
private const REQUIRED_HTTP3_MULTIPLEX_VERSION = '8.13.0';
|
||||
|
||||
// curl 7.52.0 introduced HTTPS proxy support, advertised by a feature bit
|
||||
// (a build can meet the version yet lack the feature). Earlier libcurl
|
||||
// mishandles an https:// proxy: before 7.50.2 it silently downgrades to a
|
||||
// plaintext HTTP proxy, and 7.50.2 through 7.51 reject it at connect time.
|
||||
// The 7.52.0 TLS rework also shipped verification flaws in exactly this
|
||||
// path (CVE-2017-2629, CVE-2017-7468); the latter affects 7.52.0-7.53.1
|
||||
// and was fixed in 7.54.0, so TLS to a proxy is only trusted from there.
|
||||
private const HTTPS_PROXY_VERSION = '7.54.0';
|
||||
|
||||
// HTTP/3 arrived in libcurl 7.66.0, but CURL_HTTP_VERSION_3ONLY only
|
||||
// exists from 7.88.0; requiring it keeps every HTTP/3-capable runtime
|
||||
// able to pin HTTP/3 with no downgrade.
|
||||
private const HTTP_3_VERSION = '7.88.0';
|
||||
|
||||
private const PROTOCOLS_STR_VERSION = '7.85.0';
|
||||
|
||||
private const HANDLER_SHARING_VERSION = '7.35.0';
|
||||
|
||||
private const SSL_SESSION_SHARING_VERSION = '8.6.0';
|
||||
|
||||
private const CONNECTION_SHARING_VERSION = '8.12.0';
|
||||
|
||||
// curl 7.57.0 added share-handle connection caches through
|
||||
// CURL_LOCK_DATA_CONNECT; older share objects can only hold DNS, TLS
|
||||
// session, and cookie data, never connections. This is libcurl's raw
|
||||
// capability floor for the opaque share safeguards; Guzzle-managed
|
||||
// connection sharing is separately gated by CONNECTION_SHARING_VERSION.
|
||||
private const SHARE_CONNECTION_CACHE_VERSION = '7.57.0';
|
||||
|
||||
// curl 8.22.0 applies the cURL multi connection caps from the transfer's
|
||||
// own multi handle to transfers using a share-owned connection pool, with
|
||||
// safe eviction from such pools, and documents that contract (curl #22266);
|
||||
// from 8.13.0 (df67269) until then, the limit check on share-owned pools
|
||||
// always passed (curl #22265).
|
||||
public const SHARED_POOL_CONNECTION_CAP_VERSION = '8.22.0';
|
||||
|
||||
// curl 7.83.1 added proxy TLS-SRP to the connection-reuse match
|
||||
// (CVE-2022-27782); the proxy client certificate was matched from 7.52.0,
|
||||
// so proxy TLS credentials are trusted from 7.83.1 onwards.
|
||||
private const PROXY_TLS_CREDENTIAL_REUSE_VERSION = '7.83.1';
|
||||
|
||||
// curl 8.19.0 fixed proxy tunnel reuse after credential changes
|
||||
// (CVE-2026-3784), but related proxy credential leak flaws were only
|
||||
// fixed in 8.20.0, so connection reuse is trusted from 8.20.0 onwards.
|
||||
private const PROXY_CREDENTIAL_REUSE_VERSION = '8.20.0';
|
||||
|
||||
// curl 7.69.0 started comparing SOCKS proxy credentials when matching
|
||||
// connections for reuse (curl #4835); older libcurl matches a SOCKS proxy
|
||||
// by type, host, and port only.
|
||||
private const SOCKS_PROXY_CREDENTIAL_REUSE_VERSION = '7.69.0';
|
||||
|
||||
private const PROXY_HEADER_SEPARATION_VERSION = '7.37.0';
|
||||
|
||||
// CURLOPT_SUPPRESS_CONNECT_HEADERS arrived in curl 7.54.0; proxy CONNECT
|
||||
// tunneling is gated on it so the proxy's interim reply can never surface
|
||||
// as a phantom response on any build that can tunnel.
|
||||
private const PROXY_TUNNEL_VERSION = '7.54.0';
|
||||
|
||||
/**
|
||||
* @var array{version: string, features: int}|false|null
|
||||
*/
|
||||
private static $versionInfo;
|
||||
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
public static function supportsCurlHandler(): bool
|
||||
{
|
||||
$versionInfo = self::getVersionInfo();
|
||||
|
||||
return \defined('CURL_VERSION_SSL')
|
||||
&& \defined('CURL_SSLVERSION_TLSv1_2')
|
||||
&& \defined('CURLMOPT_MAX_HOST_CONNECTIONS')
|
||||
&& \defined('CURLMOPT_MAX_TOTAL_CONNECTIONS')
|
||||
&& null !== $versionInfo
|
||||
&& version_compare($versionInfo['version'], self::MIN_VERSION, '>=')
|
||||
&& 0 !== (\CURL_VERSION_SSL & $versionInfo['features']);
|
||||
}
|
||||
|
||||
public static function supportsTls13(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return \defined('CURL_SSLVERSION_TLSv1_3')
|
||||
&& null !== $version
|
||||
&& version_compare($version, self::TLS_13_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsMultiplex(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return \defined('CURLOPT_PIPEWAIT')
|
||||
&& null !== $version
|
||||
&& version_compare($version, self::MULTIPLEX_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsHttpVersionReuseMatching(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
if (null === $version || version_compare($version, self::HTTP_VERSION_REUSE_MATCH_VERSION, '<')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return version_compare($version, self::HTTP_VERSION_REUSE_MATCH_REGRESSION, '<')
|
||||
|| version_compare($version, self::HTTP_VERSION_REUSE_MATCH_RESTORED, '>=');
|
||||
}
|
||||
|
||||
public static function supportsRequiredHttp2Multiplex(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return \defined('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE')
|
||||
&& null !== $version
|
||||
&& self::supportsHttp2()
|
||||
&& version_compare($version, self::REQUIRED_HTTP2_MULTIPLEX_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsHttp2(): bool
|
||||
{
|
||||
$versionInfo = self::getVersionInfo();
|
||||
|
||||
// Requiring dependable CURLOPT_PIPEWAIT support keeps waiting from
|
||||
// ever being silently unavailable where HTTP/2 works.
|
||||
return \defined('CURL_VERSION_HTTP2')
|
||||
&& null !== $versionInfo
|
||||
&& self::supportsMultiplex()
|
||||
&& 0 !== (\CURL_VERSION_HTTP2 & $versionInfo['features']);
|
||||
}
|
||||
|
||||
public static function supportsHttp3(): bool
|
||||
{
|
||||
if (!\defined('CURL_VERSION_HTTP3') || !\defined('CURL_HTTP_VERSION_3') || !\defined('CURL_HTTP_VERSION_3ONLY')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$versionInfo = self::getVersionInfo();
|
||||
if (null === $versionInfo || version_compare($versionInfo['version'], self::HTTP_3_VERSION, '<')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return 0 !== ((int) \constant('CURL_VERSION_HTTP3') & $versionInfo['features']);
|
||||
}
|
||||
|
||||
public static function supportsRequiredHttp3Multiplex(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return self::supportsHttp3()
|
||||
&& null !== $version
|
||||
&& version_compare($version, self::REQUIRED_HTTP3_MULTIPLEX_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsHttpsProxy(): bool
|
||||
{
|
||||
$versionInfo = self::getVersionInfo();
|
||||
|
||||
return \defined('CURL_VERSION_HTTPS_PROXY')
|
||||
&& null !== $versionInfo
|
||||
&& version_compare($versionInfo['version'], self::HTTPS_PROXY_VERSION, '>=')
|
||||
&& 0 !== (\CURL_VERSION_HTTPS_PROXY & $versionInfo['features']);
|
||||
}
|
||||
|
||||
public static function supportsHandlerSharing(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return null !== $version
|
||||
&& version_compare($version, self::HANDLER_SHARING_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function ensureHandlerSharingSupported(): void
|
||||
{
|
||||
if (!self::supportsHandlerSharing()) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'The "transport_sharing" option requires libcurl %s or higher for cURL share handles.',
|
||||
self::HANDLER_SHARING_VERSION
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
public static function supportsSslSessionSharing(): bool
|
||||
{
|
||||
$versionInfo = self::getVersionInfo();
|
||||
|
||||
return \defined('CURL_VERSION_SSL')
|
||||
&& null !== $versionInfo
|
||||
&& version_compare($versionInfo['version'], self::SSL_SESSION_SHARING_VERSION, '>=')
|
||||
&& 0 !== (\CURL_VERSION_SSL & $versionInfo['features']);
|
||||
}
|
||||
|
||||
public static function ensureSslSessionSharingSupported(): void
|
||||
{
|
||||
if (!self::supportsSslSessionSharing()) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'The "transport_sharing" option requires libcurl %s or higher with SSL support for SSL session sharing.',
|
||||
self::SSL_SESSION_SHARING_VERSION
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
public static function supportsConnectionSharing(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return null !== $version
|
||||
&& version_compare($version, self::CONNECTION_SHARING_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function ensureConnectionSharingSupported(): void
|
||||
{
|
||||
if (!self::supportsConnectionSharing()) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'The "transport_sharing" option requires libcurl %s or higher for persistent connection sharing.',
|
||||
self::CONNECTION_SHARING_VERSION
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
public static function supportsSharedPoolConnectionCaps(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return null !== $version
|
||||
&& version_compare($version, self::SHARED_POOL_CONNECTION_CAP_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsShareConnectionCaches(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
// An undetectable libcurl version is treated as capable so the
|
||||
// opaque share safeguards fail closed.
|
||||
return null === $version
|
||||
|| version_compare($version, self::SHARE_CONNECTION_CACHE_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsProxyTlsCredentialAwareConnectionReuse(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return null !== $version
|
||||
&& version_compare($version, self::PROXY_TLS_CREDENTIAL_REUSE_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsProxyCredentialAwareConnectionReuse(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return null !== $version
|
||||
&& version_compare($version, self::PROXY_CREDENTIAL_REUSE_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsSocksProxyCredentialAwareConnectionReuse(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return null !== $version
|
||||
&& version_compare($version, self::SOCKS_PROXY_CREDENTIAL_REUSE_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsProxyHeaderSeparation(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return null !== $version
|
||||
&& version_compare($version, self::PROXY_HEADER_SEPARATION_VERSION, '>=')
|
||||
&& \defined('CURLOPT_PROXYHEADER')
|
||||
&& \defined('CURLOPT_HEADEROPT')
|
||||
&& \defined('CURLHEADER_SEPARATE');
|
||||
}
|
||||
|
||||
public static function supportsProtocolsStr(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return \defined('CURLOPT_PROTOCOLS_STR')
|
||||
&& null !== $version
|
||||
&& version_compare($version, self::PROTOCOLS_STR_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsProxyTunneling(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return \defined('CURLOPT_SUPPRESS_CONNECT_HEADERS')
|
||||
&& null !== $version
|
||||
&& version_compare($version, self::PROXY_TUNNEL_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function ensureSupported(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request
|
||||
): void {
|
||||
if (self::supportsCurlHandler()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$version = self::get();
|
||||
|
||||
if (null === $version || version_compare($version, self::MIN_VERSION, '<')) {
|
||||
throw new ConnectException(\sprintf(
|
||||
'cURL %s or higher is required by the cURL handler; %s is installed.',
|
||||
self::MIN_VERSION,
|
||||
$version ?? 'an unknown version'
|
||||
), $request);
|
||||
}
|
||||
|
||||
if (!\defined('CURL_SSLVERSION_TLSv1_2')) {
|
||||
throw new ConnectException(\sprintf(
|
||||
'The PHP cURL extension must be built against cURL %s or higher to use the cURL handler.',
|
||||
self::MIN_VERSION
|
||||
), $request);
|
||||
}
|
||||
|
||||
if (!\defined('CURLMOPT_MAX_HOST_CONNECTIONS') || !\defined('CURLMOPT_MAX_TOTAL_CONNECTIONS')) {
|
||||
throw new ConnectException('The PHP cURL extension must expose CURLMOPT_MAX_HOST_CONNECTIONS and CURLMOPT_MAX_TOTAL_CONNECTIONS to use the cURL handler.', $request);
|
||||
}
|
||||
|
||||
throw new ConnectException('The cURL handler requires libcurl SSL support.', $request);
|
||||
}
|
||||
|
||||
private static function get(): ?string
|
||||
{
|
||||
$versionInfo = self::getVersionInfo();
|
||||
|
||||
return null === $versionInfo ? null : $versionInfo['version'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{version: string, features: int}|null
|
||||
*/
|
||||
private static function getVersionInfo(): ?array
|
||||
{
|
||||
if (null === self::$versionInfo) {
|
||||
if (!\function_exists('curl_version')) {
|
||||
self::$versionInfo = false;
|
||||
} else {
|
||||
$versionInfo = \curl_version();
|
||||
self::$versionInfo = \is_array($versionInfo)
|
||||
&& isset($versionInfo['version'], $versionInfo['features'])
|
||||
&& \is_string($versionInfo['version'])
|
||||
&& \is_int($versionInfo['features'])
|
||||
? [
|
||||
'version' => $versionInfo['version'],
|
||||
'features' => $versionInfo['features'],
|
||||
]
|
||||
: false;
|
||||
}
|
||||
}
|
||||
|
||||
return false === self::$versionInfo ? null : self::$versionInfo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7\Exception\TimeoutException;
|
||||
use GuzzleHttp\Psr7\StreamDecoratorTrait;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Decorates the transport stream of a buffered response so every read
|
||||
* observes the wall-clock deadline of the "timeout" request option.
|
||||
*
|
||||
* The transport resource must be in non-blocking mode: a blocking read waits
|
||||
* for data up to the transport's own timeout, so a deadline check between reads
|
||||
* never runs while the server stalls. Reads return whatever bytes are available
|
||||
* and poll briefly for more, so the deadline is checked between packets rather
|
||||
* than between buffers.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class DeadlineSourceStream implements StreamInterface
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
use StreamDecoratorTrait;
|
||||
|
||||
private const POLL_INTERVAL = 0.05;
|
||||
|
||||
private StreamInterface $stream;
|
||||
|
||||
private float $deadline;
|
||||
|
||||
private ?float $readTimeout;
|
||||
|
||||
/**
|
||||
* @param StreamInterface $stream Transport stream in non-blocking mode.
|
||||
* @param float $deadline Deadline based on Clock::now().
|
||||
* @param float|null $readTimeout Optional idle timeout per read, in seconds.
|
||||
*/
|
||||
public function __construct(StreamInterface $stream, float $deadline, ?float $readTimeout)
|
||||
{
|
||||
$this->stream = $stream;
|
||||
$this->deadline = $deadline;
|
||||
$this->readTimeout = $readTimeout;
|
||||
}
|
||||
|
||||
public function read(int $length): string
|
||||
{
|
||||
$idleStart = null;
|
||||
|
||||
while (true) {
|
||||
$remaining = $this->deadline - Clock::now();
|
||||
if ($remaining <= 0) {
|
||||
throw new TimeoutException('Unable to read from stream: timed out');
|
||||
}
|
||||
|
||||
$data = $this->stream->read($length);
|
||||
if ($data !== '') {
|
||||
return $data;
|
||||
}
|
||||
if ($this->stream->eof()) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$now = Clock::now();
|
||||
if ($idleStart === null) {
|
||||
$idleStart = $now;
|
||||
}
|
||||
if ($this->readTimeout !== null && $now - $idleStart >= $this->readTimeout) {
|
||||
throw new TimeoutException('Unable to read from stream: timed out');
|
||||
}
|
||||
|
||||
$wait = \min($remaining, self::POLL_INTERVAL);
|
||||
if ($this->readTimeout !== null) {
|
||||
$wait = \min($wait, $this->readTimeout - ($now - $idleStart));
|
||||
}
|
||||
\usleep((int) \ceil($wait * 1e6));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Psr7;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class DebugResource
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a debug stream based on the provided variable.
|
||||
*
|
||||
* @param mixed $value Optional value
|
||||
*
|
||||
* @return resource
|
||||
*/
|
||||
public static function from($value = null)
|
||||
{
|
||||
if (\is_resource($value)) {
|
||||
return $value;
|
||||
}
|
||||
if (\defined('STDOUT')) {
|
||||
return \STDOUT;
|
||||
}
|
||||
|
||||
return Psr7\Utils::tryFopen('php://output', 'w');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7\StreamDecoratorTrait;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Ends a streamed response body at its declared Content-Length.
|
||||
*
|
||||
* Reads never consume bytes beyond the response message, and the body reaches
|
||||
* EOF without waiting for the server to close the connection. A transport that
|
||||
* ends before the declared length fails the read instead of looking like a
|
||||
* complete body.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class DeclaredLengthStream implements StreamInterface
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
use StreamDecoratorTrait;
|
||||
|
||||
private StreamInterface $stream;
|
||||
|
||||
private int $remaining;
|
||||
|
||||
private ?\RuntimeException $failure = null;
|
||||
|
||||
public function __construct(StreamInterface $stream, int $declaredLength)
|
||||
{
|
||||
$this->stream = $stream;
|
||||
$this->remaining = $declaredLength;
|
||||
}
|
||||
|
||||
public function __clone()
|
||||
{
|
||||
// Detaching a clone must not detach this body's transport.
|
||||
$this->stream = clone $this->stream;
|
||||
}
|
||||
|
||||
public function eof(): bool
|
||||
{
|
||||
return $this->remaining === 0;
|
||||
}
|
||||
|
||||
public function isSeekable(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function seek(int $offset, int $whence = \SEEK_SET): void
|
||||
{
|
||||
throw new \RuntimeException('Cannot seek a response body bounded by its declared Content-Length');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getMetadata(?string $key = null)
|
||||
{
|
||||
// A failed body has not timed out, whatever a stale flag on the
|
||||
// transport says, so callers report the failure itself.
|
||||
if ($this->failure !== null && $key === 'timed_out') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$metadata = $this->stream->getMetadata($key);
|
||||
if ($this->failure !== null && $key === null && \is_array($metadata)) {
|
||||
$metadata['timed_out'] = false;
|
||||
}
|
||||
|
||||
return $metadata;
|
||||
}
|
||||
|
||||
public function read(int $length): string
|
||||
{
|
||||
if ($length < 0) {
|
||||
throw new \RuntimeException('Length parameter cannot be negative');
|
||||
}
|
||||
|
||||
if ($this->failure !== null) {
|
||||
throw $this->failure;
|
||||
}
|
||||
|
||||
if ($length === 0 || $this->remaining === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$data = $this->stream->read(\min($length, $this->remaining));
|
||||
if ($data === '' && $this->stream->eof()) {
|
||||
$this->failure = new \RuntimeException('Response body ended before the declared Content-Length was reached');
|
||||
|
||||
throw $this->failure;
|
||||
}
|
||||
|
||||
$this->remaining -= \strlen($data);
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
+260
@@ -0,0 +1,260 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\Exception\ResponseException;
|
||||
use GuzzleHttp\Exception\ResponseTransferException;
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7\DiagnosticValue;
|
||||
use GuzzleHttp\Psr7\Exception\TimeoutException;
|
||||
use GuzzleHttp\Psr7\HttpFactory;
|
||||
use GuzzleHttp\RequestOptions;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseFactoryInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Represents a cURL easy handle and the data it populates.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class EasyHandle
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* @var resource|\CurlHandle cURL resource
|
||||
*/
|
||||
public $handle;
|
||||
|
||||
public StreamInterface $sink;
|
||||
|
||||
public RequestInterface $request;
|
||||
|
||||
/**
|
||||
* @var list<string> Received HTTP headers so far
|
||||
*/
|
||||
public array $headers = [];
|
||||
|
||||
/**
|
||||
* @var list<string> Valid trailer lines, retained only when an
|
||||
* on_trailers callback is configured
|
||||
*/
|
||||
public array $trailers = [];
|
||||
|
||||
/**
|
||||
* @var bool Whether this handle was configured with CURLOPT_PIPEWAIT
|
||||
*/
|
||||
public bool $usesPipewait = false;
|
||||
|
||||
/**
|
||||
* @var bool Whether processMessages() settled the deferred promise, which
|
||||
* a rewind retry settles with a still-pending promise
|
||||
*/
|
||||
public bool $deferredSettled = false;
|
||||
|
||||
/**
|
||||
* @var ResponseInterface|null Received response (if any)
|
||||
*/
|
||||
public ?ResponseInterface $response = null;
|
||||
|
||||
/**
|
||||
* @var array Request options
|
||||
*/
|
||||
public array $options = [];
|
||||
|
||||
/**
|
||||
* @var int cURL error number (if any)
|
||||
*/
|
||||
public int $errno = 0;
|
||||
|
||||
/**
|
||||
* @var string|null Effective CURLOPT_PROXY value the handle was created with (if any)
|
||||
*/
|
||||
public ?string $effectiveProxy = null;
|
||||
|
||||
/**
|
||||
* Proxy tunnel or SOCKS proxy section signature for connection-reuse
|
||||
* isolation, or null when the request does not require sectioning.
|
||||
*/
|
||||
public ?string $proxyTunnelSignature = null;
|
||||
|
||||
/**
|
||||
* @var \Throwable|null Exception during on_headers (if any)
|
||||
*/
|
||||
public ?\Throwable $onHeadersException = null;
|
||||
|
||||
/**
|
||||
* @var \Throwable|null Exception during progress callback (if any)
|
||||
*/
|
||||
public ?\Throwable $progressException = null;
|
||||
|
||||
/**
|
||||
* @var bool Whether the progress callback requested abort
|
||||
*/
|
||||
public bool $progressAborted = false;
|
||||
|
||||
/**
|
||||
* @var \Throwable|null Exception during createResponse (if any)
|
||||
*/
|
||||
public ?\Throwable $createResponseException = null;
|
||||
|
||||
/**
|
||||
* @var ResponseException|null Response header failure, if any.
|
||||
*/
|
||||
public ?ResponseException $responseHeaderException = null;
|
||||
|
||||
/**
|
||||
* @var TimeoutException|null Exception during request body read timeout.
|
||||
*/
|
||||
public ?TimeoutException $bodyReadTimeoutException = null;
|
||||
|
||||
/**
|
||||
* @var TimeoutException|null Exception during request body rewind timeout.
|
||||
*/
|
||||
public ?TimeoutException $bodyRewindTimeoutException = null;
|
||||
|
||||
/**
|
||||
* @var \Throwable|null Exception during request body rewind.
|
||||
*/
|
||||
public ?\Throwable $bodyRewindException = null;
|
||||
|
||||
/**
|
||||
* @var \Throwable|null Exception during request body read.
|
||||
*/
|
||||
public ?\Throwable $bodyReadException = null;
|
||||
|
||||
/**
|
||||
* @var TimeoutException|null Exception during response sink write timeout.
|
||||
*/
|
||||
public ?TimeoutException $sinkWriteTimeoutException = null;
|
||||
|
||||
/**
|
||||
* @var \Throwable|null Exception during response sink write.
|
||||
*/
|
||||
public ?\Throwable $sinkWriteException = null;
|
||||
|
||||
/**
|
||||
* @var bool Whether the response sink accepted a different byte count.
|
||||
*/
|
||||
public bool $sinkWriteIncomplete = false;
|
||||
|
||||
/**
|
||||
* @var int Number of response body bytes accepted by the sink.
|
||||
*/
|
||||
public int $responseBodyBytes = 0;
|
||||
|
||||
/**
|
||||
* @var \OverflowException|null Unrepresentable response body size or byte count.
|
||||
*/
|
||||
public ?\OverflowException $responseBodySizeException = null;
|
||||
|
||||
/**
|
||||
* 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
|
||||
{
|
||||
$this->response = null;
|
||||
$this->responseBodyBytes = 0;
|
||||
$this->responseBodySizeException = null;
|
||||
$this->responseHeaderException = null;
|
||||
|
||||
[$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($this->headers);
|
||||
|
||||
// Non-101 informational responses precede the final response. Do not
|
||||
// expose them as the response for a transfer that ends before the final
|
||||
// response arrives. 101 switches protocol and is kept as terminal.
|
||||
if ($status < 200 && $status !== 101) {
|
||||
return;
|
||||
}
|
||||
|
||||
$framingFailure = null;
|
||||
try {
|
||||
$declaredLength = HeaderProcessor::validateResponseFraming($this->request->getMethod(), $status, $headers);
|
||||
HeaderProcessor::assertContentLengthWithinPlatformLimit($declaredLength);
|
||||
} catch (\RuntimeException $e) {
|
||||
$framingFailure = $e;
|
||||
}
|
||||
|
||||
$normalizedKeys = HeaderProcessor::normalizeHeaderKeys($headers);
|
||||
$decodeContent = $this->options['decode_content'] ?? false;
|
||||
if ($framingFailure === null && $decodeContent !== false && isset($normalizedKeys['content-encoding'])) {
|
||||
$headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']];
|
||||
unset($headers[$normalizedKeys['content-encoding']]);
|
||||
$encodedContentLength = HeaderProcessor::removeHeader('Content-Length', $headers);
|
||||
if ($encodedContentLength !== []) {
|
||||
$headers['x-encoded-content-length'] = $encodedContentLength;
|
||||
|
||||
try {
|
||||
$bodyLength = $this->sink->getSize();
|
||||
} catch (\Exception $e) {
|
||||
$bodyLength = null;
|
||||
}
|
||||
if ($bodyLength) {
|
||||
$headers['Content-Length'] = [(string) $bodyLength];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Attach a response to the easy handle with the parsed headers. Any
|
||||
// exception propagates to the caller (CurlFactory), which records it as
|
||||
// the createResponseException — do not catch it here.
|
||||
$responseFactory = self::requireResponseFactory($this->options[RequestOptions::RESPONSE_FACTORY] ?? new HttpFactory());
|
||||
$response = $responseFactory->createResponse($status, $reason ?? '')->withProtocolVersion($ver);
|
||||
foreach ($headers as $name => $value) {
|
||||
$response = $response->withAddedHeader((string) $name, $value);
|
||||
}
|
||||
$this->response = $response->withBody($this->sink);
|
||||
|
||||
if ($framingFailure instanceof \OverflowException) {
|
||||
$this->responseHeaderException = new ResponseException(
|
||||
$framingFailure->getMessage(),
|
||||
$this->request,
|
||||
$this->response,
|
||||
$framingFailure
|
||||
);
|
||||
} elseif ($framingFailure !== null) {
|
||||
$this->responseHeaderException = new ResponseTransferException(
|
||||
$framingFailure->getMessage(),
|
||||
$this->request,
|
||||
$this->response,
|
||||
$framingFailure
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $factory
|
||||
*/
|
||||
private static function requireResponseFactory($factory): ResponseFactoryInterface
|
||||
{
|
||||
if (!$factory instanceof ResponseFactoryInterface) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'%s must be an instance of %s',
|
||||
RequestOptions::RESPONSE_FACTORY,
|
||||
ResponseFactoryInterface::class
|
||||
));
|
||||
}
|
||||
|
||||
return $factory;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws \BadMethodCallException
|
||||
*/
|
||||
public function __get(string $name): void
|
||||
{
|
||||
$msg = $name === 'handle'
|
||||
? 'The EasyHandle has been released'
|
||||
: \sprintf('Invalid property: %s', DiagnosticValue::escape($name));
|
||||
|
||||
throw new \BadMethodCallException($msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7\StreamDecoratorTrait;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Tracks encoded response bytes beneath a content-decoding stream.
|
||||
*
|
||||
* Reads are bounded by a positive, representable Content-Length so a decoder
|
||||
* cannot consume bytes beyond the response message boundary.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class EncodedBodyStream implements StreamInterface
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
use StreamDecoratorTrait;
|
||||
|
||||
private StreamInterface $stream;
|
||||
|
||||
private ?int $limit;
|
||||
|
||||
private int $bytesRead = 0;
|
||||
|
||||
public function __construct(StreamInterface $stream, string $declaredLength)
|
||||
{
|
||||
$this->stream = $stream;
|
||||
|
||||
$limit = HeaderProcessor::contentLengthToInt($declaredLength);
|
||||
$this->limit = $limit !== null && $limit > 0 ? $limit : null;
|
||||
}
|
||||
|
||||
public function eof(): bool
|
||||
{
|
||||
return ($this->limit !== null && $this->bytesRead >= $this->limit)
|
||||
|| $this->stream->eof();
|
||||
}
|
||||
|
||||
public function isSeekable(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function seek(int $offset, int $whence = \SEEK_SET): void
|
||||
{
|
||||
throw new \RuntimeException('Cannot seek a stream while tracking encoded response bytes');
|
||||
}
|
||||
|
||||
public function read(int $length): string
|
||||
{
|
||||
if ($length < 0) {
|
||||
throw new \RuntimeException('Length parameter cannot be negative');
|
||||
}
|
||||
|
||||
if ($this->limit !== null) {
|
||||
$remaining = $this->limit - $this->bytesRead;
|
||||
if ($remaining === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$length = \min($length, $remaining);
|
||||
}
|
||||
|
||||
$data = $this->stream->read($length);
|
||||
$this->bytesRead = TransferByteCounter::add(
|
||||
$this->bytesRead,
|
||||
\strlen($data),
|
||||
'Response body exceeds the maximum integer size supported on this platform'
|
||||
);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function getBytesRead(): int
|
||||
{
|
||||
return $this->bytesRead;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Psr7;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class HeaderProcessor
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* 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');
|
||||
}
|
||||
|
||||
$headers = self::getLastHeaderBlock(\array_values($headers));
|
||||
|
||||
$statusLine = \array_shift($headers);
|
||||
if ($statusLine === null) {
|
||||
throw new \RuntimeException('Expected a non-empty array of header data');
|
||||
}
|
||||
|
||||
$parts = \explode(' ', $statusLine, 3);
|
||||
$protocol = $parts[0];
|
||||
|
||||
if (!Psr7\Utils::caselessEquals(\substr($protocol, 0, 5), 'HTTP/')) {
|
||||
throw new \RuntimeException('HTTP version missing from header data');
|
||||
}
|
||||
|
||||
$version = \substr($protocol, 5);
|
||||
|
||||
if (!\preg_match('/^\d+(?:\.\d+)?$/D', $version)) {
|
||||
throw new \RuntimeException('HTTP version is invalid');
|
||||
}
|
||||
|
||||
$status = $parts[1] ?? null;
|
||||
|
||||
if ($status === null) {
|
||||
throw new \RuntimeException('HTTP status code missing from header data');
|
||||
}
|
||||
|
||||
if (!\preg_match('/^[1-5]\d{2}$/D', $status)) {
|
||||
throw new \RuntimeException('HTTP status code is invalid');
|
||||
}
|
||||
|
||||
$reason = $parts[2] ?? null;
|
||||
|
||||
if ($reason !== null && !\preg_match('/^[\x09\x20-\x7E\x80-\xFF]*$/D', $reason)) {
|
||||
throw new \RuntimeException('HTTP reason phrase is invalid');
|
||||
}
|
||||
|
||||
foreach ($headers as $header) {
|
||||
if (\strpos($header, ':') === false) {
|
||||
throw new \RuntimeException('HTTP header line is invalid');
|
||||
}
|
||||
}
|
||||
|
||||
return [$version, (int) $status, $reason, self::headersFromLines($headers)];
|
||||
}
|
||||
|
||||
/**
|
||||
* 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], " \n\r\t\0\x0B")][] = isset($parts[1]) ? \trim($parts[1], " \n\r\t\0\x0B") : null;
|
||||
}
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
public static function isStatusLineCandidate(string $line): bool
|
||||
{
|
||||
return \preg_match('/^HTTP\/[0-9]+(?:\.[0-9]+)? [0-9]{3}(?: [^\r\n]*)?(?:\r\n|\r|\n)?$/iD', $line) === 1;
|
||||
}
|
||||
|
||||
public static function isValidHeaderFieldLine(string $line): bool
|
||||
{
|
||||
$parts = \explode(':', $line, 2);
|
||||
|
||||
if (!isset($parts[1])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!\preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $parts[0])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return \preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*(?:\r\n|\r|\n)?$/D', \trim($parts[1], " \t")) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a normalized decimal Content-Length, or null when absent.
|
||||
*
|
||||
* @param string[] $values
|
||||
*
|
||||
* @throws \RuntimeException when Content-Length is malformed or conflicting.
|
||||
*/
|
||||
public static function parseContentLength(array $values): ?string
|
||||
{
|
||||
$length = null;
|
||||
|
||||
foreach ($values as $value) {
|
||||
foreach (\explode(',', $value) as $part) {
|
||||
$part = \trim($part, " \t");
|
||||
if (\preg_match('/^[0-9]+$/D', $part) !== 1) {
|
||||
throw new \RuntimeException('value is not a non-negative decimal integer');
|
||||
}
|
||||
|
||||
$part = \ltrim($part, '0');
|
||||
$part = $part === '' ? '0' : $part;
|
||||
if ($length !== null && $part !== $length) {
|
||||
throw new \RuntimeException('values conflict');
|
||||
}
|
||||
|
||||
$length = $part;
|
||||
}
|
||||
}
|
||||
|
||||
if ($length === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $length;
|
||||
}
|
||||
|
||||
public static function contentLengthToInt(?string $length): ?int
|
||||
{
|
||||
if ($length === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$max = (string) \PHP_INT_MAX;
|
||||
if (
|
||||
\strlen($length) > \strlen($max)
|
||||
|| (\strlen($length) === \strlen($max) && \strcmp($length, $max) > 0)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) $length;
|
||||
}
|
||||
|
||||
public static function assertContentLengthWithinPlatformLimit(?string $length): void
|
||||
{
|
||||
if ($length === null || self::contentLengthToInt($length) !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new \OverflowException('Content-Length exceeds the maximum integer size supported on this platform');
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates response framing and returns its normalized Content-Length.
|
||||
* Returns null when absent or when ordinary body framing does not apply.
|
||||
*
|
||||
* @param array<string, string[]> $headers
|
||||
*
|
||||
* @throws \RuntimeException when Content-Length is malformed, conflicting,
|
||||
* or combined with Transfer-Encoding, or when a
|
||||
* transfer coding is unsupported or follows
|
||||
* chunked on the same field line
|
||||
*/
|
||||
public static function validateResponseFraming(
|
||||
string $method,
|
||||
int $status,
|
||||
array $headers
|
||||
): ?string {
|
||||
if (!self::responseCanHaveBody($method, $status)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$normalizedKeys = self::normalizeHeaderKeys($headers);
|
||||
$contentLength = self::removeHeader('Content-Length', $headers);
|
||||
|
||||
try {
|
||||
$length = self::parseContentLength($contentLength);
|
||||
} catch (\RuntimeException $e) {
|
||||
throw new \RuntimeException('Invalid Content-Length response header: '.$e->getMessage(), 0, $e);
|
||||
}
|
||||
|
||||
if ($length !== null && isset($normalizedKeys['transfer-encoding'])) {
|
||||
throw new \RuntimeException('A response must not contain both Content-Length and Transfer-Encoding');
|
||||
}
|
||||
|
||||
self::parseTransferEncoding($headers);
|
||||
|
||||
return $length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the response uses the chunked transfer coding.
|
||||
*
|
||||
* Guzzle never asks for a transfer coding, so like libcurl 8.14 and newer
|
||||
* it accepts only identity and chunked, with nothing but chunked after
|
||||
* chunked on the same field line. Empty list elements are ignored.
|
||||
*
|
||||
* @param array<string, string[]> $headers
|
||||
*
|
||||
* @throws \RuntimeException when a coding is unsupported or follows chunked
|
||||
* on the same field line
|
||||
*/
|
||||
public static function parseTransferEncoding(array $headers): bool
|
||||
{
|
||||
$chunked = false;
|
||||
|
||||
foreach ($headers as $name => $values) {
|
||||
if (!Psr7\Utils::caselessEquals((string) $name, 'Transfer-Encoding')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($values as $value) {
|
||||
$afterChunked = false;
|
||||
foreach (\explode(',', $value) as $coding) {
|
||||
$coding = \trim($coding, " \t");
|
||||
if ($coding === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Psr7\Utils::caselessEquals($coding, 'chunked')) {
|
||||
$chunked = true;
|
||||
$afterChunked = true;
|
||||
} elseif ($afterChunked) {
|
||||
throw new \RuntimeException('Invalid Transfer-Encoding response header: chunked is not the final transfer coding');
|
||||
} elseif (!Psr7\Utils::caselessEquals($coding, 'identity')) {
|
||||
throw new \RuntimeException(\sprintf(
|
||||
'Invalid Transfer-Encoding response header: unsupported transfer coding "%s"',
|
||||
Psr7\DiagnosticValue::escape($coding)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $chunked;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes every case-insensitive occurrence of a header and returns all
|
||||
* removed values in their original field order.
|
||||
*
|
||||
* @param array<string, string[]> $headers
|
||||
*
|
||||
* @return string[] Removed values across all header-name casings
|
||||
*/
|
||||
public static function removeHeader(string $name, array &$headers): array
|
||||
{
|
||||
$values = [];
|
||||
|
||||
foreach ($headers as $key => $headerValues) {
|
||||
if (Psr7\Utils::caselessEquals((string) $key, $name)) {
|
||||
\array_push($values, ...$headerValues);
|
||||
unset($headers[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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[Psr7\Utils::asciiToLower((string) $key)] = $key;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a response uses ordinary body framing. A response to HEAD, a
|
||||
* response with a 1xx, 204, or 304 status code, or a 2xx response to
|
||||
* CONNECT never has a body, whatever its framing headers claim. A 205
|
||||
* remains subject to framing even though its semantics require no content.
|
||||
*/
|
||||
public static function responseCanHaveBody(string $method, int $status): bool
|
||||
{
|
||||
return $method !== 'HEAD'
|
||||
&& !($method === 'CONNECT' && $status >= 200 && $status < 300)
|
||||
&& $status >= 200
|
||||
&& $status !== 204
|
||||
&& $status !== 304;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param non-empty-list<string> $headers
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private static function getLastHeaderBlock(array $headers): array
|
||||
{
|
||||
$lastStatusLine = 0;
|
||||
|
||||
foreach ($headers as $index => $line) {
|
||||
if (self::isStatusLineCandidate($line)) {
|
||||
$lastStatusLine = $index;
|
||||
}
|
||||
}
|
||||
|
||||
return \array_slice($headers, $lastStatusLine);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
use GuzzleHttp\Psr7;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
* Rejects request hosts that a handler could resolve differently from the host
|
||||
* the request names.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class HostValidator
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that a request names one unambiguous network host.
|
||||
*
|
||||
* A handler reparses the URI but sends the Host header as given. The URI
|
||||
* host must therefore be printable ASCII, free of percent escapes, a valid
|
||||
* RFC 3986 host, and not numeric-looking parts followed by trailing dots.
|
||||
* Every Host header value must be printable ASCII.
|
||||
*
|
||||
* @throws RequestException
|
||||
*/
|
||||
public static function assertRequestHost(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request
|
||||
): void {
|
||||
self::assertUriHost($request->getUri()->getHost(), $request);
|
||||
|
||||
foreach ($request->getHeader('Host') as $value) {
|
||||
self::assertPrintableAscii((string) $value, 'The request Host header "%s" must contain only printable ASCII characters, because an intermediary or an origin server can otherwise read it as an authority that differs from the one the request names. An internationalized host name has an A-label form that this rule accepts.', $request);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Only the URI host is reparsed for the connection. A Host header is sent
|
||||
* verbatim and may carry a port, brackets, and an RFC 6874 zone identifier.
|
||||
*
|
||||
* @throws RequestException
|
||||
*/
|
||||
private static function assertUriHost(
|
||||
string $host,
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request
|
||||
): void {
|
||||
self::assertPrintableAscii($host, 'The request URI host "%s" must contain only printable ASCII characters, because a handler can otherwise connect to a host that differs from the one the request names. An internationalized host name has an A-label form that this rule accepts.', $request);
|
||||
|
||||
if (\strpos($host, '%') !== false) {
|
||||
throw new RequestException(\sprintf('The request URI host "%s" must not contain a percent escape, because a handler decodes it and can then connect to a host that differs from the one the request names.', self::escape($host)), $request);
|
||||
}
|
||||
|
||||
// GuzzleHttp\Psr7\Uri already enforces this predicate, so it only
|
||||
// rejects invalid third-party UriInterface values.
|
||||
if (!Psr7\Rfc3986::isValidHost($host)) {
|
||||
throw new RequestException(\sprintf('The request URI host "%s" must be a valid RFC 3986 host, because a handler reparses the URI and can then connect to a host that differs from the one the request names.', self::escape($host)), $request);
|
||||
}
|
||||
|
||||
// libcurl 8.21.0 drops a trailing dot from inet_aton-style numeric
|
||||
// hosts before connecting, while other readers treat the input as a
|
||||
// name. Test the shape rather than the range so malformed numeric
|
||||
// values fail closed. rtrim() also covers multiple trailing dots if
|
||||
// libcurl later relaxes its current guard. Plain shorthand stays
|
||||
// accepted. HostIdentity uses a broader grammar for cookie matching.
|
||||
//
|
||||
// @see \GuzzleHttp\HostIdentity::canonicalHost()
|
||||
if (\str_ends_with($host, '.') && self::isNumericIpv4Host(\rtrim($host, '.'))) {
|
||||
throw new RequestException(\sprintf('The request URI host "%s" must not be written as one to four decimal, octal or hexadecimal parts followed by one or more trailing dots, because a handler can read that spelling as an IPv4 address and connect to that address while the rest of the process reads a name.', self::escape($host)), $request);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether a host has libcurl's inet_aton-style shape: one to four
|
||||
* decimal, 0-prefixed octal, or 0x-prefixed hexadecimal parts.
|
||||
*
|
||||
* Range and 32-bit overflow checks are deliberately omitted. This may
|
||||
* reject a trailing-dot spelling the transport reads as a name, but avoids
|
||||
* missing one it resolves as an address.
|
||||
*/
|
||||
public static function isNumericIpv4Host(string $host): bool
|
||||
{
|
||||
if ($host === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$parts = \explode('.', $host);
|
||||
|
||||
if (\count($parts) > 4) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($parts as $part) {
|
||||
if (!self::isNumericIpv4Part($part)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static function isNumericIpv4Part(string $part): bool
|
||||
{
|
||||
if ($part === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($part[0] === '0' && isset($part[1]) && ($part[1] === 'x' || $part[1] === 'X')) {
|
||||
return \strlen($part) > 2 && \strspn($part, '0123456789abcdefABCDEF', 2) === \strlen($part) - 2;
|
||||
}
|
||||
|
||||
$digits = $part[0] === '0' ? '01234567' : '0123456789';
|
||||
|
||||
return \strspn($part, $digits) === \strlen($part);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws RequestException
|
||||
*/
|
||||
private static function assertPrintableAscii(
|
||||
string $value,
|
||||
string $message,
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request
|
||||
): void {
|
||||
// Match positively so a PCRE failure rejects.
|
||||
if (\preg_match('/\A[\x21-\x7E]*\z/D', $value) !== 1) {
|
||||
throw new RequestException(\sprintf($message, self::escape($value)), $request);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Escapes non-printable bytes as uppercase \xNN for safe diagnostics.
|
||||
*
|
||||
* Psr7\DiagnosticValue is not used because it preserves valid non-ASCII
|
||||
* UTF-8, including invisible characters rejected here.
|
||||
*/
|
||||
private static function escape(string $value): string
|
||||
{
|
||||
$escaped = '';
|
||||
|
||||
for ($offset = 0, $length = \strlen($value); $offset < $length; ++$offset) {
|
||||
$byte = \ord($value[$offset]);
|
||||
if ($byte >= 0x20 && $byte <= 0x7E) {
|
||||
$escaped .= $value[$offset];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$escaped .= \sprintf('\\x%02X', $byte);
|
||||
}
|
||||
|
||||
return $escaped;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7\StreamWrapper;
|
||||
use GuzzleHttp\Psr7\Utils;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Inflates a gzip or deflate encoded response body as the encoded bytes arrive.
|
||||
*
|
||||
* Unlike the zlib.inflate stream filter, a read returns the bytes decoded so
|
||||
* far instead of waiting to fill the requested length, and invalid compressed
|
||||
* data always fails the read. As with libcurl, data after the compressed
|
||||
* stream, beyond up to 4 bytes after raw deflate data, fails the read that
|
||||
* follows the last decoded byte.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class InflateBodyStream implements StreamInterface
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
private const CHUNK_SIZE = 8192;
|
||||
|
||||
private const INVALID_DATA = 'Unable to decode the response body: invalid gzip or deflate data';
|
||||
|
||||
private const TRAILING_DATA = 'Unable to decode the response body: unexpected data after the compressed stream';
|
||||
|
||||
private ?StreamInterface $stream;
|
||||
|
||||
private bool $deflate;
|
||||
|
||||
/** @var \InflateContext|resource|null */
|
||||
private $context;
|
||||
|
||||
private string $header = '';
|
||||
|
||||
private string $buffer = '';
|
||||
|
||||
private int $offset = 0;
|
||||
|
||||
private int $position = 0;
|
||||
|
||||
private bool $finished = false;
|
||||
|
||||
private int $trailingAllowance = 0;
|
||||
|
||||
private bool $detachable = true;
|
||||
|
||||
private ?\RuntimeException $error = null;
|
||||
|
||||
/**
|
||||
* @param bool $deflate Whether the body is labelled "deflate", which also
|
||||
* accepts raw deflate data like libcurl does.
|
||||
*/
|
||||
public function __construct(StreamInterface $stream, bool $deflate = false)
|
||||
{
|
||||
$this->stream = $stream;
|
||||
$this->deflate = $deflate;
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->getContents();
|
||||
}
|
||||
|
||||
public function getContents(): string
|
||||
{
|
||||
return Utils::copyToString($this);
|
||||
}
|
||||
|
||||
public function close(): void
|
||||
{
|
||||
$stream = $this->stream;
|
||||
$this->release();
|
||||
|
||||
if ($stream !== null) {
|
||||
$stream->close();
|
||||
}
|
||||
}
|
||||
|
||||
public function detach()
|
||||
{
|
||||
if ($this->stream === null || !$this->detachable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Hand the decoder over to a resource that keeps yielding decoded
|
||||
// bytes. That decoder cannot be detached again, so casting the resource
|
||||
// to a descriptor fails instead of recursing.
|
||||
$stream = clone $this;
|
||||
$stream->detachable = false;
|
||||
$this->release();
|
||||
|
||||
return StreamWrapper::getResource($stream);
|
||||
}
|
||||
|
||||
public function getSize(): ?int
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function tell(): int
|
||||
{
|
||||
$this->attached();
|
||||
|
||||
return $this->position;
|
||||
}
|
||||
|
||||
public function eof(): bool
|
||||
{
|
||||
$stream = $this->attached();
|
||||
|
||||
// A failed body never ends, so resource readers see the failure
|
||||
// instead of a clean end of the stream.
|
||||
return $this->error === null && $this->offset === \strlen($this->buffer) && $stream->eof();
|
||||
}
|
||||
|
||||
public function isSeekable(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function seek(int $offset, int $whence = \SEEK_SET): void
|
||||
{
|
||||
throw new \RuntimeException('Stream is not seekable');
|
||||
}
|
||||
|
||||
public function rewind(): void
|
||||
{
|
||||
$this->seek(0);
|
||||
}
|
||||
|
||||
public function isWritable(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function write(string $string): int
|
||||
{
|
||||
throw new \RuntimeException('Cannot write to a non-writable stream');
|
||||
}
|
||||
|
||||
public function isReadable(): bool
|
||||
{
|
||||
return $this->stream !== null && $this->stream->isReadable();
|
||||
}
|
||||
|
||||
public function read(int $length): string
|
||||
{
|
||||
$stream = $this->attached();
|
||||
|
||||
if ($length < 0) {
|
||||
throw new \RuntimeException('Length parameter cannot be negative');
|
||||
}
|
||||
|
||||
if ($length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
while ($this->offset === \strlen($this->buffer)) {
|
||||
if ($this->error !== null) {
|
||||
throw $this->error;
|
||||
}
|
||||
|
||||
$encoded = $stream->read(self::CHUNK_SIZE);
|
||||
if ($encoded === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($this->finished) {
|
||||
if ($this->allowTrailing(\strlen($encoded))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
throw $this->fail(self::TRAILING_DATA);
|
||||
}
|
||||
|
||||
$this->buffer = $this->inflate($encoded);
|
||||
$this->offset = 0;
|
||||
}
|
||||
|
||||
// Slice by offset, since a single inflate_add() call can return
|
||||
// megabytes of highly compressible data.
|
||||
$data = (string) \substr($this->buffer, $this->offset, $length);
|
||||
$this->offset += \strlen($data);
|
||||
$this->position = TransferByteCounter::add(
|
||||
$this->position,
|
||||
\strlen($data),
|
||||
'Response body exceeds the maximum integer size supported on this platform'
|
||||
);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getMetadata(?string $key = null)
|
||||
{
|
||||
if ($this->stream === null) {
|
||||
return $key === null ? [] : null;
|
||||
}
|
||||
|
||||
// A decoding failure is not a timeout, even when Windows leaves the
|
||||
// transport's timed_out flag set after a read drains PHP's buffer.
|
||||
if ($key === 'timed_out' && $this->error !== null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$metadata = $this->stream->getMetadata($key);
|
||||
if ($key === null && $this->error !== null && \is_array($metadata)) {
|
||||
$metadata['timed_out'] = false;
|
||||
}
|
||||
|
||||
return $metadata;
|
||||
}
|
||||
|
||||
private function inflate(string $encoded, ?int $encoding = null): string
|
||||
{
|
||||
$retry = false;
|
||||
if ($this->context === null) {
|
||||
$this->header .= $encoded;
|
||||
if (\strlen($this->header) < 2) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$encoded = $this->header;
|
||||
$this->header = '';
|
||||
|
||||
if (!\function_exists('inflate_init')) {
|
||||
throw $this->fail('Unable to decode the response body: the zlib extension is not loaded');
|
||||
}
|
||||
|
||||
// inflate_init() has no automatic header detection, so pick the
|
||||
// format the way zlib does for the window bits 15 + 32 that the
|
||||
// zlib.inflate filter is given.
|
||||
$encoding = $encoding ?? (\strncmp($encoded, "\x1f\x8b", 2) === 0 ? \ZLIB_ENCODING_GZIP : \ZLIB_ENCODING_DEFLATE);
|
||||
$retry = $this->deflate && $encoding === \ZLIB_ENCODING_DEFLATE;
|
||||
$context = \inflate_init($encoding);
|
||||
if ($context === false) {
|
||||
throw $this->fail(self::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->context = $context;
|
||||
}
|
||||
|
||||
$readBefore = \inflate_get_read_len($this->context);
|
||||
|
||||
// Application error handlers also see @-suppressed warnings, so keep
|
||||
// the warning inflate_add() emits before returning false from them.
|
||||
\set_error_handler(static function (): bool {
|
||||
return true;
|
||||
});
|
||||
|
||||
try {
|
||||
$decoded = \inflate_add($this->context, $encoded);
|
||||
} finally {
|
||||
\restore_error_handler();
|
||||
}
|
||||
|
||||
if ($decoded === false) {
|
||||
// Like libcurl, decode deflate data that zlib rejects in the first
|
||||
// call as raw deflate, which may be followed by up to 4 unknown
|
||||
// bytes such as the checksum of a zlib stream missing its header.
|
||||
if ($retry) {
|
||||
$this->context = null;
|
||||
$this->trailingAllowance = 4;
|
||||
|
||||
return $this->inflate($encoded, \ZLIB_ENCODING_RAW);
|
||||
}
|
||||
|
||||
throw $this->fail(self::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->finished = \inflate_get_status($this->context) === \ZLIB_STREAM_END;
|
||||
if ($this->finished) {
|
||||
$consumed = \inflate_get_read_len($this->context) - $readBefore;
|
||||
if ($consumed < 0) {
|
||||
// zlib counts input in an unsigned long, which wraps at 4 GiB
|
||||
// on Windows and 32-bit builds.
|
||||
$consumed += 0x100000000;
|
||||
}
|
||||
|
||||
if (!$this->allowTrailing(\strlen($encoded) - (int) $consumed)) {
|
||||
// Throw only after the bytes decoded so far have been read.
|
||||
$this->fail(self::TRAILING_DATA);
|
||||
}
|
||||
}
|
||||
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
private function allowTrailing(int $length): bool
|
||||
{
|
||||
if ($length > $this->trailingAllowance) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->trailingAllowance -= $length;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function attached(): StreamInterface
|
||||
{
|
||||
if ($this->stream === null) {
|
||||
throw new \RuntimeException('Stream is detached');
|
||||
}
|
||||
|
||||
return $this->stream;
|
||||
}
|
||||
|
||||
private function release(): void
|
||||
{
|
||||
$this->stream = null;
|
||||
$this->context = null;
|
||||
$this->buffer = '';
|
||||
$this->offset = 0;
|
||||
}
|
||||
|
||||
private function fail(string $message): \RuntimeException
|
||||
{
|
||||
return $this->error = new \RuntimeException($message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\Exception\ResponseException;
|
||||
use GuzzleHttp\HandlerStack;
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Promise as P;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\TransferStats;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Handler that returns responses or rejection reasons from a queue.
|
||||
*/
|
||||
final class MockHandler implements \Countable
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* @var list<ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>|callable(RequestInterface, array<array-key, mixed>): (ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>)>
|
||||
*/
|
||||
private array $queue = [];
|
||||
|
||||
private ?RequestInterface $lastRequest = null;
|
||||
|
||||
/**
|
||||
* @var array<array-key, mixed>
|
||||
*/
|
||||
private array $lastOptions = [];
|
||||
|
||||
/**
|
||||
* @var (callable(ResponseInterface|null): mixed)|null
|
||||
*/
|
||||
private $onFulfilled;
|
||||
|
||||
/**
|
||||
* @var (callable(mixed): mixed)|null
|
||||
*/
|
||||
private $onRejected;
|
||||
|
||||
/**
|
||||
* Creates a new MockHandler that uses the default handler stack list of
|
||||
* middlewares.
|
||||
*
|
||||
* @param array<array-key, ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>|callable(RequestInterface, array<array-key, mixed>): (ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>)>|null $queue Array of responses, promises, callables, or throwables.
|
||||
* @param (callable(ResponseInterface|null): mixed)|null $onFulfilled Callback to invoke when the return value is fulfilled.
|
||||
* @param (callable(mixed): mixed)|null $onRejected Callback to invoke when the return value is rejected.
|
||||
*
|
||||
* @return HandlerStack<callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>>
|
||||
*/
|
||||
public static function createWithMiddleware(
|
||||
#[\SensitiveParameter]
|
||||
?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, throwables, callables, or promises.
|
||||
*
|
||||
* @param array<array-key, ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>|callable(RequestInterface, array<array-key, mixed>): (ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>)>|null $queue The parameters to be passed to the append function, as an indexed array.
|
||||
* @param (callable(ResponseInterface|null): mixed)|null $onFulfilled Callback to invoke when the return value is fulfilled.
|
||||
* @param (callable(mixed): mixed)|null $onRejected Callback to invoke when the return value is rejected.
|
||||
*/
|
||||
public function __construct(
|
||||
#[\SensitiveParameter]
|
||||
?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));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
public function __invoke(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
): PromiseInterface {
|
||||
if (!$this->queue) {
|
||||
// Test-setup error (more requests made than responses queued);
|
||||
// intentionally a bare SPL exception, not a GuzzleException.
|
||||
throw new \OutOfBoundsException('Mock queue is empty');
|
||||
}
|
||||
|
||||
if (isset($options['delay']) && \is_numeric($options['delay'])) {
|
||||
Clock::sleep((int) ($options['delay'] * 1000));
|
||||
}
|
||||
|
||||
if (isset($options['on_stats']) && !\is_callable($options['on_stats'])) {
|
||||
throw new InvalidArgumentException('on_stats must be callable');
|
||||
}
|
||||
|
||||
$this->lastRequest = $request;
|
||||
$this->lastOptions = $options;
|
||||
$response = \array_shift($this->queue);
|
||||
$onHeaders = null;
|
||||
$onHeadersResponse = null;
|
||||
|
||||
if (isset($options['on_headers'])) {
|
||||
if (!\is_callable($options['on_headers'])) {
|
||||
throw new InvalidArgumentException('on_headers must be callable');
|
||||
}
|
||||
|
||||
$onHeaders = $options['on_headers'];
|
||||
}
|
||||
|
||||
if (\is_callable($response)) {
|
||||
$response = $response($request, $options);
|
||||
}
|
||||
|
||||
$response = $response instanceof \Throwable
|
||||
? P\Create::rejectionFor($response)
|
||||
: P\Create::promiseFor($response);
|
||||
|
||||
if (\is_callable($onHeaders)) {
|
||||
$response = $response->then(
|
||||
static function (
|
||||
#[\SensitiveParameter]
|
||||
$value
|
||||
) use ($onHeaders, $request, &$onHeadersResponse) {
|
||||
if (!$value instanceof ResponseInterface) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
try {
|
||||
$onHeaders($value, $request);
|
||||
} catch (\Throwable $e) {
|
||||
$msg = 'An error was encountered during the on_headers event';
|
||||
$onHeadersResponse = $value;
|
||||
|
||||
throw new ResponseException($msg, $request, $value, $e);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
$promise = $response->then(
|
||||
function (
|
||||
#[\SensitiveParameter]
|
||||
$value
|
||||
) use ($request, $options): ?ResponseInterface {
|
||||
/** @var ResponseInterface|null $value */
|
||||
$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 (
|
||||
#[\SensitiveParameter]
|
||||
$reason
|
||||
) use ($request, $options, &$onHeadersResponse): PromiseInterface {
|
||||
$this->invokeStats($request, $options, $onHeadersResponse, $reason);
|
||||
if ($this->onRejected) {
|
||||
($this->onRejected)($reason);
|
||||
}
|
||||
|
||||
return P\Create::rejectionFor($reason);
|
||||
}
|
||||
);
|
||||
|
||||
/** @var PromiseInterface<ResponseInterface, mixed> $promise */
|
||||
return $promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds one or more variadic requests, exceptions, callables, or promises
|
||||
* to the queue.
|
||||
*
|
||||
* @param mixed ...$values Responses, promises, throwables, or request-aware callables.
|
||||
*/
|
||||
public function append(
|
||||
#[\SensitiveParameter]
|
||||
...$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 '.\get_debug_type($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(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
#[\SensitiveParameter]
|
||||
?ResponseInterface $response = null,
|
||||
#[\SensitiveParameter]
|
||||
$reason = null
|
||||
): void {
|
||||
if (isset($options['on_stats'])) {
|
||||
$transferTime = $options['transfer_time'] ?? 0.0;
|
||||
if (!\is_int($transferTime) && !\is_float($transferTime) && (!\is_string($transferTime) || !\is_numeric($transferTime))) {
|
||||
throw new InvalidArgumentException('transfer_time must be a number of seconds');
|
||||
}
|
||||
|
||||
$stats = new TransferStats($request, $response, (float) $transferTime, $reason);
|
||||
($options['on_stats'])($stats);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class Protocols
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $protocols
|
||||
*
|
||||
* @return string[]
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
public static function normalize($protocols): array
|
||||
{
|
||||
if (!\is_array($protocols) || $protocols === []) {
|
||||
throw new InvalidArgumentException('protocols must be a non-empty array of "http" and/or "https"');
|
||||
}
|
||||
|
||||
$normalized = [];
|
||||
|
||||
foreach ($protocols as $protocol) {
|
||||
if (!\is_string($protocol)) {
|
||||
throw new InvalidArgumentException('protocols must contain only strings');
|
||||
}
|
||||
|
||||
if ($protocol !== 'http' && $protocol !== 'https') {
|
||||
throw new InvalidArgumentException('protocols may only contain "http" and "https"');
|
||||
}
|
||||
|
||||
$normalized[$protocol] = true;
|
||||
}
|
||||
|
||||
return \array_keys($normalized);
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\RequestOptions;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Provides basic proxies for handlers.
|
||||
*/
|
||||
final class Proxy
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends synchronous requests to a specific handler while sending all other
|
||||
* requests to another handler.
|
||||
*
|
||||
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $default Handler used for normal responses
|
||||
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $sync Handler used for synchronous responses.
|
||||
*
|
||||
* @return callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> Returns the composed handler.
|
||||
*/
|
||||
public static function wrapSync(callable $default, callable $sync): callable
|
||||
{
|
||||
return static function (
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
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<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $default Handler used for non-streaming responses
|
||||
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $streaming Handler used for streaming responses
|
||||
*
|
||||
* @return callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> Returns the composed handler.
|
||||
*/
|
||||
public static function wrapStreaming(callable $default, callable $streaming): callable
|
||||
{
|
||||
return static function (
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
) use ($default, $streaming): PromiseInterface {
|
||||
return empty($options['stream']) ? $default($request, $options) : $streaming($request, $options);
|
||||
};
|
||||
}
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\ProxyOptions;
|
||||
use GuzzleHttp\ProxySelection;
|
||||
use GuzzleHttp\Psr7;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
/**
|
||||
* Resolves proxy configuration from the process environment with the same
|
||||
* semantics libcurl applies, shared by the built-in handlers: the cURL
|
||||
* handlers pin CURLOPT_PROXY and CURLOPT_NOPROXY explicitly so libcurl never
|
||||
* reads the environment itself, and the stream handler resolves the same way.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class ProxyEnv
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the proxy selection for a request, falling back to the proxy
|
||||
* environment variables when the proxy request option makes no decision.
|
||||
*
|
||||
* The environment no_proxy list is tokenized the way libcurl tokenizes
|
||||
* it and matched here with the same rules as the proxy option's "no"
|
||||
* list, so behavior does not depend on the installed libcurl's matcher.
|
||||
*
|
||||
* @param mixed $proxyOption
|
||||
*/
|
||||
public static function resolveProxySelection(
|
||||
UriInterface $uri,
|
||||
#[\SensitiveParameter]
|
||||
$proxyOption
|
||||
): ProxySelection {
|
||||
$selection = ProxyOptions::resolve($uri, $proxyOption);
|
||||
|
||||
// Any option decision (proxy, bypassed, or disabled) is final; only
|
||||
// a none() selection leaves room for the environment.
|
||||
if ($selection->hasProxy() || $selection->shouldDisableProxy()) {
|
||||
return $selection;
|
||||
}
|
||||
|
||||
$envProxy = self::getProxyForScheme($uri->getScheme());
|
||||
if ($envProxy === null) {
|
||||
return $selection;
|
||||
}
|
||||
|
||||
$noProxy = self::getNoProxy();
|
||||
if ($noProxy !== null && ProxyOptions::isUriInNoProxy($uri, self::splitNoProxy($noProxy))) {
|
||||
return ProxySelection::bypassed();
|
||||
}
|
||||
|
||||
// $envProxy is never '' (empty env values are treated as unset).
|
||||
return ProxySelection::proxy($envProxy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the proxy to use for the given request scheme.
|
||||
*
|
||||
* The lookup mirrors libcurl for the http and https schemes the handlers
|
||||
* accept: the lowercase scheme-specific variable first, its uppercase
|
||||
* variant next (except for "http", where uppercase HTTP_PROXY is never
|
||||
* read), then all_proxy/ALL_PROXY.
|
||||
*
|
||||
* @return string|null The proxy to use; null when the environment
|
||||
* configures none.
|
||||
*/
|
||||
public static function getProxyForScheme(string $scheme): ?string
|
||||
{
|
||||
$scheme = Psr7\Utils::asciiToLower($scheme);
|
||||
$candidates = [$scheme.'_proxy'];
|
||||
if ($scheme !== 'http') {
|
||||
// Uppercase HTTP_PROXY is deliberately never consulted: a CGI
|
||||
// request header "Proxy:" becomes HTTP_PROXY in the environment.
|
||||
// See https://httpoxy.org for more information.
|
||||
$candidates[] = Psr7\Utils::asciiToUpper($scheme).'_PROXY';
|
||||
}
|
||||
$candidates[] = 'all_proxy';
|
||||
$candidates[] = 'ALL_PROXY';
|
||||
|
||||
foreach ($candidates as $name) {
|
||||
$value = self::getenv($name);
|
||||
if ($value !== null) {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null The no-proxy list; null when nothing is set.
|
||||
*/
|
||||
public static function getNoProxy(): ?string
|
||||
{
|
||||
foreach (['no_proxy', 'NO_PROXY'] as $name) {
|
||||
$value = self::getenv($name);
|
||||
if ($value !== null) {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a no_proxy environment value into matchable entries.
|
||||
*
|
||||
* Entries may be separated by commas or blanks, the way libcurl tokenizes
|
||||
* the value.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function splitNoProxy(string $noProxy): array
|
||||
{
|
||||
$entries = [];
|
||||
|
||||
$split = \preg_split('/[\s,]+/', $noProxy);
|
||||
|
||||
if ($split === false) {
|
||||
throw new \RuntimeException('Unable to split the no_proxy value: '.\preg_last_error_msg());
|
||||
}
|
||||
|
||||
foreach ($split as $entry) {
|
||||
if ($entry !== '') {
|
||||
$entries[] = $entry;
|
||||
}
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}
|
||||
|
||||
private static function getenv(string $name): ?string
|
||||
{
|
||||
// Windows environment variables are case-insensitive, so the
|
||||
// lowercase-only httpoxy defence does not hold there. Outside the
|
||||
// CLI SAPI on Windows, environment proxies are not resolved at all
|
||||
// (a safe-side divergence from libcurl).
|
||||
if (\PHP_OS_FAMILY === 'Windows' && \PHP_SAPI !== 'cli') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// local_only: the OS environment and putenv() only - the same
|
||||
// environ(7) libcurl reads. SAPI request environments such as
|
||||
// fastcgi_param or SetEnv are deliberately excluded.
|
||||
$value = \getenv($name, true);
|
||||
|
||||
// libcurl's GetEnv (lib/getenv.c) treats variables set to an empty
|
||||
// string as unset on every version, so the lookup falls through to
|
||||
// the next candidate.
|
||||
return $value === false || $value === '' ? null : $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7;
|
||||
use GuzzleHttp\Psr7\Exception\TimeoutException;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
* Validates and normalizes request framing before a handler performs I/O.
|
||||
*
|
||||
* Body size describes the bytes available under handler rewind semantics.
|
||||
* Content-Length is the selected transport boundary and may remain unknown.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class RequestFraming
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
public RequestInterface $request;
|
||||
|
||||
/**
|
||||
* Number of bytes available after applying handler rewind semantics, if
|
||||
* known.
|
||||
*/
|
||||
public ?int $bodySize;
|
||||
|
||||
/** Canonical Content-Length boundary selected for transport, if any. */
|
||||
public ?int $contentLength;
|
||||
|
||||
private function __construct(RequestInterface $request, ?int $bodySize, ?int $contentLength)
|
||||
{
|
||||
$this->request = $request;
|
||||
$this->bodySize = $bodySize;
|
||||
$this->contentLength = $contentLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finalizes request framing for a handler dispatch.
|
||||
*
|
||||
* When $sendBody is false, body-dependent validation and size probing are
|
||||
* skipped. Content-Length is still canonicalized and Transfer-Encoding is
|
||||
* removed.
|
||||
*
|
||||
* @throws RequestException when framing or body metadata is unsafe
|
||||
*/
|
||||
public static function analyze(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
bool $sendBody = true
|
||||
): self {
|
||||
try {
|
||||
$length = HeaderProcessor::parseContentLength($request->getHeader('Content-Length'));
|
||||
} catch (\RuntimeException $e) {
|
||||
throw new RequestException('Invalid Content-Length request header: '.$e->getMessage(), $request, 0, $e);
|
||||
}
|
||||
|
||||
try {
|
||||
HeaderProcessor::assertContentLengthWithinPlatformLimit($length);
|
||||
} catch (\OverflowException $e) {
|
||||
throw new RequestException($e->getMessage(), $request, 0, $e);
|
||||
}
|
||||
|
||||
$contentLength = HeaderProcessor::contentLengthToInt($length);
|
||||
if ($length !== null) {
|
||||
$request = $request->withHeader('Content-Length', $length);
|
||||
}
|
||||
|
||||
if (!$sendBody) {
|
||||
return new self($request->withoutHeader('Transfer-Encoding'), null, $contentLength);
|
||||
}
|
||||
|
||||
$transferEncoding = $request->getHeader('Transfer-Encoding');
|
||||
if ($length !== null && $transferEncoding !== []) {
|
||||
throw new RequestException(
|
||||
'A request must not contain both Content-Length and Transfer-Encoding',
|
||||
$request
|
||||
);
|
||||
}
|
||||
|
||||
if ($transferEncoding !== []) {
|
||||
$tokens = [];
|
||||
foreach ($transferEncoding as $value) {
|
||||
foreach (\explode(',', $value) as $part) {
|
||||
$tokens[] = \trim($part, " \t");
|
||||
}
|
||||
}
|
||||
|
||||
if (\count($tokens) !== 1 || !Psr7\Utils::caselessEquals($tokens[0], 'chunked') || $request->getProtocolVersion() !== '1.1') {
|
||||
throw new RequestException('Unsupported Transfer-Encoding request header', $request);
|
||||
}
|
||||
}
|
||||
|
||||
$bodySize = self::bodySize($request);
|
||||
if ($bodySize !== null && $contentLength !== null && $bodySize !== $contentLength) {
|
||||
throw new RequestException('Content-Length does not match the request body size', $request);
|
||||
}
|
||||
|
||||
if ($bodySize === null && $contentLength === null && $request->getProtocolVersion() === '1.0') {
|
||||
throw new RequestException('An unknown-size HTTP/1.0 request body requires Content-Length', $request);
|
||||
}
|
||||
|
||||
if ($length === null && $bodySize !== null && ($bodySize > 0 || \in_array($request->getMethod(), ['PUT', 'POST'], true))) {
|
||||
$contentLength = $bodySize;
|
||||
$request = $request->withHeader('Content-Length', (string) $bodySize);
|
||||
}
|
||||
|
||||
return new self($request->withoutHeader('Transfer-Encoding'), $bodySize, $contentLength);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of bytes available for dispatch, or null when unknown.
|
||||
*
|
||||
* Seekable bodies use their total size because handlers rewind them.
|
||||
* Positioned non-seekable bodies use the total size minus their current
|
||||
* position.
|
||||
*
|
||||
* @throws RequestException when body metadata cannot be read safely
|
||||
*/
|
||||
public static function bodySize(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request
|
||||
): ?int {
|
||||
$body = $request->getBody();
|
||||
|
||||
try {
|
||||
$size = $body->getSize();
|
||||
if ($size === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($size < 0) {
|
||||
throw new \RuntimeException('Request body size must not be negative');
|
||||
}
|
||||
|
||||
$seekable = $body->isSeekable();
|
||||
} catch (\Exception $e) {
|
||||
throw self::bodyException(
|
||||
$request,
|
||||
$e,
|
||||
'Timed out while determining the request body size',
|
||||
'Failed to determine the request body size'
|
||||
);
|
||||
}
|
||||
|
||||
if ($seekable) {
|
||||
return $size;
|
||||
}
|
||||
|
||||
try {
|
||||
$position = $body->tell();
|
||||
} catch (\RuntimeException $e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($position < 0 || $position > $size) {
|
||||
throw new RequestException('The request body position is outside the stream size', $request);
|
||||
}
|
||||
|
||||
return $size - $position;
|
||||
}
|
||||
|
||||
/**
|
||||
* Materializes the body, stopping at the selected Content-Length when
|
||||
* present.
|
||||
*
|
||||
* @throws RequestException when the body cannot be fully rewound or read
|
||||
*/
|
||||
public function materialize(): string
|
||||
{
|
||||
$body = $this->request->getBody();
|
||||
|
||||
if ($this->contentLength === null) {
|
||||
try {
|
||||
return (string) $body;
|
||||
} catch (\Exception $e) {
|
||||
throw self::bodyException(
|
||||
$this->request,
|
||||
$e,
|
||||
'Timed out while reading the request body',
|
||||
'Failed to read the request body'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->contentLength === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
try {
|
||||
if ($body->isSeekable()) {
|
||||
$body->rewind();
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
throw self::bodyException(
|
||||
$this->request,
|
||||
$e,
|
||||
'Timed out while rewinding the request body',
|
||||
'Failed to rewind the request body'
|
||||
);
|
||||
}
|
||||
|
||||
$contents = '';
|
||||
$remaining = $this->contentLength;
|
||||
while ($remaining > 0) {
|
||||
$limit = \min(8192, $remaining);
|
||||
|
||||
try {
|
||||
$chunk = $body->read($limit);
|
||||
} catch (\Exception $e) {
|
||||
throw self::bodyException(
|
||||
$this->request,
|
||||
$e,
|
||||
'Timed out while reading the request body',
|
||||
'Failed to read the request body'
|
||||
);
|
||||
}
|
||||
|
||||
if ($chunk === '') {
|
||||
throw new RequestException(
|
||||
'Request body ended before the declared Content-Length was reached',
|
||||
$this->request
|
||||
);
|
||||
}
|
||||
|
||||
if (\strlen($chunk) > $limit) {
|
||||
throw new RequestException('Request body stream returned more bytes than requested', $this->request);
|
||||
}
|
||||
|
||||
$contents .= $chunk;
|
||||
$remaining -= \strlen($chunk);
|
||||
}
|
||||
|
||||
return $contents;
|
||||
}
|
||||
|
||||
private static function bodyException(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
\Exception $exception,
|
||||
string $timeoutMessage,
|
||||
string $fallbackMessage
|
||||
): RequestException {
|
||||
$message = $exception instanceof TimeoutException
|
||||
? $timeoutMessage
|
||||
: ($exception->getMessage() !== '' ? $exception->getMessage() : $fallbackMessage);
|
||||
|
||||
return new RequestException($message, $request, 0, $exception);
|
||||
}
|
||||
}
|
||||
+2073
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user