Initial commit

This commit is contained in:
Porawit Dongwang
2026-09-16 23:20:08 +07:00
commit 0041668dbb
32577 changed files with 3687927 additions and 0 deletions
@@ -0,0 +1,22 @@
<?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;
}
}
throw new RuntimeException($err);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitc448faa2bb4d17063fdd5b5dff1f2609::getLoader();
@@ -0,0 +1,28 @@
name: CI
on:
push:
pull_request:
jobs:
tests:
name: Tests on PHP ${{ matrix.php }} ${{ matrix.dependencies }}
runs-on: ubuntu-20.04
container:
image: shivammathur/node:2004
strategy:
matrix:
php: ['5.6', '7.0', '7.1', '7.2', '7.3', '7.4']
dependencies: ['', '--prefer-lowest --prefer-stable']
steps:
- name: Checkout
uses: actions/checkout@v2.3.4
- uses: shivammathur/setup-php@2.9.0
with:
php-version: ${{ matrix.php }}
- name: Install dependencies
run: composer update --no-interaction --prefer-dist ${{ matrix.dependencies }}
- name: Configure PHPUnit problem matchers
run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
- name: Run tests
run: ./vendor/bin/phpunit
@@ -0,0 +1,6 @@
.DS_Store
/composer.lock
/vendor/
tests-report/
/.idea/
.php_cs.cache
@@ -0,0 +1,57 @@
<?php
/**
* @source https://gist.github.com/codfish/c77d348820c1c6b4ebe4a66dc2291c74
*
* Rules we follow are from PSR-2 as well as the rectified PSR-2 guide.
*
* - https://github.com/FriendsOfPHP/PHP-CS-Fixer
* - https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
* - https://github.com/php-fig-rectified/fig-rectified-standards/blob/master/PSR-2-R-coding-style-guide-additions.md
*
* If something isn't addressed in either of those, some other common community rules are
* used that might not be addressed explicitly in PSR-2 in order to improve code quality
* (so that devs don't need to comment on them in Code Reviews).
*
* For instance: removing trailing white space, removing extra line breaks where
* they're not needed (back to back, beginning or end of function/class, etc.),
* adding trailing commas in the last line of an array, etc.
*/
$finder = PhpCsFixer\Finder::create()
->exclude('node_modules')
->exclude('vendor')
->in(__DIR__);
return PhpCsFixer\Config::create()
->setRules([
'@PSR2' => true,
'array_syntax' => [ 'syntax' => 'long' ],
'binary_operator_spaces' => [ 'align_equals' => false, 'align_double_arrow' => false ],
'cast_spaces' => true,
'combine_consecutive_unsets' => true,
'concat_space' => [ 'spacing' => 'one' ],
'linebreak_after_opening_tag' => true,
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
'no_extra_consecutive_blank_lines' => true,
'no_trailing_comma_in_singleline_array' => true,
'no_whitespace_in_blank_line' => true,
'no_spaces_around_offset' => true,
'no_unused_imports' => true,
'no_useless_else' => true,
'no_useless_return' => true,
'no_whitespace_before_comma_in_array' => true,
'normalize_index_brace' => true,
'phpdoc_indent' => true,
'phpdoc_to_comment' => true,
'phpdoc_trim' => true,
'single_quote' => true,
'ternary_to_null_coalescing' => true,
'trailing_comma_in_multiline_array' => true,
'trim_array_spaces' => true,
'method_argument_space' => ['ensure_fully_multiline' => false],
'no_break_comment' => false,
'blank_line_before_statement' => true,
])
->setFinder($finder);
@@ -0,0 +1,89 @@
# Changelog for `bramus/router`
## 1.next ????.??.??
## 1.6.1 2021.11.19
- Fixed: Fix `trigger404()` to work without custom 404 handler _([#169](https://github.com/bramus/router/pull/169))_ _(@mjoris)_
## 1.6 2021.07.23
- Added: Ability to set multiple 404s, depending on the route prefix _(@uvulpos)_
## 1.5 2020.10.26
- Fixed: Correctly invoke static/non-static class methods _(@bramus)_
- Fixed: Fix PHP 5.3 support _(@cikal)_
- Fixed: Fix arguments in demo _(@khromov)_
- Fixed: Fix #72 _(@acicali)_
- Added: PHP 7.4 support _(@ShaneMcC)_
- Added: Ability to externally trigger a 404 _(@PlanetTheCloud)_
## 1.4.2 2019.02.27
- Fixed: Play nice with emoji in base paths ([ref](https://github.com/bramus/router/commit/8692190532db269882f83d27cea95d4f22a50da2#commitcomment-32492636), [ref](https://github.com/bramus/router/commit/492444d84fde7e54551ff0bf8ca79ff9292094da#commitcomment-32496820)) _(@bramus)_
- Added: Extra Tests _(@bramus)_
## 1.4.1 2019.02.26
- Fixed: Fix bug where Cyrillic charges and Emojis in placeholder were urlencoded (see [#80](https://github.com/bramus/router/issues/80#issuecomment-467154490)) _(@bramus)_
- Fixed: Make `bramus/router` play nice with situations where the entry script and entry URLs are not coupled (see [#82](https://github.com/bramus/router/issues/82#issuecomment-466956078)) _(@bramus)_
- Changed: Changed visibility of `getBasePath` and `getCurrentUri` to being `public` _(@bramus)_
## 1.4 2019.02.18
- Added: Support for Cyrillic chars and Emoji in placeholder values and placeholder names (see [#80](https://github.com/bramus/router/issues/80)) _(@bramus)_
- Added: `composer test` shorthand _(@bramus)_
- Added: Changelog _(@bramus)_
- Changed: Documentation Improvements _(@bramus)_
## 1.3.1 2017.12.22
- Added: Extra Tests _(@bramus)_
- Changed: Documentation Improvements _(@artyuum)_
## 1.3 2017.12.21
- Added: Support `Class@method` callbacks in `set404()` _(@bramus)_
- Changed: Refactored callback invocation _(@bramus)_
- Changed: Documentation Improvements _(@artyuum)_
## 1.2.1 2017.10.06
- Changed: Documentation Improvements _(@bramus)_
## 1.2 2017.10.06
- Added: Support route matching using _“placeholders”_ (e.g. curly braces) _(@ovflowd)_
- Added: Default Namespace Capability using `setNamespace()`, for use with `Class@Method` calls _(@ovflowd)_
- Added: Extra Tests _(@bramus)_
- Bugfix: Make sure callable are actually callable _(@ovflowd)_
- Demo: Added a multilang demo _(@bramus)_
- Changed: Documentation Improvements _(@lai0n)_
## 1.1 2016.05.26
- Added: Return `true` if a route was handled, `false` otherwise _(@tleb)_
- Added: `getBasePath()` _(@ovflowd)_
- Added: Support `Class@Method` calls _(@ovflowd)_
- Changed: Tweak a few method signaturs so that they're protected _(@tleb)_
- Changed: Documentation Improvements _(@tleb)_
## 1.0 2015.02.04
- First 1.x release
## _(Unversioned Releases)_ 2013.04.08 - 2015.02.04
- Initial release with suppport for:
- Static and Dynamic Route Handling
- Shorthands: `get()`, `post()`, `put()`, `delete()`, and `options()`
- Before Route Middlewares / Before Route Middlewares: `before()`
- After Router Middlewares / Run Callback
- Added: Optional Route Patterns
- Added: Subrouting (mount callables onto a subroute/prefix)
- Added: `patch()` shorthand
- Added: Support for `X-HTTP-Method-Override` header
- Bugfix: Use the HTTP version as found in `['SERVER_PROTOCOL']`
- Bugfix: Nested Subpatterns / Multiple Matching _(@jbleuzen)_
@@ -0,0 +1,19 @@
Copyright (c) 2013 Bram(us) Van Damme - http://www.bram.us/
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,472 @@
# bramus/router
[![Build Status](https://github.com/bramus/router/workflows/CI/badge.svg)](https://github.com/bramus/router/actions) [![Source](http://img.shields.io/badge/source-bramus/router-blue.svg?style=flat-square)](https://github.com/bramus/router) [![Version](https://img.shields.io/packagist/v/bramus/router.svg?style=flat-square)](https://packagist.org/packages/bramus/router) [![Downloads](https://img.shields.io/packagist/dt/bramus/router.svg?style=flat-square)](https://packagist.org/packages/bramus/router/stats) [![License](https://img.shields.io/packagist/l/bramus/router.svg?style=flat-square)](https://github.com/bramus/router/blob/master/LICENSE)
A lightweight and simple object oriented PHP Router.
Built by Bram(us) Van Damme _([https://www.bram.us](https://www.bram.us))_ and [Contributors](https://github.com/bramus/router/graphs/contributors)
## Features
- Supports `GET`, `POST`, `PUT`, `DELETE`, `OPTIONS`, `PATCH` and `HEAD` request methods
- [Routing shorthands such as `get()`, `post()`, `put()`, …](#routing-shorthands)
- [Static Route Patterns](#route-patterns)
- Dynamic Route Patterns: [Dynamic PCRE-based Route Patterns](#dynamic-pcre-based-route-patterns) or [Dynamic Placeholder-based Route Patterns](#dynamic-placeholder-based-route-patterns)
- [Optional Route Subpatterns](#optional-route-subpatterns)
- [Supports `X-HTTP-Method-Override` header](#overriding-the-request-method)
- [Subrouting / Mounting Routes](#subrouting--mounting-routes)
- [Allowance of `Class@Method` calls](#classmethod-calls)
- [Custom 404 handling](#custom-404)
- [Before Route Middlewares](#before-route-middlewares)
- [Before Router Middlewares / Before App Middlewares](#before-router-middlewares)
- [After Router Middleware / After App Middleware (Finish Callback)](#after-router-middleware--run-callback)
- [Works fine in subfolders](#subfolder-support)
## Prerequisites/Requirements
- PHP 5.3 or greater
- [URL Rewriting](https://gist.github.com/bramus/5332525)
## Installation
Installation is possible using Composer
```
composer require bramus/router ~1.6
```
## Demo
A demo is included in the `demo` subfolder. Serve it using your favorite web server, or using PHP 5.4+'s built-in server by executing `php -S localhost:8080` on the shell. A `.htaccess` for use with Apache is included.
Additionally a demo of a mutilingual router is also included. This can be found in the `demo-multilang` subfolder and can be ran in the same manner as the normal demo.
## Usage
Create an instance of `\Bramus\Router\Router`, define some routes onto it, and run it.
```php
// Require composer autoloader
require __DIR__ . '/vendor/autoload.php';
// Create Router instance
$router = new \Bramus\Router\Router();
// Define routes
// ...
// Run it!
$router->run();
```
### Routing
Hook __routes__ (a combination of one or more HTTP methods and a pattern) using `$router->match(method(s), pattern, function)`:
```php
$router->match('GET|POST', 'pattern', function() { });
```
`bramus/router` supports `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD` _(see [note](#a-note-on-making-head-requests))_, and `OPTIONS` HTTP request methods. Pass in a single request method, or multiple request methods separated by `|`.
When a route matches against the current URL (e.g. `$_SERVER['REQUEST_URI']`), the attached __route handling function__ will be executed. The route handling function must be a [callable](http://php.net/manual/en/language.types.callable.php). Only the first route matched will be handled. When no matching route is found, a 404 handler will be executed.
### Routing Shorthands
Shorthands for single request methods are provided:
```php
$router->get('pattern', function() { /* ... */ });
$router->post('pattern', function() { /* ... */ });
$router->put('pattern', function() { /* ... */ });
$router->delete('pattern', function() { /* ... */ });
$router->options('pattern', function() { /* ... */ });
$router->patch('pattern', function() { /* ... */ });
```
You can use this shorthand for a route that can be accessed using any method:
```php
$router->all('pattern', function() { });
```
Note: Routes must be hooked before `$router->run();` is being called.
Note: There is no shorthand for `match()` as `bramus/router` will internally re-route such requrests to their equivalent `GET` request, in order to comply with RFC2616 _(see [note](#a-note-on-making-head-requests))_.
### Route Patterns
Route Patterns can be static or dynamic:
- __Static Route Patterns__ contain no dynamic parts and must match exactly against the `path` part of the current URL.
- __Dynamic Route Patterns__ contain dynamic parts that can vary per request. The varying parts are named __subpatterns__ and are defined using either Perl-compatible regular expressions (PCRE) or by using __placeholders__
#### Static Route Patterns
A static route pattern is a regular string representing a URI. It will be compared directly against the `path` part of the current URL.
Examples:
- `/about`
- `/contact`
Usage Examples:
```php
// This route handling function will only be executed when visiting http(s)://www.example.org/about
$router->get('/about', function() {
echo 'About Page Contents';
});
```
#### Dynamic PCRE-based Route Patterns
This type of Route Patterns contain dynamic parts which can vary per request. The varying parts are named __subpatterns__ and are defined using regular expressions.
Examples:
- `/movies/(\d+)`
- `/profile/(\w+)`
Commonly used PCRE-based subpatterns within Dynamic Route Patterns are:
- `\d+` = One or more digits (0-9)
- `\w+` = One or more word characters (a-z 0-9 _)
- `[a-z0-9_-]+` = One or more word characters (a-z 0-9 _) and the dash (-)
- `.*` = Any character (including `/`), zero or more
- `[^/]+` = Any character but `/`, one or more
Note: The [PHP PCRE Cheat Sheet](https://courses.cs.washington.edu/courses/cse154/15sp/cheat-sheets/php-regex-cheat-sheet.pdf) might come in handy.
The __subpatterns__ defined in Dynamic PCRE-based Route Patterns are converted to parameters which are passed into the route handling function. Prerequisite is that these subpatterns need to be defined as __parenthesized subpatterns__, which means that they should be wrapped between parens:
```php
// Bad
$router->get('/hello/\w+', function($name) {
echo 'Hello ' . htmlentities($name);
});
// Good
$router->get('/hello/(\w+)', function($name) {
echo 'Hello ' . htmlentities($name);
});
```
Note: The leading `/` at the very beginning of a route pattern is not mandatory, but is recommended.
When multiple subpatterns are defined, the resulting __route handling parameters__ are passed into the route handling function in the order they are defined in:
```php
$router->get('/movies/(\d+)/photos/(\d+)', function($movieId, $photoId) {
echo 'Movie #' . $movieId . ', photo #' . $photoId;
});
```
#### Dynamic Placeholder-based Route Patterns
This type of Route Patterns are the same as __Dynamic PCRE-based Route Patterns__, but with one difference: they don't use regexes to do the pattern matching but they use the more easy __placeholders__ instead. Placeholders are strings surrounded by curly braces, e.g. `{name}`. You don't need to add parens around placeholders.
Examples:
- `/movies/{id}`
- `/profile/{username}`
Placeholders are easier to use than PRCEs, but offer you less control as they internally get translated to a PRCE that matches any character (`.*`).
```php
$router->get('/movies/{movieId}/photos/{photoId}', function($movieId, $photoId) {
echo 'Movie #' . $movieId . ', photo #' . $photoId;
});
```
Note: the name of the placeholder does not need to match with the name of the parameter that is passed into the route handling function:
```php
$router->get('/movies/{foo}/photos/{bar}', function($movieId, $photoId) {
echo 'Movie #' . $movieId . ', photo #' . $photoId;
});
```
### Optional Route Subpatterns
Route subpatterns can be made optional by making the subpatterns optional by adding a `?` after them. Think of blog URLs in the form of `/blog(/year)(/month)(/day)(/slug)`:
```php
$router->get(
'/blog(/\d+)?(/\d+)?(/\d+)?(/[a-z0-9_-]+)?',
function($year = null, $month = null, $day = null, $slug = null) {
if (!$year) { echo 'Blog overview'; return; }
if (!$month) { echo 'Blog year overview'; return; }
if (!$day) { echo 'Blog month overview'; return; }
if (!$slug) { echo 'Blog day overview'; return; }
echo 'Blogpost ' . htmlentities($slug) . ' detail';
}
);
```
The code snippet above responds to the URLs `/blog`, `/blog/year`, `/blog/year/month`, `/blog/year/month/day`, and `/blog/year/month/day/slug`.
Note: With optional parameters it is important that the leading `/` of the subpatterns is put inside the subpattern itself. Don't forget to set default values for the optional parameters.
The code snipped above unfortunately also responds to URLs like `/blog/foo` and states that the overview needs to be shown - which is incorrect. Optional subpatterns can be made successive by extending the parenthesized subpatterns so that they contain the other optional subpatterns: The pattern should resemble `/blog(/year(/month(/day(/slug))))` instead of the previous `/blog(/year)(/month)(/day)(/slug)`:
```php
$router->get('/blog(/\d+(/\d+(/\d+(/[a-z0-9_-]+)?)?)?)?', function($year = null, $month = null, $day = null, $slug = null) {
// ...
});
```
Note: It is highly recommended to __always__ define successive optional parameters.
To make things complete use [quantifiers](http://www.php.net/manual/en/regexp.reference.repetition.php) to require the correct amount of numbers in the URL:
```php
$router->get('/blog(/\d{4}(/\d{2}(/\d{2}(/[a-z0-9_-]+)?)?)?)?', function($year = null, $month = null, $day = null, $slug = null) {
// ...
});
```
### Subrouting / Mounting Routes
Use `$router->mount($baseroute, $fn)` to mount a collection of routes onto a subroute pattern. The subroute pattern is prefixed onto all following routes defined in the scope. e.g. Mounting a callback `$fn` onto `/movies` will prefix `/movies` onto all following routes.
```php
$router->mount('/movies', function() use ($router) {
// will result in '/movies/'
$router->get('/', function() {
echo 'movies overview';
});
// will result in '/movies/id'
$router->get('/(\d+)', function($id) {
echo 'movie id ' . htmlentities($id);
});
});
```
Nesting of subroutes is possible, just define a second `$router->mount()` in the callable that's already contained within a preceding `$router->mount()`.
### `Class@Method` calls
We can route to the class action like so:
```php
$router->get('/(\d+)', '\App\Controllers\User@showProfile');
```
When a request matches the specified route URI, the `showProfile` method on the `User` class will be executed. The defined route parameters will be passed to the class method.
The method can be static (recommended) or non-static (not-recommended). In case of a non-static method, a new instance of the class will be created.
If most/all of your handling classes are in one and the same namespace, you can set the default namespace to use on your router instance via `setNamespace()`
```php
$router->setNamespace('\App\Controllers');
$router->get('/users/(\d+)', 'User@showProfile');
$router->get('/cars/(\d+)', 'Car@showProfile');
```
### Custom 404
The default 404 handler sets a 404 status code and exits. You can override this default 404 handler by using `$router->set404(callable);`
```php
$router->set404(function() {
header('HTTP/1.1 404 Not Found');
// ... do something special here
});
```
You can also define multiple custom routes e.x. you want to define an `/api` route, you can print a custom 404 page:
```php
$router->set404('/api(/.*)?', function() {
header('HTTP/1.1 404 Not Found');
header('Content-Type: application/json');
$jsonArray = array();
$jsonArray['status'] = "404";
$jsonArray['status_text'] = "route not defined";
echo json_encode($jsonArray);
});
```
Also supported are `Class@Method` callables:
```php
$router->set404('\App\Controllers\Error@notFound');
```
The 404 handler will be executed when no route pattern was matched to the current URL.
💡 You can also manually trigger the 404 handler by calling `$router->trigger404()`
```php
$router->get('/([a-z0-9-]+)', function($id) use ($router) {
if (!Posts::exists($id)) {
$router->trigger404();
return;
}
// …
});
```
### Before Route Middlewares
`bramus/router` supports __Before Route Middlewares__, which are executed before the route handling is processed.
Like route handling functions, you hook a handling function to a combination of one or more HTTP request methods and a specific route pattern.
```php
$router->before('GET|POST', '/admin/.*', function() {
if (!isset($_SESSION['user'])) {
header('location: /auth/login');
exit();
}
});
```
Unlike route handling functions, more than one before route middleware is executed when more than one route match is found.
### Before Router Middlewares
Before route middlewares are route specific. Using a general route pattern (viz. _all URLs_), they can become __Before Router Middlewares__ _(in other projects sometimes referred to as before app middlewares)_ which are always executed, no matter what the requested URL is.
```php
$router->before('GET', '/.*', function() {
// ... this will always be executed
});
```
### After Router Middleware / Run Callback
Run one (1) middleware function, name the __After Router Middleware__ _(in other projects sometimes referred to as after app middlewares)_ after the routing was processed. Just pass it along the `$router->run()` function. The run callback is route independent.
```php
$router->run(function() { });
```
Note: If the route handling function has `exit()`ed the run callback won't be run.
### Overriding the request method
Use `X-HTTP-Method-Override` to override the HTTP Request Method. Only works when the original Request Method is `POST`. Allowed values for `X-HTTP-Method-Override` are `PUT`, `DELETE`, or `PATCH`.
### Subfolder support
Out-of-the box `bramus/router` will run in any (sub)folder you place it into … no adjustments to your code are needed. You can freely move your _entry script_ `index.php` around, and the router will automatically adapt itself to work relatively from the current folder's path by mounting all routes onto that __basePath__.
Say you have a server hosting the domain `www.example.org` using `public_html/` as its document root, with this little _entry script_ `index.php`:
```php
$router->get('/', function() { echo 'Index'; });
$router->get('/hello', function() { echo 'Hello!'; });
```
- If your were to place this file _(along with its accompanying `.htaccess` file or the like)_ at the document root level (e.g. `public_html/index.php`), `bramus/router` will mount all routes onto the domain root (e.g. `/`) and thus respond to `https://www.example.org/` and `https://www.example.org/hello`.
- If you were to move this file _(along with its accompanying `.htaccess` file or the like)_ into a subfolder (e.g. `public_html/demo/index.php`), `bramus/router` will mount all routes onto the current path (e.g. `/demo`) and thus repsond to `https://www.example.org/demo` and `https://www.example.org/demo/hello`. There's **no** need for `$router->mount(…)` in this case.
#### Disabling subfolder support
In case you **don't** want `bramus/router` to automatically adapt itself to the folder its being placed in, it's possible to manually override the _basePath_ by calling `setBasePath()`. This is necessary in the _(uncommon)_ situation where your _entry script_ and your _entry URLs_ are not tightly coupled _(e.g. when the entry script is placed into a subfolder that does not need be part of the URLs it responds to)_.
```php
// Override auto base path detection
$router->setBasePath('/');
$router->get('/', function() { echo 'Index'; });
$router->get('/hello', function() { echo 'Hello!'; });
$router->run();
```
If you were to place this file into a subfolder (e.g. `public_html/some/sub/folder/index.php`), it will still mount the routes onto the domain root (e.g. `/`) and thus respond to `https://www.example.org/` and `https://www.example.org/hello` _(given that your `.htaccess` file placed at the document root level rewrites requests to it)_
## Integration with other libraries
Integrate other libraries with `bramus/router` by making good use of the `use` keyword to pass dependencies into the handling functions.
```php
$tpl = new \Acme\Template\Template();
$router->get('/', function() use ($tpl) {
$tpl->load('home.tpl');
$tpl->setdata(array(
'name' => 'Bramus!'
));
});
$router->run(function() use ($tpl) {
$tpl->display();
});
```
Given this structure it is still possible to manipulate the output from within the After Router Middleware
## A note on working with PUT
There's no such thing as `$_PUT` in PHP. One must fake it:
```php
$router->put('/movies/(\d+)', function($id) {
// Fake $_PUT
$_PUT = array();
parse_str(file_get_contents('php://input'), $_PUT);
// ...
});
```
## A note on making HEAD requests
When making `HEAD` requests all output will be buffered to prevent any content trickling into the response body, as defined in [RFC2616 (Hypertext Transfer Protocol -- HTTP/1.1)](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4):
> The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.
To achieve this, `bramus/router` but will internally re-route `HEAD` requests to their equivalent `GET` request and automatically suppress all output.
## Unit Testing & Code Coverage
`bramus/router` ships with unit tests using [PHPUnit](https://github.com/sebastianbergmann/phpunit/).
- If PHPUnit is installed globally run `phpunit` to run the tests.
- If PHPUnit is not installed globally, install it locally throuh composer by running `composer install --dev`. Run the tests themselves by calling `vendor/bin/phpunit`.
The included `composer.json` will also install `php-code-coverage` which allows one to generate a __Code Coverage Report__. Run `phpunit --coverage-html ./tests-report` (XDebug required), a report will be placed into the `tests-report` subfolder.
## Acknowledgements
`bramus/router` is inspired upon [Klein](https://github.com/chriso/klein.php), [Ham](https://github.com/radiosilence/Ham), and [JREAM/route](https://bitbucket.org/JREAM/route) . Whilst Klein provides lots of features it is not object oriented. Whilst Ham is Object Oriented, it's bad at _separation of concerns_ as it also provides templating within the routing class. Whilst JREAM/route is a good starting point it is limited in what it does (only GET routes for example).
## License
`bramus/router` is released under the MIT public license. See the enclosed `LICENSE` for details.
@@ -0,0 +1,31 @@
{
"name": "bramus/router",
"description": "A lightweight and simple object oriented PHP Router",
"keywords": ["router", "routing"],
"homepage": "https://github.com/bramus/router",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Bram(us) Van Damme",
"email": "bramus@bram.us",
"homepage": "http://www.bram.us"
}
],
"require": {
"php": ">=5.3.0"
},
"require-dev": {
"phpunit/phpunit": "~4.8",
"phpunit/php-code-coverage": "~2.0",
"friendsofphp/php-cs-fixer": "~2.14"
},
"autoload": {
"psr-0": {"Bramus": "src/"}
},
"scripts": {
"test": "./vendor/bin/phpunit --colors=always",
"lint": "php-cs-fixer fix --diff --dry-run",
"fix": "php-cs-fixer fix"
}
}
@@ -0,0 +1,4 @@
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
@@ -0,0 +1,82 @@
<?php
// In case one is using PHP 5.4+'s built-in server
$filename = __DIR__ . preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (php_sapi_name() === 'cli-server' && is_file($filename)) {
return false;
}
// Include the Router class
// @note: it's recommended to just use the composer autoloader when working with other packages too
require_once __DIR__ . '/../src/Bramus/Router/Router.php';
/**
* A Multilingual Router
*/
class MultilangRouter extends \Bramus\Router\Router
{
/**
* The Default langauge
* @var string
*/
private $defaultLanguage;
/**
* List of allowed languages
* @var array
*/
private $allowedLanguages = array();
/**
* A Multilingual Router
* @param array $allowedLanguages
* @param string $defaultLanguage
*/
public function __construct(array $allowedLanguages, $defaultLanguage)
{
// Store passed in data
$this->allowedLanguages = $allowedLanguages;
$this->defaultLanguage = (in_array($defaultLanguage, $allowedLanguages) ? $defaultLanguage : $allowedLanguages[0]);
// Visiting the root? Redirect to the default language index
$this->match('GET|POST|PUT|DELETE|HEAD', '/', function () {
header('location: /' . $this->defaultLanguage);
exit();
});
// Create a before handler to make sure the language checks out when visiting anything but the root.
// If the language doesn't check out, redirect to the default language index
$this->before('GET|POST|PUT|DELETE|HEAD', '/([a-z0-9_-]+)(/.*)?', function ($language, $slug = null) {
// The given language does not appear in the array of allowed languages
if (!in_array($language, $this->allowedLanguages)) {
header('location: /' . $this->defaultLanguage);
exit();
}
});
}
}
// Create a Router
$router = new MultilangRouter(
array('en','nl','fr'), //= allowed languages
'nl' // = default language
);
$router->get('/([a-z0-9_-]+)', function ($language) {
exit('This is the ' . htmlentities($language) . ' index');
});
$router->get('/([a-z0-9_-]+)/([a-z0-9_-]+)', function ($language, $slug) {
exit('This is the ' . htmlentities($language) . ' version of ' . htmlentities($slug));
});
$router->get('/([a-z0-9_-]+)/(.*)', function ($language, $slug) {
exit('This is the ' . htmlentities($language) . ' version of ' . htmlentities($slug) . ' (multiple segments allowed)');
});
// Thunderbirds are go!
$router->run();
// EOF
@@ -0,0 +1,4 @@
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
@@ -0,0 +1,134 @@
<?php
// In case one is using PHP 5.4's built-in server
$filename = __DIR__ . preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (php_sapi_name() === 'cli-server' && is_file($filename)) {
return false;
}
// Include the Router class
// @note: it's recommended to just use the composer autoloader when working with other packages too
require_once __DIR__ . '/../src/Bramus/Router/Router.php';
// Create a Router
$router = new \Bramus\Router\Router();
// Custom 404 Handler
$router->set404(function () {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
echo '404, route not found!';
});
// custom 404
$router->set404('/test(/.*)?', function () {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
echo '<h1><mark>404, route not found!</mark></h1>';
});
$router->set404('/api(/.*)?', function() {
header('HTTP/1.1 404 Not Found');
header('Content-Type: application/json');
$jsonArray = array();
$jsonArray['status'] = "404";
$jsonArray['status_text'] = "route not defined";
echo json_encode($jsonArray);
});
// Before Router Middleware
$router->before('GET', '/.*', function () {
header('X-Powered-By: bramus/router');
});
// Static route: / (homepage)
$router->get('/', function () {
echo '<h1>bramus/router</h1>
<p>Try these routes:<p>
<ul>
<li><a href="/hello/joe">/hello/<em>name</em></a></li>
<li><a href="/blog">/blog</a></li>
<li><a href="/blog/'.date('Y').'">/blog/<em>year</em></a></li>
<li><a href="/blog/'.date('Y').'/'.date('m').'">/blog/<em>year</em>/<em>month</em></a></li>
<li><a href="/blog/'.date('Y').'/'.date('m').'/'.date('d').'">/blog/<em>year</em>/<em>month</em>/<em>day</em></a></li>
<li><a href="/movies">/movies</a></li>
<li><a href="/movies/23">/movies/<em>id</em></a></li>
</ul>
<br><br>
<p>Custom error routes</p>
<ul>
<li><a href="/something">/*</a> <em>Normal 404</em></li>
<li><a href="/test">/test/*</a> <em>Custom 404</em></li>
<li><a href="/api/getUser">/api/getUser</a> <em>API 404</em></li>
</ul>
';
});
// Static route: /hello
$router->get('/hello', function () {
echo '<h1>bramus/router</h1><p>Visit <code>/hello/<em>name</em></code> to get your Hello World mojo on!</p>';
});
// Dynamic route: /hello/name
$router->get('/hello/(\w+)', function ($name) {
echo 'Hello ' . htmlentities($name);
});
// Dynamic route: /ohai/name/in/parts
$router->get('/ohai/(.*)', function ($url) {
echo 'Ohai ' . htmlentities($url);
});
// Dynamic route with (successive) optional subpatterns: /blog(/year(/month(/day(/slug))))
$router->get('/blog(/\d{4}(/\d{2}(/\d{2}(/[a-z0-9_-]+)?)?)?)?', function ($year = null, $month = null, $day = null, $slug = null) {
if (!$year) {
echo 'Blog overview';
return;
}
if (!$month) {
echo 'Blog year overview (' . $year . ')';
return;
}
if (!$day) {
echo 'Blog month overview (' . $year . '-' . $month . ')';
return;
}
if (!$slug) {
echo 'Blog day overview (' . $year . '-' . $month . '-' . $day . ')';
return;
}
echo 'Blogpost ' . htmlentities($slug) . ' detail (' . $year . '-' . $month . '-' . $day . ')';
});
// Subrouting
$router->mount('/movies', function () use ($router) {
// will result in '/movies'
$router->get('/', function () {
echo 'movies overview';
});
// will result in '/movies'
$router->post('/', function () {
echo 'add movie';
});
// will result in '/movies/id'
$router->get('/(\d+)', function ($id) {
echo 'movie id ' . htmlentities($id);
});
// will result in '/movies/id'
$router->put('/(\d+)', function ($id) {
echo 'Update movie id ' . htmlentities($id);
});
});
// Thunderbirds are go!
$router->run();
// EOF
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" syntaxCheck="false" bootstrap="tests/bootstrap.php">
<testsuites>
<testsuite name="Router Tests">
<directory>tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
</phpunit>
@@ -0,0 +1,535 @@
<?php
/**
* @author Bram(us) Van Damme <bramus@bram.us>
* @copyright Copyright (c), 2013 Bram(us) Van Damme
* @license MIT public license
*/
namespace Bramus\Router;
/**
* Class Router.
*/
class Router
{
/**
* @var array The route patterns and their handling functions
*/
private $afterRoutes = array();
/**
* @var array The before middleware route patterns and their handling functions
*/
private $beforeRoutes = array();
/**
* @var array [object|callable] The function to be executed when no route has been matched
*/
protected $notFoundCallback = [];
/**
* @var string Current base route, used for (sub)route mounting
*/
private $baseRoute = '';
/**
* @var string The Request Method that needs to be handled
*/
private $requestedMethod = '';
/**
* @var string The Server Base Path for Router Execution
*/
private $serverBasePath;
/**
* @var string Default Controllers Namespace
*/
private $namespace = '';
/**
* Store a before middleware route and a handling function to be executed when accessed using one of the specified methods.
*
* @param string $methods Allowed methods, | delimited
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function before($methods, $pattern, $fn)
{
$pattern = $this->baseRoute . '/' . trim($pattern, '/');
$pattern = $this->baseRoute ? rtrim($pattern, '/') : $pattern;
foreach (explode('|', $methods) as $method) {
$this->beforeRoutes[$method][] = array(
'pattern' => $pattern,
'fn' => $fn,
);
}
}
/**
* Store a route and a handling function to be executed when accessed using one of the specified methods.
*
* @param string $methods Allowed methods, | delimited
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function match($methods, $pattern, $fn)
{
$pattern = $this->baseRoute . '/' . trim($pattern, '/');
$pattern = $this->baseRoute ? rtrim($pattern, '/') : $pattern;
foreach (explode('|', $methods) as $method) {
$this->afterRoutes[$method][] = array(
'pattern' => $pattern,
'fn' => $fn,
);
}
}
/**
* Shorthand for a route accessed using any method.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function all($pattern, $fn)
{
$this->match('GET|POST|PUT|DELETE|OPTIONS|PATCH|HEAD', $pattern, $fn);
}
/**
* Shorthand for a route accessed using GET.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function get($pattern, $fn)
{
$this->match('GET', $pattern, $fn);
}
/**
* Shorthand for a route accessed using POST.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function post($pattern, $fn)
{
$this->match('POST', $pattern, $fn);
}
/**
* Shorthand for a route accessed using PATCH.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function patch($pattern, $fn)
{
$this->match('PATCH', $pattern, $fn);
}
/**
* Shorthand for a route accessed using DELETE.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function delete($pattern, $fn)
{
$this->match('DELETE', $pattern, $fn);
}
/**
* Shorthand for a route accessed using PUT.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function put($pattern, $fn)
{
$this->match('PUT', $pattern, $fn);
}
/**
* Shorthand for a route accessed using OPTIONS.
*
* @param string $pattern A route pattern such as /about/system
* @param object|callable $fn The handling function to be executed
*/
public function options($pattern, $fn)
{
$this->match('OPTIONS', $pattern, $fn);
}
/**
* Mounts a collection of callbacks onto a base route.
*
* @param string $baseRoute The route sub pattern to mount the callbacks on
* @param callable $fn The callback method
*/
public function mount($baseRoute, $fn)
{
// Track current base route
$curBaseRoute = $this->baseRoute;
// Build new base route string
$this->baseRoute .= $baseRoute;
// Call the callable
call_user_func($fn);
// Restore original base route
$this->baseRoute = $curBaseRoute;
}
/**
* Get all request headers.
*
* @return array The request headers
*/
public function getRequestHeaders()
{
$headers = array();
// If getallheaders() is available, use that
if (function_exists('getallheaders')) {
$headers = getallheaders();
// getallheaders() can return false if something went wrong
if ($headers !== false) {
return $headers;
}
}
// Method getallheaders() not available or went wrong: manually extract 'm
foreach ($_SERVER as $name => $value) {
if ((substr($name, 0, 5) == 'HTTP_') || ($name == 'CONTENT_TYPE') || ($name == 'CONTENT_LENGTH')) {
$headers[str_replace(array(' ', 'Http'), array('-', 'HTTP'), ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
/**
* Get the request method used, taking overrides into account.
*
* @return string The Request method to handle
*/
public function getRequestMethod()
{
// Take the method as found in $_SERVER
$method = $_SERVER['REQUEST_METHOD'];
// If it's a HEAD request override it to being GET and prevent any output, as per HTTP Specification
// @url http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4
if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
ob_start();
$method = 'GET';
}
// If it's a POST request, check for a method override header
elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
$headers = $this->getRequestHeaders();
if (isset($headers['X-HTTP-Method-Override']) && in_array($headers['X-HTTP-Method-Override'], array('PUT', 'DELETE', 'PATCH'))) {
$method = $headers['X-HTTP-Method-Override'];
}
}
return $method;
}
/**
* Set a Default Lookup Namespace for Callable methods.
*
* @param string $namespace A given namespace
*/
public function setNamespace($namespace)
{
if (is_string($namespace)) {
$this->namespace = $namespace;
}
}
/**
* Get the given Namespace before.
*
* @return string The given Namespace if exists
*/
public function getNamespace()
{
return $this->namespace;
}
/**
* Execute the router: Loop all defined before middleware's and routes, and execute the handling function if a match was found.
*
* @param object|callable $callback Function to be executed after a matching route was handled (= after router middleware)
*
* @return bool
*/
public function run($callback = null)
{
// Define which method we need to handle
$this->requestedMethod = $this->getRequestMethod();
// Handle all before middlewares
if (isset($this->beforeRoutes[$this->requestedMethod])) {
$this->handle($this->beforeRoutes[$this->requestedMethod]);
}
// Handle all routes
$numHandled = 0;
if (isset($this->afterRoutes[$this->requestedMethod])) {
$numHandled = $this->handle($this->afterRoutes[$this->requestedMethod], true);
}
// If no route was handled, trigger the 404 (if any)
if ($numHandled === 0) {
$this->trigger404($this->afterRoutes[$this->requestedMethod]);
} // If a route was handled, perform the finish callback (if any)
else {
if ($callback && is_callable($callback)) {
$callback();
}
}
// If it originally was a HEAD request, clean up after ourselves by emptying the output buffer
if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
ob_end_clean();
}
// Return true if a route was handled, false otherwise
return $numHandled !== 0;
}
/**
* Set the 404 handling function.
*
* @param object|callable|string $match_fn The function to be executed
* @param object|callable $fn The function to be executed
*/
public function set404($match_fn, $fn = null)
{
if (!is_null($fn)) {
$this->notFoundCallback[$match_fn] = $fn;
} else {
$this->notFoundCallback['/'] = $match_fn;
}
}
/**
* Triggers 404 response
*
* @param string $pattern A route pattern such as /about/system
*/
public function trigger404($match = null){
// Counter to keep track of the number of routes we've handled
$numHandled = 0;
// handle 404 pattern
if (count($this->notFoundCallback) > 0)
{
// loop fallback-routes
foreach ($this->notFoundCallback as $route_pattern => $route_callable) {
// matches result
$matches = [];
// check if there is a match and get matches as $matches (pointer)
$is_match = $this->patternMatches($route_pattern, $this->getCurrentUri(), $matches, PREG_OFFSET_CAPTURE);
// is fallback route match?
if ($is_match) {
// Rework matches to only contain the matches, not the orig string
$matches = array_slice($matches, 1);
// Extract the matched URL parameters (and only the parameters)
$params = array_map(function ($match, $index) use ($matches) {
// We have a following parameter: take the substring from the current param position until the next one's position (thank you PREG_OFFSET_CAPTURE)
if (isset($matches[$index + 1]) && isset($matches[$index + 1][0]) && is_array($matches[$index + 1][0])) {
if ($matches[$index + 1][0][1] > -1) {
return trim(substr($match[0][0], 0, $matches[$index + 1][0][1] - $match[0][1]), '/');
}
} // We have no following parameters: return the whole lot
return isset($match[0][0]) && $match[0][1] != -1 ? trim($match[0][0], '/') : null;
}, $matches, array_keys($matches));
$this->invoke($route_callable);
++$numHandled;
}
}
}
if (($numHandled == 0) && (isset($this->notFoundCallback['/']))) {
$this->invoke($this->notFoundCallback['/']);
} elseif ($numHandled == 0) {
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
}
}
/**
* Replace all curly braces matches {} into word patterns (like Laravel)
* Checks if there is a routing match
*
* @param $pattern
* @param $uri
* @param $matches
* @param $flags
*
* @return bool -> is match yes/no
*/
private function patternMatches($pattern, $uri, &$matches, $flags)
{
// Replace all curly braces matches {} into word patterns (like Laravel)
$pattern = preg_replace('/\/{(.*?)}/', '/(.*?)', $pattern);
// we may have a match!
return boolval(preg_match_all('#^' . $pattern . '$#', $uri, $matches, PREG_OFFSET_CAPTURE));
}
/**
* Handle a a set of routes: if a match is found, execute the relating handling function.
*
* @param array $routes Collection of route patterns and their handling functions
* @param bool $quitAfterRun Does the handle function need to quit after one route was matched?
*
* @return int The number of routes handled
*/
private function handle($routes, $quitAfterRun = false)
{
// Counter to keep track of the number of routes we've handled
$numHandled = 0;
// The current page URL
$uri = $this->getCurrentUri();
// Loop all routes
foreach ($routes as $route) {
// get routing matches
$is_match = $this->patternMatches($route['pattern'], $uri, $matches, PREG_OFFSET_CAPTURE);
// is there a valid match?
if ($is_match) {
// Rework matches to only contain the matches, not the orig string
$matches = array_slice($matches, 1);
// Extract the matched URL parameters (and only the parameters)
$params = array_map(function ($match, $index) use ($matches) {
// We have a following parameter: take the substring from the current param position until the next one's position (thank you PREG_OFFSET_CAPTURE)
if (isset($matches[$index + 1]) && isset($matches[$index + 1][0]) && is_array($matches[$index + 1][0])) {
if ($matches[$index + 1][0][1] > -1) {
return trim(substr($match[0][0], 0, $matches[$index + 1][0][1] - $match[0][1]), '/');
}
} // We have no following parameters: return the whole lot
return isset($match[0][0]) && $match[0][1] != -1 ? trim($match[0][0], '/') : null;
}, $matches, array_keys($matches));
// Call the handling function with the URL parameters if the desired input is callable
$this->invoke($route['fn'], $params);
++$numHandled;
// If we need to quit, then quit
if ($quitAfterRun) {
break;
}
}
}
// Return the number of routes handled
return $numHandled;
}
private function invoke($fn, $params = array())
{
if (is_callable($fn)) {
call_user_func_array($fn, $params);
}
// If not, check the existence of special parameters
elseif (stripos($fn, '@') !== false) {
// Explode segments of given route
list($controller, $method) = explode('@', $fn);
// Adjust controller class if namespace has been set
if ($this->getNamespace() !== '') {
$controller = $this->getNamespace() . '\\' . $controller;
}
try {
$reflectedMethod = new \ReflectionMethod($controller, $method);
// Make sure it's callable
if ($reflectedMethod->isPublic() && (!$reflectedMethod->isAbstract())) {
if ($reflectedMethod->isStatic()) {
forward_static_call_array(array($controller, $method), $params);
} else {
// Make sure we have an instance, because a non-static method must not be called statically
if (\is_string($controller)) {
$controller = new $controller();
}
call_user_func_array(array($controller, $method), $params);
}
}
} catch (\ReflectionException $reflectionException) {
// The controller class is not available or the class does not have the method $method
}
}
}
/**
* Define the current relative URI.
*
* @return string
*/
public function getCurrentUri()
{
// Get the current Request URI and remove rewrite base path from it (= allows one to run the router in a sub folder)
$uri = substr(rawurldecode($_SERVER['REQUEST_URI']), strlen($this->getBasePath()));
// Don't take query params into account on the URL
if (strstr($uri, '?')) {
$uri = substr($uri, 0, strpos($uri, '?'));
}
// Remove trailing slash + enforce a slash at the start
return '/' . trim($uri, '/');
}
/**
* Return server base Path, and define it if isn't defined.
*
* @return string
*/
public function getBasePath()
{
// Check if server base path is defined, if not define it.
if ($this->serverBasePath === null) {
$this->serverBasePath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
}
return $this->serverBasePath;
}
/**
* Explicilty sets the server base path. To be used when your entry script path differs from your entry URLs.
* @see https://github.com/bramus/router/issues/82#issuecomment-466956078
*
* @param string
*/
public function setBasePath($serverBasePath)
{
$this->serverBasePath = $serverBasePath;
}
}
@@ -0,0 +1,959 @@
<?php
namespace {
class Handler
{
public function notfound()
{
echo 'route not found';
}
}
class RouterTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
// Clear SCRIPT_NAME because bramus/router tries to guess the subfolder the script is run in
$_SERVER['SCRIPT_NAME'] = '/index.php';
// Default request method to GET
$_SERVER['REQUEST_METHOD'] = 'GET';
// Default SERVER_PROTOCOL method to HTTP/1.1
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
}
protected function tearDown()
{
// nothing
}
public function testInit()
{
$this->assertInstanceOf('\Bramus\Router\Router', new \Bramus\Router\Router());
}
public function testUri()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->match('GET', '/about', function () {
echo 'about';
});
// Fake some data
$_SERVER['SCRIPT_NAME'] = '/sub/folder/index.php';
$_SERVER['REQUEST_URI'] = '/sub/folder/about/whatever';
$method = new ReflectionMethod(
'\Bramus\Router\Router',
'getCurrentUri'
);
$method->setAccessible(true);
$this->assertEquals(
'/about/whatever',
$method->invoke(new \Bramus\Router\Router())
);
}
public function testBasePathOverride()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->match('GET', '/about', function () {
echo 'about';
});
// Fake some data
$_SERVER['SCRIPT_NAME'] = '/public/index.php';
$_SERVER['REQUEST_URI'] = '/about';
$router->setBasePath('/');
$this->assertEquals(
'/',
$router->getBasePath()
);
// Test the /about route
ob_start();
$_SERVER['REQUEST_URI'] = '/about';
$router->run();
$this->assertEquals('about', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testBasePathThatContainsEmoji()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->match('GET', '/about', function () {
echo 'about';
});
// Fake some data
$_SERVER['SCRIPT_NAME'] = '/sub/folder/💩/index.php';
$_SERVER['REQUEST_URI'] = '/sub/folder/%F0%9F%92%A9/about';
// Test the /hello/bramus route
ob_start();
$router->run();
$this->assertEquals('about', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testStaticRoute()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->match('GET', '/about', function () {
echo 'about';
});
// Test the /about route
ob_start();
$_SERVER['REQUEST_URI'] = '/about';
$router->run();
$this->assertEquals('about', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testStaticRouteUsingShorthand()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/about', function () {
echo 'about';
});
// Test the /about route
ob_start();
$_SERVER['REQUEST_URI'] = '/about';
$router->run();
$this->assertEquals('about', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testRequestMethods()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'get';
});
$router->post('/', function () {
echo 'post';
});
$router->put('/', function () {
echo 'put';
});
$router->patch('/', function () {
echo 'patch';
});
$router->delete('/', function () {
echo 'delete';
});
$router->options('/', function () {
echo 'options';
});
// Test GET
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('get', ob_get_contents());
// Test POST
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'POST';
$router->run();
$this->assertEquals('post', ob_get_contents());
// Test PUT
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'PUT';
$router->run();
$this->assertEquals('put', ob_get_contents());
// Test PATCH
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'PATCH';
$router->run();
$this->assertEquals('patch', ob_get_contents());
// Test DELETE
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'DELETE';
$router->run();
$this->assertEquals('delete', ob_get_contents());
// Test OPTIONS
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'OPTIONS';
$router->run();
$this->assertEquals('options', ob_get_contents());
// Test HEAD
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'HEAD';
$router->run();
$this->assertEquals('', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testShorthandAll()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->all('/', function () {
echo 'all';
});
$_SERVER['REQUEST_URI'] = '/';
// Test GET
ob_start();
$_SERVER['REQUEST_METHOD'] = 'GET';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test POST
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'POST';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test PUT
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'PUT';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test DELETE
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'DELETE';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test OPTIONS
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'OPTIONS';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test PATCH
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'PATCH';
$router->run();
$this->assertEquals('all', ob_get_contents());
// Test HEAD
ob_clean();
$_SERVER['REQUEST_METHOD'] = 'HEAD';
$router->run();
$this->assertEquals('', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRoute()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/(\w+)', function ($name) {
echo 'Hello ' . $name;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus';
$router->run();
$this->assertEquals('Hello bramus', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithMultiple()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/(\w+)/(\w+)', function ($name, $lastname) {
echo 'Hello ' . $name . ' ' . $lastname;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesRoutes()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/{name}/{lastname}', function ($name, $lastname) {
echo 'Hello ' . $name . ' ' . $lastname;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesRoutesWithNonAZCharsInPlaceholderNames()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/{arg1}/{arg2}', function ($arg1, $arg2) {
echo 'Hello ' . $arg1 . ' ' . $arg2;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesRoutesWithCyrillicCharactersInPlaceholderNames()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/{това}/{това}', function ($arg1, $arg2) {
echo 'Hello ' . $arg1 . ' ' . $arg2;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesRoutesWithEmojiInPlaceholderNames()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/{😂}/{😅}', function ($arg1, $arg2) {
echo 'Hello ' . $arg1 . ' ' . $arg2;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesWithCyrillicCharacters()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/bg/{arg}', function ($arg) {
echo 'BG: ' . $arg;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/bg/това';
$router->run();
$this->assertEquals('BG: това', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesWithMultipleCyrillicCharacters()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/bg/{arg}/{arg}', function ($arg1, $arg2) {
echo 'BG: ' . $arg1 . ' - ' . $arg2;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/bg/това/слъг';
$router->run();
$this->assertEquals('BG: това - слъг', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesWithEmoji()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/emoji/{emoji}', function ($emoji) {
echo 'Emoji: ' . $emoji;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/emoji/%F0%9F%92%A9'; // 💩
$router->run();
$this->assertEquals('Emoji: 💩', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testCurlyBracesWithEmojiCombinedWithBasePathThatContainsEmoji()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/emoji/{emoji}', function ($emoji) {
echo 'Emoji: ' . $emoji;
});
// Fake some data
$_SERVER['SCRIPT_NAME'] = '/sub/folder/💩/index.php';
$_SERVER['REQUEST_URI'] = '/sub/folder/%F0%9F%92%A9/emoji/%F0%9F%A4%AF'; // 🤯
// Test the /hello/bramus route
ob_start();
$router->run();
$this->assertEquals('Emoji: 🤯', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithOptionalSubpatterns()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello(/\w+)?', function ($name = null) {
echo 'Hello ' . (($name) ? $name : 'stranger');
});
// Test the /hello route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello';
$router->run();
$this->assertEquals('Hello stranger', ob_get_contents());
// Test the /hello/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/hello/bramus';
$router->run();
$this->assertEquals('Hello bramus', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithMultipleSubpatterns()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/(.*)/page([0-9]+)', function ($place, $page) {
echo 'Hello ' . $place . ' page : ' . $page;
});
// Test the /hello/bramus/page3 route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/page3';
$router->run();
$this->assertEquals('Hello hello/bramus page : 3', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithOptionalNestedSubpatterns()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/blog(/\d{4}(/\d{2}(/\d{2}(/[a-z0-9_-]+)?)?)?)?', function ($year = null, $month = null, $day = null, $slug = null) {
if ($year === null) {
echo 'Blog overview';
return;
}
if ($month === null) {
echo 'Blog year overview (' . $year . ')';
return;
}
if ($day === null) {
echo 'Blog month overview (' . $year . '-' . $month . ')';
return;
}
if ($slug === null) {
echo 'Blog day overview (' . $year . '-' . $month . '-' . $day . ')';
return;
}
echo 'Blogpost ' . htmlentities($slug) . ' detail (' . $year . '-' . $month . '-' . $day . ')';
});
// Test the /blog route
ob_start();
$_SERVER['REQUEST_URI'] = '/blog';
$router->run();
$this->assertEquals('Blog overview', ob_get_contents());
// Test the /blog/year route
ob_clean();
$_SERVER['REQUEST_URI'] = '/blog/1983';
$router->run();
$this->assertEquals('Blog year overview (1983)', ob_get_contents());
// Test the /blog/year/month route
ob_clean();
$_SERVER['REQUEST_URI'] = '/blog/1983/12';
$router->run();
$this->assertEquals('Blog month overview (1983-12)', ob_get_contents());
// Test the /blog/year/month/day route
ob_clean();
$_SERVER['REQUEST_URI'] = '/blog/1983/12/26';
$router->run();
$this->assertEquals('Blog day overview (1983-12-26)', ob_get_contents());
// Test the /blog/year/month/day/slug route
ob_clean();
$_SERVER['REQUEST_URI'] = '/blog/1983/12/26/bramus';
$router->run();
$this->assertEquals('Blogpost bramus detail (1983-12-26)', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithNestedOptionalSubpatterns()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello(/\w+(/\w+)?)?', function ($name1 = null, $name2 = null) {
echo 'Hello ' . (($name1) ? $name1 : 'stranger') . ' ' . (($name2) ? $name2 : 'stranger');
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus';
$router->run();
$this->assertEquals('Hello bramus stranger', ob_get_contents());
// Test the /hello/bramus/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/hello/bramus/bramus';
$router->run();
$this->assertEquals('Hello bramus bramus', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithWildcard()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('(.*)', function ($name) {
echo 'Hello ' . $name;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus';
$router->run();
$this->assertEquals('Hello hello/bramus', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testDynamicRouteWithPartialWildcard()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/hello/(.*)', function ($name) {
echo 'Hello ' . $name;
});
// Test the /hello/bramus route
ob_start();
$_SERVER['REQUEST_URI'] = '/hello/bramus/sumarb';
$router->run();
$this->assertEquals('Hello bramus/sumarb', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function test404()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'home';
});
$router->set404(function () {
echo 'route not found';
});
$router->set404('/api(/.*)?', function () {
echo 'api route not found';
});
// Test the /hello route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('home', ob_get_contents());
// Test the /hello/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/foo';
$router->run();
$this->assertEquals('route not found', ob_get_contents());
// Test the custom api 404
ob_clean();
$_SERVER['REQUEST_URI'] = '/api/getUser';
$router->run();
$this->assertEquals('api route not found', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function test404WithClassAtMethod()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'home';
});
$router->set404('Handler@notFound');
// Test the /hello route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('home', ob_get_contents());
// Test the /hello/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/foo';
$router->run();
$this->assertEquals('route not found', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function test404WithClassAtStaticMethod()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'home';
});
$router->set404('Handler@notFound');
// Test the /hello route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('home', ob_get_contents());
// Test the /hello/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/foo';
$router->run();
$this->assertEquals('route not found', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function test404WithManualTrigger()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function() use ($router) {
$router->trigger404();
});
$router->set404(function () {
echo 'route not found';
});
// Test the / route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('route not found', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testBeforeRouterMiddleware()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->before('GET|POST', '/.*', function () {
echo 'before ';
});
$router->get('/', function () {
echo 'root';
});
$router->get('/about', function () {
echo 'about';
});
$router->get('/contact', function () {
echo 'contact';
});
$router->post('/post', function () {
echo 'post';
});
// Test the / route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run();
$this->assertEquals('before root', ob_get_contents());
// Test the /about route
ob_clean();
$_SERVER['REQUEST_URI'] = '/about';
$router->run();
$this->assertEquals('before about', ob_get_contents());
// Test the /contact route
ob_clean();
$_SERVER['REQUEST_URI'] = '/contact';
$router->run();
$this->assertEquals('before contact', ob_get_contents());
// Test the /post route
ob_clean();
$_SERVER['REQUEST_URI'] = '/post';
$_SERVER['REQUEST_METHOD'] = 'POST';
$router->run();
$this->assertEquals('before post', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testAfterRouterMiddleware()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'home';
});
// Test the / route
ob_start();
$_SERVER['REQUEST_URI'] = '/';
$router->run(function () {
echo 'finished';
});
$this->assertEquals('homefinished', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testBasicController()
{
$router = new \Bramus\Router\Router();
$router->get('/show/(.*)', 'RouterTestController@show');
ob_start();
$_SERVER['REQUEST_URI'] = '/show/foo';
$router->run();
$this->assertEquals('foo', ob_get_contents());
// cleanup
ob_end_clean();
}
public function testDefaultNamespace()
{
$router = new \Bramus\Router\Router();
$router->setNamespace('\Hello');
$router->get('/show/(.*)', 'HelloRouterTestController@show');
ob_start();
$_SERVER['REQUEST_URI'] = '/show/foo';
$router->run();
$this->assertEquals('foo', ob_get_contents());
// cleanup
ob_end_clean();
}
public function testSubfolders()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/', function () {
echo 'home';
});
// Test the / route in a fake subfolder
ob_start();
$_SERVER['SCRIPT_NAME'] = '/about/index.php';
$_SERVER['REQUEST_URI'] = '/about/';
$router->run();
$this->assertEquals('home', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testSubrouteMouting()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->mount('/movies', function () use ($router) {
$router->get('/', function () {
echo 'overview';
});
$router->get('/(\d+)', function ($id) {
echo htmlentities($id);
});
});
// Test the /movies route
ob_start();
$_SERVER['REQUEST_URI'] = '/movies';
$router->run();
$this->assertEquals('overview', ob_get_contents());
// Test the /hello/bramus route
ob_clean();
$_SERVER['REQUEST_URI'] = '/movies/1';
$router->run();
$this->assertEquals('1', ob_get_contents());
// Cleanup
ob_end_clean();
}
public function testHttpMethodOverride()
{
// Fake the request method to being POST and override it
$_SERVER['REQUEST_METHOD'] = 'POST';
$_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'PUT';
$method = new ReflectionMethod(
'\Bramus\Router\Router',
'getRequestMethod'
);
$method->setAccessible(true);
$this->assertEquals(
'PUT',
$method->invoke(new \Bramus\Router\Router())
);
}
public function testControllerMethodReturningFalse()
{
// Create Router
$router = new \Bramus\Router\Router();
$router->get('/false', 'RouterTestController@returnFalse');
$router->get('/static-false', 'RouterTestController@staticReturnFalse');
// Test returnFalse
ob_start();
$_SERVER['REQUEST_URI'] = '/false';
$router->run();
$this->assertEquals('returnFalse', ob_get_contents());
// Test staticReturnFalse
ob_clean();
$_SERVER['REQUEST_URI'] = '/static-false';
$router->run();
$this->assertEquals('staticReturnFalse', ob_get_contents());
// Cleanup
ob_end_clean();
}
}
}
namespace {
class RouterTestController
{
public function show($id)
{
echo $id;
}
public function returnFalse()
{
echo 'returnFalse';
return false;
}
public static function staticReturnFalse()
{
echo 'staticReturnFalse';
return false;
}
}
}
namespace Hello {
class HelloRouterTestController
{
public function show($id)
{
echo $id;
}
}
}
// EOF
@@ -0,0 +1,3 @@
<?php
require 'src/Bramus/Router/Router.php';
@@ -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);
}
}
@@ -0,0 +1,396 @@
<?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 string|null if set (by reflection by Composer), this should be set to the path where this class is being copied to
* @internal
*/
private static $selfDir = null;
/**
* @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
*/
private static $installedIsLocalDir;
/**
* @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();
// when using reload, we disable the duplicate protection to ensure that self::$installed data is
// always returned, but we cannot know whether it comes from the installed.php in __DIR__ or not,
// so we have to assume it does not, and that may result in duplicate data being returned when listing
// all installed packages for example
self::$installedIsLocalDir = false;
}
/**
* @return string
*/
private static function getSelfDir()
{
if (self::$selfDir === null) {
self::$selfDir = strtr(__DIR__, '\\', '/');
}
return self::$selfDir;
}
/**
* @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();
$copiedLocalDir = false;
if (self::$canGetVendors) {
$selfDir = self::getSelfDir();
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
$vendorDir = strtr($vendorDir, '\\', '/');
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';
self::$installedByVendor[$vendorDir] = $required;
$installed[] = $required;
if (self::$installed === null && $vendorDir.'/composer' === $selfDir) {
self::$installed = $required;
self::$installedIsLocalDir = true;
}
}
if (self::$installedIsLocalDir && $vendorDir.'/composer' === $selfDir) {
$copiedLocalDir = true;
}
}
}
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() && !$copiedLocalDir) {
$installed[] = self::$installed;
}
return $installed;
}
}
@@ -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.
@@ -0,0 +1,15 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Attribute' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.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',
);
@@ -0,0 +1,15 @@
<?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',
'7b11c4dc42b3b3023073cb14e519683c' => $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php',
);
@@ -0,0 +1,10 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Bramus' => array($vendorDir . '/bramus/router/src'),
);
@@ -0,0 +1,23 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/src'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-factory/src', $vendorDir . '/psr/http-message/src'),
'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'),
'PhpOption\\' => array($vendorDir . '/phpoption/phpoption/src/PhpOption'),
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
'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'),
'Dotenv\\' => array($vendorDir . '/vlucas/phpdotenv/src'),
'App\\' => array($baseDir . '/src'),
);
@@ -0,0 +1,50 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitc448faa2bb4d17063fdd5b5dff1f2609
{
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('ComposerAutoloaderInitc448faa2bb4d17063fdd5b5dff1f2609', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInitc448faa2bb4d17063fdd5b5dff1f2609', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitc448faa2bb4d17063fdd5b5dff1f2609::getInitializer($loader));
$loader->register(true);
$filesToLoad = \Composer\Autoload\ComposerStaticInitc448faa2bb4d17063fdd5b5dff1f2609::$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;
}
}
@@ -0,0 +1,142 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInitc448faa2bb4d17063fdd5b5dff1f2609
{
public static $files = array (
'6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php',
'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php',
'7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php',
);
public static $prefixLengthsPsr4 = array (
'S' =>
array (
'Symfony\\Polyfill\\Php80\\' => 23,
'Symfony\\Polyfill\\Mbstring\\' => 26,
'Symfony\\Polyfill\\Ctype\\' => 23,
),
'P' =>
array (
'Psr\\Log\\' => 8,
'Psr\\Http\\Message\\' => 17,
'Psr\\Http\\Client\\' => 16,
'PhpOption\\' => 10,
),
'M' =>
array (
'Monolog\\' => 8,
),
'G' =>
array (
'GuzzleHttp\\Psr7\\' => 16,
'GuzzleHttp\\Promise\\' => 19,
'GuzzleHttp\\' => 11,
'GrahamCampbell\\ResultType\\' => 26,
),
'D' =>
array (
'Dotenv\\' => 7,
),
'A' =>
array (
'App\\' => 4,
),
);
public static $prefixDirsPsr4 = array (
'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',
),
'Psr\\Log\\' =>
array (
0 => __DIR__ . '/..' . '/psr/log/src',
),
'Psr\\Http\\Message\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-factory/src',
1 => __DIR__ . '/..' . '/psr/http-message/src',
),
'Psr\\Http\\Client\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-client/src',
),
'PhpOption\\' =>
array (
0 => __DIR__ . '/..' . '/phpoption/phpoption/src/PhpOption',
),
'Monolog\\' =>
array (
0 => __DIR__ . '/..' . '/monolog/monolog/src/Monolog',
),
'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',
),
'Dotenv\\' =>
array (
0 => __DIR__ . '/..' . '/vlucas/phpdotenv/src',
),
'App\\' =>
array (
0 => __DIR__ . '/../..' . '/src',
),
);
public static $prefixesPsr0 = array (
'B' =>
array (
'Bramus' =>
array (
0 => __DIR__ . '/..' . '/bramus/router/src',
),
),
);
public static $classMap = array (
'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.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 = ComposerStaticInitc448faa2bb4d17063fdd5b5dff1f2609::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitc448faa2bb4d17063fdd5b5dff1f2609::$prefixDirsPsr4;
$loader->prefixesPsr0 = ComposerStaticInitc448faa2bb4d17063fdd5b5dff1f2609::$prefixesPsr0;
$loader->classMap = ComposerStaticInitc448faa2bb4d17063fdd5b5dff1f2609::$classMap;
}, null, ClassLoader::class);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,200 @@
<?php return array(
'root' => array(
'name' => 'porawit/soar-wazuh',
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'reference' => null,
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev' => true,
),
'versions' => array(
'bramus/router' => array(
'pretty_version' => '1.6.1',
'version' => '1.6.1.0',
'reference' => '55657b76da8a0a509250fb55b9dd24e1aa237eba',
'type' => 'library',
'install_path' => __DIR__ . '/../bramus/router',
'aliases' => array(),
'dev_requirement' => false,
),
'graham-campbell/result-type' => array(
'pretty_version' => 'v1.1.4',
'version' => '1.1.4.0',
'reference' => 'e01f4a821471308ba86aa202fed6698b6b695e3b',
'type' => 'library',
'install_path' => __DIR__ . '/../graham-campbell/result-type',
'aliases' => array(),
'dev_requirement' => false,
),
'guzzlehttp/guzzle' => array(
'pretty_version' => '7.15.3',
'version' => '7.15.3.0',
'reference' => 'ae311b8f045ea93ce7b1c9cdb7cec06c53f944bc',
'type' => 'library',
'install_path' => __DIR__ . '/../guzzlehttp/guzzle',
'aliases' => array(),
'dev_requirement' => false,
),
'guzzlehttp/promises' => array(
'pretty_version' => '2.5.2',
'version' => '2.5.2.0',
'reference' => '2823687acff28b2dbe67b2508a6b300e2c3fa4ce',
'type' => 'library',
'install_path' => __DIR__ . '/../guzzlehttp/promises',
'aliases' => array(),
'dev_requirement' => false,
),
'guzzlehttp/psr7' => array(
'pretty_version' => '2.13.0',
'version' => '2.13.0.0',
'reference' => 'dad89620b7a6edb60c15858442eb2e408b45d8f4',
'type' => 'library',
'install_path' => __DIR__ . '/../guzzlehttp/psr7',
'aliases' => array(),
'dev_requirement' => false,
),
'monolog/monolog' => array(
'pretty_version' => '3.10.0',
'version' => '3.10.0.0',
'reference' => 'b321dd6749f0bf7189444158a3ce785cc16d69b0',
'type' => 'library',
'install_path' => __DIR__ . '/../monolog/monolog',
'aliases' => array(),
'dev_requirement' => false,
),
'phpoption/phpoption' => array(
'pretty_version' => '1.9.5',
'version' => '1.9.5.0',
'reference' => '75365b91986c2405cf5e1e012c5595cd487a98be',
'type' => 'library',
'install_path' => __DIR__ . '/../phpoption/phpoption',
'aliases' => array(),
'dev_requirement' => false,
),
'porawit/soar-wazuh' => array(
'pretty_version' => '1.0.0+no-version-set',
'version' => '1.0.0.0',
'reference' => null,
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'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.0',
),
),
'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 => '1.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',
),
),
'ralouphie/getallheaders' => array(
'pretty_version' => '3.0.3',
'version' => '3.0.3.0',
'reference' => '120b605dfeb996808c31b6477290a714d356e822',
'type' => 'library',
'install_path' => __DIR__ . '/../ralouphie/getallheaders',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/deprecation-contracts' => array(
'pretty_version' => 'v3.7.1',
'version' => '3.7.1.0',
'reference' => 'f3202fa1b5097b0af062dc978b32ecf63404e31d',
'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.38.2',
'version' => '1.38.2.0',
'reference' => 'd3d318bad5e7a1bfbd026009c8bfb8d8f99ae6b6',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-mbstring',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/polyfill-php80' => array(
'pretty_version' => 'v1.37.0',
'version' => '1.37.0.0',
'reference' => 'dfb55726c3a76ea3b6459fcfda1ec2d80a682411',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-php80',
'aliases' => array(),
'dev_requirement' => false,
),
'vlucas/phpdotenv' => array(
'pretty_version' => 'v5.6.4',
'version' => '5.6.4.0',
'reference' => '416df702837983f8d5ff48c9c3fee4f5f57b980b',
'type' => 'library',
'install_path' => __DIR__ . '/../vlucas/phpdotenv',
'aliases' => array(),
'dev_requirement' => false,
),
),
);
@@ -0,0 +1,25 @@
<?php
// platform_check.php @generated by Composer
$issues = array();
if (!(PHP_VERSION_ID >= 80100)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 8.1.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;
}
}
throw new \RuntimeException(
'Composer detected issues in your platform: ' . implode(' ', $issues)
);
}
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2020-2024 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.9.5"
},
"require-dev": {
"phpunit/phpunit": "^8.5.41 || ^9.6.22 || ^10.5.45 || ^11.5.7"
},
"autoload": {
"psr-4": {
"GrahamCampbell\\ResultType\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"GrahamCampbell\\Tests\\ResultType\\": "tests/"
}
},
"config": {
"preferred-install": "dist"
}
}
@@ -0,0 +1,121 @@
<?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 T
* @template E
*
* @extends \GrahamCampbell\ResultType\Result<T,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\Result<T,F>
*/
public static function create($value)
{
return new self($value);
}
/**
* Get the success option value.
*
* @return \PhpOption\Option<T>
*/
public function success()
{
return None::create();
}
/**
* Map over the success value.
*
* @template S
*
* @param callable(T):S $f
*
* @return \GrahamCampbell\ResultType\Result<S,E>
*/
public function map(callable $f)
{
return self::create($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)
{
/** @var \GrahamCampbell\ResultType\Result<S,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\Result<T,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 T
* @template 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,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);
}
@@ -0,0 +1,120 @@
<?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 T
* @template E
*
* @extends \GrahamCampbell\ResultType\Result<T,E>
*/
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 error value.
*
* @template S
*
* @param S $value
*
* @return \GrahamCampbell\ResultType\Result<S,E>
*/
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\Result<S,E>
*/
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<E>
*/
public function error()
{
return None::create();
}
/**
* Map over the error value.
*
* @template F
*
* @param callable(E):F $f
*
* @return \GrahamCampbell\ResultType\Result<T,F>
*/
public function mapError(callable $f)
{
return self::create($this->value);
}
}
@@ -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.
@@ -0,0 +1,94 @@
![Guzzle](.github/logo.png?raw=true)
# Guzzle, PHP HTTP client
[![Latest Version](https://img.shields.io/github/release/guzzle/guzzle.svg?style=flat-square)](https://github.com/guzzle/guzzle/releases)
[![Build Status](https://img.shields.io/github/actions/workflow/status/guzzle/guzzle/ci.yml?label=ci%20build&style=flat-square)](https://github.com/guzzle/guzzle/actions?query=workflow%3ACI)
[![Total Downloads](https://img.shields.io/packagist/dt/guzzlehttp/guzzle.svg?style=flat-square)](https://packagist.org/packages/guzzlehttp/guzzle)
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 between 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.
```php
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');
echo $response->getStatusCode(); // 200
echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}'
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
```
## Help and docs
We use GitHub issues only to discuss bugs and new features. For support please refer to:
- [Documentation](docs/index.md)
- [Stack Overflow](https://stackoverflow.com/questions/tagged/guzzle)
- [#guzzle](https://app.slack.com/client/T0D2S9JCT/CE6UAAKL4) channel on [PHP-HTTP Slack](https://slack.httplug.io/)
- [Gitter](https://gitter.im/guzzle/guzzle)
## Installing Guzzle
The recommended way to install Guzzle is through
[Composer](https://getcomposer.org/).
```bash
composer require guzzlehttp/guzzle
```
## Version Guidance
| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 | PHP Version |
|---------|---------------------|---------------------|--------------|---------------------|---------------------|-------|--------------|
| 3.x | EOL (2016-10-31) | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No | >=5.3.3,<7.0 |
| 4.x | EOL (2016-10-31) | `guzzlehttp/guzzle` | `GuzzleHttp` | [v4][guzzle-4-repo] | N/A | No | >=5.4,<7.0 |
| 5.x | EOL (2019-10-31) | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No | >=5.4,<7.4 |
| 6.x | EOL (2023-10-31) | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes | >=5.5,<8.0 |
| 7.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v7][guzzle-7-repo] | [v7][guzzle-7-docs] | Yes | >=7.2.5,<8.6 |
[guzzle-3-repo]: https://github.com/guzzle/guzzle3
[guzzle-4-repo]: https://github.com/guzzle/guzzle/tree/4.x
[guzzle-5-repo]: https://github.com/guzzle/guzzle/tree/5.3
[guzzle-6-repo]: https://github.com/guzzle/guzzle/tree/6.5
[guzzle-7-repo]: https://github.com/guzzle/guzzle/tree/7.15
[guzzle-3-docs]: https://github.com/guzzle/guzzle3/tree/master/docs
[guzzle-5-docs]: https://github.com/guzzle/guzzle/tree/5.3/docs
[guzzle-6-docs]: https://github.com/guzzle/guzzle/tree/6.5/docs
[guzzle-7-docs]: https://github.com/guzzle/guzzle/blob/7.15/docs/index.md
## 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. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/guzzle/security/policy) for more information.
## 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)
@@ -0,0 +1,133 @@
{
"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.2.5 || ^8.0",
"ext-json": "*",
"guzzlehttp/promises": "^2.5.2",
"guzzlehttp/psr7": "^2.13",
"psr/http-client": "^1.0",
"symfony/deprecation-contracts": "^2.5 || ^3.0",
"symfony/polyfill-php80": "^1.25"
},
"require-dev": {
"ext-curl": "*",
"bamarni/composer-bin-plugin": "^1.8.2",
"guzzle/client-integration-tests": "3.0.3",
"guzzlehttp/test-server": "^0.7",
"php-http/message-factory": "^1.1",
"phpunit/phpunit": "^8.5.52 || ^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": "v3.0.3",
"require": {
"guzzlehttp/psr7": "^1.7 || ^2.0",
"php": "^7.2.5 || ^8.0",
"php-http/message": "^1.0 || ^2.0",
"phpunit/phpunit": "^7.5.20 || ^8.5.8 || ^9.3.11",
"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/30edbabe49dedd95e3f21d8a25438f767b653d75"
}
}
}
],
"autoload": {
"psr-4": {
"GuzzleHttp\\": "src/"
},
"files": [
"src/functions_include.php"
]
},
"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
}
}
}
@@ -0,0 +1,28 @@
<?php
namespace GuzzleHttp;
use Psr\Http\Message\MessageInterface;
final class BodySummarizer implements BodySummarizerInterface
{
/**
* @var int|null
*/
private $truncateAt;
public function __construct(?int $truncateAt = null)
{
$this->truncateAt = $truncateAt;
}
/**
* Returns a summarized message body.
*/
public function summarize(MessageInterface $message): ?string
{
return $this->truncateAt === null
? Psr7\Message::bodySummary($message)
: Psr7\Message::bodySummary($message, $this->truncateAt);
}
}
@@ -0,0 +1,13 @@
<?php
namespace GuzzleHttp;
use Psr\Http\Message\MessageInterface;
interface BodySummarizerInterface
{
/**
* Returns a summarized message body.
*/
public function summarize(MessageInterface $message): ?string;
}
@@ -0,0 +1,84 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* Client interface for sending HTTP requests.
*/
interface ClientInterface
{
/**
* The Guzzle major version.
*/
public const MAJOR_VERSION = 7;
/**
* Send an HTTP request.
*
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
*
* @throws GuzzleException
*/
public function send(RequestInterface $request, array $options = []): ResponseInterface;
/**
* Asynchronously send an HTTP request.
*
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
*/
public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface;
/**
* Create and send an HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string $method HTTP method.
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function request(string $method, $uri, array $options = []): ResponseInterface;
/**
* Create and send an asynchronous HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function requestAsync(string $method, $uri, array $options = []): PromiseInterface;
/**
* Get a client configuration option.
*
* These options include default request options of the client, a "handler"
* (if utilized by the concrete client), and a "base_uri" if utilized by
* the concrete client.
*
* @param string|null $option The config option to retrieve.
*
* @return mixed
*
* @deprecated ClientInterface::getConfig will be removed in guzzlehttp/guzzle:8.0.
*/
public function getConfig(?string $option = null);
}
@@ -0,0 +1,241 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* Client interface for sending HTTP requests.
*/
trait ClientTrait
{
/**
* Create and send an HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string $method HTTP method.
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
abstract public function request(string $method, $uri, array $options = []): ResponseInterface;
/**
* Create and send an HTTP GET request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function get($uri, array $options = []): ResponseInterface
{
return $this->request('GET', $uri, $options);
}
/**
* Create and send an HTTP HEAD request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function head($uri, array $options = []): ResponseInterface
{
return $this->request('HEAD', $uri, $options);
}
/**
* Create and send an HTTP PUT request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function put($uri, array $options = []): ResponseInterface
{
return $this->request('PUT', $uri, $options);
}
/**
* Create and send an HTTP POST request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function post($uri, array $options = []): ResponseInterface
{
return $this->request('POST', $uri, $options);
}
/**
* Create and send an HTTP PATCH request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function patch($uri, array $options = []): ResponseInterface
{
return $this->request('PATCH', $uri, $options);
}
/**
* Create and send an HTTP DELETE request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*
* @throws GuzzleException
*/
public function delete($uri, array $options = []): ResponseInterface
{
return $this->request('DELETE', $uri, $options);
}
/**
* Create and send an asynchronous HTTP request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
abstract public function requestAsync(string $method, $uri, array $options = []): PromiseInterface;
/**
* Create and send an asynchronous HTTP GET request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function getAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('GET', $uri, $options);
}
/**
* Create and send an asynchronous HTTP HEAD request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function headAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('HEAD', $uri, $options);
}
/**
* Create and send an asynchronous HTTP PUT request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function putAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('PUT', $uri, $options);
}
/**
* Create and send an asynchronous HTTP POST request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function postAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('POST', $uri, $options);
}
/**
* Create and send an asynchronous HTTP PATCH request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function patchAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('PATCH', $uri, $options);
}
/**
* Create and send an asynchronous HTTP DELETE request.
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
*
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
*/
public function deleteAsync($uri, array $options = []): PromiseInterface
{
return $this->requestAsync('DELETE', $uri, $options);
}
}
@@ -0,0 +1,378 @@
<?php
namespace GuzzleHttp\Cookie;
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 $cookies = [];
/**
* @var bool
*/
private $strictMode;
/**
* @param bool $strictMode Set to true to throw exceptions when invalid
* cookies are added to the cookie jar.
* @param array $cookieArray Array of SetCookie objects or a hash of
* arrays that can be used with the SetCookie
* constructor
*/
public function __construct(bool $strictMode = false, array $cookieArray = [])
{
$this->strictMode = $strictMode;
foreach ($cookieArray as $cookie) {
if (!$cookie instanceof SetCookie) {
$cookie = new SetCookie($cookie);
}
$this->setCookie($cookie);
}
}
/**
* Create a new Cookie jar from an associative array and domain.
*
* @param array $cookies Cookies to create the jar from
* @param string $domain Domain to set the cookies to
*/
public static function fromArray(array $cookies, string $domain): self
{
$cookieJar = new self();
foreach ($cookies as $name => $value) {
$cookieJar->setCookie(new SetCookie([
'Domain' => $domain,
'Name' => $name,
'Value' => $value,
'Discard' => true,
]));
}
return $cookieJar;
}
/**
* Evaluate if this cookie should be persisted to storage
* that survives between requests.
*
* @param SetCookie $cookie Being evaluated.
* @param bool $allowSessionCookies If we should persist session cookies
*/
public static function shouldPersist(SetCookie $cookie, bool $allowSessionCookies = false): bool
{
if ($cookie->getExpires() || $allowSessionCookies) {
if (!$cookie->getDiscard()) {
return true;
}
}
return false;
}
/**
* Finds and returns the cookie based on the name
*
* @param string $name cookie name to search for
*
* @return SetCookie|null cookie that was found or null if not found
*/
public function getCookieByName(string $name): ?SetCookie
{
foreach ($this->cookies as $cookie) {
if ($cookie->getName() !== null && Psr7\Utils::caselessEquals($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) {
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(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) {
if ($cookie->getDomain() !== null) {
$this->removeCookie($cookie);
}
return false;
}
// Resolve conflicts with previously set cookies
foreach ($this->cookies as $i => $c) {
// Two cookies are identical, when their path, and domain are
// identical.
if ($c->getPath() !== $cookie->getPath()
|| $c->getDomain() !== $cookie->getDomain()
|| $c->getHostOnly() !== $cookie->getHostOnly()
|| $c->getName() !== $cookie->getName()
) {
continue;
}
// The previously set cookie is a discard cookie and this one is
// not so allow the new cookie to be set
if (!$cookie->getDiscard() && $c->getDiscard()) {
unset($this->cookies[$i]);
continue;
}
// If the new cookie's expiration is further into the future, then
// replace the old cookie
if ($cookie->getExpires() > $c->getExpires()) {
unset($this->cookies[$i]);
continue;
}
// If the value has changed, we better change it
if ($cookie->getValue() !== $c->getValue()) {
unset($this->cookies[$i]);
continue;
}
// The cookie exists, so no need to continue
return false;
}
$this->cookies[] = $cookie;
return true;
}
public function count(): int
{
return \count($this->cookies);
}
/**
* @return \ArrayIterator<int, SetCookie>
*/
public function getIterator(): \ArrayIterator
{
return new \ArrayIterator(\array_values($this->cookies));
}
public function extractCookies(RequestInterface $request, ResponseInterface $response): void
{
if ($cookieHeader = $response->getHeader('Set-Cookie')) {
$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($request->getUri()->getHost());
$sc->setHostOnly(true);
} elseif (\substr($domain, -1) === '.' && '' !== \trim($domain, '.')) {
// Keep pure-dot domains rejected by the dot-only fix.
$sc->setDomain($request->getUri()->getHost());
$sc->setHostOnly(true);
} else {
$sc->setHostOnly(false);
}
if (0 !== \strpos($sc->getPath(), '/')) {
$sc->setPath($this->getCookiePathFromRequest($request));
}
if (!$sc->matchesDomain($request->getUri()->getHost())) {
continue;
}
// Note: At this point `$sc->getDomain()` being a public suffix should
// be rejected, but we don't want to pull in the full PSL dependency.
if ($this->setCookie($sc) && ++$accepted === self::MAX_SET_COOKIE_FIELDS) {
break;
}
}
}
}
/**
* Computes cookie path following RFC 6265 section 5.1.4
*
* @see https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4
*/
private function getCookiePathFromRequest(RequestInterface $request): string
{
$uriPath = $request->getUri()->getPath();
if ('' === $uriPath) {
return '/';
}
if (0 !== \strpos($uriPath, '/')) {
return '/';
}
if ('/' === $uriPath) {
return '/';
}
$lastSlashPos = \strrpos($uriPath, '/');
if (0 === $lastSlashPos || false === $lastSlashPos) {
return '/';
}
return \substr($uriPath, 0, $lastSlashPos);
}
public function withCookieHeader(RequestInterface $request): RequestInterface
{
$values = [];
$headerLength = 8;
$uri = $request->getUri();
$scheme = $uri->getScheme();
$host = $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[] = $name.'='.$value;
$headerLength += $separatorLength + $valueLength;
if (\count($values) === self::MAX_REQUEST_COOKIES) {
break;
}
}
}
return $values
? $request->withHeader('Cookie', \implode('; ', $values))
: $request;
}
/**
* If a cookie already exists and the server asks to set it again with a
* null value, the cookie must be deleted.
*/
private function removeCookieIfEmpty(SetCookie $cookie): void
{
$cookieValue = $cookie->getValue();
if (($cookieValue === null || $cookieValue === '') && $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()
&& self::cookieDomainsEqual($stored->getDomain(), $cookie->getDomain())
&& $stored->getHostOnly() === $cookie->getHostOnly());
}
);
}
private static function cookieDomainsEqual(?string $first, ?string $second): bool
{
if ($first === null || $second === null) {
return $first === $second;
}
if (isset($first[0]) && $first[0] === '.') {
$first = \substr($first, 1);
}
if (isset($second[0]) && $second[0] === '.') {
$second = \substr($second, 1);
}
return Psr7\Utils::caselessEquals($first, $second);
}
}
@@ -0,0 +1,80 @@
<?php
namespace GuzzleHttp\Cookie;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Stores HTTP cookies.
*
* It extracts cookies from HTTP requests, and returns them in HTTP responses.
* CookieJarInterface instances automatically expire contained cookies when
* necessary. Subclasses are also responsible for storing and retrieving
* cookies from a file, database, etc.
*
* @see https://docs.python.org/2/library/cookielib.html Inspiration
*
* @extends \IteratorAggregate<SetCookie>
*/
interface CookieJarInterface extends \Countable, \IteratorAggregate
{
/**
* Create a request with added cookie headers.
*
* If no matching cookies are found in the cookie jar, then no Cookie
* header is added to the request and the same request is returned.
*
* @param RequestInterface $request Request object to modify.
*
* @return RequestInterface returns the modified request.
*/
public function withCookieHeader(RequestInterface $request): RequestInterface;
/**
* Extract cookies from an HTTP response and store them in the CookieJar.
*
* @param RequestInterface $request Request that was sent
* @param ResponseInterface $response Response that was received
*/
public function extractCookies(RequestInterface $request, ResponseInterface $response): void;
/**
* Sets a cookie in the cookie jar.
*
* @param SetCookie $cookie Cookie to set.
*
* @return bool Returns true on success or false on failure
*/
public function setCookie(SetCookie $cookie): bool;
/**
* Remove cookies currently held in the cookie jar.
*
* Invoking this method without arguments will empty the whole cookie jar.
* If given a $domain argument only cookies belonging to that domain will
* be removed. If given a $domain and $path argument, cookies belonging to
* the specified path within that domain are removed. If given all three
* arguments, then the cookie with the specified name, path and domain is
* removed.
*
* @param string|null $domain Clears cookies matching a domain
* @param string|null $path Clears cookies matching a domain and path
* @param string|null $name Clears cookies matching a domain, path, and name
*/
public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void;
/**
* Discard all sessions cookies.
*
* Removes cookies that don't have an expire field or a have a discard
* field set to true. To be called when the user agent shuts down according
* to RFC 2965.
*/
public function clearSessionCookies(): void;
/**
* Converts the cookie jar to an array.
*/
public function toArray(): array;
}
@@ -0,0 +1,121 @@
<?php
namespace GuzzleHttp\Cookie;
use GuzzleHttp\Exception\InvalidArgumentException;
/**
* Persists non-session cookies using a JSON formatted file
*/
class FileCookieJar extends CookieJar
{
/**
* @var string filename
*/
private $filename;
/**
* @var bool Control whether to persist session cookies or not.
*/
private $storeSessionCookies;
/**
* Create a new FileCookieJar object
*
* @param string $cookieFile File to store the cookie data
* @param bool $storeSessionCookies Set to true to store session cookies
* in the cookie jar.
*
* @throws \RuntimeException if the file cannot be found or created
*/
public function __construct(string $cookieFile, bool $storeSessionCookies = false)
{
parent::__construct();
$this->filename = $cookieFile;
$this->storeSessionCookies = $storeSessionCookies;
if (\file_exists($cookieFile)) {
$this->load($cookieFile);
}
}
/**
* Saves the file when shutting down
*/
public function __destruct()
{
$this->save($this->filename);
}
/**
* Saves the cookies to a file.
*
* @param string $filename File to save
*
* @throws \RuntimeException if the file cannot be found or created
*/
public function save(string $filename): void
{
$json = [];
/** @var SetCookie $cookie */
foreach ($this as $cookie) {
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
$data = $cookie->toArray();
$data['HostOnly'] = $cookie->getHostOnly();
$json[] = $data;
}
}
$jsonStr = \json_encode($json);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_encode error: '.\json_last_error_msg());
}
/** @var non-empty-string $jsonStr */
if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) {
throw new \RuntimeException("Unable to save file {$filename}");
}
}
/**
* Load cookies from a JSON formatted file.
*
* Old cookies are kept unless overwritten by newly loaded ones.
*
* @param string $filename Cookie file to load.
*
* @throws \RuntimeException if the file cannot be loaded.
*/
public function load(string $filename): void
{
$json = \file_get_contents($filename);
if (false === $json) {
throw new \RuntimeException("Unable to load file {$filename}");
}
if ($json === '') {
return;
}
$data = \json_decode($json, true);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_decode error: '.\json_last_error_msg());
}
if (\is_array($data)) {
$cookies = [];
foreach ($data as $cookie) {
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
throw new \RuntimeException("Invalid cookie file: {$filename}");
}
$cookies[] = new SetCookie($cookie);
}
foreach ($cookies as $cookie) {
$this->setCookie($cookie);
}
} elseif (\is_scalar($data) && !empty($data)) {
throw new \RuntimeException("Invalid cookie file: {$filename}");
}
}
}
@@ -0,0 +1,99 @@
<?php
namespace GuzzleHttp\Cookie;
/**
* Persists cookies in the client session
*/
class SessionCookieJar extends CookieJar
{
/**
* @var string session key
*/
private $sessionKey;
/**
* @var bool Control whether to persist session cookies or not.
*/
private $storeSessionCookies;
/**
* Create a new SessionCookieJar object
*
* @param string $sessionKey Session key name to store the cookie
* data in session
* @param bool $storeSessionCookies Set to true to store session cookies
* in the cookie jar.
*/
public function __construct(string $sessionKey, bool $storeSessionCookies = false)
{
parent::__construct();
$this->sessionKey = $sessionKey;
$this->storeSessionCookies = $storeSessionCookies;
$this->load();
}
/**
* Saves cookies to session when shutting down
*/
public function __destruct()
{
$this->save();
}
/**
* Save cookies to the client session
*/
public function save(): void
{
$json = [];
/** @var SetCookie $cookie */
foreach ($this as $cookie) {
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
$data = $cookie->toArray();
$data['HostOnly'] = $cookie->getHostOnly();
$json[] = $data;
}
}
$json = \json_encode($json);
if (false === $json) {
throw new \RuntimeException('Unable to encode cookie data');
}
$_SESSION[$this->sessionKey] = $json;
}
/**
* Load the contents of the client session into the data array
*/
protected function load(): void
{
if (!isset($_SESSION[$this->sessionKey])) {
return;
}
$json = $_SESSION[$this->sessionKey];
if (!\is_string($json)) {
throw new \RuntimeException('Invalid cookie data');
}
$data = \json_decode($json, true);
if (\is_array($data)) {
$cookies = [];
foreach ($data as $cookie) {
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
throw new \RuntimeException('Invalid cookie data');
}
$cookies[] = new SetCookie($cookie);
}
foreach ($cookies as $cookie) {
$this->setCookie($cookie);
}
} elseif (\is_scalar($data) && \strlen((string) $data)) {
throw new \RuntimeException('Invalid cookie data');
}
}
}
@@ -0,0 +1,611 @@
<?php
namespace GuzzleHttp\Cookie;
use GuzzleHttp\Handler\HostValidator;
use GuzzleHttp\Psr7;
/**
* Set-Cookie object
*/
class SetCookie
{
/**
* @var array
*/
private static $defaults = [
'Name' => null,
'Value' => null,
'Domain' => null,
'Path' => '/',
'Max-Age' => null,
'Expires' => null,
'Secure' => false,
'Discard' => false,
'HttpOnly' => false,
];
/**
* @var array Cookie data
*/
private $data;
/**
* @var bool Whether this cookie was set without a Domain attribute
*/
private $hostOnly = false;
/**
* Create a new SetCookie object from a string.
*
* @param string $cookie Set-Cookie header string
*/
public static function fromString(string $cookie): self
{
// Create the default return array
$data = self::$defaults;
// Explode the cookie string using a series of semicolons
$pieces = \array_filter(\array_map(static function (string $piece): string {
return \trim($piece, " \n\r\t\0\x0B");
}, \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], " \n\r\t\0\x0B");
$value = isset($cookieParts[1])
? \trim($cookieParts[1], " \n\r\t\0\x0B")
: true;
// Only check for non-cookies when cookies have been found
if (!isset($data['Name'])) {
$data['Name'] = $key;
$data['Value'] = $value;
} else {
foreach (\array_keys(self::$defaults) as $search) {
if (Psr7\Utils::caselessEquals($search, $key)) {
if ($search === 'Max-Age') {
if (is_numeric($value)) {
$data[$search] = (int) $value;
}
} elseif ($search === 'Secure' || $search === 'Discard' || $search === 'HttpOnly') {
if ($value) {
$data[$search] = true;
}
} else {
$data[$search] = $value;
}
continue 2;
}
}
if (Psr7\Utils::caselessEquals('HostOnly', $key)) {
continue;
}
$data[$key] = $value;
}
}
return new self($data);
}
/**
* @param array $data Array of cookie data provided by a Cookie parser
*/
public function __construct(array $data = [])
{
$this->data = self::$defaults;
if (\array_key_exists('HostOnly', $data)) {
if (!\is_bool($data['HostOnly'])) {
throw new \InvalidArgumentException('Cookie field "HostOnly" must be a boolean');
}
$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];
}
// Extract the Expires value and turn it into a UNIX timestamp if needed
$maxAge = $this->getMaxAge();
if (!$this->getExpires() && $maxAge !== null) {
// Calculate the Expires date
$this->setExpires(self::maxAgeToExpires($maxAge, \time()));
} elseif (null !== ($expires = $this->getExpires()) && !\is_numeric($expires)) {
$this->setExpires($expires);
}
}
private static function maxAgeToExpires(int $maxAge, int $now): int
{
if ($maxAge <= 0) {
return $now - 1;
}
if ($maxAge > \PHP_INT_MAX - $now) {
return \PHP_INT_MAX;
}
return $now + $maxAge;
}
public function __toString()
{
$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.
*
* @return string
*/
public function getName()
{
return $this->data['Name'];
}
/**
* Set the cookie name.
*
* @param string $name Cookie name
*/
public function setName($name): void
{
if (!is_string($name)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Name'] = (string) $name;
}
/**
* Get the cookie value.
*
* @return string|null
*/
public function getValue()
{
return $this->data['Value'];
}
/**
* Set the cookie value.
*
* @param string $value Cookie value
*/
public function setValue($value): void
{
if (!is_string($value)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Value'] = (string) $value;
}
/**
* Get the domain.
*
* @return string|null
*/
public function getDomain()
{
return $this->data['Domain'];
}
/**
* Set the domain of the cookie.
*
* @param string|null $domain
*/
public function setDomain($domain): void
{
if (!is_string($domain) && null !== $domain) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Domain'] = null === $domain ? null : (string) $domain;
}
/**
* Get whether this cookie is scoped to the origin host only.
*
* @return bool
*/
public function getHostOnly()
{
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.
*
* @return string
*/
public function getPath()
{
return $this->data['Path'];
}
/**
* Set the path of the cookie.
*
* @param string $path Path of the cookie
*/
public function setPath($path): void
{
if (!is_string($path)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Path'] = (string) $path;
}
/**
* Maximum lifetime of the cookie in seconds.
*
* @return int|null
*/
public function getMaxAge()
{
return null === $this->data['Max-Age'] ? null : (int) $this->data['Max-Age'];
}
/**
* Set the max-age of the cookie.
*
* @param int|null $maxAge Max age of the cookie in seconds
*/
public function setMaxAge($maxAge): void
{
if (!is_int($maxAge) && null !== $maxAge) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Max-Age'] = $maxAge === null ? null : (int) $maxAge;
}
/**
* The UNIX timestamp when the cookie Expires.
*
* @return string|int|null
*/
public function getExpires()
{
return $this->data['Expires'];
}
/**
* Set the unix timestamp for which the cookie will expire.
*
* @param int|string|null $timestamp Unix timestamp or any English textual datetime description.
*/
public function setExpires($timestamp): void
{
if (!is_int($timestamp) && !is_string($timestamp) && null !== $timestamp) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int, string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
if (null === $timestamp) {
$this->data['Expires'] = null;
} elseif (\is_numeric($timestamp)) {
$this->data['Expires'] = (int) $timestamp;
} else {
// Store unparseable dates as session cookies, not as expired cookies.
$expires = \strtotime((string) $timestamp);
$this->data['Expires'] = $expires === false ? null : $expires;
}
}
/**
* Get whether or not this is a secure cookie.
*
* @return bool
*/
public function getSecure()
{
return $this->data['Secure'];
}
/**
* Set whether or not the cookie is secure.
*
* @param bool $secure Set to true or false if secure
*/
public function setSecure($secure): void
{
if (!is_bool($secure)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Secure'] = (bool) $secure;
}
/**
* Get whether or not this is a session cookie.
*
* @return bool|null
*/
public function getDiscard()
{
return $this->data['Discard'];
}
/**
* Set whether or not this is a session cookie.
*
* @param bool $discard Set to true or false if this is a session cookie
*/
public function setDiscard($discard): void
{
if (!is_bool($discard)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Discard'] = (bool) $discard;
}
/**
* Get whether or not this is an HTTP only cookie.
*
* @return bool
*/
public function getHttpOnly()
{
return $this->data['HttpOnly'];
}
/**
* Set whether or not this is an HTTP only cookie.
*
* @param bool $httpOnly Set to true or false if this is HTTP only
*/
public function setHttpOnly($httpOnly): void
{
if (!is_bool($httpOnly)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['HttpOnly'] = (bool) $httpOnly;
}
/**
* Check if the cookie matches a path value.
*
* A request-path path-matches a given cookie-path if at least one of
* the following conditions holds:
*
* - The cookie-path and the request-path are identical.
* - The cookie-path is a prefix of the request-path, and the last
* character of the cookie-path is %x2F ("/").
* - The cookie-path is a prefix of the request-path, and the first
* character of the request-path that is not included in the cookie-
* path is a %x2F ("/") character.
*
* @param string $requestPath Path to check against
*/
public function matchesPath(string $requestPath): bool
{
$cookiePath = $this->getPath();
// Match on exact matches or when path is the default empty "/"
if ($cookiePath === '/' || $cookiePath === $requestPath) {
return true;
}
// Ensure that the cookie-path is a prefix of the request path.
if (0 !== \strpos($requestPath, $cookiePath)) {
return false;
}
// Match if the last character of the cookie-path is "/"
if (\substr($cookiePath, -1, 1) === '/') {
return true;
}
// Match if the first character not included in cookie path is "/"
return \substr($requestPath, \strlen($cookiePath), 1) === '/';
}
/**
* Check if the cookie matches a domain value.
*
* @param string $domain Domain to check against
*/
public function matchesDomain(string $domain): bool
{
$cookieDomain = $this->getDomain();
if (null === $cookieDomain) {
return !$this->getHostOnly();
}
if ($this->getHostOnly()) {
return Psr7\Utils::asciiToLower($domain) === Psr7\Utils::asciiToLower($cookieDomain);
}
// Remove the leading '.' as per spec in RFC 6265.
// https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.3
$cookieDomain = Psr7\Utils::asciiToLower($cookieDomain);
if ($cookieDomain !== '' && $cookieDomain[0] === '.') {
/** @var string */
$cookieDomain = \substr($cookieDomain, 1);
}
if ('' === $cookieDomain) {
return false;
}
$domain = Psr7\Utils::asciiToLower($domain);
if ($domain === $cookieDomain) {
return true;
}
// A percent-escaped cookie domain can decode to another host spelling.
// Keep it exact-match-only to avoid extending that host's cookie scope.
if (\strpos($cookieDomain, '%') !== false) {
return false;
}
// IP literals and numeric hosts are exact-match-only per RFC 6265.
// Only the exact match above may succeed for those cookie domains.
if (self::isIpAddressOrNumericHost($cookieDomain)) {
return false;
}
// Matching the subdomain according to RFC 6265.
// https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3
if (\filter_var($domain, \FILTER_VALIDATE_IP)) {
return false;
}
return (bool) \preg_match('/\.'.\preg_quote($cookieDomain, '/').'$/D', $domain);
}
private static function isIpAddressOrNumericHost(string $host): bool
{
// Strip one root dot before detection so trailing-dot numeric hosts
// still cannot be matched by subdomains.
if ($host !== '' && \str_ends_with($host, '.')) {
$host = \substr($host, 0, -1);
}
if (\str_starts_with($host, '[') && \str_ends_with($host, ']')) {
$host = \substr($host, 1, -1);
}
if (\filter_var($host, \FILTER_VALIDATE_IP) !== false) {
return true;
}
// Public DNS names do not have an all-numeric rightmost label; treat
// those private/internal hosts as exact-match-only too.
$labels = \explode('.', $host);
$last = (string) \end($labels);
if ($last !== '' && \ctype_digit($last)) {
return true;
}
// Apply the transport's decimal, octal and hexadecimal inet_aton-style
// grammar. Omitting range checks conservatively holds some names to an
// exact match.
return HostValidator::isNumericIpv4Host(\rtrim($host, '.'));
}
/**
* Check if the cookie is expired.
*/
public function isExpired(): bool
{
return $this->getExpires() !== null && \time() > $this->getExpires();
}
/**
* Check if the cookie is valid according to RFC 6265.
*
* @return bool|string Returns true if valid or an error message if invalid
*/
public function validate()
{
$name = $this->getName();
if ($name === '') {
return 'The cookie name must not be empty';
}
// Check if any of the invalid characters are present in the cookie name
if (\preg_match('/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', $name) !== 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 === '' || (null !== $domain && '' === \ltrim(\trim($domain, " \n\r\t\0\x0B"), '.'))) {
return 'The cookie domain must not be empty';
}
return true;
}
}
@@ -0,0 +1,39 @@
<?php
namespace GuzzleHttp\Exception;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Exception when an HTTP error occurs (4xx or 5xx error)
*/
class BadResponseException extends RequestException
{
public function __construct(
string $message,
RequestInterface $request,
ResponseInterface $response,
?\Throwable $previous = null,
array $handlerContext = []
) {
parent::__construct($message, $request, $response, $previous, $handlerContext);
}
/**
* Current exception and the ones that extend it will always have a response.
*/
public function hasResponse(): bool
{
return true;
}
/**
* This function narrows the return type from the parent class and does not allow it to be nullable.
*/
public function getResponse(): ResponseInterface
{
/** @var ResponseInterface */
return parent::getResponse();
}
}
@@ -0,0 +1,10 @@
<?php
namespace GuzzleHttp\Exception;
/**
* Exception when a client error is encountered (4xx codes)
*/
class ClientException extends BadResponseException
{
}
@@ -0,0 +1,54 @@
<?php
namespace GuzzleHttp\Exception;
use Psr\Http\Client\NetworkExceptionInterface;
use Psr\Http\Message\RequestInterface;
/**
* Exception thrown when a connection cannot be established.
*/
class ConnectException extends TransferException implements NetworkExceptionInterface
{
/**
* @var RequestInterface
*/
private $request;
/**
* @var array
*/
private $handlerContext;
public function __construct(
string $message,
RequestInterface $request,
?\Throwable $previous = null,
array $handlerContext = []
) {
parent::__construct($message, 0, $previous);
$this->request = $request;
$this->handlerContext = $handlerContext;
}
/**
* Get the request that caused the exception
*/
public function getRequest(): RequestInterface
{
return $this->request;
}
/**
* Get contextual information about the error from the underlying handler.
*
* The contents of this array will vary depending on which handler you are
* using. It may also be just an empty array. Relying on this data will
* couple you to a specific handler, but can give more debug information
* when needed.
*/
public function getHandlerContext(): array
{
return $this->handlerContext;
}
}
@@ -0,0 +1,9 @@
<?php
namespace GuzzleHttp\Exception;
use Psr\Http\Client\ClientExceptionInterface;
interface GuzzleException extends ClientExceptionInterface
{
}
@@ -0,0 +1,7 @@
<?php
namespace GuzzleHttp\Exception;
final class InvalidArgumentException extends \InvalidArgumentException implements GuzzleException
{
}
@@ -0,0 +1,154 @@
<?php
namespace GuzzleHttp\Exception;
use GuzzleHttp\BodySummarizer;
use GuzzleHttp\BodySummarizerInterface;
use Psr\Http\Client\RequestExceptionInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* HTTP Request exception
*/
class RequestException extends TransferException implements RequestExceptionInterface
{
/**
* @var RequestInterface
*/
private $request;
/**
* @var ResponseInterface|null
*/
private $response;
/**
* @var array
*/
private $handlerContext;
public function __construct(
string $message,
RequestInterface $request,
?ResponseInterface $response = null,
?\Throwable $previous = null,
array $handlerContext = []
) {
// Set the code of the exception if the response is set and not future.
$code = $response ? $response->getStatusCode() : 0;
parent::__construct($message, $code, $previous);
$this->request = $request;
$this->response = $response;
$this->handlerContext = $handlerContext;
}
/**
* Wrap non-RequestExceptions with a RequestException
*
* @deprecated since 7.11. Create a RequestException directly instead.
*/
public static function wrapException(RequestInterface $request, \Throwable $e): RequestException
{
\trigger_deprecation('guzzlehttp/guzzle', '7.11', '%s::wrapException() is deprecated and will be removed in 8.0. Create a %s directly instead.', self::class, self::class);
return $e instanceof RequestException ? $e : new RequestException($e->getMessage(), $request, null, $e);
}
/**
* Factory method to create a new exception with a normalized error message
*
* @param RequestInterface $request Request sent
* @param ResponseInterface $response Response received
* @param \Throwable|null $previous Previous exception
* @param array $handlerContext Optional handler context
* @param BodySummarizerInterface|null $bodySummarizer Optional body summarizer
*/
public static function create(
RequestInterface $request,
?ResponseInterface $response = null,
?\Throwable $previous = null,
array $handlerContext = [],
?BodySummarizerInterface $bodySummarizer = null
): self {
if (!$response) {
return new self(
'Error completing request',
$request,
null,
$previous,
$handlerContext
);
}
$level = (int) \floor($response->getStatusCode() / 100);
if ($level === 4) {
$label = 'Client error';
$className = ClientException::class;
} elseif ($level === 5) {
$label = 'Server error';
$className = ServerException::class;
} else {
$label = 'Unsuccessful request';
$className = __CLASS__;
}
$uri = \GuzzleHttp\Psr7\Utils::redactUserInfo($request->getUri());
// Client Error: `GET /` resulted in a `404 Not Found` response:
// <html> ... (truncated)
$message = \sprintf(
'%s: `%s %s` resulted in a `%s %s` response',
$label,
$request->getMethod(),
$uri->__toString(),
$response->getStatusCode(),
$response->getReasonPhrase()
);
$summary = ($bodySummarizer ?? new BodySummarizer())->summarize($response);
if ($summary !== null) {
$message .= ":\n{$summary}\n";
}
return new $className($message, $request, $response, $previous, $handlerContext);
}
/**
* Get the request that caused the exception
*/
public function getRequest(): RequestInterface
{
return $this->request;
}
/**
* Get the associated response
*/
public function getResponse(): ?ResponseInterface
{
return $this->response;
}
/**
* Check if a response was received
*/
public function hasResponse(): bool
{
return $this->response !== null;
}
/**
* Get contextual information about the error from the underlying handler.
*
* The contents of this array will vary depending on which handler you are
* using. It may also be just an empty array. Relying on this data will
* couple you to a specific handler, but can give more debug information
* when needed.
*/
public function getHandlerContext(): array
{
return $this->handlerContext;
}
}
@@ -0,0 +1,10 @@
<?php
namespace GuzzleHttp\Exception;
/**
* Exception when a server error is encountered (5xx codes)
*/
class ServerException extends BadResponseException
{
}
@@ -0,0 +1,7 @@
<?php
namespace GuzzleHttp\Exception;
class TooManyRedirectsException extends RequestException
{
}
@@ -0,0 +1,7 @@
<?php
namespace GuzzleHttp\Exception;
class TransferException extends \RuntimeException implements GuzzleException
{
}
@@ -0,0 +1,25 @@
<?php
namespace GuzzleHttp\Handler;
use Psr\Http\Message\RequestInterface;
interface CurlFactoryInterface
{
/**
* Creates a cURL handle resource.
*
* @param RequestInterface $request Request
* @param array $options Transfer options
*
* @throws \RuntimeException when an option cannot be applied
*/
public function create(RequestInterface $request, array $options): EasyHandle;
/**
* Release an easy handle, allowing it to be reused or closed.
*
* This function must call unset on the easy handle's "handle" property.
*/
public function release(EasyHandle $easy): void;
}
@@ -0,0 +1,90 @@
<?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\TransportSharing;
use Psr\Http\Message\RequestInterface;
/**
* HTTP handler that uses cURL easy handles as a transport layer.
*
* When using the CurlHandler, custom curl options can be specified as an
* associative array of curl option constants mapping to values in the
* **curl** key of the "client" key of the request.
*
* @final
*/
class CurlHandler
{
private const KNOWN_CONSTRUCTOR_OPTIONS = [
'handle_factory' => true,
'transport_sharing' => true,
];
/**
* @var CurlFactoryInterface
*/
private $factory;
/**
* @var CurlShareHandleState|null
*/
private $shareHandleState;
/**
* Accepts an associative array of options:
*
* - handle_factory: Optional curl factory used to create cURL handles.
* - transport_sharing: Optional transport sharing mode.
*
* @param array{handle_factory?: ?CurlFactoryInterface, 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])) {
\trigger_deprecation('guzzlehttp/guzzle', '7.14', \sprintf('The "%s" CurlHandler constructor option is unknown; guzzlehttp/guzzle 8.0 will reject unknown constructor options.', (string) $name));
}
}
CurlShareHandleState::assertNoRequiredSharingCustomFactoryConflict($options, 'CurlHandler');
$transportSharing = $options['transport_sharing'] ?? null;
$sharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing');
if (\array_key_exists('handle_factory', $options) && $options['handle_factory'] !== null) {
$this->shareHandleState = null;
$this->factory = $options['handle_factory'];
return;
}
$this->shareHandleState = $sharingMode !== TransportSharing::NONE
? CurlShareHandleState::fromOption($transportSharing)
: null;
$this->factory = $this->shareHandleState !== null
? new CurlFactory(3, $this->shareHandleState->mode, $this->shareHandleState)
: new CurlFactory(3);
}
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
HostValidator::assertRequestHost($request);
if (isset($options['delay'])) {
\usleep($options['delay'] * 1000);
}
// A Multiplexing::NONE request option holds unconditionally here:
// transport sharing never shares the connection cache on this
// branch, and nothing else executes during the blocking curl_exec(),
// so the transfer cannot share 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);
}
}
@@ -0,0 +1,182 @@
<?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\TransportSharing;
/**
* @internal
*/
final class CurlShareHandleState
{
/**
* @var resource|\CurlShareHandle|null
*/
public $handle;
/**
* @var string
*/
public $mode;
/**
* @param resource|\CurlShareHandle|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);
}
return self::createHandlerShare($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) {
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 ($mode !== TransportSharing::HANDLER_REQUIRE) {
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
));
}
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);
}
/**
* @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;
}
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,322 @@
<?php
namespace GuzzleHttp\Handler;
/**
* @internal
*/
final class CurlVersion
{
private const MIN_VERSION = '7.21.2';
private const TLS_12_VERSION = '7.34.0';
private const TLS_13_VERSION = '7.52.0';
private const CONNECTION_CAP_VERSION = '7.30.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 request could silently be sent over a reused HTTP/1.1
// connection.
private const REQUIRED_MULTIPLEX_VERSION = '8.14.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.
private const HTTPS_PROXY_VERSION = '7.52.0';
private const HANDLER_SHARING_VERSION = '7.35.0';
private const SSL_SESSION_SHARING_VERSION = '8.6.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.
private const SHARE_CONNECTION_CACHE_VERSION = '7.57.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';
/**
* @var array{version: string, features: int}|false|null
*/
private static $versionInfo;
private function __construct()
{
}
public static function supportsCurlHandler(): bool
{
$version = self::getVersion();
return $version !== null && \version_compare($version, self::MIN_VERSION, '>=');
}
public static function supportsTls12(): bool
{
$version = self::getVersion();
return self::supportsSsl()
&& \defined('CURL_SSLVERSION_TLSv1_2')
&& $version !== null
&& \version_compare($version, self::TLS_12_VERSION, '>=');
}
public static function supportsTls13(): bool
{
$version = self::getVersion();
return self::supportsSsl()
&& \defined('CURL_SSLVERSION_TLSv1_3')
&& $version !== null
&& \version_compare($version, self::TLS_13_VERSION, '>=');
}
public static function supportsHttp2(): bool
{
$versionInfo = self::getVersionInfo();
return self::supportsTls12()
&& \defined('CURL_VERSION_HTTP2')
&& $versionInfo !== null
&& 0 !== (\CURL_VERSION_HTTP2 & $versionInfo['features']);
}
public static function supportsMultiplex(): bool
{
$version = self::getVersion();
return \defined('CURLOPT_PIPEWAIT')
&& $version !== null
&& \version_compare($version, self::MULTIPLEX_VERSION, '>=');
}
public static function supportsHttpVersionReuseMatching(): bool
{
$version = self::getVersion();
if ($version === null || \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 supportsConnectionCaps(): bool
{
$version = self::getVersion();
return \defined('CURLMOPT_MAX_HOST_CONNECTIONS')
&& \defined('CURLMOPT_MAX_TOTAL_CONNECTIONS')
&& $version !== null
&& \version_compare($version, self::CONNECTION_CAP_VERSION, '>=');
}
public static function ensureConnectionCapsSupported(string $option): void
{
if (self::supportsConnectionCaps()) {
return;
}
throw new \InvalidArgumentException(\sprintf(
'The "%s" option requires PHP cURL support for CURLMOPT_MAX_HOST_CONNECTIONS and CURLMOPT_MAX_TOTAL_CONNECTIONS with libcurl %s or newer.',
$option,
self::CONNECTION_CAP_VERSION
));
}
public static function supportsRequiredMultiplex(): bool
{
$version = self::getVersion();
return \defined('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE')
&& $version !== null
&& self::supportsHttp2()
&& \version_compare($version, self::REQUIRED_MULTIPLEX_VERSION, '>=');
}
public static function supportsHttpsProxy(): bool
{
$versionInfo = self::getVersionInfo();
// CURL_VERSION_HTTPS_PROXY is not defined on every supported PHP
// version; fall back to the curl.h bit value.
$httpsProxyFeature = \defined('CURL_VERSION_HTTPS_PROXY') ? \CURL_VERSION_HTTPS_PROXY : (1 << 21);
return $versionInfo !== null
&& \version_compare($versionInfo['version'], self::HTTPS_PROXY_VERSION, '>=')
&& 0 !== ($httpsProxyFeature & $versionInfo['features']);
}
public static function supportsNtlm(): bool
{
$versionInfo = self::getVersionInfo();
// CURL_VERSION_NTLM is not defined on every supported PHP version; fall
// back to the curl.h bit value.
$ntlmFeature = \defined('CURL_VERSION_NTLM') ? \CURL_VERSION_NTLM : (1 << 4);
return \defined('CURLAUTH_NTLM')
&& $versionInfo !== null
&& 0 !== ($ntlmFeature & $versionInfo['features']);
}
public static function supportsHandlerSharing(): bool
{
$version = self::getVersion();
return $version !== null && \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
{
$version = self::getVersion();
return self::supportsSsl()
&& $version !== null
&& \version_compare($version, self::SSL_SESSION_SHARING_VERSION, '>=');
}
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 supportsShareConnectionCaches(): bool
{
$version = self::getVersion();
// An undetectable libcurl version is treated as capable so the
// opaque share safeguards fail closed.
return $version === null || \version_compare($version, self::SHARE_CONNECTION_CACHE_VERSION, '>=');
}
public static function supportsProxyTlsCredentialAwareConnectionReuse(): bool
{
$version = self::getVersion();
return $version !== null
&& \version_compare($version, self::PROXY_TLS_CREDENTIAL_REUSE_VERSION, '>=');
}
public static function supportsProxyCredentialAwareConnectionReuse(): bool
{
$version = self::getVersion();
return $version !== null
&& \version_compare($version, self::PROXY_CREDENTIAL_REUSE_VERSION, '>=');
}
public static function supportsSocksProxyCredentialAwareConnectionReuse(): bool
{
$version = self::getVersion();
return $version !== null
&& \version_compare($version, self::SOCKS_PROXY_CREDENTIAL_REUSE_VERSION, '>=');
}
public static function supportsProxyHeaderSeparation(): bool
{
$version = self::getVersion();
return $version !== null
&& \version_compare($version, self::PROXY_HEADER_SEPARATION_VERSION, '>=')
&& \defined('CURLOPT_PROXYHEADER')
&& \defined('CURLOPT_HEADEROPT')
&& \defined('CURLHEADER_SEPARATE');
}
private static function supportsSsl(): bool
{
$versionInfo = self::getVersionInfo();
return \defined('CURL_VERSION_SSL')
&& $versionInfo !== null
&& 0 !== (\CURL_VERSION_SSL & $versionInfo['features']);
}
public static function getVersion(): ?string
{
$versionInfo = self::getVersionInfo();
return $versionInfo === null ? null : $versionInfo['version'];
}
/**
* @return array{version: string, features: int}|null
*/
private static function getVersionInfo(): ?array
{
if (self::$versionInfo === null) {
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 self::$versionInfo === false ? null : self::$versionInfo;
}
}
@@ -0,0 +1,138 @@
<?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Utils;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
/**
* Represents a cURL easy handle and the data it populates.
*
* @internal
*/
final class EasyHandle
{
/**
* @var resource|\CurlHandle cURL resource
*/
public $handle;
/**
* @var StreamInterface Where data is being written
*/
public $sink;
/**
* @var array Received HTTP headers so far
*/
public $headers = [];
/**
* @var array Valid trailer lines, retained only when an on_trailers
* callback is configured
*/
public $trailers = [];
/**
* @var bool Whether this handle was configured with CURLOPT_PIPEWAIT
*/
public $usesPipewait = false;
/**
* @var ResponseInterface|null Received response (if any)
*/
public $response;
/**
* @var RequestInterface Request being sent
*/
public $request;
/**
* @var array Request options
*/
public $options = [];
/**
* @var int cURL error number (if any)
*/
public $errno = 0;
/**
* @var string|null Effective CURLOPT_PROXY value the handle was created with (if any)
*/
public $effectiveProxy;
/**
* Proxy tunnel or SOCKS proxy section signature for connection-reuse
* isolation, or null when the request does not require sectioning.
*
* @var string|null
*/
public $proxyTunnelSignature;
/**
* @var \Throwable|null Exception during on_headers (if any)
*/
public $onHeadersException;
/**
* @var \Throwable|null Exception during createResponse (if any)
*/
public $createResponseException;
/**
* Attach a response to the easy handle based on the received headers.
*
* @throws \RuntimeException if no headers have been received or the first
* header line is invalid.
*/
public function createResponse(): void
{
$this->response = null;
[$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($this->headers);
$normalizedKeys = Utils::normalizeHeaderKeys($headers);
if (isset($this->options['decode_content']) && $this->options['decode_content'] !== false && isset($normalizedKeys['content-encoding'])) {
$headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']];
unset($headers[$normalizedKeys['content-encoding']]);
if (isset($normalizedKeys['content-length'])) {
$headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']];
$bodyLength = (int) $this->sink->getSize();
if ($bodyLength) {
$headers[$normalizedKeys['content-length']] = [(string) $bodyLength];
} else {
unset($headers[$normalizedKeys['content-length']]);
}
}
}
// Attach a response to the easy handle with the parsed headers.
$this->response = new Response(
$status,
$headers,
$this->sink,
$ver,
$reason
);
}
/**
* @param string $name
*
* @return void
*
* @throws \BadMethodCallException
*/
public function __get($name)
{
$msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: '.$name;
throw new \BadMethodCallException($msg);
}
}
@@ -0,0 +1,97 @@
<?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Utils;
/**
* @internal
*/
final class HeaderProcessor
{
/**
* Returns the HTTP version, status code, reason phrase, and headers.
*
* @param string[] $headers
*
* @return array{0:string, 1:int, 2:?string, 3:array}
*
* @throws \RuntimeException
*/
public static function parseHeaders(array $headers): array
{
if ($headers === []) {
throw new \RuntimeException('Expected a non-empty array of header data');
}
$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);
$version = \explode('/', $parts[0])[1] ?? null;
if ($version === null) {
throw new \RuntimeException('HTTP version missing from header data');
}
$status = $parts[1] ?? null;
if ($status === null) {
throw new \RuntimeException('HTTP status code missing from header data');
}
if (!\preg_match('/^\d{3}$/D', $status)) {
throw new \RuntimeException('HTTP status code is invalid');
}
foreach ($headers as $header) {
if (\strpos($header, ':') === false) {
throw new \RuntimeException('HTTP header line is invalid');
}
}
return [$version, (int) $status, $parts[2] ?? null, Utils::headersFromLines($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;
}
/**
* @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,198 @@
<?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\RequestException;
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.
*
* The URI host and every Host header value must use printable ASCII without
* percent escapes. The URI host must also exclude authority delimiters and
* numeric-looking parts followed by trailing dots. Handlers reparse the URI
* but send the Host header as given, so ambiguous spellings can name
* different connection and request hosts.
*
* @throws RequestException
*/
public static function assertRequestHost(RequestInterface $request): void
{
$host = $request->getUri()->getHost();
self::assertUriHostValue($host, $request);
self::assertNoAuthorityDelimiter($host, $request);
self::assertNotADottedAddress($host, $request);
foreach ($request->getHeader('Host') as $value) {
self::assertHostHeaderValue((string) $value, $request);
}
}
/**
* @throws RequestException
*/
private static function assertUriHostValue(string $value, RequestInterface $request): void
{
if (!self::isPrintableAscii($value)) {
throw new RequestException(\sprintf('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.', self::escape($value)), $request);
}
if (\strpos($value, '%') !== false) {
throw new RequestException(\sprintf('The request URI host "%s" must not contain a percent escape, because a handler can decode it and then connect to a host that differs from the one the request names.', self::escape($value)), $request);
}
}
/**
* The Host header is sent rather than reparsed for the connection, so its
* diagnostics describe a request authority the caller did not write.
*
* @throws RequestException
*/
private static function assertHostHeaderValue(string $value, RequestInterface $request): void
{
if (!self::isPrintableAscii($value)) {
throw new RequestException(\sprintf('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.', self::escape($value)), $request);
}
if (\strpos($value, '%') !== false) {
throw new RequestException(\sprintf('The request Host header "%s" must not contain a percent escape, because an intermediary or an origin server can decode it and then read it as an authority that differs from the one the request names.', self::escape($value)), $request);
}
}
/**
* Matches the accepted shape positively so a PCRE failure rejects.
*/
private static function isPrintableAscii(string $value): bool
{
return \preg_match('/\A[\x21-\x7E]*\z/D', $value) === 1;
}
/**
* Rejects a delimiter the transport could treat as the end of the URI host.
*
* This mirrors GuzzleHttp\Psr7\Uri::assertValidHost() and only affects
* third-party UriInterface values. Host headers may carry a port and are
* sent verbatim.
*
* @throws RequestException
*/
private static function assertNoAuthorityDelimiter(string $host, RequestInterface $request): void
{
$message = 'The request URI host "%s" must not contain a URI authority delimiter, because a handler reparses the URI and can then connect to a host that differs from the one the request names.';
// Match the accepted shape positively so a PCRE engine failure rejects.
if (\preg_match('/\A[^\/?#@\\\\]*\z/D', $host) !== 1) {
throw new RequestException(\sprintf($message, self::escape($host)), $request);
}
if (\strpos($host, '[') !== false || \strpos($host, ']') !== false) {
if (\strpos($host, '[') !== 0 || \substr($host, -1) !== ']') {
throw new RequestException(\sprintf($message, self::escape($host)), $request);
}
return;
}
if (\strpos($host, ':') !== false) {
throw new RequestException(\sprintf($message, self::escape($host)), $request);
}
}
/**
* Rejects one to four numeric-looking parts followed by trailing dots.
*
* libcurl 8.21.0 drops a trailing dot from inet_aton-style numeric hosts
* before connecting, while other validators treat the input as a name.
* Testing the shape also rejects some out-of-range values that transports
* keep as names; isNumericIpv4Host() explains that fail-closed tradeoff.
* Plain numeric shorthand stays accepted.
*
* @throws RequestException
*/
private static function assertNotADottedAddress(string $host, RequestInterface $request): void
{
if (\substr($host, -1) !== '.') {
return;
}
if (!self::isNumericIpv4Host(\rtrim($host, '.'))) {
return;
}
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 value has the transport'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. No PCRE is used.
*/
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);
}
/**
* Escapes non-printable bytes as uppercase \xNN for safe diagnostics.
* Printable delimiters and dots stay visible. The result is not a
* reversible encoding.
*/
private static function escape(string $value): string
{
$escaped = '';
for ($offset = 0, $length = \strlen($value); $offset < $length; ++$offset) {
$byte = \ord($value[$offset]);
$escaped .= $byte >= 0x21 && $byte <= 0x7E ? $value[$offset] : \sprintf('\\x%02X', $byte);
}
return $escaped;
}
}
@@ -0,0 +1,211 @@
<?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\HandlerStack;
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 throw exceptions from a queue.
*
* @final
*/
class MockHandler implements \Countable
{
/**
* @var array
*/
private $queue = [];
/**
* @var RequestInterface|null
*/
private $lastRequest;
/**
* @var array
*/
private $lastOptions = [];
/**
* @var callable|null
*/
private $onFulfilled;
/**
* @var callable|null
*/
private $onRejected;
/**
* Creates a new MockHandler that uses the default handler stack list of
* middlewares.
*
* @param array|null $queue Array of responses, callables, or exceptions.
* @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled.
* @param callable|null $onRejected Callback to invoke when the return value is rejected.
*/
public static function createWithMiddleware(?array $queue = null, ?callable $onFulfilled = null, ?callable $onRejected = null): HandlerStack
{
return HandlerStack::create(new self($queue, $onFulfilled, $onRejected));
}
/**
* The passed in value must be an array of
* {@see ResponseInterface} objects, Exceptions,
* callables, or Promises.
*
* @param array<int, mixed>|null $queue The parameters to be passed to the append function, as an indexed array.
* @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled.
* @param callable|null $onRejected Callback to invoke when the return value is rejected.
*/
public function __construct(?array $queue = null, ?callable $onFulfilled = null, ?callable $onRejected = null)
{
$this->onFulfilled = $onFulfilled;
$this->onRejected = $onRejected;
if ($queue) {
// array_values included for BC
$this->append(...array_values($queue));
}
}
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
if (!$this->queue) {
throw new \OutOfBoundsException('Mock queue is empty');
}
if (isset($options['delay']) && \is_numeric($options['delay'])) {
\usleep((int) $options['delay'] * 1000);
}
$this->lastRequest = $request;
$this->lastOptions = $options;
$response = \array_shift($this->queue);
if (isset($options['on_headers'])) {
if (!\is_callable($options['on_headers'])) {
throw new \InvalidArgumentException('on_headers must be callable');
}
try {
$options['on_headers']($response);
} catch (\Exception $e) {
$msg = 'An error was encountered during the on_headers event';
$response = new RequestException($msg, $request, $response, $e);
}
}
if (\is_callable($response)) {
$response = $response($request, $options);
}
$response = $response instanceof \Throwable
? P\Create::rejectionFor($response)
: P\Create::promiseFor($response);
return $response->then(
function (?ResponseInterface $value) use ($request, $options) {
$this->invokeStats($request, $options, $value);
if ($this->onFulfilled) {
($this->onFulfilled)($value);
}
if ($value !== null && isset($options['sink'])) {
$contents = (string) $value->getBody();
$sink = $options['sink'];
if (\is_resource($sink)) {
\fwrite($sink, $contents);
} elseif (\is_string($sink)) {
\file_put_contents($sink, $contents);
} elseif ($sink instanceof StreamInterface) {
$sink->write($contents);
}
}
return $value;
},
function ($reason) use ($request, $options) {
$this->invokeStats($request, $options, null, $reason);
if ($this->onRejected) {
($this->onRejected)($reason);
}
return P\Create::rejectionFor($reason);
}
);
}
/**
* Adds one or more variadic requests, exceptions, callables, or promises
* to the queue.
*
* @param mixed ...$values
*/
public function append(...$values): void
{
foreach ($values as $value) {
if ($value instanceof ResponseInterface
|| $value instanceof \Throwable
|| $value instanceof PromiseInterface
|| \is_callable($value)
) {
$this->queue[] = $value;
} else {
throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found '.\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(
RequestInterface $request,
array $options,
?ResponseInterface $response = null,
$reason = null
): void {
if (isset($options['on_stats'])) {
$transferTime = $options['transfer_time'] ?? 0;
$stats = new TransferStats($request, $response, $transferTime, $reason);
($options['on_stats'])($stats);
}
}
}
@@ -0,0 +1,81 @@
<?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\RequestOptions;
use Psr\Http\Message\RequestInterface;
/**
* Provides basic proxies for handlers.
*
* @final
*/
class Proxy
{
/**
* Sends synchronous requests to a specific handler while sending all other
* requests to another handler.
*
* @param callable(RequestInterface, array): PromiseInterface $default Handler used for normal responses
* @param callable(RequestInterface, array): PromiseInterface $sync Handler used for synchronous responses.
*
* @return callable(RequestInterface, array): PromiseInterface Returns the composed handler.
*/
public static function wrapSync(callable $default, callable $sync): callable
{
return static function (RequestInterface $request, array $options) use ($default, $sync): PromiseInterface {
return empty($options[RequestOptions::SYNCHRONOUS]) ? $default($request, $options) : $sync($request, $options);
};
}
/**
* Sends streaming requests to a streaming compatible handler while sending
* all other requests to a default handler.
*
* This, for example, could be useful for taking advantage of the
* performance benefits of curl while still supporting true streaming
* through the StreamHandler.
*
* @param callable(RequestInterface, array): PromiseInterface $default Handler used for non-streaming responses
* @param callable(RequestInterface, array): PromiseInterface $streaming Handler used for streaming responses
*
* @return callable(RequestInterface, array): PromiseInterface Returns the composed handler.
*/
public static function wrapStreaming(callable $default, callable $streaming): callable
{
return static function (RequestInterface $request, array $options) use ($default, $streaming): PromiseInterface {
return empty($options['stream']) ? $default($request, $options) : $streaming($request, $options);
};
}
/**
* Sends requests to a fallback handler when the default cURL handler cannot
* honor TLS 1.2 selection.
*
* @param callable(RequestInterface, array): PromiseInterface $default
* @param callable(RequestInterface, array): PromiseInterface $fallback
*
* @return callable(RequestInterface, array): PromiseInterface Returns the composed handler.
*/
public static function wrapTlsFallback(callable $default, callable $fallback): callable
{
return static function (RequestInterface $request, array $options) use ($default, $fallback): PromiseInterface {
if (self::requiresTls12Fallback($options)) {
return $fallback($request, $options);
}
return $default($request, $options);
};
}
/**
* @param array<string, mixed> $options
*/
private static function requiresTls12Fallback(array $options): bool
{
return isset($options[RequestOptions::CRYPTO_METHOD])
&& $options[RequestOptions::CRYPTO_METHOD] === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
&& !CurlVersion::supportsTls12();
}
}
@@ -0,0 +1,121 @@
<?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Psr7;
/**
* Resolves proxy configuration from the process environment with the same
* semantics libcurl applies, so the cURL handlers can pin CURLOPT_PROXY and
* CURLOPT_NOPROXY explicitly and libcurl never reads the environment itself.
*
* @internal
*/
final class ProxyEnvironment
{
private function __construct()
{
}
/**
* 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.
*
* Mirrors libcurl's tokenization: entries may be separated by commas or
* blanks, and a single leading dot is ignored, so ".example.com" bypasses
* example.com and its subdomains exactly as a bare domain entry does.
*
* @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 !== '' && $entry[0] === '.') {
$entry = \substr($entry, 1);
}
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,84 @@
<?php
namespace GuzzleHttp\Handler;
/**
* @internal
*/
final class TlsVersion
{
/**
* @param mixed $value
*/
public static function ordinal(string $option, $value): int
{
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT) {
return 10;
}
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT) {
return 11;
}
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT) {
return 12;
}
if (\defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) {
return 13;
}
throw new \InvalidArgumentException(\sprintf('Invalid %s request option: unknown version provided', $option));
}
/**
* @param mixed $min
* @param mixed $max
*/
public static function assertRange($min, $max): void
{
if ($min === null || $max === null) {
return;
}
if (self::ordinal('crypto_method_max', $max) < self::ordinal('crypto_method', $min)) {
throw new \InvalidArgumentException('Invalid crypto_method_max request option: maximum TLS version must be greater than or equal to crypto_method');
}
}
/**
* @param mixed $value
*/
public static function streamProtocolVersion(string $option, $value): int
{
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT) {
return self::requireStreamProto('STREAM_CRYPTO_PROTO_TLSv1_0', $option);
}
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT) {
return self::requireStreamProto('STREAM_CRYPTO_PROTO_TLSv1_1', $option);
}
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT) {
return self::requireStreamProto('STREAM_CRYPTO_PROTO_TLSv1_2', $option);
}
if (\defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) {
return self::requireStreamProto('STREAM_CRYPTO_PROTO_TLSv1_3', $option);
}
throw new \InvalidArgumentException(\sprintf('Invalid %s request option: unknown version provided', $option));
}
/**
* Resolves a STREAM_CRYPTO_PROTO_* constant. The ssl.max_proto_version
* context option and these constants were added in PHP 7.3.0 (TLS 1.3 in
* 7.4.0); on older runtimes the option cannot be honored, so reject loudly.
*/
private static function requireStreamProto(string $constant, string $option): int
{
if (\defined($constant)) {
/** @var int */
return \constant($constant);
}
throw new \InvalidArgumentException(\sprintf(
'Invalid %s request option: maximum TLS version control is not supported by your version of PHP',
$option
));
}
}
@@ -0,0 +1,289 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Creates a composed Guzzle handler function by stacking middlewares on top of
* an HTTP handler function.
*
* @final
*/
class HandlerStack
{
/**
* @var (callable(RequestInterface, array): PromiseInterface)|null
*/
private $handler;
/**
* @var array{(callable(callable(RequestInterface, array): PromiseInterface): callable), (string|null)}[]
*/
private $stack = [];
/**
* @var (callable(RequestInterface, array): PromiseInterface)|null
*/
private $cached;
/**
* Creates a default handler stack that can be used by clients.
*
* The returned handler will wrap the provided handler or use the most
* appropriate default handler for your system. The returned HandlerStack has
* support for cookies, redirects, HTTP error exceptions, and preparing a body
* before sending.
*
* The returned handler stack can be passed to a client in the "handler"
* option.
*
* @param (callable(RequestInterface, array): PromiseInterface)|null $handler HTTP handler function to use with the stack. If no
* handler is provided, the best handler for your
* system will be utilized.
*/
public static function create(?callable $handler = null): self
{
$stack = new self($handler ?: Utils::chooseHandler());
$stack->push(Middleware::httpErrors(), 'http_errors');
$stack->push(Middleware::redirect(), 'allow_redirects');
$stack->push(Middleware::cookies(), 'cookies');
$stack->push(Middleware::prepareBody(), 'prepare_body');
return $stack;
}
/**
* @param (callable(RequestInterface, array): PromiseInterface)|null $handler Underlying HTTP handler.
*/
public function __construct(?callable $handler = null)
{
$this->handler = $handler;
}
/**
* Invokes the handler stack as a composed handler
*
* @return ResponseInterface|PromiseInterface
*/
public function __invoke(RequestInterface $request, array $options)
{
$handler = $this->resolve();
return $handler($request, $options);
}
/**
* Dumps a string representation of the stack.
*
* @return string
*/
public function __toString()
{
$depth = 0;
$stack = [];
if ($this->handler !== null) {
$stack[] = '0) Handler: '.$this->debugCallable($this->handler);
}
$result = '';
foreach (\array_reverse($this->stack) as $tuple) {
++$depth;
$str = "{$depth}) Name: '{$tuple[1]}', ";
$str .= 'Function: '.$this->debugCallable($tuple[0]);
$result = "> {$str}\n{$result}";
$stack[] = $str;
}
foreach (\array_keys($stack) as $k) {
$result .= "< {$stack[$k]}\n";
}
return $result;
}
/**
* Set the HTTP handler that actually returns a promise.
*
* @param callable(RequestInterface, array): PromiseInterface $handler Accepts a request and array of options and
* returns a Promise.
*/
public function setHandler(callable $handler): void
{
$this->handler = $handler;
$this->cached = null;
}
/**
* Returns true if the builder has a handler.
*/
public function hasHandler(): bool
{
return $this->handler !== null;
}
/**
* Unshift a middleware to the bottom of the stack.
*
* @param callable(callable): callable $middleware Middleware function
* @param string $name Name to register for this middleware.
*/
public function unshift(callable $middleware, ?string $name = null): void
{
\array_unshift($this->stack, [$middleware, $name]);
$this->cached = null;
}
/**
* Push a middleware to the top of the stack.
*
* @param callable(callable): callable $middleware Middleware function
* @param string $name Name to register for this middleware.
*/
public function push(callable $middleware, string $name = ''): void
{
$this->stack[] = [$middleware, $name];
$this->cached = null;
}
/**
* Add a middleware before another middleware by name.
*
* @param string $findName Middleware to find
* @param callable(callable): callable $middleware Middleware function
* @param string $withName Name to register for this middleware.
*/
public function before(string $findName, callable $middleware, string $withName = ''): void
{
$this->splice($findName, $withName, $middleware, true);
}
/**
* Add a middleware after another middleware by name.
*
* @param string $findName Middleware to find
* @param callable(callable): callable $middleware Middleware function
* @param string $withName Name to register for this middleware.
*/
public function after(string $findName, callable $middleware, string $withName = ''): void
{
$this->splice($findName, $withName, $middleware, false);
}
/**
* Remove a middleware by instance or name from the stack.
*
* @param callable|string $remove Middleware to remove by instance or name.
*/
public function remove($remove): void
{
if (!is_string($remove) && !is_callable($remove)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a callable or string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->cached = null;
if (\is_string($remove)) {
$count = \count($this->stack);
$this->stack = \array_values(\array_filter(
$this->stack,
static function ($tuple) use ($remove) {
return $tuple[1] !== $remove;
}
));
if ($count !== \count($this->stack) || !\is_callable($remove)) {
return;
}
}
$this->stack = \array_values(\array_filter(
$this->stack,
static function ($tuple) use ($remove) {
return $tuple[0] !== $remove;
}
));
}
/**
* Compose the middleware and handler into a single callable function.
*
* @return callable(RequestInterface, array): PromiseInterface
*/
public function resolve(): callable
{
if ($this->cached === null) {
if (($prev = $this->handler) === null) {
throw new \LogicException('No handler has been specified');
}
foreach (\array_reverse($this->stack) as $fn) {
/** @var callable(RequestInterface, array): PromiseInterface $prev */
$prev = $fn[0]($prev);
}
$this->cached = $prev;
}
return $this->cached;
}
private function findByName(string $name): int
{
foreach ($this->stack as $k => $v) {
if ($v[1] === $name) {
return $k;
}
}
throw new \InvalidArgumentException("Middleware not found: $name");
}
/**
* Splices a function into the middleware list at a specific position.
*/
private function splice(string $findName, string $withName, callable $middleware, bool $before): void
{
$this->cached = null;
$idx = $this->findByName($findName);
$tuple = [$middleware, $withName];
if ($before) {
if ($idx === 0) {
\array_unshift($this->stack, $tuple);
} else {
$replacement = [$tuple, $this->stack[$idx]];
\array_splice($this->stack, $idx, 1, $replacement);
}
} elseif ($idx === \count($this->stack) - 1) {
$this->stack[] = $tuple;
} else {
$replacement = [$this->stack[$idx], $tuple];
\array_splice($this->stack, $idx, 1, $replacement);
}
}
/**
* Provides a debug string for a given callable.
*
* @param callable|string $fn Function to write as a string.
*/
private function debugCallable($fn): string
{
if (\is_string($fn)) {
return "callable({$fn})";
}
if (\is_array($fn)) {
return \is_string($fn[0])
? "callable({$fn[0]}::{$fn[1]})"
: "callable(['".\get_class($fn[0])."', '{$fn[1]}'])";
}
/** @var object $fn */
return 'callable('.\spl_object_hash($fn).')';
}
}
@@ -0,0 +1,204 @@
<?php
namespace GuzzleHttp;
use Psr\Http\Message\MessageInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Formats log messages using variable substitutions for requests, responses,
* and other transactional data.
*
* The following variable substitutions are supported:
*
* - {request}: Full HTTP request message
* - {response}: Full HTTP response message
* - {ts}: ISO 8601 date in GMT
* - {date_iso_8601} ISO 8601 date in GMT
* - {date_common_log} Apache common log date using the configured timezone.
* - {host}: Host of the request
* - {method}: Method of the request
* - {uri}: URI of the request
* - {version}: Protocol version
* - {target}: Request target of the request (path + query + fragment)
* - {hostname}: Hostname of the machine that sent the request
* - {code}: Status code of the response (if available)
* - {phrase}: Reason phrase of the response (if available)
* - {error}: Any error messages (if available)
* - {req_header_*}: Replace `*` with the lowercased name of a request header to add to the message
* - {res_header_*}: Replace `*` with the lowercased name of a response header to add to the message
* - {req_headers}: Request headers
* - {res_headers}: Response headers
* - {req_body}: Request body
* - {res_body}: Response body
*
* @final
*/
class MessageFormatter implements MessageFormatterInterface
{
/**
* Apache Common Log Format.
*
* @see https://httpd.apache.org/docs/2.4/logs.html#common
*
* @var string
*/
public const CLF = '{hostname} {req_header_User-Agent} - [{date_common_log}] "{method} {target} HTTP/{version}" {code} {res_header_Content-Length}';
public const DEBUG = ">>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}";
public const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}';
/**
* @var string Template used to format log messages
*/
private $template;
/**
* @param string $template Log message template
*/
public function __construct(?string $template = self::CLF)
{
$this->template = $template ?: self::CLF;
}
/**
* Returns a formatted message string.
*
* @param RequestInterface $request Request that was sent
* @param ResponseInterface|null $response Response that was received
* @param \Throwable|null $error Exception that was received
*/
public function format(RequestInterface $request, ?ResponseInterface $response = null, ?\Throwable $error = null): string
{
$cache = [];
$result = \preg_replace_callback(
'/{\s*([A-Za-z_\-\.0-9]+)\s*}/',
function (array $matches) use ($request, $response, $error, &$cache) {
if (isset($cache[$matches[1]])) {
return $cache[$matches[1]];
}
$result = '';
switch ($matches[1]) {
case 'request':
$result = Psr7\Message::toString($request);
break;
case 'response':
$result = $response ? Psr7\Message::toString($response) : '';
break;
case 'req_headers':
$result = \trim($request->getMethod()
.' '.$request->getRequestTarget(), " \n\r\t\0\x0B")
.' HTTP/'.$request->getProtocolVersion()."\r\n"
.$this->headers($request);
break;
case 'res_headers':
$result = $response ?
\sprintf(
'HTTP/%s %d %s',
$response->getProtocolVersion(),
$response->getStatusCode(),
$response->getReasonPhrase()
)."\r\n".$this->headers($response)
: 'NULL';
break;
case 'req_body':
$result = $request->getBody()->__toString();
break;
case 'res_body':
if (!$response instanceof ResponseInterface) {
$result = 'NULL';
break;
}
$body = $response->getBody();
if (!$body->isSeekable()) {
$result = 'RESPONSE_NOT_LOGGEABLE';
break;
}
$result = $response->getBody()->__toString();
break;
case 'ts':
case 'date_iso_8601':
$result = \gmdate('c');
break;
case 'date_common_log':
$result = \date('d/M/Y:H:i:s O');
break;
case 'method':
$result = $request->getMethod();
break;
case 'version':
$result = $request->getProtocolVersion();
break;
case 'uri':
case 'url':
$result = $request->getUri()->__toString();
break;
case 'target':
$result = $request->getRequestTarget();
break;
case 'req_version':
$result = $request->getProtocolVersion();
break;
case 'res_version':
$result = $response
? $response->getProtocolVersion()
: 'NULL';
break;
case 'host':
$result = $request->getHeaderLine('Host');
break;
case 'hostname':
$result = \gethostname();
break;
case 'code':
$result = $response ? $response->getStatusCode() : 'NULL';
break;
case 'phrase':
$result = $response ? $response->getReasonPhrase() : 'NULL';
break;
case 'error':
$result = $error ? $error->getMessage() : 'NULL';
break;
default:
// handle prefixed dynamic headers
if (\strpos($matches[1], 'req_header_') === 0) {
$result = $request->getHeaderLine(\substr($matches[1], 11));
} elseif (\strpos($matches[1], 'res_header_') === 0) {
$result = $response
? $response->getHeaderLine(\substr($matches[1], 11))
: 'NULL';
}
}
$cache[$matches[1]] = $result;
return $result;
},
$this->template
);
if ($result === null) {
throw new \RuntimeException('Unable to format message: '.\preg_last_error_msg());
}
return $result;
}
/**
* Get headers from message as string
*/
private function headers(MessageInterface $message): string
{
$result = '';
foreach ($message->getHeaders() as $name => $values) {
$result .= $name.': '.\implode(', ', $values)."\r\n";
}
return \trim($result, " \n\r\t\0\x0B");
}
}
@@ -0,0 +1,18 @@
<?php
namespace GuzzleHttp;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
interface MessageFormatterInterface
{
/**
* Returns a formatted message string.
*
* @param RequestInterface $request Request that was sent
* @param ResponseInterface|null $response Response that was received
* @param \Throwable|null $error Exception that was received
*/
public function format(RequestInterface $request, ?ResponseInterface $response = null, ?\Throwable $error = null): string;
}
@@ -0,0 +1,268 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Cookie\CookieJarInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
/**
* Functions used to create and wrap handlers with handler middleware.
*/
final class Middleware
{
/**
* Middleware that adds cookies to requests.
*
* The options array must be set to a CookieJarInterface in order to use
* cookies. This is typically handled for you by a client.
*
* @return callable Returns a function that accepts the next handler.
*/
public static function cookies(): callable
{
return static function (callable $handler): callable {
return static function ($request, array $options) use ($handler) {
if (empty($options['cookies'])) {
return $handler($request, $options);
} elseif (!$options['cookies'] instanceof CookieJarInterface) {
throw new \InvalidArgumentException('cookies must be an instance of GuzzleHttp\Cookie\CookieJarInterface');
}
$cookieJar = $options['cookies'];
$request = $cookieJar->withCookieHeader($request);
return $handler($request, $options)
->then(
static function (ResponseInterface $response) use ($cookieJar, $request): ResponseInterface {
$cookieJar->extractCookies($request, $response);
return $response;
}
);
};
};
}
/**
* Middleware that throws exceptions for 4xx or 5xx responses when the
* "http_errors" request option is set to true.
*
* @param BodySummarizerInterface|null $bodySummarizer The body summarizer to use in exception messages.
*
* @return callable(callable): callable Returns a function that accepts the next handler.
*/
public static function httpErrors(?BodySummarizerInterface $bodySummarizer = null): callable
{
return static function (callable $handler) use ($bodySummarizer): callable {
return static function ($request, array $options) use ($handler, $bodySummarizer) {
if (empty($options['http_errors'])) {
return $handler($request, $options);
}
return $handler($request, $options)->then(
static function (ResponseInterface $response) use ($request, $bodySummarizer) {
$code = $response->getStatusCode();
if ($code < 400) {
return $response;
}
throw RequestException::create($request, $response, null, [], $bodySummarizer);
}
);
};
};
}
/**
* Middleware that pushes history data to an ArrayAccess container.
*
* @param array|\ArrayAccess<int, array> $container Container to hold the history (by reference).
*
* @return callable(callable): callable Returns a function that accepts the next handler.
*
* @throws \InvalidArgumentException if container is not an array or ArrayAccess.
*/
public static function history(&$container): callable
{
if (!\is_array($container) && !$container instanceof \ArrayAccess) {
throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess');
}
return static function (callable $handler) use (&$container): callable {
return static function (RequestInterface $request, array $options) use ($handler, &$container) {
return $handler($request, $options)->then(
static function ($value) use ($request, &$container, $options) {
$container[] = [
'request' => $request,
'response' => $value,
'error' => null,
'options' => $options,
];
return $value;
},
static function ($reason) use ($request, &$container, $options) {
$container[] = [
'request' => $request,
'response' => null,
'error' => $reason,
'options' => $options,
];
return P\Create::rejectionFor($reason);
}
);
};
};
}
/**
* Middleware that invokes a callback before and after sending a request.
*
* The provided listener cannot modify or alter the response. It simply
* "taps" into the chain to be notified before returning the promise. The
* before listener accepts a request and options array, and the after
* listener accepts a request, options array, and response promise.
*
* @param callable $before Function to invoke before forwarding the request.
* @param callable $after Function invoked after forwarding.
*
* @return callable Returns a function that accepts the next handler.
*/
public static function tap(?callable $before = null, ?callable $after = null): callable
{
return static function (callable $handler) use ($before, $after): callable {
return static function (RequestInterface $request, array $options) use ($handler, $before, $after) {
if ($before) {
$before($request, $options);
}
$response = $handler($request, $options);
if ($after) {
$after($request, $options, $response);
}
return $response;
};
};
}
/**
* Middleware that handles request redirects.
*
* @return callable Returns a function that accepts the next handler.
*/
public static function redirect(): callable
{
return static function (callable $handler): RedirectMiddleware {
return new RedirectMiddleware($handler);
};
}
/**
* Middleware that retries requests based on the boolean result of
* invoking the provided "decider" function.
*
* If no delay function is provided, a simple implementation of exponential
* backoff will be utilized.
*
* @param callable $decider Function that accepts the number of retries,
* a request, [response], and [exception] and
* returns true if the request is to be retried.
* @param callable $delay Function that accepts the number of retries and
* returns the number of milliseconds to delay.
*
* @return callable Returns a function that accepts the next handler.
*/
public static function retry(callable $decider, ?callable $delay = null): callable
{
return static function (callable $handler) use ($decider, $delay): RetryMiddleware {
return new RetryMiddleware($decider, $handler, $delay);
};
}
/**
* Middleware that logs requests, responses, and errors using a message
* formatter.
*
* @param LoggerInterface $logger Logs messages.
* @param MessageFormatterInterface|MessageFormatter $formatter Formatter used to create message strings.
* @param string $logLevel Level at which to log requests.
*
* @phpstan-param \Psr\Log\LogLevel::* $logLevel Level at which to log requests.
*
* @return callable Returns a function that accepts the next handler.
*/
public static function log(LoggerInterface $logger, $formatter, string $logLevel = 'info'): callable
{
// To be compatible with Guzzle 7.1.x we need to allow users to pass a MessageFormatter
if (!$formatter instanceof MessageFormatter && !$formatter instanceof MessageFormatterInterface) {
throw new \LogicException(sprintf('Argument 2 to %s::log() must be of type %s', self::class, MessageFormatterInterface::class));
}
return static function (callable $handler) use ($logger, $formatter, $logLevel): callable {
return static function (RequestInterface $request, array $options = []) use ($handler, $logger, $formatter, $logLevel) {
return $handler($request, $options)->then(
static function ($response) use ($logger, $request, $formatter, $logLevel): ResponseInterface {
$message = $formatter->format($request, $response);
$logger->log($logLevel, $message);
return $response;
},
static function ($reason) use ($logger, $request, $formatter): PromiseInterface {
$response = $reason instanceof RequestException ? $reason->getResponse() : null;
$message = $formatter->format($request, $response, P\Create::exceptionFor($reason));
$logger->error($message);
return P\Create::rejectionFor($reason);
}
);
};
};
}
/**
* This middleware adds a default content-type if possible, a default
* content-length or transfer-encoding header, and the expect header.
*/
public static function prepareBody(): callable
{
return static function (callable $handler): PrepareBodyMiddleware {
return new PrepareBodyMiddleware($handler);
};
}
/**
* Middleware that applies a map function to the request before passing to
* the next handler.
*
* @param callable $fn Function that accepts a RequestInterface and returns
* a RequestInterface.
*/
public static function mapRequest(callable $fn): callable
{
return static function (callable $handler) use ($fn): callable {
return static function (RequestInterface $request, array $options) use ($handler, $fn) {
return $handler($fn($request), $options);
};
};
}
/**
* Middleware that applies a map function to the resolved promise's
* response.
*
* @param callable $fn Function that accepts a ResponseInterface and
* returns a ResponseInterface.
*/
public static function mapResponse(callable $fn): callable
{
return static function (callable $handler) use ($fn): callable {
return static function (RequestInterface $request, array $options) use ($handler, $fn) {
return $handler($request, $options)->then($fn);
};
};
}
}
@@ -0,0 +1,26 @@
<?php
namespace GuzzleHttp;
/**
* Multiplexing modes for the "multiplex" request option.
*
* NONE disables multiplexing for a whole handler when passed as the
* "multiplex" client configuration option or, when constructing a handler
* directly, as the CurlMultiHandler "multiplex" constructor option. As a
* request option value it guarantees the transfer does not share its
* connection with any concurrent transfer, and is accepted only where that
* guarantee holds.
*/
final class Multiplexing
{
public const NONE = 'none';
public const EAGER = 'eager';
public const WAIT = 'wait';
public const REQUIRE_EAGER = 'require_eager';
public const REQUIRE_WAIT = 'require_wait';
private function __construct()
{
}
}
@@ -0,0 +1,137 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\EachPromise;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Promise\PromisorInterface;
use Psr\Http\Message\RequestInterface;
/**
* Sends an iterator of requests concurrently using a capped pool size.
*
* The pool will read from an iterator until it is cancelled or until the
* iterator is consumed. When a request is yielded, the request is sent after
* applying the "request_options" request options (if provided in the ctor).
*
* When a function is yielded by the iterator, the function is provided the
* "request_options" array that should be merged on top of any existing
* options, and the function MUST then return a wait-able promise.
*
* @final
*/
class Pool implements PromisorInterface
{
/**
* @var EachPromise
*/
private $each;
/**
* @param ClientInterface $client Client used to send the requests.
* @param array|\Iterator $requests Requests or functions that return
* requests to send concurrently.
* @param array $config Associative array of options
* - concurrency: (int) Maximum number of requests to send concurrently
* - options: Array of request options to apply to each request.
* - fulfilled: (callable) Function to invoke when a request completes.
* - rejected: (callable) Function to invoke when a request is rejected.
*/
public function __construct(ClientInterface $client, $requests, array $config = [])
{
if (!isset($config['concurrency'])) {
$config['concurrency'] = 25;
}
if (isset($config['options'])) {
$opts = $config['options'];
unset($config['options']);
} else {
$opts = [];
}
if (!\is_iterable($requests)) {
\trigger_deprecation(
'guzzlehttp/guzzle',
'7.11',
'Passing a non-iterable request collection to %s::__construct() or %s::batch() is deprecated; guzzlehttp/guzzle 8.0 will require an iterable.',
__CLASS__,
__CLASS__
);
$requests = [$requests];
}
$iterable = P\Create::iterFor($requests);
$requests = static function () use ($iterable, $client, $opts) {
foreach ($iterable as $key => $rfn) {
if ($rfn instanceof RequestInterface) {
yield $key => $client->sendAsync($rfn, $opts);
} elseif (\is_callable($rfn)) {
yield $key => $rfn($opts);
} else {
throw new \InvalidArgumentException('Each value yielded by the iterator must be a Psr\Http\Message\RequestInterface or a callable that returns a promise that fulfills with a Psr\Http\Message\ResponseInterface object.');
}
}
};
$this->each = new EachPromise($requests(), $config);
}
/**
* Get promise
*/
public function promise(): PromiseInterface
{
return $this->each->promise();
}
/**
* Sends multiple requests concurrently and returns an array of responses
* and exceptions that uses the same ordering as the provided requests.
*
* IMPORTANT: This method keeps every request and response in memory, and
* as such, is NOT recommended when sending a large number or an
* indeterminate number of requests concurrently.
*
* @param ClientInterface $client Client used to send the requests
* @param array|\Iterator $requests Requests to send concurrently.
* @param array $options Passes through the options available in
* {@see Pool::__construct}
*
* @return array Returns an array containing the response or an exception
* in the same order that the requests were sent.
*
* @throws \InvalidArgumentException if the event format is incorrect.
*/
public static function batch(ClientInterface $client, $requests, array $options = []): array
{
$res = [];
self::cmpCallback($options, 'fulfilled', $res);
self::cmpCallback($options, 'rejected', $res);
$pool = new static($client, $requests, $options);
$pool->promise()->wait();
\ksort($res);
return $res;
}
/**
* Execute callback(s)
*/
private static function cmpCallback(array &$options, string $name, array &$results): void
{
if (!isset($options[$name])) {
$options[$name] = static function ($v, $k) use (&$results) {
$results[$k] = $v;
};
} else {
$currentFn = $options[$name];
$options[$name] = static function ($v, $k) use (&$results, $currentFn) {
$currentFn($v, $k);
$results[$k] = $v;
};
}
}
}
@@ -0,0 +1,105 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
/**
* Prepares requests that contain a body, adding the Content-Length,
* Content-Type, and Expect headers.
*
* @final
*/
class PrepareBodyMiddleware
{
/**
* @var callable(RequestInterface, array): PromiseInterface
*/
private $nextHandler;
/**
* @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke.
*/
public function __construct(callable $nextHandler)
{
$this->nextHandler = $nextHandler;
}
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
$fn = $this->nextHandler;
// Don't do anything if the request has no body.
if ($request->getBody()->getSize() === 0) {
return $fn($request, $options);
}
$modify = [];
// Add a default content-type if possible.
if (!$request->hasHeader('Content-Type')) {
if ($uri = $request->getBody()->getMetadata('uri')) {
if (is_string($uri) && $type = Psr7\MimeType::fromFilename($uri)) {
$modify['set_headers']['Content-Type'] = $type;
}
}
}
// Add a default content-length or transfer-encoding header.
if (!$request->hasHeader('Content-Length')
&& !$request->hasHeader('Transfer-Encoding')
) {
$size = $request->getBody()->getSize();
if ($size !== null) {
$modify['set_headers']['Content-Length'] = (string) $size;
} else {
$modify['set_headers']['Transfer-Encoding'] = 'chunked';
}
}
// Add the expect header if needed.
$this->addExpectHeader($request, $options, $modify);
return $fn(Psr7\Utils::modifyRequest($request, $modify), $options);
}
/**
* Add expect header
*/
private function addExpectHeader(RequestInterface $request, array $options, array &$modify): void
{
// Determine if the Expect header should be used
if ($request->hasHeader('Expect')) {
return;
}
$expect = $options['expect'] ?? null;
// Return if disabled or using HTTP/1.0
if ($expect === false || $request->getProtocolVersion() === '1.0') {
return;
}
// The expect header is unconditionally enabled
if ($expect === true) {
$modify['set_headers']['Expect'] = '100-Continue';
return;
}
// By default, send the expect header when the payload is > 1mb
if ($expect === null) {
$expect = 1048576;
}
// Always add if the body cannot be rewound, the size cannot be
// determined, or the size is greater than the cutoff threshold
$body = $request->getBody();
$size = $body->getSize();
if ($size === null || $size >= (int) $expect || !$body->isSeekable()) {
$modify['set_headers']['Expect'] = '100-Continue';
}
}
}
@@ -0,0 +1,248 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\TooManyRedirectsException;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* Request redirect middleware.
*
* Apply this middleware like other middleware using
* {@see Middleware::redirect()}.
*
* @final
*/
class RedirectMiddleware
{
public const HISTORY_HEADER = 'X-Guzzle-Redirect-History';
public const STATUS_HISTORY_HEADER = 'X-Guzzle-Redirect-Status-History';
/**
* @var array
*/
public static $defaultSettings = [
'max' => 5,
'protocols' => ['http', 'https'],
'strict' => false,
'referer' => false,
'track_redirects' => false,
];
/**
* @var callable(RequestInterface, array): PromiseInterface
*/
private $nextHandler;
/**
* @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke.
*/
public function __construct(callable $nextHandler)
{
$this->nextHandler = $nextHandler;
}
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
$fn = $this->nextHandler;
if (empty($options['allow_redirects'])) {
return $fn($request, $options);
}
if ($options['allow_redirects'] === true) {
$options['allow_redirects'] = self::$defaultSettings;
} elseif (!\is_array($options['allow_redirects'])) {
throw new \InvalidArgumentException('allow_redirects must be true, false, or array');
} else {
// Merge the default settings with the provided settings
$options['allow_redirects'] += self::$defaultSettings;
}
if (empty($options['allow_redirects']['max'])) {
return $fn($request, $options);
}
return $fn($request, $options)
->then(function (ResponseInterface $response) use ($request, $options) {
return $this->checkRedirect($request, $options, $response);
});
}
/**
* @return ResponseInterface|PromiseInterface
*/
public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response)
{
if (\strpos((string) $response->getStatusCode(), '3') !== 0
|| !$response->hasHeader('Location')
) {
return $response;
}
$this->guardMax($request, $response, $options);
$nextRequest = $this->modifyRequest($request, $options, $response);
// If authorization is handled by curl, unset it if URI is cross-origin.
if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $nextRequest->getUri()) && defined('\CURLOPT_HTTPAUTH')) {
unset(
$options['curl'][\CURLOPT_HTTPAUTH],
$options['curl'][\CURLOPT_USERPWD]
);
}
if (isset($options['allow_redirects']['on_redirect'])) {
($options['allow_redirects']['on_redirect'])(
$request,
$response,
$nextRequest->getUri()
);
}
// The caller's delay applies once, before the initial request, not
// before each followed redirect.
unset($options['delay']);
$promise = $this($nextRequest, $options);
// Add headers to be able to track history of redirects.
if (!empty($options['allow_redirects']['track_redirects'])) {
return $this->withTracking(
$promise,
(string) $nextRequest->getUri(),
$response->getStatusCode()
);
}
return $promise;
}
/**
* Enable tracking on promise.
*/
private function withTracking(PromiseInterface $promise, string $uri, int $statusCode): PromiseInterface
{
return $promise->then(
static function (ResponseInterface $response) use ($uri, $statusCode) {
// Note that we are pushing to the front of the list as this
// would be an earlier response than what is currently present
// in the history header.
$historyHeader = $response->getHeader(self::HISTORY_HEADER);
$statusHeader = $response->getHeader(self::STATUS_HISTORY_HEADER);
\array_unshift($historyHeader, $uri);
\array_unshift($statusHeader, (string) $statusCode);
return $response->withHeader(self::HISTORY_HEADER, $historyHeader)
->withHeader(self::STATUS_HISTORY_HEADER, $statusHeader);
}
);
}
/**
* Check for too many redirects.
*
* @throws TooManyRedirectsException Too many redirects.
*/
private function guardMax(RequestInterface $request, ResponseInterface $response, array &$options): void
{
$current = $options['__redirect_count']
?? 0;
$options['__redirect_count'] = $current + 1;
$max = $options['allow_redirects']['max'];
if ($options['__redirect_count'] > $max) {
throw new TooManyRedirectsException("Will not follow more than {$max} redirects", $request, $response);
}
}
public function modifyRequest(RequestInterface $request, array $options, ResponseInterface $response): RequestInterface
{
// Request modifications to apply.
$modify = [];
$protocols = $options['allow_redirects']['protocols'];
// Use a GET request if this is an entity enclosing request and we are
// not forcing RFC compliance, but rather emulating what all browsers
// would do.
$statusCode = $response->getStatusCode();
if ($statusCode == 303
|| ($statusCode <= 302 && !$options['allow_redirects']['strict'])
) {
$requestMethod = $request->getMethod();
if ($requestMethod !== 'QUERY' || !\in_array($statusCode, [301, 302], true)) {
$modify['method'] = \in_array($requestMethod, ['GET', 'HEAD', 'OPTIONS'], true) ? $requestMethod : 'GET';
$modify['body'] = '';
$modify['remove_headers'] = ['Content-Length', 'Transfer-Encoding'];
}
}
$uri = self::redirectUri($request, $response, $protocols);
$idnOptions = Utils::normalizeIdnConversionOption($options['idn_conversion'] ?? null);
if ($idnOptions !== null) {
$uri = Utils::idnUriConvert($uri, $idnOptions);
}
$modify['uri'] = $uri;
// The body only needs to be rewound when the next request reuses it.
if (!isset($modify['body'])) {
try {
Psr7\Message::rewindBody($request);
} catch (\RuntimeException $e) {
throw new RequestException(
'Redirect failed because the request body could not be rewound: '.$e->getMessage(),
$request,
$response,
$e
);
}
}
// Add the Referer header if it is told to do so and only
// add the header if we are not redirecting from https to http.
if ($options['allow_redirects']['referer']
&& $modify['uri']->getScheme() === $request->getUri()->getScheme()
) {
$uri = $request->getUri()->withUserInfo('')->withFragment('');
$modify['set_headers']['Referer'] = (string) $uri;
} else {
$modify['remove_headers'][] = 'Referer';
}
// Remove Authorization and Cookie headers if URI is cross-origin.
if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $modify['uri'])) {
$modify['remove_headers'][] = 'Authorization';
$modify['remove_headers'][] = 'Cookie';
}
return Psr7\Utils::modifyRequest($request, $modify);
}
/**
* Set the appropriate URL on the request based on the location header.
*/
private static function redirectUri(
RequestInterface $request,
ResponseInterface $response,
array $protocols
): UriInterface {
$location = Psr7\UriResolver::resolve(
$request->getUri(),
new Psr7\Uri($response->getHeaderLine('Location'))
);
// Ensure that the redirect URI is allowed based on the protocols.
if (!\in_array($location->getScheme(), $protocols)) {
throw new BadResponseException(\sprintf('Redirect URI, %s, does not use one of the allowed redirect protocols: %s', $location, \implode(', ', $protocols)), $request, $response);
}
return $location;
}
}
@@ -0,0 +1,434 @@
<?php
namespace GuzzleHttp;
/**
* This class contains a list of built-in Guzzle request options.
*
* @see https://github.com/guzzle/guzzle/blob/7.15/docs/request-options.md
*/
final class RequestOptions
{
/**
* allow_redirects: (bool|array) Controls redirect behavior. Pass false
* to disable redirects, pass true to enable redirects, pass an
* associative to provide custom redirect settings. Defaults to "false".
* This option only works if your handler has the RedirectMiddleware. When
* passing an associative array, you can provide the following key value
* pairs:
*
* - max: (int, default=5) maximum number of allowed redirects.
* - strict: (bool, default=false) Set to true to use strict redirects
* meaning redirect POST requests with POST requests vs. doing what most
* browsers do which is redirect POST requests with GET requests. The
* QUERY method keeps its method and body across non-strict 301 and 302
* redirects, and a 303 redirect is followed with a body-less GET.
* - referer: (bool, default=false) Set to true to enable the Referer
* header.
* - protocols: (non-empty-array<array-key, string>, default=['http', 'https'])
* Allowed redirect protocols. Redirect matching is case-sensitive; use
* "http" and "https".
* - on_redirect: (callable) PHP callable that is invoked when a redirect
* is encountered. The callable is invoked with the request, the redirect
* response that was received, and the effective URI. Any return value
* from the on_redirect function is ignored.
* - track_redirects: (bool, default=false) Track redirected URI and status
* history in response headers.
*/
public const ALLOW_REDIRECTS = 'allow_redirects';
/**
* auth: (array{0: string, 1: string, 2?: string|null}|string|false|null)
* Pass an array of HTTP authentication parameters to use with the request.
* The array must contain the username in index [0], the password in index
* [1], and you can optionally provide a built-in authentication type in
* index [2]. Pass false or null to disable authentication for a request.
* String values are passed through for custom handlers.
*/
public const AUTH = 'auth';
/**
* body: (resource|string|null|int|float|bool|\Psr\Http\Message\StreamInterface|(callable&object)|\Iterator|\Stringable)
* Body to send in the request. Callable arrays are arrays, and arrays are
* not valid body values in Guzzle.
*/
public const BODY = 'body';
/**
* cert: (string|array{0: string, 1?: string|null}) Set to a string to
* specify the path to a client certificate file. PEM is the default
* certificate format. If a password is required, set cert to an array
* containing the certificate path in the first array element followed by
* the certificate password in the second array element. A null password is
* treated the same as omitting it. Use cert_type to specify another
* supported certificate format.
*/
public const CERT = 'cert';
/**
* cert_type: (string) Specify the SSL client certificate file type.
*/
public const CERT_TYPE = 'cert_type';
/**
* cookies: (false|GuzzleHttp\Cookie\CookieJarInterface, default=false)
* Specifies whether or not cookies are used in a request or what cookie
* jar to use or what cookies to send. This option only works if your
* handler has the `cookie` middleware. Valid values are `false` and
* an instance of {@see Cookie\CookieJarInterface}.
*/
public const COOKIES = 'cookies';
/**
* connect_timeout: (int|float, default=0) Number of seconds to wait while
* trying to connect to a server. Use 0 to wait 300 seconds (the default
* behavior).
*/
public const CONNECT_TIMEOUT = 'connect_timeout';
/**
* crypto_method: (int) A value describing the minimum TLS protocol
* version to use.
*
* This setting must be set to one of the
* ``STREAM_CRYPTO_METHOD_TLS*_CLIENT`` constants. PHP 7.4 or higher is
* required in order to use TLS 1.3, and cURL 7.34.0 or higher is required
* in order to specify a crypto method, with cURL 7.52.0 or higher being
* required to use TLS 1.3.
*/
public const CRYPTO_METHOD = 'crypto_method';
/**
* crypto_method_max: (int) A value describing the maximum TLS protocol
* version to use.
*
* This setting must be set to one of the
* ``STREAM_CRYPTO_METHOD_TLS*_CLIENT`` constants. On the stream handler,
* PHP 7.3 or higher is required to set a maximum TLS version, and PHP 7.4
* or higher is required to use TLS 1.3. cURL 7.54.0 or higher is required
* in order to specify a maximum TLS version with the cURL handler.
*/
public const CRYPTO_METHOD_MAX = 'crypto_method_max';
/**
* curl: (array) Raw cURL options to apply when using a built-in cURL handler.
*/
public const CURL = 'curl';
/**
* debug: (bool|resource) Set to true or set to a PHP stream returned by
* fopen() enable debug output with the HTTP handler used to send a
* request.
*/
public const DEBUG = 'debug';
/**
* decode_content: (bool|string, default=true) Specify whether or not
* Content-Encoding responses (gzip, deflate, etc.) are automatically
* decoded.
*/
public const DECODE_CONTENT = 'decode_content';
/**
* delay: (int|float) The amount of time to delay before sending in
* milliseconds.
*/
public const DELAY = 'delay';
/**
* expect: (bool|integer) Controls the behavior of the
* "Expect: 100-Continue" header.
*
* Set to `true` to enable the "Expect: 100-Continue" header for all
* requests that sends a body. Set to `false` to disable the
* "Expect: 100-Continue" header for all requests. Set to a number so that
* the size of the payload must be greater than the number in order to send
* the Expect header. Setting to a number will send the Expect header for
* all requests in which the size of the payload cannot be determined or
* where the body is not rewindable.
*
* By default, Guzzle will add the "Expect: 100-Continue" header when the
* size of the body of a request is greater than 1 MB and a request is
* using HTTP/1.1.
*/
public const EXPECT = 'expect';
/**
* form_params: (array<array-key, string|int|float|bool|null|array>)
* Associative array of form field names to scalar, null, or nested array
* values. Sets the Content-Type header to application/x-www-form-urlencoded
* when no Content-Type header is already present.
*/
public const FORM_PARAMS = 'form_params';
/**
* headers: (array<array-key, string|non-empty-array<array-key, string>>|null)
* Associative array of HTTP headers. Each value MUST be a string or non-empty
* array of strings.
*/
public const HEADERS = 'headers';
/**
* http_errors: (bool, default=true) Set to false to disable exceptions
* when a non- successful HTTP response is received. By default,
* exceptions will be thrown for 4xx and 5xx responses. This option only
* works if your handler has the `httpErrors` middleware.
*/
public const HTTP_ERRORS = 'http_errors';
/**
* idn_conversion: (bool|int|null, default=false) A combination of IDNA_*
* constants for PHP's idn_to_ascii() function. Set to false or null to
* disable IDN support, or to true to use the default configuration
* (IDNA_DEFAULT constant).
*/
public const IDN_CONVERSION = 'idn_conversion';
/**
* json: (mixed) Adds JSON data to a request. The provided value is JSON
* encoded and a Content-Type header of application/json will be added to
* the request if no Content-Type header is already present.
*/
public const JSON = 'json';
/**
* multipart: (array) Array of part arrays, each containing a required
* "name" key mapping to the string or integer form field name, a required
* "contents" key mapping to any non-array value accepted by PSR-7
* Utils::streamFor() or a nested array of field values, an optional
* "headers" array of string custom header values, and an optional
* "filename" key mapping to a string to send as the filename in the part.
* "headers" and "filename" cannot be used when "contents" is an array.
*/
public const MULTIPART = 'multipart';
/**
* multiplex: (string) Controls how a request sent through a built-in
* cURL handler relates to shared, multiplexed connections: how an HTTP/2
* request pursues one, or, with Multiplexing::NONE, whether the transfer
* may share its connection at all. When the option is not set,
* multiplexing is left to libcurl: nothing waits, and established
* multiplex-capable connections are still shared. Use
* Multiplexing::EAGER to explicitly never wait for pending connections,
* Multiplexing::WAIT to wait on libcurl-eligible pending connections with
* CURLOPT_PIPEWAIT, normally to the same origin,
* Multiplexing::REQUIRE_EAGER to fail unless a multiplexed protocol is
* guaranteed while dialing eagerly, or Multiplexing::REQUIRE_WAIT for the
* same guarantee while also waiting on pending connections. The required
* modes require a handler that permits actual multiplexing, not merely a
* multiplexed protocol, and are rejected on a Multiplexing::NONE handler.
* The stream handler ignores EAGER and WAIT, and rejects the required
* family; CurlHandler has no multi handle to multiplex over. Explicit
* modes reject deprecated raw cURL options they conflict with: the
* required family cannot be combined with a raw CURLOPT_HTTP_VERSION,
* CURLOPT_URL, or CURLOPT_FOLLOWLOCATION; no explicit mode can be
* combined with a raw CURLOPT_PIPEWAIT on the CurlMultiHandler; and
* Multiplexing::NONE on a CurlMultiHandler that permits multiplexing
* cannot be combined with the raw CURLOPT_HTTP_VERSION, CURLOPT_HTTPAUTH
* (including the "auth" request option's "digest" and "ntlm" modes,
* which set it), CURLOPT_PROXYAUTH, CURLOPT_FOLLOWLOCATION,
* CURLOPT_HTTPHEADER, CURLOPT_ALTSVC, CURLOPT_ALTSVC_CTRL, or
* CURLOPT_PROXYTYPE cURL options. The required family also
* rejects final CURLOPT_HTTPAUTH masks that permit NTLM, which libcurl
* retries over HTTP/1.1. The required family validates its cleartext
* proxy rule against the final cURL configuration, after raw options
* such as CURLOPT_PROXY and CURLOPT_PRE_PROXY are applied; only the
* exact raw CURLOPT_NOPROXY wildcard '*' disables the primary proxy and
* pre-proxy there, and raw host-specific patterns are conservatively
* treated as leaving them active. These rejections are
* configuration-conflict checks, not remote security checks.
*
* Multiplexing::NONE disables multiplexing for a whole handler when
* passed as the "multiplex" client configuration option, which
* configures the default handler and also becomes the default request
* option, or, when constructing a handler directly, as the
* CurlMultiHandler "multiplex" constructor option. A handler
* configured with Multiplexing::NONE rejects explicitly requested wait
* modes as a configuration conflict when the transfer would actually
* wait, and always rejects the required modes, because they require a
* handler that permits actual multiplexing, not merely a multiplexed
* protocol. As a request option value, Multiplexing::NONE guarantees the
* transfer does not share its connection with any concurrent transfer.
* Multiplexing::NONE does not force HTTP/1.1: on a Multiplexing::NONE
* handler, HTTP/2 still negotiates and each transfer keeps its
* connection to itself.
*
* The request option value is accepted exactly where the guarantee
* holds and can be verified: on a CurlMultiHandler configured with
* Multiplexing::NONE, for requests whose declared protocol version is
* HTTP/1.x, on CurlHandler, and on the stream handler, which never
* multiplexes. An HTTP/2 request with a Multiplexing::NONE request
* option is rejected on a CurlMultiHandler that permits multiplexing.
* On a CurlMultiHandler that permits multiplexing, Multiplexing::NONE
* is also rejected with a custom "handle_factory", alongside a raw
* CURLMOPT_PIPELINING cURL multi option, and combined with the raw
* CURLOPT_HTTP_VERSION, CURLOPT_HTTPAUTH (including the "auth" request
* option's "digest" and "ntlm" modes, which set it), CURLOPT_PROXYAUTH,
* CURLOPT_FOLLOWLOCATION, CURLOPT_HTTPHEADER, CURLOPT_ALTSVC,
* CURLOPT_ALTSVC_CTRL, or CURLOPT_PROXYTYPE cURL options. It is also
* rejected when the request carries an Expect: 100-continue header (its
* 417 retries select connections outside the safeguards; remove an
* explicitly supplied header, or set the "expect" request option to
* false to prevent it being added automatically).
*
* On a client whose multi handler permits multiplexing, the ordinary
* non-streaming default stack - both cURL handlers available and no
* connection caps forcing multi-only routing - runs synchronous
* requests on the CurlHandler path, which satisfies the guarantee for
* any protocol version, while asynchronous requests run on the
* CurlMultiHandler, so an HTTP/2 request with Multiplexing::NONE
* succeeds synchronously and is rejected asynchronously on the same
* client. Keep-alive reuse between consecutive transfers is
* unaffected, except on libcurl versions below 7.77.0 and from 8.11.0
* through 8.12.1, where an accepted HTTP/1.x request on a multiplexing
* CurlMultiHandler forces a fresh connection. Custom handlers receive
* the "multiplex" option unchanged: its semantics are handler-defined,
* Guzzle does not guarantee it is honored, and a client-level
* Multiplexing::NONE with a custom handler flows to it as a default
* request option without client-side enforcement.
*/
public const MULTIPLEX = 'multiplex';
/**
* on_headers: (callable) A callable that is invoked when the HTTP headers
* of the response have been received but the body has not yet begun to
* download.
*/
public const ON_HEADERS = 'on_headers';
/**
* on_stats: (callable) allows you to get access to transfer statistics of
* a request and access the lower level transfer details of the handler
* associated with your client. ``on_stats`` is a callable that is invoked
* when a handler has finished sending a request. The callback is invoked
* with transfer statistics about the request, the response received, or
* the error encountered. Included in the data is the total amount of time
* taken to send the request.
*/
public const ON_STATS = 'on_stats';
/**
* on_trailers: (callable) A callable that is invoked by the built-in cURL
* handlers once per successful transfer, after the response body has been
* received, with an associative array of the parsed HTTP trailers followed
* by the response. Trailer field names are lowercased and grouped
* case-insensitively; values keep their wire order. Malformed trailer
* field lines are discarded before parsing. Trailer fields are reported
* separately from response headers and are never merged into the response.
*/
public const ON_TRAILERS = 'on_trailers';
/**
* progress: (callable) Defines a function to invoke when transfer
* progress is made. The function accepts the following positional
* arguments: the total number of bytes expected to be downloaded, the
* number of bytes downloaded so far, the number of bytes expected to be
* uploaded, the number of bytes uploaded so far.
*/
public const PROGRESS = 'progress';
/**
* protocols: (non-empty-array<array-key, string>, default=['http', 'https'])
* Allowed URI schemes. Built-in handlers accept only the case-sensitive
* values "http" and "https".
*/
public const PROTOCOLS = 'protocols';
/**
* proxy: (string|array) Pass a string to specify an HTTP proxy, or an
* array to specify different proxies for different protocols (where the
* key is the protocol and the value is a proxy string or null). Provide a
* "no" key as a comma-delimited string, array of strings, or null to
* specify hosts or host-and-port pairs that should not be proxied.
*/
public const PROXY = 'proxy';
/**
* query: (array<array-key, mixed>|string) Associative array of query string
* values to add to the request. This option uses PHP's http_build_query()
* to create the string representation. Pass a string value if you need
* more control than what this method provides
*/
public const QUERY = 'query';
/**
* sink: (resource|string|\Psr\Http\Message\StreamInterface) Where the data
* of the response is written to. Defaults to a PHP temp stream. Providing
* a string will write data to a file by the given name.
*/
public const SINK = 'sink';
/**
* synchronous: (bool) Set to true to inform HTTP handlers that you intend
* on waiting on the response. This can be useful for optimizations. Note
* that a promise is still returned if you are using one of the async
* client methods.
*/
public const SYNCHRONOUS = 'synchronous';
/**
* ssl_key: (array{0: string, 1?: string|null}|string) Specify the path to
* a private SSL key file. PEM is the default private key format. If a
* password is required, set ssl_key to an array containing the key path in
* the first array element followed by the key password in the second
* element. A null password is treated the same as omitting it. Use
* ssl_key_type to specify another supported key format.
*/
public const SSL_KEY = 'ssl_key';
/**
* ssl_key_type: (string) Specify the SSL private key file type.
*/
public const SSL_KEY_TYPE = 'ssl_key_type';
/**
* stream: (bool) Set to true to attempt to stream a response rather than
* download it all up-front.
*/
public const STREAM = 'stream';
/**
* stream_context: (array) PHP stream context options to merge into the
* context used by the built-in stream handler.
*/
public const STREAM_CONTEXT = 'stream_context';
/**
* verify: (bool|string, default=true) Describes the SSL certificate
* verification behavior of a request. Set to true to enable SSL
* certificate verification using the system CA bundle when available
* (the default). Set to false to disable certificate verification (this
* is insecure!). Set to a string to provide the path to a CA bundle on
* disk to enable verification using a custom certificate.
*/
public const VERIFY = 'verify';
/**
* timeout: (int|float, default=0) Number describing the timeout of the
* request in seconds. Use 0 to wait indefinitely (the default behavior).
*/
public const TIMEOUT = 'timeout';
/**
* read_timeout: (int|float, default=default_socket_timeout ini setting)
* Number describing the body read timeout, for stream requests.
*/
public const READ_TIMEOUT = 'read_timeout';
/**
* retries: (int) Current retry count used by the retry middleware.
*/
public const RETRIES = 'retries';
/**
* version: (string|int|float) Specifies the HTTP protocol version to attempt
* to use.
*/
public const VERSION = 'version';
/**
* force_ip_resolve: (string) Set to "v4" to force IPv4 resolution or "v6"
* for IPv6 resolution when supported by the handler.
*/
public const FORCE_IP_RESOLVE = 'force_ip_resolve';
}
@@ -0,0 +1,125 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Middleware that retries requests based on the boolean result of
* invoking the provided "decider" function.
*
* @final
*/
class RetryMiddleware
{
/**
* @var callable(RequestInterface, array): PromiseInterface
*/
private $nextHandler;
/**
* @var callable
*/
private $decider;
/**
* @var callable(int)
*/
private $delay;
/**
* @param callable $decider Function that accepts the number of retries,
* a request, [response], and [exception] and
* returns true if the request is to be
* retried.
* @param callable(RequestInterface, array): PromiseInterface $nextHandler Next handler to invoke.
* @param (callable(int): int)|null $delay Function that accepts the number of retries
* and returns the number of
* milliseconds to delay.
*/
public function __construct(callable $decider, callable $nextHandler, ?callable $delay = null)
{
$this->decider = $decider;
$this->nextHandler = $nextHandler;
$this->delay = $delay ?: static function (int $retries): int {
return (int) 2 ** ($retries - 1) * 1000;
};
}
/**
* Default exponential backoff delay function.
*
* @return int milliseconds.
*
* @deprecated since 7.11, will be removed in 8.0.
*/
public static function exponentialDelay(int $retries): int
{
\trigger_deprecation('guzzlehttp/guzzle', '7.11', '%s::%s() is deprecated and will be removed in 8.0.', __CLASS__, __FUNCTION__);
return (int) 2 ** ($retries - 1) * 1000;
}
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
if (!isset($options['retries'])) {
$options['retries'] = 0;
}
$fn = $this->nextHandler;
return $fn($request, $options)
->then(
$this->onFulfilled($request, $options),
$this->onRejected($request, $options)
);
}
/**
* Execute fulfilled closure
*/
private function onFulfilled(RequestInterface $request, array $options): callable
{
return function ($value) use ($request, $options) {
if (!($this->decider)(
$options['retries'],
$request,
$value,
null
)) {
return $value;
}
return $this->doRetry($request, $options, $value);
};
}
/**
* Execute rejected closure
*/
private function onRejected(RequestInterface $req, array $options): callable
{
return function ($reason) use ($req, $options) {
if (!($this->decider)(
$options['retries'],
$req,
null,
$reason
)) {
return P\Create::rejectionFor($reason);
}
return $this->doRetry($req, $options);
};
}
private function doRetry(RequestInterface $request, array $options, ?ResponseInterface $response = null): PromiseInterface
{
$options['delay'] = ($this->delay)(++$options['retries'], $response, $request);
return $this($request, $options);
}
}
@@ -0,0 +1,133 @@
<?php
namespace GuzzleHttp;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* Represents data at the point after it was transferred either successfully
* or after a network error.
*/
final class TransferStats
{
/**
* @var RequestInterface
*/
private $request;
/**
* @var ResponseInterface|null
*/
private $response;
/**
* @var float|null
*/
private $transferTime;
/**
* @var array
*/
private $handlerStats;
/**
* @var mixed|null
*/
private $handlerErrorData;
/**
* @param RequestInterface $request Request that was sent.
* @param ResponseInterface|null $response Response received (if any)
* @param float|null $transferTime Total handler transfer time.
* @param mixed $handlerErrorData Handler error data.
* @param array $handlerStats Handler specific stats.
*/
public function __construct(
RequestInterface $request,
?ResponseInterface $response = null,
?float $transferTime = null,
$handlerErrorData = null,
array $handlerStats = []
) {
$this->request = $request;
$this->response = $response;
$this->transferTime = $transferTime;
$this->handlerErrorData = $handlerErrorData;
$this->handlerStats = $handlerStats;
}
public function getRequest(): RequestInterface
{
return $this->request;
}
/**
* Returns the response that was received (if any).
*/
public function getResponse(): ?ResponseInterface
{
return $this->response;
}
/**
* Returns true if a response was received.
*/
public function hasResponse(): bool
{
return $this->response !== null;
}
/**
* Gets handler specific error data.
*
* This might be an exception, a integer representing an error code, or
* anything else. Relying on this value assumes that you know what handler
* you are using.
*
* @return mixed
*/
public function getHandlerErrorData()
{
return $this->handlerErrorData;
}
/**
* Get the effective URI the request was sent to.
*/
public function getEffectiveUri(): UriInterface
{
return $this->request->getUri();
}
/**
* Get the estimated time the request was being transferred by the handler.
*
* @return float|null Time in seconds.
*/
public function getTransferTime(): ?float
{
return $this->transferTime;
}
/**
* Gets an array of all of the handler specific transfer data.
*/
public function getHandlerStats(): array
{
return $this->handlerStats;
}
/**
* Get a specific handler statistic from the handler by name.
*
* @param string $stat Handler specific transfer stat to retrieve.
*
* @return mixed|null
*/
public function getHandlerStat(string $stat)
{
return $this->handlerStats[$stat] ?? null;
}
}
@@ -0,0 +1,14 @@
<?php
namespace GuzzleHttp;
final class TransportSharing
{
public const NONE = 'none';
public const HANDLER_PREFER = 'handler_prefer';
public const HANDLER_REQUIRE = 'handler_require';
private function __construct()
{
}
}
@@ -0,0 +1,942 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Exception\InvalidArgumentException;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Handler\CurlMultiHandler;
use GuzzleHttp\Handler\CurlShareHandleState;
use GuzzleHttp\Handler\CurlVersion;
use GuzzleHttp\Handler\Proxy;
use GuzzleHttp\Handler\StreamHandler;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\UriInterface;
final class Utils
{
/**
* Debug function used to describe the provided value type and class.
*
* @param mixed $input
*
* @return string Returns a string containing the type of the variable and
* if a class is provided, the class name.
*
* @deprecated Utils::describeType() will be removed in guzzlehttp/guzzle:8.0. Use get_debug_type() instead.
*/
public static function describeType($input): string
{
\trigger_deprecation(
'guzzlehttp/guzzle',
'7.12',
'%s() is deprecated and will be removed in 8.0. Use get_debug_type() instead.',
__METHOD__
);
switch (\gettype($input)) {
case 'object':
return 'object('.\get_class($input).')';
case 'array':
return 'array('.\count($input).')';
default:
\ob_start();
\var_dump($input);
// normalize float vs double
/** @var string $varDumpContent */
$varDumpContent = \ob_get_clean();
return \str_replace('double(', 'float(', \rtrim($varDumpContent, " \n\r\t\0\x0B"));
}
}
/**
* 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;
}
/**
* Returns a debug stream based on the provided variable.
*
* @param mixed $value Optional value
*
* @return resource
*/
public static function debugResource($value = null)
{
if (\is_resource($value)) {
return $value;
}
if (\defined('STDOUT')) {
return \STDOUT;
}
return Psr7\Utils::tryFopen('php://output', 'w');
}
/**
* Chooses and creates a default handler to use based on the environment.
*
* The returned handler is not wrapped by any default middlewares.
*
* @param array{transport_sharing?: mixed, max_host_connections?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions Handler constructor options.
*
* @return callable(RequestInterface, array): Promise\PromiseInterface Returns the best handler for the given system.
*
* @throws \RuntimeException if no viable Handler is available.
*/
public static function chooseHandler(array $handlerOptions = []): callable
{
$sharingMode = CurlShareHandleState::normalizeMode($handlerOptions['transport_sharing'] ?? null, 'transport_sharing');
$sharingRequired = self::isTransportSharingRequired($sharingMode);
$connectionCapsRequired = self::hasConnectionCapOptions($handlerOptions);
$handler = self::createCurlHandler($sharingMode, $handlerOptions);
if ($sharingRequired && $handler === null) {
throw new \RuntimeException('Required transport sharing requires the PHP cURL extension, curl_exec() or curl_multi_exec(), and libcurl 7.21.2 or higher.');
}
if (\ini_get('allow_url_fopen')) {
return self::addStreamHandler($handler, $sharingMode, $sharingRequired, self::connectionCapOptions($handlerOptions));
}
if ($handler !== null) {
return $handler;
}
if ($connectionCapsRequired) {
throw new \RuntimeException('Connection cap options require a cap-capable cURL multi handler or the allow_url_fopen ini setting for stream fallback.');
}
throw new \RuntimeException('GuzzleHttp requires cURL, the allow_url_fopen ini setting, or a custom HTTP handler.');
}
private static function isTransportSharingRequired(string $sharingMode): bool
{
return $sharingMode === TransportSharing::HANDLER_REQUIRE;
}
/**
* @param array{max_host_connections?: mixed, max_total_connections?: mixed} $handlerOptions
*/
private static function hasConnectionCapOptions(array $handlerOptions): bool
{
return self::connectionCapOptions($handlerOptions) !== [];
}
/**
* @param array{max_host_connections?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions
*
* @return (callable(RequestInterface, array): Promise\PromiseInterface)|null
*/
private static function createCurlHandler(string $sharingMode, array $handlerOptions): ?callable
{
if (!\defined('CURLOPT_CUSTOMREQUEST') || !CurlVersion::supportsCurlHandler()) {
return null;
}
$connectionCapOptions = self::connectionCapOptions($handlerOptions);
if ($connectionCapOptions !== [] && (!CurlVersion::supportsConnectionCaps() || !\function_exists('curl_multi_exec'))) {
return null;
}
$curlHandlerOptions = self::createCurlHandlerOptions($sharingMode);
$curlMultiHandlerOptions = $curlHandlerOptions + $connectionCapOptions;
if (($handlerOptions['multiplex'] ?? null) === Multiplexing::NONE) {
// Forwarded to the CurlMultiHandler only: CurlHandler and
// StreamHandler validate known options, and both satisfy NONE
// per-request without a handler option.
$curlMultiHandlerOptions['multiplex'] = Multiplexing::NONE;
}
if (\function_exists('curl_multi_exec') && \function_exists('curl_exec')) {
$multiHandler = new CurlMultiHandler($curlMultiHandlerOptions);
if ($connectionCapOptions !== []) {
// Connection caps only govern transfers on the multi handle, so
// the synchronous CurlHandler fast path would escape them.
return $multiHandler;
}
return Proxy::wrapSync($multiHandler, new CurlHandler($curlHandlerOptions));
}
if ($connectionCapOptions === [] && \function_exists('curl_exec')) {
return new CurlHandler($curlHandlerOptions);
}
if (\function_exists('curl_multi_exec')) {
return new CurlMultiHandler($curlMultiHandlerOptions);
}
return null;
}
/**
* @return array<string, mixed>
*/
private static function createCurlHandlerOptions(string $sharingMode): array
{
if ($sharingMode === TransportSharing::NONE) {
return [];
}
$shareState = CurlShareHandleState::fromOption($sharingMode);
return $shareState === null ? [] : ['transport_sharing' => $shareState];
}
/**
* @param array{max_host_connections?: mixed, max_total_connections?: mixed} $handlerOptions
*
* @return array{max_host_connections?: int, max_total_connections?: int}
*/
private static function connectionCapOptions(array $handlerOptions): array
{
$options = [];
foreach (['max_host_connections', 'max_total_connections'] as $capOption) {
$value = $handlerOptions[$capOption] ?? null;
if ($value === null) {
continue;
}
if (!\is_int($value) || $value < 1) {
throw new InvalidArgumentException(\sprintf('%s must be a positive integer.', $capOption));
}
$options[$capOption] = $value;
}
return $options;
}
/**
* @param (callable(RequestInterface, array): Promise\PromiseInterface)|null $handler
* @param array{max_host_connections?: int, max_total_connections?: int} $connectionCapOptions
*
* @return callable(RequestInterface, array): Promise\PromiseInterface
*/
private static function addStreamHandler(?callable $handler, string $sharingMode, bool $sharingRequired, array $connectionCapOptions): callable
{
$streamHandler = new StreamHandler(['transport_sharing' => $sharingMode] + $connectionCapOptions);
if ($handler === null) {
return $streamHandler;
}
if (!$sharingRequired) {
$handler = Proxy::wrapTlsFallback($handler, $streamHandler);
}
return Proxy::wrapStreaming($handler, $streamHandler);
}
/**
* Get the default User-Agent string to use with Guzzle.
*/
public static function defaultUserAgent(): string
{
return sprintf('GuzzleHttp/%d', ClientInterface::MAJOR_VERSION);
}
/**
* Returns the default cacert bundle for the current system.
*
* First, the openssl.cafile and curl.cainfo php.ini settings are checked.
* If those settings are not configured, then the common locations for
* bundles found on Red Hat, CentOS, Fedora, Ubuntu, Debian, FreeBSD, OS X
* and Windows are checked. If any of these file locations are found on
* disk, they will be utilized.
*
* Note: the result of this function is cached for subsequent calls.
*
* @throws \RuntimeException if no bundle can be found.
*
* @deprecated Utils::defaultCaBundle will be removed in guzzlehttp/guzzle:8.0. This method is not needed in PHP 5.6+.
*/
public static function defaultCaBundle(): string
{
\trigger_deprecation('guzzlehttp/guzzle', '7.1', '%s() is deprecated and will be removed in 8.0. This method is not needed in PHP 5.6+.', __METHOD__);
static $cached = null;
static $cafiles = [
// Red Hat, CentOS, Fedora (provided by the ca-certificates package)
'/etc/pki/tls/certs/ca-bundle.crt',
// Ubuntu, Debian (provided by the ca-certificates package)
'/etc/ssl/certs/ca-certificates.crt',
// FreeBSD (provided by the ca_root_nss package)
'/usr/local/share/certs/ca-root-nss.crt',
// SLES 12 (provided by the ca-certificates package)
'/var/lib/ca-certificates/ca-bundle.pem',
// OS X provided by homebrew (using the default path)
'/usr/local/etc/openssl/cert.pem',
// Google app engine
'/etc/ca-certificates.crt',
// Windows?
'C:\\windows\\system32\\curl-ca-bundle.crt',
'C:\\windows\\curl-ca-bundle.crt',
];
if ($cached) {
return $cached;
}
if ($ca = \ini_get('openssl.cafile')) {
return $cached = $ca;
}
if ($ca = \ini_get('curl.cainfo')) {
return $cached = $ca;
}
foreach ($cafiles as $filename) {
if (\file_exists($filename)) {
return $cached = $filename;
}
}
throw new \RuntimeException(
<<< EOT
No system CA bundle could be found in any of the the common system locations.
PHP versions earlier than 5.6 are not properly configured to use the system's
CA bundle by default. In order to verify peer certificates, you will need to
supply the path on disk to a certificate bundle to the 'verify' request option:
https://github.com/guzzle/guzzle/blob/7.15/docs/request-options.md#verify. If
you do not need a specific certificate bundle, then Mozilla provides a commonly
used CA bundle which can be downloaded here (provided by the maintainer of
cURL): https://curl.se/ca/cacert.pem. Once you have a CA bundle available on
disk, you can set the 'openssl.cafile' PHP ini setting to point to the path to
the file, allowing you to omit the 'verify' request option. See
https://curl.se/docs/sslcerts.html for more information.
EOT
);
}
/**
* Creates an associative array of lowercase header names to the actual
* header casing.
*/
public static function normalizeHeaderKeys(array $headers): array
{
$result = [];
foreach (\array_keys($headers) as $key) {
$result[Psr7\Utils::asciiToLower((string) $key)] = $key;
}
return $result;
}
/**
* @param mixed $protocols
*
* @return string[]
*
* @throws InvalidArgumentException
*/
public static function normalizeProtocols($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);
}
/**
* Returns true if the provided host matches any of the no proxy areas.
*
* This method will strip a port from the host if it is present. Domain
* patterns are matched case-insensitively. Exact IP literal patterns are
* matched by their normalized binary address.
*
* Areas are matched in the following cases:
* 1. "*" (without quotes) always matches any hosts.
* 2. An exact domain or IP literal match.
* 3. A bare domain matches itself and its subdomains. e.g. 'mit.edu' will
* match 'mit.edu' and 'foo.mit.edu'.
* 4. The area starts with "." and the area is the last part of the host. e.g.
* '.mit.edu' will match any host that ends with '.mit.edu'.
* 5. IP CIDR entries match IP literal hosts. e.g. '192.168.0.0/16' will
* match '192.168.1.10' and 'fd00::/8' will match '[fd00::1]'.
*
* @param string $host Host to check against the patterns.
* @param string[] $noProxyArray An array of host or CIDR patterns.
*
* @throws InvalidArgumentException
*/
public static function isHostInNoProxy(string $host, array $noProxyArray): bool
{
if (\strlen($host) === 0) {
throw new InvalidArgumentException('Empty host provided');
}
$target = self::parseNoProxyHostString($host);
if ($target === null) {
return false;
}
return self::matchesNoProxyList($target, $noProxyArray);
}
/**
* Returns true if the provided URI matches any of the no proxy areas.
*
* Matching follows the same rules as isHostInNoProxy(), with the
* addition that areas may carry a port (e.g. "example.com:8080" or
* "[::1]:8080") which is compared against the URI port (or the scheme
* default port when the URI has none).
*
* @param mixed $noProxy No-proxy host, host-and-port, or CIDR patterns.
*
* @internal
*/
public static function isUriInNoProxy(UriInterface $uri, $noProxy): bool
{
if (\is_string($noProxy)) {
$noProxy = \explode(',', $noProxy);
}
if (!\is_array($noProxy)) {
return false;
}
$target = self::parseNoProxyTarget($uri);
if ($target === null) {
return false;
}
return self::matchesNoProxyList($target, $noProxy);
}
/**
* @param array{type: string, value: string, port: int|null, matchesRoot: bool} $target
* @param array<array-key, mixed> $noProxy
*/
private static function matchesNoProxyList(array $target, array $noProxy): bool
{
foreach ($noProxy as $area) {
if (!\is_string($area)) {
continue;
}
$area = \trim($area, " \n\r\t\0\x0B");
// Always match on wildcards.
if ($area === '*') {
return true;
}
$rule = self::parseNoProxyRule($area);
if ($rule !== null && self::noProxyRuleMatches($target, $rule)) {
return true;
}
}
return false;
}
/**
* @return array{type: string, value: string, port: int|null, matchesRoot: bool}|null
*/
private static function parseNoProxyTarget(UriInterface $uri): ?array
{
$host = $uri->getHost();
if ($host === '') {
return null;
}
return self::parseNoProxyHost($host, $uri->getPort() ?? self::getDefaultPort($uri->getScheme()), true);
}
/**
* @return array{type: string, value: string, port: int|null, matchesRoot: bool}|null
*/
private static function parseNoProxyHostString(string $host): ?array
{
$hostAndPort = self::splitNoProxyHostAndPort($host);
if ($hostAndPort === null) {
return null;
}
[$host] = $hostAndPort;
return self::parseNoProxyHost($host, null, true);
}
/**
* @return array{type: string, value: string, port: int|null, matchesRoot: bool}|array{type: string, value: string, prefix: int}|null
*/
private static function parseNoProxyRule(string $area): ?array
{
$area = \trim($area, " \n\r\t\0\x0B");
if ($area === '' || $area === '*') {
return null;
}
if (\strpos($area, '/') !== false) {
return self::parseNoProxyCidrRule($area);
}
$matchesRoot = true;
if ($area[0] === '.') {
$matchesRoot = false;
$area = \substr($area, 1);
}
$hostAndPort = self::splitNoProxyHostAndPort($area);
if ($hostAndPort === null) {
return null;
}
[$host, $port] = $hostAndPort;
if ($host === '*') {
if (!$matchesRoot) {
return null;
}
return [
'type' => 'wildcard',
'value' => '*',
'port' => $port,
'matchesRoot' => true,
];
}
$rule = self::parseNoProxyHost($host, $port, $matchesRoot);
if ($rule !== null && !$matchesRoot && $rule['type'] === 'ip') {
return null;
}
return $rule;
}
/**
* @return array{type: string, value: string, port: int|null, matchesRoot: bool}|null
*/
private static function parseNoProxyHost(string $host, ?int $port, bool $matchesRoot): ?array
{
if ($host !== '' && $host[0] === '[') {
if (\substr($host, -1) !== ']') {
return null;
}
$address = \substr($host, 1, -1);
if (!\filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
return null;
}
$host = $address;
}
$packedIp = self::packIpAddress($host);
if ($packedIp !== false) {
return [
'type' => 'ip',
'value' => $packedIp,
'port' => $port,
'matchesRoot' => $matchesRoot,
];
}
if ($host === '' || \strpos($host, ':') !== false) {
return null;
}
// Normalize a single DNS root dot for no-proxy domain matching.
if (\substr($host, -1) === '.') {
$host = \substr($host, 0, -1);
if ($host === '') {
return null;
}
}
return [
'type' => 'domain',
'value' => Psr7\Utils::asciiToLower($host),
'port' => $port,
'matchesRoot' => $matchesRoot,
];
}
/**
* @return array{0: string, 1: int|null}|null
*/
private static function splitNoProxyHostAndPort(string $area): ?array
{
if ($area !== '' && $area[0] === '[') {
$closingBracket = \strpos($area, ']');
if ($closingBracket === false) {
return null;
}
$host = \substr($area, 0, $closingBracket + 1);
$tail = \substr($area, $closingBracket + 1);
if ($tail === '') {
return [$host, null];
}
if ($tail[0] !== ':') {
return null;
}
$port = self::parseNoProxyPort(\substr($tail, 1));
return $port === null ? null : [$host, $port];
}
if (self::packIpAddress($area) !== false) {
return [$area, null];
}
$colon = \strrpos($area, ':');
if ($colon === false) {
return [$area, null];
}
$port = self::parseNoProxyPort(\substr($area, $colon + 1));
if ($port === null) {
return null;
}
return [\substr($area, 0, $colon), $port];
}
private static function parseNoProxyPort(string $port): ?int
{
return self::parseBoundedUnsignedInteger($port, 65535);
}
/**
* @return array{type: string, value: string, prefix: int}|null
*/
private static function parseNoProxyCidrRule(string $area): ?array
{
$slash = \strpos($area, '/');
if ($slash === false) {
return null;
}
$prefix = \substr($area, $slash + 1);
$network = \substr($area, 0, $slash);
if ($network !== '' && $network[0] === '[' && \substr($network, -1) === ']') {
$network = \substr($network, 1, -1);
}
$network = self::packIpAddress($network);
if ($network === false) {
return null;
}
$prefix = self::parseBoundedUnsignedInteger($prefix, \strlen($network) * 8);
if ($prefix === null) {
return null;
}
return [
'type' => 'cidr',
'value' => $network,
'prefix' => $prefix,
];
}
private static function parseBoundedUnsignedInteger(string $value, int $max): ?int
{
if ($value === '' || !\ctype_digit($value)) {
return null;
}
$normalized = \ltrim($value, '0');
$normalized = $normalized === '' ? '0' : $normalized;
$limit = (string) $max;
if (\strlen($normalized) > \strlen($limit) || (\strlen($normalized) === \strlen($limit) && \strcmp($normalized, $limit) > 0)) {
return null;
}
return (int) $normalized;
}
/**
* @param array{type: string, value: string, port: int|null, matchesRoot: bool} $target
* @param array{type: string, value: string, port?: int|null, matchesRoot?: bool, prefix?: int|null} $rule
*/
private static function noProxyRuleMatches(array $target, array $rule): bool
{
if ($rule['type'] === 'wildcard') {
return ($rule['port'] ?? null) === null || $rule['port'] === $target['port'];
}
if ($rule['type'] === 'cidr') {
if ($target['type'] !== 'ip' || !isset($rule['prefix'])) {
return false;
}
if (\strlen($target['value']) !== \strlen($rule['value'])) {
return false;
}
return self::ipMatchesPrefix($target['value'], $rule['value'], $rule['prefix']);
}
if (($rule['port'] ?? null) !== null && $rule['port'] !== $target['port']) {
return false;
}
if ($rule['type'] !== $target['type']) {
return false;
}
if ($rule['type'] === 'ip') {
return $rule['value'] === $target['value'];
}
if (($rule['matchesRoot'] ?? false) && $target['value'] === $rule['value']) {
return true;
}
$suffix = '.'.$rule['value'];
return \substr($target['value'], -\strlen($suffix)) === $suffix;
}
/**
* @return string|false
*/
private static function packIpAddress(string $ip)
{
if (!\filter_var($ip, \FILTER_VALIDATE_IP)) {
return false;
}
return \inet_pton($ip);
}
private static function ipMatchesPrefix(string $address, string $network, int $prefix): bool
{
$fullBytes = \intdiv($prefix, 8);
$remainingBits = $prefix % 8;
if ($fullBytes > 0 && \substr($address, 0, $fullBytes) !== \substr($network, 0, $fullBytes)) {
return false;
}
if ($remainingBits === 0) {
return true;
}
$mask = (0xFF << (8 - $remainingBits)) & 0xFF;
return (\ord($address[$fullBytes]) & $mask) === (\ord($network[$fullBytes]) & $mask);
}
private static function getDefaultPort(string $scheme): ?int
{
if ($scheme === 'http') {
return 80;
}
if ($scheme === 'https') {
return 443;
}
return null;
}
/**
* Wrapper for json_decode that throws when an error occurs.
*
* @param string $json JSON data to parse
* @param bool $assoc When true, returned objects will be converted
* into associative arrays.
* @param int $depth User specified recursion depth.
* @param int $options Bitmask of JSON decode options.
*
* @return object|array|string|int|float|bool|null
*
* @throws InvalidArgumentException if the JSON cannot be decoded.
*
* @see https://www.php.net/manual/en/function.json-decode.php
* @deprecated Utils::jsonDecode() will be removed in guzzlehttp/guzzle:8.0. Use PHP's json_decode() instead.
*/
public static function jsonDecode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)
{
\trigger_deprecation('guzzlehttp/guzzle', '7.15', '%s() is deprecated and will be removed in 8.0. Use PHP\'s json_decode() instead.', __METHOD__);
if ($depth < 1) {
throw new InvalidArgumentException('json_decode error: Maximum stack depth exceeded');
}
$data = \json_decode($json, $assoc, $depth, $options);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_decode error: '.\json_last_error_msg());
}
return $data;
}
/**
* Wrapper for JSON encoding that throws when an error occurs.
*
* @param mixed $value The value being encoded
* @param int $options JSON encode option bitmask
* @param int $depth Set the maximum depth. Must be greater than zero.
*
* @throws InvalidArgumentException if the JSON cannot be encoded.
*
* @see https://www.php.net/manual/en/function.json-encode.php
* @deprecated Utils::jsonEncode() will be removed in guzzlehttp/guzzle:8.0. Use PHP's json_encode() instead.
*/
public static function jsonEncode($value, int $options = 0, int $depth = 512): string
{
\trigger_deprecation('guzzlehttp/guzzle', '7.15', '%s() is deprecated and will be removed in 8.0. Use PHP\'s json_encode() instead.', __METHOD__);
$json = \json_encode($value, $options, $depth);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_encode error: '.\json_last_error_msg());
}
/** @var string */
return $json;
}
/**
* Wrapper for the hrtime() or microtime() functions
* (depending on the PHP version, one of the two is used)
*
* @return float UNIX timestamp
*
* @internal
*/
public static function currentTime(): float
{
return (float) \function_exists('hrtime') ? \hrtime(true) / 1e9 : \microtime(true);
}
/**
* @param mixed $value
*
* @internal
*/
public static function normalizeIdnConversionOption($value): ?int
{
if ($value === null || $value === false) {
return null;
}
if ($value === true) {
return \IDNA_DEFAULT;
}
if (\is_int($value)) {
return $value;
}
if ((\is_string($value) && \is_numeric($value)) || (\is_float($value) && \is_finite($value))) {
\trigger_deprecation(
'guzzlehttp/guzzle',
'7.11',
'Passing %s as the "idn_conversion" request option is deprecated; guzzlehttp/guzzle 8.0 will reject values that are not true, false, null, or an integer IDNA_* bitmask.',
\get_debug_type($value)
);
return (int) $value;
}
throw new InvalidArgumentException('idn_conversion must be true, false, null, or an integer IDNA_* bitmask');
}
/**
* @throws InvalidArgumentException
*
* @internal
*/
public static function idnUriConvert(UriInterface $uri, int $options = 0): UriInterface
{
if ($uri->getHost()) {
$asciiHost = self::idnToAsci($uri->getHost(), $options, $info);
if ($asciiHost === false) {
$errorBitSet = $info['errors'] ?? 0;
$errorConstants = array_filter(array_keys(get_defined_constants()), static function (string $name): bool {
return substr($name, 0, 11) === 'IDNA_ERROR_';
});
$errors = [];
foreach ($errorConstants as $errorConstant) {
if ($errorBitSet & constant($errorConstant)) {
$errors[] = $errorConstant;
}
}
$errorMessage = 'IDN conversion failed';
if ($errors) {
$errorMessage .= ' (errors: '.implode(', ', $errors).')';
}
throw new InvalidArgumentException($errorMessage);
}
if ($uri->getHost() !== $asciiHost) {
// Replace URI only if the ASCII version is different
$uri = $uri->withHost($asciiHost);
}
}
return $uri;
}
/**
* @internal
*/
public static function getenv(string $name): ?string
{
if (isset($_SERVER[$name])) {
return (string) $_SERVER[$name];
}
if (\PHP_SAPI === 'cli' && ($value = \getenv($name)) !== false && $value !== null) {
return (string) $value;
}
return null;
}
/**
* @return string|false
*/
private static function idnToAsci(string $domain, int $options, ?array &$info = [])
{
if (\function_exists('idn_to_ascii') && \defined('INTL_IDNA_VARIANT_UTS46')) {
return \idn_to_ascii($domain, $options, \INTL_IDNA_VARIANT_UTS46, $info);
}
throw new \Error('ext-idn or symfony/polyfill-intl-idn not loaded or too old');
}
}
@@ -0,0 +1,268 @@
<?php
namespace GuzzleHttp;
/**
* Debug function used to describe the provided value type and class.
*
* @param mixed $input Any type of variable to describe the type of. This
* parameter misses a typehint because of that.
*
* @return string Returns a string containing the type of the variable and
* if a class is provided, the class name.
*
* @deprecated describe_type will be removed in guzzlehttp/guzzle:8.0. Use get_debug_type() instead.
*/
function describe_type($input): string
{
\trigger_deprecation('guzzlehttp/guzzle', '7.1', '%s() is deprecated and will be removed in 8.0. Use get_debug_type() instead.', __FUNCTION__);
switch (\gettype($input)) {
case 'object':
return 'object('.\get_class($input).')';
case 'array':
return 'array('.\count($input).')';
default:
\ob_start();
\var_dump($input);
// normalize float vs double
/** @var string $varDumpContent */
$varDumpContent = \ob_get_clean();
return \str_replace('double(', 'float(', \rtrim($varDumpContent, " \n\r\t\0\x0B"));
}
}
/**
* Parses an array of header lines into an associative array of headers.
*
* @param iterable $lines Header lines array of strings in the following
* format: "Name: Value"
*
* @deprecated headers_from_lines will be removed in guzzlehttp/guzzle:8.0. Use Utils::headersFromLines instead.
*/
function headers_from_lines(iterable $lines): array
{
\trigger_deprecation('guzzlehttp/guzzle', '7.1', '%s() is deprecated and will be removed in 8.0. Use Utils::headersFromLines() instead.', __FUNCTION__);
return Utils::headersFromLines($lines);
}
/**
* Returns a debug stream based on the provided variable.
*
* @param mixed $value Optional value
*
* @return resource
*
* @deprecated debug_resource will be removed in guzzlehttp/guzzle:8.0. Use Utils::debugResource instead.
*/
function debug_resource($value = null)
{
\trigger_deprecation('guzzlehttp/guzzle', '7.1', '%s() is deprecated and will be removed in 8.0. Use Utils::debugResource() instead.', __FUNCTION__);
return Utils::debugResource($value);
}
/**
* Chooses and creates a default handler to use based on the environment.
*
* The returned handler is not wrapped by any default middlewares.
*
* @return callable(\Psr\Http\Message\RequestInterface, array): Promise\PromiseInterface Returns the best handler for the given system.
*
* @throws \RuntimeException if no viable Handler is available.
*
* @deprecated choose_handler will be removed in guzzlehttp/guzzle:8.0. Use Utils::chooseHandler instead.
*/
function choose_handler(): callable
{
\trigger_deprecation('guzzlehttp/guzzle', '7.1', '%s() is deprecated and will be removed in 8.0. Use Utils::chooseHandler() instead.', __FUNCTION__);
return Utils::chooseHandler();
}
/**
* Get the default User-Agent string to use with Guzzle.
*
* @deprecated default_user_agent will be removed in guzzlehttp/guzzle:8.0. Use Utils::defaultUserAgent instead.
*/
function default_user_agent(): string
{
\trigger_deprecation('guzzlehttp/guzzle', '7.1', '%s() is deprecated and will be removed in 8.0. Use Utils::defaultUserAgent() instead.', __FUNCTION__);
return Utils::defaultUserAgent();
}
/**
* Returns the default cacert bundle for the current system.
*
* First, the openssl.cafile and curl.cainfo php.ini settings are checked.
* If those settings are not configured, then the common locations for
* bundles found on Red Hat, CentOS, Fedora, Ubuntu, Debian, FreeBSD, OS X
* and Windows are checked. If any of these file locations are found on
* disk, they will be utilized.
*
* Note: the result of this function is cached for subsequent calls.
*
* @throws \RuntimeException if no bundle can be found.
*
* @deprecated default_ca_bundle will be removed in guzzlehttp/guzzle:8.0. This function is not needed in PHP 5.6+.
*/
function default_ca_bundle(): string
{
\trigger_deprecation('guzzlehttp/guzzle', '7.1', '%s() is deprecated and will be removed in 8.0. This function is not needed in PHP 5.6+.', __FUNCTION__);
static $cached = null;
static $cafiles = [
// Red Hat, CentOS, Fedora (provided by the ca-certificates package)
'/etc/pki/tls/certs/ca-bundle.crt',
// Ubuntu, Debian (provided by the ca-certificates package)
'/etc/ssl/certs/ca-certificates.crt',
// FreeBSD (provided by the ca_root_nss package)
'/usr/local/share/certs/ca-root-nss.crt',
// SLES 12 (provided by the ca-certificates package)
'/var/lib/ca-certificates/ca-bundle.pem',
// OS X provided by homebrew (using the default path)
'/usr/local/etc/openssl/cert.pem',
// Google app engine
'/etc/ca-certificates.crt',
// Windows?
'C:\\windows\\system32\\curl-ca-bundle.crt',
'C:\\windows\\curl-ca-bundle.crt',
];
if ($cached) {
return $cached;
}
if ($ca = \ini_get('openssl.cafile')) {
return $cached = $ca;
}
if ($ca = \ini_get('curl.cainfo')) {
return $cached = $ca;
}
foreach ($cafiles as $filename) {
if (\file_exists($filename)) {
return $cached = $filename;
}
}
throw new \RuntimeException(
<<< EOT
No system CA bundle could be found in any of the the common system locations.
PHP versions earlier than 5.6 are not properly configured to use the system's
CA bundle by default. In order to verify peer certificates, you will need to
supply the path on disk to a certificate bundle to the 'verify' request option:
https://github.com/guzzle/guzzle/blob/7.15/docs/request-options.md#verify. If
you do not need a specific certificate bundle, then Mozilla provides a commonly
used CA bundle which can be downloaded here (provided by the maintainer of
cURL): https://curl.se/ca/cacert.pem. Once you have a CA bundle available on
disk, you can set the 'openssl.cafile' PHP ini setting to point to the path to
the file, allowing you to omit the 'verify' request option. See
https://curl.se/docs/sslcerts.html for more information.
EOT
);
}
/**
* Creates an associative array of lowercase header names to the actual
* header casing.
*
* @deprecated normalize_header_keys will be removed in guzzlehttp/guzzle:8.0. Use Utils::normalizeHeaderKeys instead.
*/
function normalize_header_keys(array $headers): array
{
\trigger_deprecation('guzzlehttp/guzzle', '7.1', '%s() is deprecated and will be removed in 8.0. Use Utils::normalizeHeaderKeys() instead.', __FUNCTION__);
return Utils::normalizeHeaderKeys($headers);
}
/**
* Returns true if the provided host matches any of the no proxy areas.
*
* This method will strip a port from the host if it is present. Each pattern
* can be matched with an exact match (e.g., "foo.com" == "foo.com") or a
* partial match: (e.g., "foo.com" == "baz.foo.com" and ".foo.com" ==
* "baz.foo.com", but ".foo.com" != "foo.com").
*
* Areas are matched in the following cases:
* 1. "*" (without quotes) always matches any hosts.
* 2. An exact match.
* 3. The area starts with "." and the area is the last part of the host. e.g.
* '.mit.edu' will match any host that ends with '.mit.edu'.
*
* @param string $host Host to check against the patterns.
* @param string[] $noProxyArray An array of host patterns.
*
* @throws Exception\InvalidArgumentException
*
* @deprecated is_host_in_noproxy will be removed in guzzlehttp/guzzle:8.0. Use Utils::isHostInNoProxy instead.
*/
function is_host_in_noproxy(string $host, array $noProxyArray): bool
{
\trigger_deprecation('guzzlehttp/guzzle', '7.1', '%s() is deprecated and will be removed in 8.0. Use Utils::isHostInNoProxy() instead.', __FUNCTION__);
return Utils::isHostInNoProxy($host, $noProxyArray);
}
/**
* Wrapper for json_decode that throws when an error occurs.
*
* @param string $json JSON data to parse
* @param bool $assoc When true, returned objects will be converted
* into associative arrays.
* @param int $depth User specified recursion depth.
* @param int $options Bitmask of JSON decode options.
*
* @return object|array|string|int|float|bool|null
*
* @throws Exception\InvalidArgumentException if the JSON cannot be decoded.
*
* @see https://www.php.net/manual/en/function.json-decode.php
* @deprecated json_decode will be removed in guzzlehttp/guzzle:8.0. Use PHP's json_decode() instead.
*/
function json_decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)
{
\trigger_deprecation('guzzlehttp/guzzle', '7.1', '%s() is deprecated and will be removed in 8.0. Use PHP\'s json_decode() instead.', __FUNCTION__);
if ($depth < 1) {
throw new Exception\InvalidArgumentException('json_decode error: Maximum stack depth exceeded');
}
$data = \json_decode($json, $assoc, $depth, $options);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new Exception\InvalidArgumentException('json_decode error: '.\json_last_error_msg());
}
/** @var object|array|string|int|float|bool|null $data */
return $data;
}
/**
* Wrapper for JSON encoding that throws when an error occurs.
*
* @param mixed $value The value being encoded
* @param int $options JSON encode option bitmask
* @param int $depth Set the maximum depth. Must be greater than zero.
*
* @throws Exception\InvalidArgumentException if the JSON cannot be encoded.
*
* @see https://www.php.net/manual/en/function.json-encode.php
* @deprecated json_encode will be removed in guzzlehttp/guzzle:8.0. Use PHP's json_encode() instead.
*/
function json_encode($value, int $options = 0, int $depth = 512): string
{
\trigger_deprecation('guzzlehttp/guzzle', '7.1', '%s() is deprecated and will be removed in 8.0. Use PHP\'s json_encode() instead.', __FUNCTION__);
/** @var positive-int $depth */
$json = \json_encode($value, $options, $depth);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new Exception\InvalidArgumentException('json_encode error: '.\json_last_error_msg());
}
/** @var non-empty-string $json */
return $json;
}
@@ -0,0 +1,6 @@
<?php
// Don't redefine the functions if included multiple times.
if (!\function_exists('GuzzleHttp\describe_type')) {
require __DIR__.'/functions.php';
}
@@ -0,0 +1,230 @@
# CHANGELOG
## 2.5.2 - 2026-08-05
### Fixed
- Fixed `EachPromise` abandoning its aggregate when the pending window drains unsettled
- Fixed `EachPromise` admitting new work after its aggregate has settled
## 2.5.1 - 2026-07-08
### Fixed
- Fixed recursive `Utils::all()` rejecting generator inputs
## 2.5.0 - 2026-06-02
### Deprecated
- Deprecated passing non-iterable inputs to promise collection helpers and `EachPromise`
## 2.4.1 - 2026-05-20
### Fixed
- Fixed cancelling settled coroutines when no current promise remains
## 2.4.0 - 2026-05-20
### Changed
- Empty `EachPromise` instances now resolve when the task queue runs without `wait()`
## 2.3.1 - 2026-05-19
### Fixed
- Fixed `Utils::inspect()` returning the internal reason array instead of the `AggregateException`
## 2.3.0 - 2025-08-22
### Added
- PHP 8.5 support
## 2.2.0 - 2025-03-27
### Fixed
- Revert "Allow an empty EachPromise to be resolved by running the queue"
## 2.1.0 - 2025-03-27
### Added
- Allow an empty EachPromise to be resolved by running the queue
## 2.0.4 - 2024-10-17
### Fixed
- Once settled, don't allow further rejection of additional promises
## 2.0.3 - 2024-07-18
### Changed
- PHP 8.4 support
## 2.0.2 - 2023-12-03
### Changed
- Replaced `call_user_func*` with native calls
## 2.0.1 - 2023-08-03
### Changed
- PHP 8.3 support
## 2.0.0 - 2023-05-21
### Added
- Added PHP 7 type hints
### Changed
- All previously non-final non-exception classes have been marked as soft-final
### Removed
- Dropped PHP < 7.2 support
- All functions in the `GuzzleHttp\Promise` namespace
## 1.5.3 - 2023-05-21
### Changed
- Removed remaining usage of deprecated functions
## 1.5.2 - 2022-08-07
### Changed
- Officially support PHP 8.2
## 1.5.1 - 2021-10-22
### Fixed
- Revert "Call handler when waiting on fulfilled/rejected Promise"
- Fix pool memory leak when empty array of promises provided
## 1.5.0 - 2021-10-07
### Changed
- Call handler when waiting on fulfilled/rejected Promise
- Officially support PHP 8.1
### Fixed
- Fix manually settle promises generated with `Utils::task`
## 1.4.1 - 2021-02-18
### Fixed
- Fixed `each_limit` skipping promises and failing
## 1.4.0 - 2020-09-30
### Added
- Support for PHP 8
- Optional `$recursive` flag to `all`
- Replaced functions by static methods
### Fixed
- Fix empty `each` processing
- Fix promise handling for Iterators of non-unique keys
- Fixed `method_exists` crashes on PHP 8
- Memory leak on exceptions
## 1.3.1 - 2016-12-20
### Fixed
- `wait()` foreign promise compatibility
## 1.3.0 - 2016-11-18
### Added
- Adds support for custom task queues.
### Fixed
- Fixed coroutine promise memory leak.
## 1.2.0 - 2016-05-18
### Changed
- Update to now catch `\Throwable` on PHP 7+
## 1.1.0 - 2016-03-07
### Changed
- Update EachPromise to prevent recurring on a iterator when advancing, as this
could trigger fatal generator errors.
- Update Promise to allow recursive waiting without unwrapping exceptions.
## 1.0.3 - 2015-10-15
### Changed
- Update EachPromise to immediately resolve when the underlying promise iterator
is empty. Previously, such a promise would throw an exception when its `wait`
function was called.
## 1.0.2 - 2015-05-15
### Changed
- Conditionally require functions.php.
## 1.0.1 - 2015-06-24
### Changed
- Updating EachPromise to call next on the underlying promise iterator as late
as possible to ensure that generators that generate new requests based on
callbacks are not iterated until after callbacks are invoked.
## 1.0.0 - 2015-05-12
- Initial release
@@ -0,0 +1,24 @@
The MIT License (MIT)
Copyright (c) 2015 Michael Dowling <mtdowling@gmail.com>
Copyright (c) 2015 Graham Campbell <hello@gjcampbell.co.uk>
Copyright (c) 2017 Tobias Schultze <webmaster@tubo-world.de>
Copyright (c) 2020 Tobias Nyholm <tobias.nyholm@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.
@@ -0,0 +1,536 @@
# Guzzle Promises
[Promises/A+](https://promisesaplus.com/) implementation that handles promise
chaining and resolution iteratively, allowing for "infinite" promise chaining
while keeping the stack size constant. Read [this blog post](https://blog.domenic.me/youre-missing-the-point-of-promises/)
for a general introduction to promises.
- [Features](#features)
- [Quick start](#quick-start)
- [Synchronous wait](#synchronous-wait)
- [Cancellation](#cancellation)
- [API](#api)
- [Promise](#promise)
- [FulfilledPromise](#fulfilledpromise)
- [RejectedPromise](#rejectedpromise)
- [Promise interop](#promise-interop)
- [Implementation notes](#implementation-notes)
## Features
- [Promises/A+](https://promisesaplus.com/) implementation.
- Promise resolution and chaining is handled iteratively, allowing for
"infinite" promise chaining.
- Promises have a synchronous `wait` method.
- Promises can be cancelled.
- Works with any object that has a `then` function.
- C# style async/await coroutine promises using
`GuzzleHttp\Promise\Coroutine::of()`.
## Installation
```shell
composer require guzzlehttp/promises
```
## Version Guidance
| Version | Status | PHP Version |
|---------|---------------------|--------------|
| 1.x | Security fixes only | >=5.5,<8.3 |
| 2.x | Latest | >=7.2.5,<8.6 |
## Quick Start
A *promise* represents the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
### Callbacks
Callbacks are registered with the `then` method by providing an optional
`$onFulfilled` followed by an optional `$onRejected` function.
```php
use GuzzleHttp\Promise\Promise;
$promise = new Promise();
$promise->then(
// $onFulfilled
function ($value) {
echo 'The promise was fulfilled.';
},
// $onRejected
function ($reason) {
echo 'The promise was rejected.';
}
);
```
*Resolving* a promise means that you either fulfill a promise with a *value* or
reject a promise with a *reason*. Resolving a promise triggers callbacks
registered with the promise's `then` method. These callbacks are triggered
only once and in the order in which they were added.
### Resolving a Promise
Promises are fulfilled using the `resolve($value)` method. Resolving a promise
with any value other than a `GuzzleHttp\Promise\RejectedPromise` will trigger
all of the onFulfilled callbacks (resolving a promise with a rejected promise
will reject the promise and trigger the `$onRejected` callbacks).
```php
use GuzzleHttp\Promise\Promise;
$promise = new Promise();
$promise
->then(function ($value) {
// Return a value and don't break the chain
return "Hello, " . $value;
})
// This then is executed after the first then and receives the value
// returned from the first then.
->then(function ($value) {
echo $value;
});
// Resolving the promise triggers the $onFulfilled callbacks and outputs
// "Hello, reader."
$promise->resolve('reader.');
```
### Promise Forwarding
Promises can be chained one after the other. Each then in the chain is a new
promise. The return value of a promise is what's forwarded to the next
promise in the chain. Returning a promise in a `then` callback will cause the
subsequent promises in the chain to only be fulfilled when the returned promise
has been fulfilled. The next promise in the chain will be invoked with the
resolved value of the promise.
```php
use GuzzleHttp\Promise\Promise;
$promise = new Promise();
$nextPromise = new Promise();
$promise
->then(function ($value) use ($nextPromise) {
echo $value;
return $nextPromise;
})
->then(function ($value) {
echo $value;
});
// Triggers the first callback and outputs "A"
$promise->resolve('A');
// Triggers the second callback and outputs "B"
$nextPromise->resolve('B');
```
### Promise Rejection
When a promise is rejected, the `$onRejected` callbacks are invoked with the
rejection reason.
```php
use GuzzleHttp\Promise\Promise;
$promise = new Promise();
$promise->then(null, function ($reason) {
echo $reason;
});
$promise->reject('Error!');
// Outputs "Error!"
```
### Rejection Forwarding
If an exception is thrown in an `$onRejected` callback, subsequent
`$onRejected` callbacks are invoked with the thrown exception as the reason.
```php
use GuzzleHttp\Promise\Promise;
$promise = new Promise();
$promise->then(null, function ($reason) {
throw new Exception($reason);
})->then(null, function ($reason) {
assert($reason->getMessage() === 'Error!');
});
$promise->reject('Error!');
```
You can also forward a rejection down the promise chain by returning a
`GuzzleHttp\Promise\RejectedPromise` in either an `$onFulfilled` or
`$onRejected` callback.
```php
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Promise\RejectedPromise;
$promise = new Promise();
$promise->then(null, function ($reason) {
return new RejectedPromise($reason);
})->then(null, function ($reason) {
assert($reason === 'Error!');
});
$promise->reject('Error!');
```
If an exception is not thrown in a `$onRejected` callback and the callback
does not return a rejected promise, downstream `$onFulfilled` callbacks are
invoked using the value returned from the `$onRejected` callback.
```php
use GuzzleHttp\Promise\Promise;
$promise = new Promise();
$promise
->then(null, function ($reason) {
return "It's ok";
})
->then(function ($value) {
assert($value === "It's ok");
});
$promise->reject('Error!');
```
## Synchronous Wait
You can synchronously force promises to complete using a promise's `wait`
method. When creating a promise, you can provide a wait function that is used
to synchronously force a promise to complete. When a wait function is invoked
it is expected to deliver a value to the promise or reject the promise. If the
wait function does not deliver a value, then an exception is thrown. The wait
function provided to a promise constructor is invoked when the `wait` function
of the promise is called.
```php
$promise = new Promise(function () use (&$promise) {
$promise->resolve('foo');
});
// Calling wait will return the value of the promise.
echo $promise->wait(); // outputs "foo"
```
If a throwable is encountered while invoking the wait function of a promise,
the promise is rejected with the throwable and the throwable is thrown.
```php
$promise = new Promise(function () use (&$promise) {
throw new Exception('foo');
});
$promise->wait(); // throws the exception.
```
Calling `wait` on a promise that has been fulfilled will not trigger the wait
function. It will simply return the previously resolved value.
```php
$promise = new Promise(function () { die('this is not called!'); });
$promise->resolve('foo');
echo $promise->wait(); // outputs "foo"
```
Calling `wait` on a promise that has been rejected will throw. If the rejection
reason is an instance of `\Throwable` the reason is thrown.
Otherwise, a `GuzzleHttp\Promise\RejectionException` is thrown and the reason
can be obtained by calling the `getReason` method of the exception.
```php
$promise = new Promise();
$promise->reject('foo');
$promise->wait();
```
> PHP Fatal error: Uncaught exception 'GuzzleHttp\Promise\RejectionException' with message 'The promise was rejected with value: foo'
### Unwrapping a Promise
When synchronously waiting on a promise, you are joining the state of the
promise into the current state of execution (i.e., return the value of the
promise if it was fulfilled or throw an exception if it was rejected). This is
called "unwrapping" the promise. Waiting on a promise will by default unwrap
the promise state.
You can force a promise to resolve and *not* unwrap the state of the promise
by passing `false` to the first argument of the `wait` function:
```php
$promise = new Promise();
$promise->reject('foo');
// This will not throw an exception. It simply ensures the promise has
// been resolved.
$promise->wait(false);
```
When unwrapping a promise, the resolved value of the promise will be waited
upon until the unwrapped value is not a promise. This means that if you resolve
promise A with a promise B and unwrap promise A, the value returned by the
wait function will be the value delivered to promise B.
**Note**: when you do not unwrap the promise, no value is returned.
## Cancellation
You can cancel a promise that has not yet been fulfilled using the `cancel()`
method of a promise. When creating a promise you can provide an optional
cancel function that when invoked cancels the action of computing a resolution
of the promise.
## API
### Promise
When creating a promise object, you can provide an optional `$waitFn` and
`$cancelFn`. `$waitFn` is a function that is invoked with no arguments and is
expected to resolve the promise. `$cancelFn` is a function with no arguments
that is expected to cancel the computation of a promise. It is invoked when the
`cancel()` method of a promise is called.
```php
use GuzzleHttp\Promise\Promise;
$promise = new Promise(
function () use (&$promise) {
$promise->resolve('waited');
},
function () {
// do something that will cancel the promise computation (e.g., close
// a socket, cancel a database query, etc...)
}
);
assert('waited' === $promise->wait());
```
A promise has the following methods:
- `then(?callable $onFulfilled = null, ?callable $onRejected = null) : PromiseInterface`
Appends fulfillment and rejection handlers to the promise, and returns a new
promise resolving to the return value of the called handler. If a handler is
omitted, the original fulfillment value or rejection reason is forwarded.
- `otherwise(callable $onRejected) : PromiseInterface`
Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled.
- `wait($unwrap = true) : mixed`
Synchronously waits on the promise to complete.
`$unwrap` controls whether or not the value of the promise is returned for a
fulfilled promise or if an exception is thrown if the promise is rejected.
This is set to `true` by default.
- `cancel()`
Attempts to cancel the promise if possible. The promise being cancelled and
the parent most ancestor that has not yet been resolved will also be
cancelled. Any promises waiting on the cancelled promise to resolve will also
be cancelled.
- `getState() : string`
Returns the state of the promise. One of `pending`, `fulfilled`, or
`rejected`.
- `resolve($value)`
Fulfills the promise with the given `$value`.
- `reject($reason)`
Rejects the promise with the given `$reason`.
### FulfilledPromise
A fulfilled promise can be created to represent a promise that has been
fulfilled.
```php
use GuzzleHttp\Promise\FulfilledPromise;
$promise = new FulfilledPromise('value');
// Fulfilled callbacks are immediately invoked.
$promise->then(function ($value) {
echo $value;
});
```
### RejectedPromise
A rejected promise can be created to represent a promise that has been
rejected.
```php
use GuzzleHttp\Promise\RejectedPromise;
$promise = new RejectedPromise('Error');
// Rejected callbacks are immediately invoked.
$promise->then(null, function ($reason) {
echo $reason;
});
```
## Promise Interoperability
This library works with foreign promises that have a `then` method. This means
you can use Guzzle promises with [React promises](https://github.com/reactphp/promise)
for example. When a foreign promise is returned inside of a then method
callback, promise resolution will occur recursively.
```php
// Create a React promise
$deferred = new React\Promise\Deferred();
$reactPromise = $deferred->promise();
// Create a Guzzle promise that is fulfilled with a React promise.
$guzzlePromise = new GuzzleHttp\Promise\Promise();
$guzzlePromise->then(function ($value) use ($reactPromise) {
// Do something something with the value...
// Return the React promise
return $reactPromise;
});
```
Please note that wait and cancel chaining is no longer possible when forwarding
a foreign promise. You will need to wrap a third-party promise with a Guzzle
promise in order to utilize wait and cancel functions with foreign promises.
### Event Loop Integration
In order to keep the stack size constant, Guzzle promises are resolved
asynchronously using a task queue. When waiting on promises synchronously, the
task queue will be automatically run to ensure that the blocking promise and
any forwarded promises are resolved. When using promises asynchronously in an
event loop, you will need to run the task queue on each tick of the loop. If
you do not run the task queue, then promises will not be resolved.
You can run the task queue using the `run()` method of the global task queue
instance.
```php
// Get the global task queue
$queue = GuzzleHttp\Promise\Utils::queue();
$queue->run();
```
For example, you could use Guzzle promises with React using a short periodic
timer. Avoid zero-interval timers because they may keep the loop busy even when
there is no promise work to run.
```php
$loop = React\EventLoop\Factory::create();
$loop->addPeriodicTimer(0.01, [$queue, 'run']);
```
## Implementation Notes
### Promise Resolution and Chaining is Handled Iteratively
By shuffling pending handlers from one owner to another, promises are
resolved iteratively, allowing for "infinite" then chaining.
```php
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Promise\Promise;
$parent = new Promise();
$p = $parent;
for ($i = 0; $i < 1000; $i++) {
$p = $p->then(function ($v) {
// The stack size remains constant (a good thing)
echo xdebug_get_stack_depth() . ', ';
return $v + 1;
});
}
$parent->resolve(0);
var_dump($p->wait()); // int(1000)
```
When a promise is fulfilled or rejected with a non-promise value, the promise
then takes ownership of the handlers of each child promise and delivers values
down the chain without using recursion.
When a promise is resolved with another promise, the original promise transfers
all of its pending handlers to the new promise. When the new promise is
eventually resolved, all of the pending handlers are delivered the forwarded
value.
### A Promise is the Deferred
Some promise libraries implement promises using a deferred object to represent
a computation and a promise object to represent the delivery of the result of
the computation. This is a nice separation of computation and delivery because
consumers of the promise cannot modify the value that will be eventually
delivered.
One side effect of being able to implement promise resolution and chaining
iteratively is that you need to be able for one promise to reach into the state
of another promise to shuffle around ownership of handlers. In order to achieve
this without making the handlers of a promise publicly mutable, a promise is
also the deferred value, allowing promises of the same parent class to reach
into and modify the private properties of promises of the same type. While this
does allow consumers of the value to modify the resolution or rejection of the
deferred, it is a small price to pay for keeping the stack size constant.
```php
$promise = new Promise();
$promise->then(function ($value) { echo $value; });
// The promise is the deferred value, so you can deliver a value to it.
$promise->resolve('foo');
// prints "foo"
```
## Upgrading
See [UPGRADING.md](UPGRADING.md) for package upgrade notes.
## 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. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/promises/security/policy) for more information.
## 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-promises?utm_source=packagist-guzzlehttp-promises&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
@@ -0,0 +1,83 @@
Guzzle Promises Upgrade Guide
=============================
1.x to 2.0
----------
Guzzle Promises 2.0 is a major release that removes deprecated APIs, raises the
minimum PHP version, and adds PHP 7 parameter and return types. Applications that
only use the object-oriented API should usually need small changes. Applications
that call helper functions, implement package interfaces, extend package classes,
or pass invalid argument types need closer review.
#### PHP Version and Dependencies
Guzzle Promises 2.0 requires PHP `^7.2.5 || ^8.0`. Guzzle Promises 1.x
supported PHP `>=5.5`.
#### PHP 7 Type Hints and Return Types
Type hints and return types were added wherever possible. Please make sure:
- You pass values of the documented type when calling methods and functions.
- Classes that implement `PromiseInterface`, `PromisorInterface`, or
`TaskQueueInterface` update method signatures to remain compatible.
- Classes that extend Guzzle Promises classes update any overridden method
signatures to remain compatible.
- Code that expected package-specific exceptions for invalid argument types may
now receive PHP `TypeError` exceptions instead.
#### Soft-Final Classes
All previously non-final non-exception classes are now final or annotated with
`@final`. If your code extends one of these classes, replace inheritance with
composition or implement the relevant interface directly.
#### Removed Function API
The static API was introduced in 1.4.0 to mitigate problems with functions
conflicting between global and local copies of the package. The function API was
removed in 2.0.0, along with the Composer `files` autoload entry that loaded
`src/functions_include.php`.
Replace namespaced function calls with the corresponding static methods in the
`GuzzleHttp\Promise` namespace:
```php
// Before:
use function GuzzleHttp\Promise\promise_for;
$promise = promise_for('value');
// After:
use GuzzleHttp\Promise\Create;
$promise = Create::promiseFor('value');
```
| Original Function | Replacement Method |
|-------------------|--------------------|
| `queue` | `Utils::queue` |
| `task` | `Utils::task` |
| `promise_for` | `Create::promiseFor` |
| `rejection_for` | `Create::rejectionFor` |
| `exception_for` | `Create::exceptionFor` |
| `iter_for` | `Create::iterFor` |
| `inspect` | `Utils::inspect` |
| `inspect_all` | `Utils::inspectAll` |
| `unwrap` | `Utils::unwrap` |
| `all` | `Utils::all` |
| `some` | `Utils::some` |
| `any` | `Utils::any` |
| `settle` | `Utils::settle` |
| `each` | `Each::of` |
| `each_limit` | `Each::ofLimit` |
| `each_limit_all` | `Each::ofLimitAll` |
| `!is_fulfilled` | `Is::pending` |
| `is_fulfilled` | `Is::fulfilled` |
| `is_rejected` | `Is::rejected` |
| `is_settled` | `Is::settled` |
| `coroutine` | `Coroutine::of` |
For the full 2.0 diff, see
https://github.com/guzzle/promises/compare/1.5.3...2.0.0.
@@ -0,0 +1,61 @@
{
"name": "guzzlehttp/promises",
"description": "Guzzle promises library",
"license": "MIT",
"keywords": [
"promise"
],
"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": "Tobias Nyholm",
"email": "tobias.nyholm@gmail.com",
"homepage": "https://github.com/Nyholm"
},
{
"name": "Tobias Schultze",
"email": "webmaster@tubo-world.de",
"homepage": "https://github.com/Tobion"
}
],
"require": {
"php": "^7.2.5 || ^8.0",
"symfony/deprecation-contracts": "^2.5 || ^3.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"phpunit/phpunit": "^8.5.52 || ^9.6.34"
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Promise\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"GuzzleHttp\\Promise\\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
}
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* Exception thrown when too many errors occur in the some() or any() methods.
*/
class AggregateException extends RejectionException
{
public function __construct(string $msg, array $reasons)
{
parent::__construct(
$reasons,
sprintf('%s; %d rejected promises', $msg, count($reasons))
);
}
}
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* Exception that is set as the reason for a promise that has been cancelled.
*/
class CancellationException extends RejectionException
{
}
@@ -0,0 +1,165 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
use Generator;
use Throwable;
/**
* Creates a promise that is resolved using a generator that yields values or
* promises (somewhat similar to C#'s async keyword).
*
* When called, the Coroutine::of method will start an instance of the generator
* and returns a promise that is fulfilled with its final yielded value.
*
* Control is returned back to the generator when the yielded promise settles.
* This can lead to less verbose code when doing lots of sequential async calls
* with minimal processing in between.
*
* use GuzzleHttp\Promise;
*
* function createPromise($value) {
* return new Promise\FulfilledPromise($value);
* }
*
* $promise = Promise\Coroutine::of(function () {
* $value = (yield createPromise('a'));
* try {
* $value = (yield createPromise($value . 'b'));
* } catch (\Throwable $e) {
* // The promise was rejected.
* }
* yield $value . 'c';
* });
*
* // Outputs "abc"
* $promise->then(function ($v) { echo $v; });
*
* @param callable $generatorFn Generator function to wrap into a promise.
*
* @return Promise
*
* @see https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration
*/
final class Coroutine implements PromiseInterface
{
/**
* @var PromiseInterface|null
*/
private $currentPromise;
/**
* @var Generator
*/
private $generator;
/**
* @var Promise
*/
private $result;
public function __construct(callable $generatorFn)
{
$this->generator = $generatorFn();
$this->result = new Promise(function (): void {
while (isset($this->currentPromise)) {
$this->currentPromise->wait();
}
});
try {
$this->nextCoroutine($this->generator->current());
} catch (Throwable $throwable) {
$this->result->reject($throwable);
}
}
/**
* Create a new coroutine.
*/
public static function of(callable $generatorFn): self
{
return new self($generatorFn);
}
public function then(
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
return $this->result->then($onFulfilled, $onRejected);
}
public function otherwise(callable $onRejected): PromiseInterface
{
return $this->result->otherwise($onRejected);
}
public function wait(bool $unwrap = true)
{
return $this->result->wait($unwrap);
}
public function getState(): string
{
return $this->result->getState();
}
public function resolve($value): void
{
$this->result->resolve($value);
}
public function reject($reason): void
{
$this->result->reject($reason);
}
public function cancel(): void
{
if (isset($this->currentPromise)) {
$this->currentPromise->cancel();
}
$this->result->cancel();
}
private function nextCoroutine($yielded): void
{
$this->currentPromise = Create::promiseFor($yielded)
->then([$this, '_handleSuccess'], [$this, '_handleFailure']);
}
/**
* @internal
*/
public function _handleSuccess($value): void
{
unset($this->currentPromise);
try {
$next = $this->generator->send($value);
if ($this->generator->valid()) {
$this->nextCoroutine($next);
} else {
$this->result->resolve($value);
}
} catch (Throwable $throwable) {
$this->result->reject($throwable);
}
}
/**
* @internal
*/
public function _handleFailure($reason): void
{
unset($this->currentPromise);
try {
$nextYield = $this->generator->throw(Create::exceptionFor($reason));
// The throw was caught, so keep iterating on the coroutine
$this->nextCoroutine($nextYield);
} catch (Throwable $throwable) {
$this->result->reject($throwable);
}
}
}
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
final class Create
{
/**
* Creates a promise for a value if the value is not a promise.
*
* @param mixed $value Promise or value.
*/
public static function promiseFor($value): PromiseInterface
{
if ($value instanceof PromiseInterface) {
return $value;
}
// Return a Guzzle promise that shadows the given promise.
if (is_object($value) && method_exists($value, 'then')) {
$wfn = method_exists($value, 'wait') ? [$value, 'wait'] : null;
$cfn = method_exists($value, 'cancel') ? [$value, 'cancel'] : null;
$promise = new Promise($wfn, $cfn);
$value->then([$promise, 'resolve'], [$promise, 'reject']);
return $promise;
}
return new FulfilledPromise($value);
}
/**
* Creates a rejected promise for a reason if the reason is not a promise.
* If the provided reason is a promise, then it is returned as-is.
*
* @param mixed $reason Promise or reason.
*/
public static function rejectionFor($reason): PromiseInterface
{
if ($reason instanceof PromiseInterface) {
return $reason;
}
return new RejectedPromise($reason);
}
/**
* Create an exception for a rejected promise value.
*
* @param mixed $reason
*/
public static function exceptionFor($reason): \Throwable
{
if ($reason instanceof \Throwable) {
return $reason;
}
return new RejectionException($reason);
}
/**
* Returns an iterator for the given value.
*
* @param mixed $value
*/
public static function iterFor($value): \Iterator
{
if ($value instanceof \Iterator) {
return $value;
}
if (is_array($value)) {
return new \ArrayIterator($value);
}
if (!is_iterable($value)) {
\trigger_deprecation(
'guzzlehttp/promises',
'2.5',
'Passing a non-iterable to %s::%s() is deprecated; guzzlehttp/promises 3.0 will require an iterable.',
__CLASS__,
__FUNCTION__
);
}
return new \ArrayIterator([$value]);
}
}
@@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
final class Each
{
/**
* Given an iterator that yields promises or values, returns a promise that
* is fulfilled with a null value when the iterator has been consumed or
* the aggregate promise has been fulfilled or rejected.
*
* $onFulfilled is a function that accepts the fulfilled value, iterator
* index, and the aggregate promise. The callback can invoke any necessary
* side effects and choose to resolve or reject the aggregate if needed.
*
* $onRejected is a function that accepts the rejection reason, iterator
* index, and the aggregate promise. The callback can invoke any necessary
* side effects and choose to resolve or reject the aggregate if needed.
*
* @param mixed $iterable Iterator or array to iterate over.
*/
public static function of(
$iterable,
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
$iterable = self::prepareIterable($iterable, __FUNCTION__);
return (new EachPromise($iterable, [
'fulfilled' => $onFulfilled,
'rejected' => $onRejected,
]))->promise();
}
/**
* Like of, but only allows a certain number of outstanding promises at any
* given time.
*
* $concurrency may be an integer or a function that accepts the number of
* pending promises and returns a numeric concurrency limit value to allow
* for dynamic a concurrency size.
*
* @param mixed $iterable
* @param int|callable $concurrency
*/
public static function ofLimit(
$iterable,
$concurrency,
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
$iterable = self::prepareIterable($iterable, __FUNCTION__);
return (new EachPromise($iterable, [
'fulfilled' => $onFulfilled,
'rejected' => $onRejected,
'concurrency' => $concurrency,
]))->promise();
}
/**
* Like limit, but ensures that no promise in the given $iterable argument
* is rejected. If any promise is rejected, then the aggregate promise is
* rejected with the encountered rejection.
*
* @param mixed $iterable
* @param int|callable $concurrency
*/
public static function ofLimitAll(
$iterable,
$concurrency,
?callable $onFulfilled = null
): PromiseInterface {
$iterable = self::prepareIterable($iterable, __FUNCTION__);
return self::ofLimit(
$iterable,
$concurrency,
$onFulfilled,
function ($reason, $idx, PromiseInterface $aggregate): void {
$aggregate->reject($reason);
}
);
}
private static function prepareIterable($iterable, string $method): iterable
{
if (is_iterable($iterable)) {
return $iterable;
}
\trigger_deprecation(
'guzzlehttp/promises',
'2.5',
'Passing a non-iterable to %s::%s() is deprecated; guzzlehttp/promises 3.0 will require an iterable.',
self::class,
$method
);
return [$iterable];
}
}
@@ -0,0 +1,298 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* Represents a promise that iterates over many promises and invokes
* side-effect functions in the process.
*
* @final
*/
class EachPromise implements PromisorInterface
{
private $pending = [];
private $nextPendingIndex = 0;
/** @var \Iterator|null */
private $iterable;
/** @var callable|int|null */
private $concurrency;
/** @var callable|null */
private $onFulfilled;
/** @var callable|null */
private $onRejected;
/** @var Promise|null */
private $aggregate;
/** @var bool|null */
private $mutex;
/** @var bool */
private $stepWhileLocked = false;
/**
* Configuration hash can include the following key value pairs:
*
* - fulfilled: (callable) Invoked when a promise fulfills. The function
* is invoked with three arguments: the fulfillment value, the index
* position from the iterable list of the promise, and the aggregate
* promise that manages all of the promises. The aggregate promise may
* be resolved from within the callback to short-circuit the promise.
* - rejected: (callable) Invoked when a promise is rejected. The
* function is invoked with three arguments: the rejection reason, the
* index position from the iterable list of the promise, and the
* aggregate promise that manages all of the promises. The aggregate
* promise may be resolved from within the callback to short-circuit
* the promise.
* - concurrency: (integer) Pass this configuration option to limit the
* allowed number of outstanding concurrently executing promises,
* creating a capped pool of promises. There is no limit by default.
*
* @param mixed $iterable Promises or values to iterate.
* @param array $config Configuration options
*/
public function __construct($iterable, array $config = [])
{
if (!is_iterable($iterable)) {
\trigger_deprecation(
'guzzlehttp/promises',
'2.5',
'Passing a non-iterable to %s::%s() is deprecated; guzzlehttp/promises 3.0 will require an iterable.',
__CLASS__,
__FUNCTION__
);
$iterable = [$iterable];
}
$this->iterable = Create::iterFor($iterable);
if (isset($config['concurrency'])) {
$this->concurrency = $config['concurrency'];
}
if (isset($config['fulfilled'])) {
$this->onFulfilled = $config['fulfilled'];
}
if (isset($config['rejected'])) {
$this->onRejected = $config['rejected'];
}
}
/** @psalm-suppress InvalidNullableReturnType */
public function promise(): PromiseInterface
{
if ($this->aggregate) {
return $this->aggregate;
}
try {
$this->createPromise();
/** @psalm-assert Promise $this->aggregate */
$this->iterable->rewind();
$this->refillPending();
if (!$this->pending) {
Utils::queue()->add(function (): void {
if (!$this->aggregate || Is::settled($this->aggregate)) {
return;
}
try {
$this->checkIfFinished();
} catch (\Throwable $e) {
$this->aggregate->reject($e);
}
});
}
} catch (\Throwable $e) {
$this->aggregate->reject($e);
}
/**
* @psalm-suppress NullableReturnStatement
*/
return $this->aggregate;
}
private function createPromise(): void
{
$this->mutex = false;
$this->aggregate = new Promise(function (): void {
while (true) {
if ($this->checkIfFinished()) {
return;
}
reset($this->pending);
// Consume a potentially fluctuating list of promises while
// ensuring that indexes are maintained (precluding array_shift).
while ($promise = current($this->pending)) {
next($this->pending);
$promise->wait();
if (Is::settled($this->aggregate)) {
return;
}
}
// Refill and re-sweep; give up only when nothing remains.
$this->refillPending();
if (Is::settled($this->aggregate) || !$this->pending) {
return;
}
}
});
// Clear the references when the promise is resolved.
$clearFn = function (): void {
$this->iterable = $this->concurrency = $this->pending = null;
$this->onFulfilled = $this->onRejected = null;
$this->nextPendingIndex = 0;
};
$this->aggregate->then($clearFn, $clearFn);
}
private function refillPending(): void
{
if (!$this->concurrency) {
// Add all pending promises.
while ($this->addPending() && $this->advanceIterator()) {
}
return;
}
// Add only up to N pending promises.
$concurrency = is_callable($this->concurrency)
? ($this->concurrency)(count($this->pending))
: $this->concurrency;
// The callable can settle the aggregate; admit nothing more.
if (Is::settled($this->aggregate)) {
return;
}
$concurrency = max($concurrency - count($this->pending), 0);
// Concurrency may be set to 0 to disallow new promises.
if (!$concurrency) {
return;
}
// Add the first pending promise.
$this->addPending();
// Note this is special handling for concurrency=1 so that we do
// not advance the iterator after adding the first promise. This
// helps work around issues with generators that might not have the
// next value to yield until promise callbacks are called.
while (--$concurrency
&& $this->advanceIterator()
&& $this->addPending()) {
}
}
private function addPending(): bool
{
if (!$this->iterable || !$this->iterable->valid()) {
return false;
}
$promise = Create::promiseFor($this->iterable->current());
$key = $this->iterable->key();
// Iterable keys may not be unique, so we use a counter to
// guarantee uniqueness
$idx = $this->nextPendingIndex++;
$this->pending[$idx] = $promise->then(
function ($value) use ($idx, $key): void {
if ($this->onFulfilled) {
($this->onFulfilled)(
$value,
$key,
$this->aggregate
);
}
$this->step($idx);
},
function ($reason) use ($idx, $key): void {
if ($this->onRejected) {
($this->onRejected)(
$reason,
$key,
$this->aggregate
);
}
$this->step($idx);
}
);
return true;
}
private function advanceIterator(): bool
{
// Place a lock on the iterator so that we ensure to not recurse,
// preventing fatal generator errors.
if ($this->mutex) {
$this->stepWhileLocked = true;
return false;
}
$this->mutex = true;
try {
$this->iterable->next();
$this->mutex = false;
} catch (\Throwable $e) {
$this->aggregate->reject($e);
$this->mutex = false;
return false;
}
// Run the completion check that locked steps skipped.
if ($this->stepWhileLocked) {
$this->stepWhileLocked = false;
if (!Is::settled($this->aggregate)) {
$this->checkIfFinished();
}
}
return true;
}
private function step(int $idx): void
{
// If the promise was already resolved, then ignore this step.
if (Is::settled($this->aggregate)) {
return;
}
unset($this->pending[$idx]);
// Only refill pending promises if we are not locked, preventing the
// EachPromise to recursively invoke the provided iterator, which
// cause a fatal error: "Cannot resume an already running generator"
if ($this->advanceIterator() && !$this->checkIfFinished()) {
// Add more pending promises if possible.
$this->refillPending();
}
}
/** @phpstan-impure */
private function checkIfFinished(): bool
{
if (!$this->pending && !$this->iterable->valid()) {
// Resolve the promise if there's nothing left to do.
$this->aggregate->resolve(null);
return true;
}
return false;
}
}
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* A promise that has been fulfilled.
*
* Thenning off of this promise will invoke the onFulfilled callback
* immediately and ignore other callbacks.
*
* @final
*/
class FulfilledPromise implements PromiseInterface
{
private $value;
/**
* @param mixed $value
*/
public function __construct($value)
{
if (is_object($value) && method_exists($value, 'then')) {
throw new \InvalidArgumentException(
'You cannot create a FulfilledPromise with a promise.'
);
}
$this->value = $value;
}
public function then(
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
// Return itself if there is no onFulfilled function.
if (!$onFulfilled) {
return $this;
}
$queue = Utils::queue();
$p = new Promise([$queue, 'run']);
$value = $this->value;
$queue->add(static function () use ($p, $value, $onFulfilled): void {
if (Is::pending($p)) {
try {
$p->resolve($onFulfilled($value));
} catch (\Throwable $e) {
$p->reject($e);
}
}
});
return $p;
}
public function otherwise(callable $onRejected): PromiseInterface
{
return $this->then(null, $onRejected);
}
public function wait(bool $unwrap = true)
{
return $unwrap ? $this->value : null;
}
public function getState(): string
{
return self::FULFILLED;
}
public function resolve($value): void
{
if ($value !== $this->value) {
throw new \LogicException('Cannot resolve a fulfilled promise');
}
}
public function reject($reason): void
{
throw new \LogicException('Cannot reject a fulfilled promise');
}
public function cancel(): void
{
// pass
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
final class Is
{
/**
* Returns true if a promise is pending.
*/
public static function pending(PromiseInterface $promise): bool
{
return $promise->getState() === PromiseInterface::PENDING;
}
/**
* Returns true if a promise is fulfilled or rejected.
*/
public static function settled(PromiseInterface $promise): bool
{
return $promise->getState() !== PromiseInterface::PENDING;
}
/**
* Returns true if a promise is fulfilled.
*/
public static function fulfilled(PromiseInterface $promise): bool
{
return $promise->getState() === PromiseInterface::FULFILLED;
}
/**
* Returns true if a promise is rejected.
*/
public static function rejected(PromiseInterface $promise): bool
{
return $promise->getState() === PromiseInterface::REJECTED;
}
}
@@ -0,0 +1,281 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* Promises/A+ implementation that avoids recursion when possible.
*
* @see https://promisesaplus.com/
*
* @final
*/
class Promise implements PromiseInterface
{
private $state = self::PENDING;
private $result;
private $cancelFn;
private $waitFn;
private $waitList;
private $handlers = [];
/**
* @param callable $waitFn Fn that when invoked resolves the promise.
* @param callable $cancelFn Fn that when invoked cancels the promise.
*/
public function __construct(
?callable $waitFn = null,
?callable $cancelFn = null
) {
$this->waitFn = $waitFn;
$this->cancelFn = $cancelFn;
}
public function then(
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
if ($this->state === self::PENDING) {
$p = new Promise(null, [$this, 'cancel']);
$this->handlers[] = [$p, $onFulfilled, $onRejected];
$p->waitList = $this->waitList;
$p->waitList[] = $this;
return $p;
}
// Return a fulfilled promise and immediately invoke any callbacks.
if ($this->state === self::FULFILLED) {
$promise = Create::promiseFor($this->result);
return $onFulfilled ? $promise->then($onFulfilled) : $promise;
}
// It's either cancelled or rejected, so return a rejected promise
// and immediately invoke any callbacks.
$rejection = Create::rejectionFor($this->result);
return $onRejected ? $rejection->then(null, $onRejected) : $rejection;
}
public function otherwise(callable $onRejected): PromiseInterface
{
return $this->then(null, $onRejected);
}
public function wait(bool $unwrap = true)
{
$this->waitIfPending();
if ($this->result instanceof PromiseInterface) {
return $this->result->wait($unwrap);
}
if ($unwrap) {
if ($this->state === self::FULFILLED) {
return $this->result;
}
// It's rejected so "unwrap" and throw an exception.
throw Create::exceptionFor($this->result);
}
}
public function getState(): string
{
return $this->state;
}
public function cancel(): void
{
if ($this->state !== self::PENDING) {
return;
}
$this->waitFn = $this->waitList = null;
if ($this->cancelFn) {
$fn = $this->cancelFn;
$this->cancelFn = null;
try {
$fn();
} catch (\Throwable $e) {
$this->reject($e);
}
}
// Reject the promise only if it wasn't rejected in a then callback.
/** @psalm-suppress RedundantCondition */
if ($this->state === self::PENDING) {
$this->reject(new CancellationException('Promise has been cancelled'));
}
}
public function resolve($value): void
{
$this->settle(self::FULFILLED, $value);
}
public function reject($reason): void
{
$this->settle(self::REJECTED, $reason);
}
private function settle(string $state, $value): void
{
if ($this->state !== self::PENDING) {
// Ignore calls with the same resolution.
if ($state === $this->state && $value === $this->result) {
return;
}
throw $this->state === $state
? new \LogicException("The promise is already {$state}.")
: new \LogicException("Cannot change a {$this->state} promise to {$state}");
}
if ($value === $this) {
throw new \LogicException('Cannot fulfill or reject a promise with itself');
}
// Clear out the state of the promise but stash the handlers.
$this->state = $state;
$this->result = $value;
$handlers = $this->handlers;
$this->handlers = null;
$this->waitList = $this->waitFn = null;
$this->cancelFn = null;
if (!$handlers) {
return;
}
// If the value was not a settled promise or a thenable, then resolve
// it in the task queue using the correct ID.
if (!is_object($value) || !method_exists($value, 'then')) {
$id = $state === self::FULFILLED ? 1 : 2;
// It's a success, so resolve the handlers in the queue.
Utils::queue()->add(static function () use ($id, $value, $handlers): void {
foreach ($handlers as $handler) {
self::callHandler($id, $value, $handler);
}
});
} elseif ($value instanceof Promise && Is::pending($value)) {
// We can just merge our handlers onto the next promise.
$value->handlers = array_merge($value->handlers, $handlers);
} else {
// Resolve the handlers when the forwarded promise is resolved.
$value->then(
static function ($value) use ($handlers): void {
foreach ($handlers as $handler) {
self::callHandler(1, $value, $handler);
}
},
static function ($reason) use ($handlers): void {
foreach ($handlers as $handler) {
self::callHandler(2, $reason, $handler);
}
}
);
}
}
/**
* Call a stack of handlers using a specific callback index and value.
*
* @param int $index 1 (resolve) or 2 (reject).
* @param mixed $value Value to pass to the callback.
* @param array $handler Array of handler data (promise and callbacks).
*/
private static function callHandler(int $index, $value, array $handler): void
{
/** @var PromiseInterface $promise */
$promise = $handler[0];
// The promise may have been cancelled or resolved before placing
// this thunk in the queue.
if (Is::settled($promise)) {
return;
}
try {
if (isset($handler[$index])) {
/*
* If $f throws an exception, then $handler will be in the exception
* stack trace. Since $handler contains a reference to the callable
* itself we get a circular reference. We clear the $handler
* here to avoid that memory leak.
*/
$f = $handler[$index];
unset($handler);
$promise->resolve($f($value));
} elseif ($index === 1) {
// Forward resolution values as-is.
$promise->resolve($value);
} else {
// Forward rejections down the chain.
$promise->reject($value);
}
} catch (\Throwable $reason) {
$promise->reject($reason);
}
}
private function waitIfPending(): void
{
if ($this->state !== self::PENDING) {
return;
} elseif ($this->waitFn) {
$this->invokeWaitFn();
} elseif ($this->waitList) {
$this->invokeWaitList();
} else {
// If there's no wait function, then reject the promise.
$this->reject('Cannot wait on a promise that has '
.'no internal wait function. You must provide a wait '
.'function when constructing the promise to be able to '
.'wait on a promise.');
}
Utils::queue()->run();
/** @psalm-suppress RedundantCondition */
if ($this->state === self::PENDING) {
$this->reject('Invoking the wait callback did not resolve the promise');
}
}
private function invokeWaitFn(): void
{
try {
$wfn = $this->waitFn;
$this->waitFn = null;
$wfn(true);
} catch (\Throwable $reason) {
if ($this->state === self::PENDING) {
// The promise has not been resolved yet, so reject the promise
// with the exception.
$this->reject($reason);
} else {
// The promise was already resolved, so there's a problem in
// the application.
throw $reason;
}
}
}
private function invokeWaitList(): void
{
$waitList = $this->waitList;
$this->waitList = null;
foreach ($waitList as $result) {
do {
$result->waitIfPending();
$result = $result->result;
} while ($result instanceof Promise);
if ($result instanceof PromiseInterface) {
$result->wait(false);
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More