updated packages

This commit is contained in:
2019-05-18 09:06:43 +00:00
parent 901d16349e
commit e9487fa58a
2025 changed files with 30366 additions and 49653 deletions

View File

@@ -1,6 +1,13 @@
CHANGELOG
=========
1.1.0
-----
* added `HttpClient` namespace with contracts for implementing flexible HTTP clients
* added `EventDispatcherInterface` and `Event` in namespace `EventDispatcher`
* added `ServiceProviderInterface` in namespace `Service`
1.0.0
-----

View File

@@ -13,6 +13,7 @@ namespace Symfony\Contracts\Cache;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException;
use Psr\Log\LoggerInterface;
/**
* An implementation of CacheInterface for PSR-6 CacheItemPoolInterface classes.
@@ -37,7 +38,7 @@ trait CacheTrait
return $this->deleteItem($key);
}
private function doGet(CacheItemPoolInterface $pool, string $key, callable $callback, ?float $beta, array &$metadata = null)
private function doGet(CacheItemPoolInterface $pool, string $key, callable $callback, ?float $beta, array &$metadata = null, LoggerInterface $logger = null)
{
if (0 > $beta = $beta ?? 1.0) {
throw new class(sprintf('Argument "$beta" provided to "%s::get()" must be a positive number, %f given.', \get_class($this), $beta)) extends \InvalidArgumentException implements InvalidArgumentException {
@@ -46,15 +47,19 @@ trait CacheTrait
$item = $pool->getItem($key);
$recompute = !$item->isHit() || INF === $beta;
$metadata = $item instanceof ItemInterface ? $item->getMetadata() : array();
$metadata = $item instanceof ItemInterface ? $item->getMetadata() : [];
if (!$recompute && $metadata) {
$expiry = $metadata[ItemInterface::METADATA_EXPIRY] ?? false;
$ctime = $metadata[ItemInterface::METADATA_CTIME] ?? false;
if ($recompute = $ctime && $expiry && $expiry <= microtime(true) - $ctime / 1000 * $beta * log(random_int(1, PHP_INT_MAX) / PHP_INT_MAX)) {
if ($recompute = $ctime && $expiry && $expiry <= ($now = microtime(true)) - $ctime / 1000 * $beta * log(random_int(1, PHP_INT_MAX) / PHP_INT_MAX)) {
// force applying defaultLifetime to expiry
$item->expiresAt(null);
$this->logger && $this->logger->info('Item "{key}" elected for early recomputation {delta}s before its expiration', [
'key' => $key,
'delta' => sprintf('%.1f', $expiry - $now),
]);
}
}

View File

@@ -0,0 +1,96 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\EventDispatcher;
use Psr\EventDispatcher\StoppableEventInterface;
if (interface_exists(StoppableEventInterface::class)) {
/**
* Event is the base class for classes containing event data.
*
* This class contains no event data. It is used by events that do not pass
* state information to an event handler when an event is raised.
*
* You can call the method stopPropagation() to abort the execution of
* further listeners in your event listener.
*
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
* @author Bernhard Schussek <bschussek@gmail.com>
* @author Nicolas Grekas <p@tchwork.com>
*/
class Event implements StoppableEventInterface
{
private $propagationStopped = false;
/**
* Returns whether further event listeners should be triggered.
*/
public function isPropagationStopped(): bool
{
return $this->propagationStopped;
}
/**
* Stops the propagation of the event to further event listeners.
*
* If multiple event listeners are connected to the same event, no
* further event listener will be triggered once any trigger calls
* stopPropagation().
*/
public function stopPropagation(): void
{
$this->propagationStopped = true;
}
}
} else {
/**
* Event is the base class for classes containing event data.
*
* This class contains no event data. It is used by events that do not pass
* state information to an event handler when an event is raised.
*
* You can call the method stopPropagation() to abort the execution of
* further listeners in your event listener.
*
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Jonathan Wage <jonwage@gmail.com>
* @author Roman Borschel <roman@code-factory.org>
* @author Bernhard Schussek <bschussek@gmail.com>
* @author Nicolas Grekas <p@tchwork.com>
*/
class Event
{
private $propagationStopped = false;
/**
* Returns whether further event listeners should be triggered.
*/
public function isPropagationStopped(): bool
{
return $this->propagationStopped;
}
/**
* Stops the propagation of the event to further event listeners.
*
* If multiple event listeners are connected to the same event, no
* further event listener will be triggered once any trigger calls
* stopPropagation().
*/
public function stopPropagation(): void
{
$this->propagationStopped = true;
}
}
}

View File

@@ -0,0 +1,58 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\EventDispatcher;
use Psr\EventDispatcher\EventDispatcherInterface as PsrEventDispatcherInterface;
if (interface_exists(PsrEventDispatcherInterface::class)) {
/**
* Allows providing hooks on domain-specific lifecycles by dispatching events.
*/
interface EventDispatcherInterface extends PsrEventDispatcherInterface
{
/**
* Dispatches an event to all registered listeners.
*
* For BC with Symfony 4, the $eventName argument is not declared explicitly on the
* signature of the method. Implementations that are not bound by this BC contraint
* MUST declare it explicitly, as allowed by PHP.
*
* @param object $event The event to pass to the event handlers/listeners
* @param string|null $eventName The name of the event to dispatch. If not supplied,
* the class of $event should be used instead.
*
* @return object The passed $event MUST be returned
*/
public function dispatch($event/*, string $eventName = null*/);
}
} else {
/**
* Allows providing hooks on domain-specific lifecycles by dispatching events.
*/
interface EventDispatcherInterface
{
/**
* Dispatches an event to all registered listeners.
*
* For BC with Symfony 4, the $eventName argument is not declared explicitly on the
* signature of the method. Implementations that are not bound by this BC contraint
* MUST declare it explicitly, as allowed by PHP.
*
* @param object $event The event to pass to the event handlers/listeners
* @param string|null $eventName The name of the event to dispatch. If not supplied,
* the class of $event should be used instead.
*
* @return object The passed $event MUST be returned
*/
public function dispatch($event/*, string $eventName = null*/);
}
}

View File

@@ -0,0 +1,66 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
/**
* The interface of chunks returned by ResponseStreamInterface::current().
*
* When the chunk is first, last or timeout, the content MUST be empty.
* When an unchecked timeout or a network error occurs, a TransportExceptionInterface
* MUST be thrown by the destructor unless one was already thrown by another method.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @experimental in 1.1
*/
interface ChunkInterface
{
/**
* Tells when the inactivity timeout has been reached.
*
* @throws TransportExceptionInterface on a network error
*/
public function isTimeout(): bool;
/**
* Tells when headers just arrived.
*
* @throws TransportExceptionInterface on a network error or when the inactivity timeout is reached
*/
public function isFirst(): bool;
/**
* Tells when the body just completed.
*
* @throws TransportExceptionInterface on a network error or when the inactivity timeout is reached
*/
public function isLast(): bool;
/**
* Returns the content of the response chunk.
*
* @throws TransportExceptionInterface on a network error or when the inactivity timeout is reached
*/
public function getContent(): string;
/**
* Returns the offset of the chunk in the response body.
*/
public function getOffset(): int;
/**
* In case of error, returns the message that describes it.
*/
public function getError(): ?string;
}

View File

@@ -0,0 +1,23 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Exception;
/**
* When a 4xx response is returned.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @experimental in 1.1
*/
interface ClientExceptionInterface extends HttpExceptionInterface
{
}

View File

@@ -0,0 +1,23 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Exception;
/**
* The base interface for all exceptions in the contract.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @experimental in 1.1
*/
interface ExceptionInterface extends \Throwable
{
}

View File

@@ -0,0 +1,26 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Exception;
use Symfony\Contracts\HttpClient\ResponseInterface;
/**
* Base interface for HTTP-related exceptions.
*
* @author Anton Chernikov <anton_ch1989@mail.ru>
*
* @experimental in 1.1
*/
interface HttpExceptionInterface extends ExceptionInterface
{
public function getResponse(): ResponseInterface;
}

View File

@@ -0,0 +1,23 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Exception;
/**
* When a 3xx response is returned and the "max_redirects" option has been reached.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @experimental in 1.1
*/
interface RedirectionExceptionInterface extends HttpExceptionInterface
{
}

View File

@@ -0,0 +1,23 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Exception;
/**
* When a 5xx response is returned.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @experimental in 1.1
*/
interface ServerExceptionInterface extends HttpExceptionInterface
{
}

View File

@@ -0,0 +1,23 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Exception;
/**
* When any error happens at the transport level.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @experimental in 1.1
*/
interface TransportExceptionInterface extends ExceptionInterface
{
}

View File

@@ -0,0 +1,91 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\Test\HttpClientTestCase;
/**
* Provides flexible methods for requesting HTTP resources synchronously or asynchronously.
*
* @see HttpClientTestCase for a reference test suite
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @experimental in 1.1
*/
interface HttpClientInterface
{
public const OPTIONS_DEFAULTS = [
'auth_basic' => null, // array|string - an array containing the username as first value, and optionally the
// password as the second one; or string like username:password - enabling HTTP Basic
// authentication (RFC 7617)
'auth_bearer' => null, // string - a token enabling HTTP Bearer authorization (RFC 6750)
'query' => [], // string[] - associative array of query string values to merge with the request's URL
'headers' => [], // iterable|string[]|string[][] - headers names provided as keys or as part of values
'body' => '', // array|string|resource|\Traversable|\Closure - the callback SHOULD yield a string
// smaller than the amount requested as argument; the empty string signals EOF; when
// an array is passed, it is meant as a form payload of field names and values
'json' => null, // array|\JsonSerializable - when set, implementations MUST set the "body" option to
// the JSON-encoded value and set the "content-type" headers to a JSON-compatible
// value if they are not defined - typically "application/json"
'user_data' => null, // mixed - any extra data to attach to the request (scalar, callable, object...) that
// MUST be available via $response->getInfo('user_data') - not used internally
'max_redirects' => 20, // int - the maximum number of redirects to follow; a value lower or equal to 0 means
// redirects should not be followed; "Authorization" and "Cookie" headers MUST
// NOT follow except for the initial host name
'http_version' => null, // string - defaults to the best supported version, typically 1.1 or 2.0
'base_uri' => null, // string - the URI to resolve relative URLs, following rules in RFC 3986, section 2
'buffer' => true, // bool - whether the content of the response should be buffered or not
'on_progress' => null, // callable(int $dlNow, int $dlSize, array $info) - throwing any exceptions MUST abort
// the request; it MUST be called on DNS resolution, on arrival of headers and on
// completion; it SHOULD be called on upload/download of data and at least 1/s
'resolve' => [], // string[] - a map of host to IP address that SHOULD replace DNS resolution
'proxy' => null, // string - by default, the proxy-related env vars handled by curl SHOULD be honored
'no_proxy' => null, // string - a comma separated list of hosts that do not require a proxy to be reached
'timeout' => null, // float - the inactivity timeout - defaults to ini_get('default_socket_timeout')
'bindto' => '0', // string - the interface or the local socket to bind to
'verify_peer' => true, // see https://php.net/context.ssl for the following options
'verify_host' => true,
'cafile' => null,
'capath' => null,
'local_cert' => null,
'local_pk' => null,
'passphrase' => null,
'ciphers' => null,
'peer_fingerprint' => null,
'capture_peer_cert_chain' => false,
'extra' => [], // array - additional options that can be ignored if unsupported, unlike regular options
];
/**
* Requests an HTTP resource.
*
* Responses MUST be lazy, but their status code MUST be
* checked even if none of their public methods are called.
*
* Implementations are not required to support all options described above; they can also
* support more custom options; but in any case, they MUST throw a TransportExceptionInterface
* when an unsupported option is passed.
*
* @throws TransportExceptionInterface When an unsupported option is passed
*/
public function request(string $method, string $url, array $options = []): ResponseInterface;
/**
* Yields responses chunk by chunk as they complete.
*
* @param ResponseInterface|ResponseInterface[]|iterable $responses One or more responses created by the current HTTP client
* @param float|null $timeout The inactivity timeout before exiting the iterator
*/
public function stream($responses, float $timeout = null): ResponseStreamInterface;
}

View File

@@ -0,0 +1,101 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
/**
* A (lazily retrieved) HTTP response.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @experimental in 1.1
*/
interface ResponseInterface
{
/**
* Gets the HTTP status code of the response.
*
* @throws TransportExceptionInterface when a network error occurs
*/
public function getStatusCode(): int;
/**
* Gets the HTTP headers of the response.
*
* @param bool $throw Whether an exception should be thrown on 3/4/5xx status codes
*
* @return string[][] The headers of the response keyed by header names in lowercase
*
* @throws TransportExceptionInterface When a network error occurs
* @throws RedirectionExceptionInterface On a 3xx when $throw is true and the "max_redirects" option has been reached
* @throws ClientExceptionInterface On a 4xx when $throw is true
* @throws ServerExceptionInterface On a 5xx when $throw is true
*/
public function getHeaders(bool $throw = true): array;
/**
* Gets the response body as a string.
*
* @param bool $throw Whether an exception should be thrown on 3/4/5xx status codes
*
* @throws TransportExceptionInterface When a network error occurs
* @throws RedirectionExceptionInterface On a 3xx when $throw is true and the "max_redirects" option has been reached
* @throws ClientExceptionInterface On a 4xx when $throw is true
* @throws ServerExceptionInterface On a 5xx when $throw is true
*/
public function getContent(bool $throw = true): string;
/**
* Gets the response body decoded as array, typically from a JSON payload.
*
* @param bool $throw Whether an exception should be thrown on 3/4/5xx status codes
*
* @throws TransportExceptionInterface When the body cannot be decoded or when a network error occurs
* @throws RedirectionExceptionInterface On a 3xx when $throw is true and the "max_redirects" option has been reached
* @throws ClientExceptionInterface On a 4xx when $throw is true
* @throws ServerExceptionInterface On a 5xx when $throw is true
*/
public function toArray(bool $throw = true): array;
/**
* Returns info coming from the transport layer.
*
* This method SHOULD NOT throw any ExceptionInterface and SHOULD be non-blocking.
* The returned info is "live": it can be empty and can change from one call to
* another, as the request/response progresses.
*
* The following info MUST be returned:
* - response_headers - an array modelled after the special $http_response_header variable
* - redirect_count - the number of redirects followed while executing the request
* - redirect_url - the resolved location of redirect responses, null otherwise
* - start_time - the time when the request was sent or 0.0 when it's pending
* - http_method - the HTTP verb of the last request
* - http_code - the last response code or 0 when it is not known yet
* - error - the error message when the transfer was aborted, null otherwise
* - user_data - the value of the "user_data" request option, null if not set
* - url - the last effective URL of the request
*
* When the "capture_peer_cert_chain" option is true, the "peer_certificate_chain"
* attribute SHOULD list the peer certificates as an array of OpenSSL X.509 resources.
*
* Other info SHOULD be named after curl_getinfo()'s associative return value.
*
* @return array|mixed|null An array of all available info, or one of them when $type is
* provided, or null when an unsupported type is requested
*/
public function getInfo(string $type = null);
}

View File

@@ -0,0 +1,26 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient;
/**
* Yields response chunks, returned by HttpClientInterface::stream().
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @experimental in 1.1
*/
interface ResponseStreamInterface extends \Iterator
{
public function key(): ResponseInterface;
public function current(): ChunkInterface;
}

View File

@@ -0,0 +1,124 @@
<?php
if ('cli-server' !== \PHP_SAPI) {
// safe guard against unwanted execution
throw new \Exception("You cannot run this script directly, it's a fixture for TestHttpServer.");
}
$vars = [];
if (!$_POST) {
$_POST = json_decode(file_get_contents('php://input'), true);
$_POST['content-type'] = $_SERVER['HTTP_CONTENT_TYPE'] ?? '?';
}
foreach ($_SERVER as $k => $v) {
switch ($k) {
default:
if (0 !== strpos($k, 'HTTP_')) {
continue 2;
}
// no break
case 'SERVER_NAME':
case 'SERVER_PROTOCOL':
case 'REQUEST_URI':
case 'REQUEST_METHOD':
case 'PHP_AUTH_USER':
case 'PHP_AUTH_PW':
$vars[$k] = $v;
}
}
switch ($vars['REQUEST_URI']) {
default:
exit;
case '/':
case '/?a=a&b=b':
case 'http://127.0.0.1:8057/':
case 'http://localhost:8057/':
header('Content-Type: application/json');
ob_start('ob_gzhandler');
break;
case '/404':
header('Content-Type: application/json', true, 404);
break;
case '/301':
if ('Basic Zm9vOmJhcg==' === $vars['HTTP_AUTHORIZATION']) {
header('Location: http://127.0.0.1:8057/302', true, 301);
}
break;
case '/301/bad-tld':
header('Location: http://foo.example.', true, 301);
break;
case '/302':
if (!isset($vars['HTTP_AUTHORIZATION'])) {
header('Location: http://localhost:8057/', true, 302);
}
break;
case '/302/relative':
header('Location: ..', true, 302);
break;
case '/307':
header('Location: http://localhost:8057/post', true, 307);
break;
case '/length-broken':
header('Content-Length: 1000');
break;
case '/post':
$output = json_encode($_POST + ['REQUEST_METHOD' => $vars['REQUEST_METHOD']], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
header('Content-Type: application/json', true);
header('Content-Length: '.\strlen($output));
echo $output;
exit;
case '/timeout-header':
usleep(300000);
break;
case '/timeout-body':
echo '<1>';
@ob_flush();
flush();
usleep(500000);
echo '<2>';
exit;
case '/timeout-long':
ignore_user_abort(false);
sleep(1);
while (true) {
echo '<1>';
@ob_flush();
flush();
usleep(500);
}
exit;
case '/chunked':
header('Transfer-Encoding: chunked');
echo "8\r\nSymfony \r\n5\r\nis aw\r\n6\r\nesome!\r\n0\r\n\r\n";
exit;
case '/chunked-broken':
header('Transfer-Encoding: chunked');
echo "8\r\nSymfony \r\n5\r\nis aw\r\n6\r\ne";
exit;
case '/gzip-broken':
header('Content-Encoding: gzip');
echo str_repeat('-', 1000);
exit;
}
header('Content-Type: application/json', true);
echo json_encode($vars, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

View File

@@ -0,0 +1,733 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Test;
use PHPUnit\Framework\TestCase;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* A reference test suite for HttpClientInterface implementations.
*
* @experimental in 1.1
*/
abstract class HttpClientTestCase extends TestCase
{
private static $server;
public static function setUpBeforeClass()
{
TestHttpServer::start();
}
abstract protected function getHttpClient(string $testCase): HttpClientInterface;
public function testGetRequest()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057', [
'headers' => ['Foo' => 'baR'],
'user_data' => $data = new \stdClass(),
]);
$this->assertSame([], $response->getInfo('response_headers'));
$this->assertSame($data, $response->getInfo()['user_data']);
$this->assertSame(200, $response->getStatusCode());
$info = $response->getInfo();
$this->assertNull($info['error']);
$this->assertSame(0, $info['redirect_count']);
$this->assertSame('HTTP/1.1 200 OK', $info['response_headers'][0]);
$this->assertSame('Host: localhost:8057', $info['response_headers'][1]);
$this->assertSame('http://localhost:8057/', $info['url']);
$headers = $response->getHeaders();
$this->assertSame('localhost:8057', $headers['host'][0]);
$this->assertSame(['application/json'], $headers['content-type']);
$body = json_decode($response->getContent(), true);
$this->assertSame($body, $response->toArray());
$this->assertSame('HTTP/1.1', $body['SERVER_PROTOCOL']);
$this->assertSame('/', $body['REQUEST_URI']);
$this->assertSame('GET', $body['REQUEST_METHOD']);
$this->assertSame('localhost:8057', $body['HTTP_HOST']);
$this->assertSame('baR', $body['HTTP_FOO']);
$response = $client->request('GET', 'http://localhost:8057/length-broken');
$this->expectException(TransportExceptionInterface::class);
$response->getContent();
}
public function testNonBufferedGetRequest()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057', [
'buffer' => false,
'headers' => ['Foo' => 'baR'],
]);
$body = $response->toArray();
$this->assertSame('baR', $body['HTTP_FOO']);
$this->expectException(TransportExceptionInterface::class);
$response->getContent();
}
public function testUnsupportedOption()
{
$client = $this->getHttpClient(__FUNCTION__);
$this->expectException(\InvalidArgumentException::class);
$client->request('GET', 'http://localhost:8057', [
'capture_peer_cert' => 1.0,
]);
}
public function testHttpVersion()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057', [
'http_version' => 1.0,
]);
$this->assertSame(200, $response->getStatusCode());
$this->assertSame('HTTP/1.0 200 OK', $response->getInfo('response_headers')[0]);
$body = $response->toArray();
$this->assertSame('HTTP/1.0', $body['SERVER_PROTOCOL']);
$this->assertSame('GET', $body['REQUEST_METHOD']);
$this->assertSame('/', $body['REQUEST_URI']);
}
public function testChunkedEncoding()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/chunked');
$this->assertSame(['chunked'], $response->getHeaders()['transfer-encoding']);
$this->assertSame('Symfony is awesome!', $response->getContent());
$response = $client->request('GET', 'http://localhost:8057/chunked-broken');
$this->expectException(TransportExceptionInterface::class);
$response->getContent();
}
public function testClientError()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/404');
$client->stream($response)->valid();
$this->assertSame(404, $response->getInfo('http_code'));
try {
$response->getHeaders();
$this->fail(ClientExceptionInterface::class.' expected');
} catch (ClientExceptionInterface $e) {
}
try {
$response->getContent();
$this->fail(ClientExceptionInterface::class.' expected');
} catch (ClientExceptionInterface $e) {
}
$this->assertSame(404, $response->getStatusCode());
$this->assertSame(['application/json'], $response->getHeaders(false)['content-type']);
$this->assertNotEmpty($response->getContent(false));
}
public function testIgnoreErrors()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/404');
$this->assertSame(404, $response->getStatusCode());
}
public function testDnsError()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/301/bad-tld');
try {
$response->getStatusCode();
$this->fail(TransportExceptionInterface::class.' expected');
} catch (TransportExceptionInterface $e) {
$this->addToAssertionCount(1);
}
try {
$response->getStatusCode();
$this->fail(TransportExceptionInterface::class.' still expected');
} catch (TransportExceptionInterface $e) {
$this->addToAssertionCount(1);
}
$response = $client->request('GET', 'http://localhost:8057/301/bad-tld');
try {
foreach ($client->stream($response) as $r => $chunk) {
}
$this->fail(TransportExceptionInterface::class.' expected');
} catch (TransportExceptionInterface $e) {
$this->addToAssertionCount(1);
}
$this->assertSame($response, $r);
$this->assertNotNull($chunk->getError());
$this->expectException(TransportExceptionInterface::class);
foreach ($client->stream($response) as $chunk) {
}
}
public function testInlineAuth()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://foo:bar%3Dbar@localhost:8057');
$body = $response->toArray();
$this->assertSame('foo', $body['PHP_AUTH_USER']);
$this->assertSame('bar=bar', $body['PHP_AUTH_PW']);
}
public function testBadRequestBody()
{
$client = $this->getHttpClient(__FUNCTION__);
$this->expectException(TransportExceptionInterface::class);
$response = $client->request('POST', 'http://localhost:8057/', [
'body' => function () { yield []; },
]);
$response->getStatusCode();
}
public function testRedirects()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('POST', 'http://localhost:8057/301', [
'auth_basic' => 'foo:bar',
'body' => function () {
yield 'foo=bar';
},
]);
$body = $response->toArray();
$this->assertSame('GET', $body['REQUEST_METHOD']);
$this->assertSame('Basic Zm9vOmJhcg==', $body['HTTP_AUTHORIZATION']);
$this->assertSame('http://localhost:8057/', $response->getInfo('url'));
$this->assertSame(2, $response->getInfo('redirect_count'));
$this->assertNull($response->getInfo('redirect_url'));
$expected = [
'HTTP/1.1 301 Moved Permanently',
'Location: http://127.0.0.1:8057/302',
'Content-Type: application/json',
'HTTP/1.1 302 Found',
'Location: http://localhost:8057/',
'Content-Type: application/json',
'HTTP/1.1 200 OK',
'Content-Type: application/json',
];
$filteredHeaders = array_values(array_filter($response->getInfo('response_headers'), function ($h) {
return \in_array(substr($h, 0, 4), ['HTTP', 'Loca', 'Cont'], true) && 'Content-Encoding: gzip' !== $h;
}));
$this->assertSame($expected, $filteredHeaders);
}
public function testRelativeRedirects()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/302/relative');
$body = $response->toArray();
$this->assertSame('/', $body['REQUEST_URI']);
$this->assertNull($response->getInfo('redirect_url'));
$response = $client->request('GET', 'http://localhost:8057/302/relative', [
'max_redirects' => 0,
]);
$this->assertSame(302, $response->getStatusCode());
$this->assertSame('http://localhost:8057/', $response->getInfo('redirect_url'));
}
public function testRedirect307()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('POST', 'http://localhost:8057/307', [
'body' => function () {
yield 'foo=bar';
},
'max_redirects' => 0,
]);
$this->assertSame(307, $response->getStatusCode());
$response = $client->request('POST', 'http://localhost:8057/307', [
'body' => 'foo=bar',
]);
$body = $response->toArray();
$this->assertSame(['foo' => 'bar', 'REQUEST_METHOD' => 'POST'], $body);
}
public function testMaxRedirects()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/301', [
'max_redirects' => 1,
'auth_basic' => 'foo:bar',
]);
try {
$response->getHeaders();
$this->fail(RedirectionExceptionInterface::class.' expected');
} catch (RedirectionExceptionInterface $e) {
}
$this->assertSame(302, $response->getStatusCode());
$this->assertSame(1, $response->getInfo('redirect_count'));
$this->assertSame('http://localhost:8057/', $response->getInfo('redirect_url'));
$expected = [
'HTTP/1.1 301 Moved Permanently',
'Location: http://127.0.0.1:8057/302',
'Content-Type: application/json',
'HTTP/1.1 302 Found',
'Location: http://localhost:8057/',
'Content-Type: application/json',
];
$filteredHeaders = array_values(array_filter($response->getInfo('response_headers'), function ($h) {
return \in_array(substr($h, 0, 4), ['HTTP', 'Loca', 'Cont'], true);
}));
$this->assertSame($expected, $filteredHeaders);
}
public function testStream()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057');
$chunks = $client->stream($response);
$result = [];
foreach ($chunks as $r => $chunk) {
if ($chunk->isTimeout()) {
$result[] = 't';
} elseif ($chunk->isLast()) {
$result[] = 'l';
} elseif ($chunk->isFirst()) {
$result[] = 'f';
}
}
$this->assertSame($response, $r);
$this->assertSame(['f', 'l'], $result);
$chunk = null;
$i = 0;
foreach ($client->stream($response) as $chunk) {
++$i;
}
$this->assertSame(1, $i);
$this->assertTrue($chunk->isLast());
}
public function testAddToStream()
{
$client = $this->getHttpClient(__FUNCTION__);
$r1 = $client->request('GET', 'http://localhost:8057');
$completed = [];
$pool = [$r1];
while ($pool) {
$chunks = $client->stream($pool);
$pool = [];
foreach ($chunks as $r => $chunk) {
if (!$chunk->isLast()) {
continue;
}
if ($r1 === $r) {
$r2 = $client->request('GET', 'http://localhost:8057');
$pool[] = $r2;
}
$completed[] = $r;
}
}
$this->assertSame([$r1, $r2], $completed);
}
public function testCompleteTypeError()
{
$client = $this->getHttpClient(__FUNCTION__);
$this->expectException(\TypeError::class);
$client->stream(123);
}
public function testOnProgress()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('POST', 'http://localhost:8057/post', [
'headers' => ['Content-Length' => 14],
'body' => 'foo=0123456789',
'on_progress' => function (...$state) use (&$steps) { $steps[] = $state; },
]);
$body = $response->toArray();
$this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $body);
$this->assertSame([0, 0], \array_slice($steps[0], 0, 2));
$lastStep = \array_slice($steps, -1)[0];
$this->assertSame([57, 57], \array_slice($lastStep, 0, 2));
$this->assertSame('http://localhost:8057/post', $steps[0][2]['url']);
}
public function testPostJson()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('POST', 'http://localhost:8057/post', [
'json' => ['foo' => 'bar'],
]);
$body = $response->toArray();
$this->assertContains('json', $body['content-type']);
unset($body['content-type']);
$this->assertSame(['foo' => 'bar', 'REQUEST_METHOD' => 'POST'], $body);
}
public function testPostArray()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('POST', 'http://localhost:8057/post', [
'body' => ['foo' => 'bar'],
]);
$this->assertSame(['foo' => 'bar', 'REQUEST_METHOD' => 'POST'], $response->toArray());
}
public function testPostResource()
{
$client = $this->getHttpClient(__FUNCTION__);
$h = fopen('php://temp', 'w+');
fwrite($h, 'foo=0123456789');
rewind($h);
$response = $client->request('POST', 'http://localhost:8057/post', [
'body' => $h,
]);
$body = $response->toArray();
$this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $body);
}
public function testPostCallback()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('POST', 'http://localhost:8057/post', [
'body' => function () {
yield 'foo';
yield '';
yield '=';
yield '0123456789';
},
]);
$this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $response->toArray());
}
public function testOnProgressCancel()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/timeout-body', [
'on_progress' => function ($dlNow) {
if (0 < $dlNow) {
throw new \Exception('Aborting the request');
}
},
]);
try {
foreach ($client->stream([$response]) as $chunk) {
}
$this->fail(ClientExceptionInterface::class.' expected');
} catch (TransportExceptionInterface $e) {
$this->assertSame('Aborting the request', $e->getPrevious()->getMessage());
}
$this->assertNotNull($response->getInfo('error'));
$this->expectException(TransportExceptionInterface::class);
$response->getContent();
}
public function testOnProgressError()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/timeout-body', [
'on_progress' => function ($dlNow) {
if (0 < $dlNow) {
throw new \Error('BUG');
}
},
]);
try {
foreach ($client->stream([$response]) as $chunk) {
}
$this->fail('Error expected');
} catch (\Error $e) {
$this->assertSame('BUG', $e->getMessage());
}
$this->assertNotNull($response->getInfo('error'));
$this->expectException(TransportExceptionInterface::class);
$response->getContent();
}
public function testResolve()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://symfony.com:8057/', [
'resolve' => ['symfony.com' => '127.0.0.1'],
]);
$this->assertSame(200, $response->getStatusCode());
$this->assertSame(200, $client->request('GET', 'http://symfony.com:8057/')->getStatusCode());
$response = null;
$this->expectException(TransportExceptionInterface::class);
$client->request('GET', 'http://symfony.com:8057/', ['timeout' => 3]);
}
public function testTimeoutOnAccess()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/timeout-header', [
'timeout' => 0.1,
]);
$this->expectException(TransportExceptionInterface::class);
$response->getHeaders();
}
public function testTimeoutOnStream()
{
usleep(300000); // wait for the previous test to release the server
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/timeout-body');
$this->assertSame(200, $response->getStatusCode());
$chunks = $client->stream([$response], 0.2);
$result = [];
foreach ($chunks as $r => $chunk) {
if ($chunk->isTimeout()) {
$result[] = 't';
} else {
$result[] = $chunk->getContent();
}
}
$this->assertSame(['<1>', 't'], $result);
$chunks = $client->stream([$response]);
foreach ($chunks as $r => $chunk) {
$this->assertSame('<2>', $chunk->getContent());
$this->assertSame('<1><2>', $r->getContent());
return;
}
$this->fail('The response should have completed');
}
public function testUncheckedTimeoutThrows()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/timeout-body');
$chunks = $client->stream([$response], 0.1);
$this->expectException(TransportExceptionInterface::class);
foreach ($chunks as $r => $chunk) {
}
}
public function testDestruct()
{
$client = $this->getHttpClient(__FUNCTION__);
$downloaded = 0;
$start = microtime(true);
$client->request('GET', 'http://localhost:8057/timeout-long');
$client = null;
$duration = microtime(true) - $start;
$this->assertGreaterThan(1, $duration);
$this->assertLessThan(3, $duration);
}
public function testProxy()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/', [
'proxy' => 'http://localhost:8057',
]);
$body = $response->toArray();
$this->assertSame('localhost:8057', $body['HTTP_HOST']);
$this->assertRegexp('#^http://(localhost|127\.0\.0\.1):8057/$#', $body['REQUEST_URI']);
$response = $client->request('GET', 'http://localhost:8057/', [
'proxy' => 'http://foo:b%3Dar@localhost:8057',
]);
$body = $response->toArray();
$this->assertSame('Basic Zm9vOmI9YXI=', $body['HTTP_PROXY_AUTHORIZATION']);
}
public function testNoProxy()
{
putenv('no_proxy='.$_SERVER['no_proxy'] = 'example.com, localhost');
try {
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/', [
'proxy' => 'http://localhost:8057',
]);
$body = $response->toArray();
$this->assertSame('HTTP/1.1', $body['SERVER_PROTOCOL']);
$this->assertSame('/', $body['REQUEST_URI']);
$this->assertSame('GET', $body['REQUEST_METHOD']);
} finally {
putenv('no_proxy');
unset($_SERVER['no_proxy']);
}
}
/**
* @requires extension zlib
*/
public function testAutoEncodingRequest()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057');
$this->assertSame(200, $response->getStatusCode());
$headers = $response->getHeaders();
$this->assertSame(['Accept-Encoding'], $headers['vary']);
$this->assertContains('gzip', $headers['content-encoding'][0]);
$body = $response->toArray();
$this->assertContains('gzip', $body['HTTP_ACCEPT_ENCODING']);
}
public function testBaseUri()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', '../404', [
'base_uri' => 'http://localhost:8057/abc/',
]);
$this->assertSame(404, $response->getStatusCode());
$this->assertSame(['application/json'], $response->getHeaders(false)['content-type']);
}
public function testQuery()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/?a=a', [
'query' => ['b' => 'b'],
]);
$body = $response->toArray();
$this->assertSame('GET', $body['REQUEST_METHOD']);
$this->assertSame('/?a=a&b=b', $body['REQUEST_URI']);
}
/**
* @requires extension zlib
*/
public function testUserlandEncodingRequest()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057', [
'headers' => ['Accept-Encoding' => 'gzip'],
]);
$headers = $response->getHeaders();
$this->assertSame(['Accept-Encoding'], $headers['vary']);
$this->assertContains('gzip', $headers['content-encoding'][0]);
$body = $response->getContent();
$this->assertSame("\x1F", $body[0]);
$body = json_decode(gzdecode($body), true);
$this->assertSame('gzip', $body['HTTP_ACCEPT_ENCODING']);
}
/**
* @requires extension zlib
*/
public function testGzipBroken()
{
$client = $this->getHttpClient(__FUNCTION__);
$response = $client->request('GET', 'http://localhost:8057/gzip-broken');
$this->expectException(TransportExceptionInterface::class);
$response->getContent();
}
}

View File

@@ -0,0 +1,49 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\HttpClient\Test;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Process;
/**
* @experimental in 1.1
*/
class TestHttpServer
{
private static $server;
public static function start()
{
if (null !== self::$server) {
return;
}
$finder = new PhpExecutableFinder();
$process = new Process(array_merge([$finder->find(false)], $finder->findArguments(), ['-dopcache.enable=0', '-dvariables_order=EGPCS', '-S', '127.0.0.1:8057']));
$process->setWorkingDirectory(__DIR__.'/Fixtures/web');
$process->setTimeout(300);
$process->start();
self::$server = new class() {
public $process;
public function __destruct()
{
$this->process->stop();
}
};
self::$server->process = $process;
sleep('\\' === \DIRECTORY_SEPARATOR ? 10 : 1);
}
}

View File

@@ -1,4 +1,4 @@
Copyright (c) 2018 Fabien Potencier
Copyright (c) 2018-2019 Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@@ -11,7 +11,7 @@ Design Principles
* contracts are split by domain, each into their own sub-namespaces;
* contracts are small and consistent sets of PHP interfaces, traits, normative
docblocks and reference test suites when applicable, etc.;
docblocks and reference test suites when applicable, ...;
* all contracts must have a proven implementation to enter this repository;
* they must be backward compatible with existing Symfony components.

View File

@@ -15,7 +15,7 @@ use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
/**
* A trait to help implement PSR-11 service locators.
* A trait to help implement ServiceProviderInterface.
*
* @author Robin Chalas <robin.chalas@gmail.com>
* @author Nicolas Grekas <p@tchwork.com>
@@ -23,7 +23,8 @@ use Psr\Container\NotFoundExceptionInterface;
trait ServiceLocatorTrait
{
private $factories;
private $loading = array();
private $loading = [];
private $providedTypes;
/**
* @param callable[] $factories
@@ -66,6 +67,28 @@ trait ServiceLocatorTrait
}
}
/**
* {@inheritdoc}
*/
public function getProvidedServices(): array
{
if (null === $this->providedTypes) {
$this->providedTypes = [];
foreach ($this->factories as $name => $factory) {
if (!\is_callable($factory)) {
$this->providedTypes[$name] = '?';
} else {
$type = (new \ReflectionFunction($factory))->getReturnType();
$this->providedTypes[$name] = $type ? ($type->allowsNull() ? '?' : '').$type->getName() : '?';
}
}
}
return $this->providedTypes;
}
private function createNotFoundException(string $id): NotFoundExceptionInterface
{
if (!$alternatives = array_keys($this->factories)) {

View File

@@ -0,0 +1,36 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Contracts\Service;
use Psr\Container\ContainerInterface;
/**
* A ServiceProviderInterface exposes the identifiers and the types of services provided by a container.
*
* @author Nicolas Grekas <p@tchwork.com>
* @author Mateusz Sip <mateusz.sip@gmail.com>
*/
interface ServiceProviderInterface extends ContainerInterface
{
/**
* Returns an associative array of service types keyed by the identifiers provided by the current container.
*
* Examples:
*
* * ['logger' => 'Psr\Log\LoggerInterface'] means the object provides a service named "logger" that implements Psr\Log\LoggerInterface
* * ['foo' => '?'] means the container provides service name "foo" of unspecified type
* * ['bar' => '?Bar\Baz'] means the container provides a service "bar" of type Bar\Baz|null
*
* @return string[] The provided service types, keyed by service names
*/
public function getProvidedServices(): array;
}

View File

@@ -33,19 +33,19 @@ interface ServiceSubscriberInterface
*
* For mandatory dependencies:
*
* * array('logger' => 'Psr\Log\LoggerInterface') means the objects use the "logger" name
* * ['logger' => 'Psr\Log\LoggerInterface'] means the objects use the "logger" name
* internally to fetch a service which must implement Psr\Log\LoggerInterface.
* * array('loggers' => 'Psr\Log\LoggerInterface[]') means the objects use the "loggers" name
* * ['loggers' => 'Psr\Log\LoggerInterface[]'] means the objects use the "loggers" name
* internally to fetch an iterable of Psr\Log\LoggerInterface instances.
* * array('Psr\Log\LoggerInterface') is a shortcut for
* * array('Psr\Log\LoggerInterface' => 'Psr\Log\LoggerInterface')
* * ['Psr\Log\LoggerInterface'] is a shortcut for
* * ['Psr\Log\LoggerInterface' => 'Psr\Log\LoggerInterface']
*
* otherwise:
*
* * array('logger' => '?Psr\Log\LoggerInterface') denotes an optional dependency
* * array('loggers' => '?Psr\Log\LoggerInterface[]') denotes an optional iterable dependency
* * array('?Psr\Log\LoggerInterface') is a shortcut for
* * array('Psr\Log\LoggerInterface' => '?Psr\Log\LoggerInterface')
* * ['logger' => '?Psr\Log\LoggerInterface'] denotes an optional dependency
* * ['loggers' => '?Psr\Log\LoggerInterface[]'] denotes an optional iterable dependency
* * ['?Psr\Log\LoggerInterface'] is a shortcut for
* * ['Psr\Log\LoggerInterface' => '?Psr\Log\LoggerInterface']
*
* @return array The required service types, optionally keyed by service names
*/

View File

@@ -32,7 +32,7 @@ trait ServiceSubscriberTrait
return $services;
}
$services = \is_callable(array('parent', __FUNCTION__)) ? parent::getSubscribedServices() : array();
$services = \is_callable(['parent', __FUNCTION__]) ? parent::getSubscribedServices() : [];
foreach ((new \ReflectionClass(self::class))->getMethods() as $method) {
if ($method->isStatic() || $method->isAbstract() || $method->isGenerator() || $method->isInternal() || $method->getNumberOfRequiredParameters()) {
@@ -54,7 +54,7 @@ trait ServiceSubscriberTrait
{
$this->container = $container;
if (\is_callable(array('parent', __FUNCTION__))) {
if (\is_callable(['parent', __FUNCTION__])) {
return parent::setContainer($container);
}
}

View File

@@ -34,7 +34,7 @@ class CacheTraitTest extends TestCase
->with('computed data');
$cache = $this->getMockBuilder(TestPool::class)
->setMethods(array('getItem', 'save'))
->setMethods(['getItem', 'save'])
->getMock();
$cache->expects($this->once())
->method('getItem')
@@ -60,7 +60,7 @@ class CacheTraitTest extends TestCase
->method('set');
$cache = $this->getMockBuilder(TestPool::class)
->setMethods(array('getItem', 'save'))
->setMethods(['getItem', 'save'])
->getMock();
$cache->expects($this->once())
@@ -91,7 +91,7 @@ class CacheTraitTest extends TestCase
->with('computed data');
$cache = $this->getMockBuilder(TestPool::class)
->setMethods(array('getItem', 'save'))
->setMethods(['getItem', 'save'])
->getMock();
$cache->expects($this->once())
@@ -111,7 +111,7 @@ class CacheTraitTest extends TestCase
public function testExceptionOnNegativeBeta()
{
$cache = $this->getMockBuilder(TestPool::class)
->setMethods(array('getItem', 'save'))
->setMethods(['getItem', 'save'])
->getMock();
$callback = function (CacheItemInterface $item) {
@@ -135,7 +135,7 @@ class TestPool implements CacheItemPoolInterface
{
}
public function deleteItems(array $keys = array())
public function deleteItems(array $keys = [])
{
}
@@ -143,7 +143,7 @@ class TestPool implements CacheItemPoolInterface
{
}
public function getItems(array $key = array())
public function getItems(array $key = [])
{
}

View File

@@ -26,11 +26,11 @@ class ServiceLocatorTest extends TestCase
public function testHas()
{
$locator = $this->getServiceLocator(array(
$locator = $this->getServiceLocator([
'foo' => function () { return 'bar'; },
'bar' => function () { return 'baz'; },
function () { return 'dummy'; },
));
]);
$this->assertTrue($locator->has('foo'));
$this->assertTrue($locator->has('bar'));
@@ -39,10 +39,10 @@ class ServiceLocatorTest extends TestCase
public function testGet()
{
$locator = $this->getServiceLocator(array(
$locator = $this->getServiceLocator([
'foo' => function () { return 'bar'; },
'bar' => function () { return 'baz'; },
));
]);
$this->assertSame('bar', $locator->get('foo'));
$this->assertSame('baz', $locator->get('bar'));
@@ -51,13 +51,13 @@ class ServiceLocatorTest extends TestCase
public function testGetDoesNotMemoize()
{
$i = 0;
$locator = $this->getServiceLocator(array(
$locator = $this->getServiceLocator([
'foo' => function () use (&$i) {
++$i;
return 'bar';
},
));
]);
$this->assertSame('bar', $locator->get('foo'));
$this->assertSame('bar', $locator->get('foo'));
@@ -70,9 +70,9 @@ class ServiceLocatorTest extends TestCase
*/
public function testThrowsOnUndefinedInternalService()
{
$locator = $this->getServiceLocator(array(
$locator = $this->getServiceLocator([
'foo' => function () use (&$locator) { return $locator->get('bar'); },
));
]);
$locator->get('foo');
}
@@ -83,11 +83,11 @@ class ServiceLocatorTest extends TestCase
*/
public function testThrowsOnCircularReference()
{
$locator = $this->getServiceLocator(array(
$locator = $this->getServiceLocator([
'foo' => function () use (&$locator) { return $locator->get('bar'); },
'bar' => function () use (&$locator) { return $locator->get('baz'); },
'baz' => function () use (&$locator) { return $locator->get('bar'); },
));
]);
$locator->get('foo');
}

View File

@@ -21,14 +21,14 @@ class ServiceSubscriberTraitTest extends TestCase
{
public function testMethodsOnParentsAndChildrenAreIgnoredInGetSubscribedServices()
{
$expected = array(TestService::class.'::aService' => '?Symfony\Contracts\Tests\Service\Service2');
$expected = [TestService::class.'::aService' => '?Symfony\Contracts\Tests\Service\Service2'];
$this->assertEquals($expected, ChildTestService::getSubscribedServices());
}
public function testSetContainerIsCalledOnParent()
{
$container = new class(array()) implements ContainerInterface {
$container = new class([]) implements ContainerInterface {
use ServiceLocatorTrait;
};

View File

@@ -55,7 +55,7 @@ class TranslatorTest extends TestCase
$translator = $this->getTranslator();
$translator->setLocale('en');
$this->assertEquals($expected, $translator->trans($id, array('%count%' => $number)));
$this->assertEquals($expected, $translator->trans($id, ['%count%' => $number]));
}
/**
@@ -67,7 +67,7 @@ class TranslatorTest extends TestCase
$translator = $this->getTranslator();
$this->assertEquals($expected, $translator->trans($id, array('%count%' => $number)));
$this->assertEquals($expected, $translator->trans($id, ['%count%' => $number]));
}
public function testGetSetLocale()
@@ -94,24 +94,24 @@ class TranslatorTest extends TestCase
public function getTransTests()
{
return array(
array('Symfony is great!', 'Symfony is great!', array()),
array('Symfony is awesome!', 'Symfony is %what%!', array('%what%' => 'awesome')),
);
return [
['Symfony is great!', 'Symfony is great!', []],
['Symfony is awesome!', 'Symfony is %what%!', ['%what%' => 'awesome']],
];
}
public function getTransChoiceTests()
{
return array(
array('There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0),
array('There is one apple', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 1),
array('There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10),
array('There are 0 apples', 'There is 1 apple|There are %count% apples', 0),
array('There is 1 apple', 'There is 1 apple|There are %count% apples', 1),
array('There are 10 apples', 'There is 1 apple|There are %count% apples', 10),
return [
['There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0],
['There is one apple', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 1],
['There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10],
['There are 0 apples', 'There is 1 apple|There are %count% apples', 0],
['There is 1 apple', 'There is 1 apple|There are %count% apples', 1],
['There are 10 apples', 'There is 1 apple|There are %count% apples', 10],
// custom validation messages may be coded with a fixed value
array('There are 2 apples', 'There are 2 apples', 2),
);
['There are 2 apples', 'There are 2 apples', 2],
];
}
/**
@@ -121,22 +121,22 @@ class TranslatorTest extends TestCase
{
$translator = $this->getTranslator();
$this->assertEquals($expected, $translator->trans($interval.' foo|[1,Inf[ bar', array('%count%' => $number)));
$this->assertEquals($expected, $translator->trans($interval.' foo|[1,Inf[ bar', ['%count%' => $number]));
}
public function getInternal()
{
return array(
array('foo', 3, '{1,2, 3 ,4}'),
array('bar', 10, '{1,2, 3 ,4}'),
array('bar', 3, '[1,2]'),
array('foo', 1, '[1,2]'),
array('foo', 2, '[1,2]'),
array('bar', 1, ']1,2['),
array('bar', 2, ']1,2['),
array('foo', log(0), '[-Inf,2['),
array('foo', -log(0), '[-2,+Inf]'),
);
return [
['foo', 3, '{1,2, 3 ,4}'],
['bar', 10, '{1,2, 3 ,4}'],
['bar', 3, '[1,2]'],
['foo', 1, '[1,2]'],
['foo', 2, '[1,2]'],
['bar', 1, ']1,2['],
['bar', 2, ']1,2['],
['foo', log(0), '[-Inf,2['],
['foo', -log(0), '[-2,+Inf]'],
];
}
/**
@@ -146,14 +146,14 @@ class TranslatorTest extends TestCase
{
$translator = $this->getTranslator();
$this->assertEquals($expected, $translator->trans($id, array('%count%' => $number)));
$this->assertEquals($expected, $translator->trans($id, ['%count%' => $number]));
}
public function testReturnMessageIfExactlyOneStandardRuleIsGiven()
{
$translator = $this->getTranslator();
$this->assertEquals('There are two apples', $translator->trans('There are two apples', array('%count%' => 2)));
$this->assertEquals('There are two apples', $translator->trans('There are two apples', ['%count%' => 2]));
}
/**
@@ -164,98 +164,98 @@ class TranslatorTest extends TestCase
{
$translator = $this->getTranslator();
$translator->trans($id, array('%count%' => $number));
$translator->trans($id, ['%count%' => $number]);
}
public function getNonMatchingMessages()
{
return array(
array('{0} There are no apples|{1} There is one apple', 2),
array('{1} There is one apple|]1,Inf] There are %count% apples', 0),
array('{1} There is one apple|]2,Inf] There are %count% apples', 2),
array('{0} There are no apples|There is one apple', 2),
);
return [
['{0} There are no apples|{1} There is one apple', 2],
['{1} There is one apple|]1,Inf] There are %count% apples', 0],
['{1} There is one apple|]2,Inf] There are %count% apples', 2],
['{0} There are no apples|There is one apple', 2],
];
}
public function getChooseTests()
{
return array(
array('There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0),
array('There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0),
array('There are no apples', '{0}There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0),
return [
['There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0],
['There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0],
['There are no apples', '{0}There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0],
array('There is one apple', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 1),
['There is one apple', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 1],
array('There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10),
array('There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf]There are %count% apples', 10),
array('There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10),
['There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10],
['There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf]There are %count% apples', 10],
['There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10],
array('There are 0 apples', 'There is one apple|There are %count% apples', 0),
array('There is one apple', 'There is one apple|There are %count% apples', 1),
array('There are 10 apples', 'There is one apple|There are %count% apples', 10),
['There are 0 apples', 'There is one apple|There are %count% apples', 0],
['There is one apple', 'There is one apple|There are %count% apples', 1],
['There are 10 apples', 'There is one apple|There are %count% apples', 10],
array('There are 0 apples', 'one: There is one apple|more: There are %count% apples', 0),
array('There is one apple', 'one: There is one apple|more: There are %count% apples', 1),
array('There are 10 apples', 'one: There is one apple|more: There are %count% apples', 10),
['There are 0 apples', 'one: There is one apple|more: There are %count% apples', 0],
['There is one apple', 'one: There is one apple|more: There are %count% apples', 1],
['There are 10 apples', 'one: There is one apple|more: There are %count% apples', 10],
array('There are no apples', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 0),
array('There is one apple', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 1),
array('There are 10 apples', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 10),
['There are no apples', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 0],
['There is one apple', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 1],
['There are 10 apples', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 10],
array('', '{0}|{1} There is one apple|]1,Inf] There are %count% apples', 0),
array('', '{0} There are no apples|{1}|]1,Inf] There are %count% apples', 1),
['', '{0}|{1} There is one apple|]1,Inf] There are %count% apples', 0],
['', '{0} There are no apples|{1}|]1,Inf] There are %count% apples', 1],
// Indexed only tests which are Gettext PoFile* compatible strings.
array('There are 0 apples', 'There is one apple|There are %count% apples', 0),
array('There is one apple', 'There is one apple|There are %count% apples', 1),
array('There are 2 apples', 'There is one apple|There are %count% apples', 2),
['There are 0 apples', 'There is one apple|There are %count% apples', 0],
['There is one apple', 'There is one apple|There are %count% apples', 1],
['There are 2 apples', 'There is one apple|There are %count% apples', 2],
// Tests for float numbers
array('There is almost one apple', '{0} There are no apples|]0,1[ There is almost one apple|{1} There is one apple|[1,Inf] There is more than one apple', 0.7),
array('There is one apple', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 1),
array('There is more than one apple', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 1.7),
array('There are no apples', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0),
array('There are no apples', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0.0),
array('There are no apples', '{0.0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0),
['There is almost one apple', '{0} There are no apples|]0,1[ There is almost one apple|{1} There is one apple|[1,Inf] There is more than one apple', 0.7],
['There is one apple', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 1],
['There is more than one apple', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 1.7],
['There are no apples', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0],
['There are no apples', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0.0],
['There are no apples', '{0.0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0],
// Test texts with new-lines
// with double-quotes and \n in id & double-quotes and actual newlines in text
array("This is a text with a\n new-line in it. Selector = 0.", '{0}This is a text with a
["This is a text with a\n new-line in it. Selector = 0.", '{0}This is a text with a
new-line in it. Selector = 0.|{1}This is a text with a
new-line in it. Selector = 1.|[1,Inf]This is a text with a
new-line in it. Selector > 1.', 0),
new-line in it. Selector > 1.', 0],
// with double-quotes and \n in id and single-quotes and actual newlines in text
array("This is a text with a\n new-line in it. Selector = 1.", '{0}This is a text with a
["This is a text with a\n new-line in it. Selector = 1.", '{0}This is a text with a
new-line in it. Selector = 0.|{1}This is a text with a
new-line in it. Selector = 1.|[1,Inf]This is a text with a
new-line in it. Selector > 1.', 1),
array("This is a text with a\n new-line in it. Selector > 1.", '{0}This is a text with a
new-line in it. Selector > 1.', 1],
["This is a text with a\n new-line in it. Selector > 1.", '{0}This is a text with a
new-line in it. Selector = 0.|{1}This is a text with a
new-line in it. Selector = 1.|[1,Inf]This is a text with a
new-line in it. Selector > 1.', 5),
new-line in it. Selector > 1.', 5],
// with double-quotes and id split accros lines
array('This is a text with a
['This is a text with a
new-line in it. Selector = 1.', '{0}This is a text with a
new-line in it. Selector = 0.|{1}This is a text with a
new-line in it. Selector = 1.|[1,Inf]This is a text with a
new-line in it. Selector > 1.', 1),
new-line in it. Selector > 1.', 1],
// with single-quotes and id split accros lines
array('This is a text with a
['This is a text with a
new-line in it. Selector > 1.', '{0}This is a text with a
new-line in it. Selector = 0.|{1}This is a text with a
new-line in it. Selector = 1.|[1,Inf]This is a text with a
new-line in it. Selector > 1.', 5),
new-line in it. Selector > 1.', 5],
// with single-quotes and \n in text
array('This is a text with a\nnew-line in it. Selector = 0.', '{0}This is a text with a\nnew-line in it. Selector = 0.|{1}This is a text with a\nnew-line in it. Selector = 1.|[1,Inf]This is a text with a\nnew-line in it. Selector > 1.', 0),
['This is a text with a\nnew-line in it. Selector = 0.', '{0}This is a text with a\nnew-line in it. Selector = 0.|{1}This is a text with a\nnew-line in it. Selector = 1.|[1,Inf]This is a text with a\nnew-line in it. Selector > 1.', 0],
// with double-quotes and id split accros lines
array("This is a text with a\nnew-line in it. Selector = 1.", "{0}This is a text with a\nnew-line in it. Selector = 0.|{1}This is a text with a\nnew-line in it. Selector = 1.|[1,Inf]This is a text with a\nnew-line in it. Selector > 1.", 1),
["This is a text with a\nnew-line in it. Selector = 1.", "{0}This is a text with a\nnew-line in it. Selector = 0.|{1}This is a text with a\nnew-line in it. Selector = 1.|[1,Inf]This is a text with a\nnew-line in it. Selector > 1.", 1],
// esacape pipe
array('This is a text with | in it. Selector = 0.', '{0}This is a text with || in it. Selector = 0.|{1}This is a text with || in it. Selector = 1.', 0),
['This is a text with | in it. Selector = 0.', '{0}This is a text with || in it. Selector = 0.|{1}This is a text with || in it. Selector = 1.', 0],
// Empty plural set (2 plural forms) from a .PO file
array('', '|', 1),
['', '|', 1],
// Empty plural set (3 plural forms) from a .PO file
array('', '||', 1),
);
['', '||', 1],
];
}
/**
@@ -285,13 +285,13 @@ class TranslatorTest extends TestCase
*/
public function successLangcodes()
{
return array(
array('1', array('ay', 'bo', 'cgg', 'dz', 'id', 'ja', 'jbo', 'ka', 'kk', 'km', 'ko', 'ky')),
array('2', array('nl', 'fr', 'en', 'de', 'de_GE', 'hy', 'hy_AM')),
array('3', array('be', 'bs', 'cs', 'hr')),
array('4', array('cy', 'mt', 'sl')),
array('6', array('ar')),
);
return [
['1', ['ay', 'bo', 'cgg', 'dz', 'id', 'ja', 'jbo', 'ka', 'kk', 'km', 'ko', 'ky']],
['2', ['nl', 'fr', 'en', 'de', 'de_GE', 'hy', 'hy_AM']],
['3', ['be', 'bs', 'cs', 'hr']],
['4', ['cy', 'mt', 'sl']],
['6', ['ar']],
];
}
/**
@@ -304,13 +304,13 @@ class TranslatorTest extends TestCase
*/
public function failingLangcodes()
{
return array(
array('1', array('fa')),
array('2', array('jbo')),
array('3', array('cbs')),
array('4', array('gd', 'kw')),
array('5', array('ga')),
);
return [
['1', ['fa']],
['2', ['jbo']],
['3', ['cbs']],
['4', ['gd', 'kw']],
['5', ['ga']],
];
}
/**
@@ -340,7 +340,7 @@ class TranslatorTest extends TestCase
}
};
$matrix = array();
$matrix = [];
foreach ($langCodes as $langCode) {
for ($count = 0; $count < 200; ++$count) {
$plural = $translator->getPluralizationRule($count, $langCode);

View File

@@ -61,5 +61,5 @@ interface TranslatorInterface
*
* @throws \InvalidArgumentException If the locale contains invalid characters
*/
public function trans($id, array $parameters = array(), $domain = null, $locale = null);
public function trans($id, array $parameters = [], $domain = null, $locale = null);
}

View File

@@ -41,7 +41,7 @@ trait TranslatorTrait
/**
* {@inheritdoc}
*/
public function trans($id, array $parameters = array(), $domain = null, $locale = null)
public function trans($id, array $parameters = [], $domain = null, $locale = null)
{
$id = (string) $id;
@@ -52,7 +52,7 @@ trait TranslatorTrait
$number = (float) $parameters['%count%'];
$locale = (string) $locale ?: $this->getLocale();
$parts = array();
$parts = [];
if (preg_match('/^\|++$/', $id)) {
$parts = explode('|', $id);
} elseif (preg_match_all('/(?:\|\||[^\|])++/', $id, $matches)) {
@@ -77,7 +77,7 @@ trait TranslatorTrait
)\s*(?P<message>.*?)$/xs
EOF;
$standardRules = array();
$standardRules = [];
foreach ($parts as $part) {
$part = trim(str_replace('||', '|', $part));

View File

@@ -20,12 +20,15 @@
},
"require-dev": {
"psr/cache": "^1.0",
"psr/container": "^1.0"
"psr/container": "^1.0",
"symfony/polyfill-intl-idn": "^1.10"
},
"suggest": {
"psr/cache": "When using the Cache contracts",
"psr/container": "When using the Service contracts",
"symfony/cache-contracts-implementation": "",
"symfony/event-dispatcher-implementation": "",
"symfony/http-client-contracts-implementation": "",
"symfony/service-contracts-implementation": "",
"symfony/translation-contracts-implementation": ""
},
@@ -38,7 +41,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-master": "1.0-dev"
"dev-master": "1.1-dev"
}
}
}