vendor/friendsofsymfony/http-cache/src/ProxyClient/HttpDispatcher.php line 294

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the FOSHttpCache package.
  4.  *
  5.  * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace FOS\HttpCache\ProxyClient;
  11. use FOS\HttpCache\Exception\ExceptionCollection;
  12. use FOS\HttpCache\Exception\InvalidArgumentException;
  13. use FOS\HttpCache\Exception\InvalidUrlException;
  14. use FOS\HttpCache\Exception\MissingHostException;
  15. use FOS\HttpCache\Exception\ProxyResponseException;
  16. use FOS\HttpCache\Exception\ProxyUnreachableException;
  17. use Http\Client\Common\Plugin\ErrorPlugin;
  18. use Http\Client\Common\PluginClient;
  19. use Http\Client\Exception\HttpException;
  20. use Http\Client\Exception\NetworkException;
  21. use Http\Client\HttpAsyncClient;
  22. use Http\Discovery\HttpAsyncClientDiscovery;
  23. use Http\Discovery\UriFactoryDiscovery;
  24. use Http\Message\UriFactory;
  25. use Http\Promise\Promise;
  26. use Psr\Http\Message\RequestInterface;
  27. use Psr\Http\Message\UriInterface;
  28. /**
  29.  * Queue and send HTTP requests with a Httplug asynchronous client.
  30.  *
  31.  * @author David Buchmann <mail@davidbu.ch>
  32.  */
  33. class HttpDispatcher implements Dispatcher
  34. {
  35.     /**
  36.      * @var HttpAsyncClient
  37.      */
  38.     private $httpClient;
  39.     /**
  40.      * @var UriFactory
  41.      */
  42.     private $uriFactory;
  43.     /**
  44.      * Queued requests.
  45.      *
  46.      * @var RequestInterface[]
  47.      */
  48.     private $queue = [];
  49.     /**
  50.      * Caching proxy server host names or IP addresses.
  51.      *
  52.      * @var UriInterface[]
  53.      */
  54.     private $servers;
  55.     /**
  56.      * Application host name and optional base URL.
  57.      *
  58.      * @var UriInterface
  59.      */
  60.     private $baseUri;
  61.     /**
  62.      * If you specify a custom HTTP client, make sure that it converts HTTP
  63.      * errors to exceptions.
  64.      *
  65.      * If your proxy server IPs can not be statically configured, extend this
  66.      * class and overwrite getServers. Be sure to have some caching in
  67.      * getServers.
  68.      *
  69.      * @param string[]             $servers    Caching proxy server hostnames or IP
  70.      *                                         addresses, including port if not port 80.
  71.      *                                         E.g. ['127.0.0.1:6081']
  72.      * @param string               $baseUri    Default application hostname, optionally
  73.      *                                         including base URL, for purge and refresh
  74.      *                                         requests (optional). This is required if
  75.      *                                         you purge and refresh paths instead of
  76.      *                                         absolute URLs
  77.      * @param HttpAsyncClient|null $httpClient Client capable of sending HTTP requests. If no
  78.      *                                         client is supplied, a default one is created
  79.      * @param UriFactory|null      $uriFactory Factory for PSR-7 URIs. If not specified, a
  80.      *                                         default one is created
  81.      */
  82.     public function __construct(
  83.         array $servers,
  84.         $baseUri '',
  85.         HttpAsyncClient $httpClient null,
  86.         UriFactory $uriFactory null
  87.     ) {
  88.         if (!$httpClient) {
  89.             $httpClient = new PluginClient(
  90.                 HttpAsyncClientDiscovery::find(),
  91.                 [new ErrorPlugin()]
  92.             );
  93.         }
  94.         $this->httpClient $httpClient;
  95.         $this->uriFactory $uriFactory ?: UriFactoryDiscovery::find();
  96.         $this->setServers($servers);
  97.         $this->setBaseUri($baseUri);
  98.     }
  99.     /**
  100.      * {@inheritdoc}
  101.      */
  102.     public function invalidate(RequestInterface $invalidationRequest$validateHost true)
  103.     {
  104.         if ($validateHost && !$this->baseUri && !$invalidationRequest->getUri()->getHost()) {
  105.             throw MissingHostException::missingHost((string) $invalidationRequest->getUri());
  106.         }
  107.         $signature $this->getRequestSignature($invalidationRequest);
  108.         if (isset($this->queue[$signature])) {
  109.             return;
  110.         }
  111.         $this->queue[$signature] = $invalidationRequest;
  112.     }
  113.     /**
  114.      * {@inheritdoc}
  115.      */
  116.     public function flush()
  117.     {
  118.         $queue $this->queue;
  119.         $this->queue = [];
  120.         /** @var Promise[] $promises */
  121.         $promises = [];
  122.         $exceptions = new ExceptionCollection();
  123.         foreach ($queue as $request) {
  124.             foreach ($this->fanOut($request) as $proxyRequest) {
  125.                 try {
  126.                     $promises[] = $this->httpClient->sendAsyncRequest($proxyRequest);
  127.                 } catch (\Exception $e) {
  128.                     $exceptions->add(new InvalidArgumentException($e->getMessage(), $e->getCode(), $e));
  129.                 }
  130.             }
  131.         }
  132.         foreach ($promises as $promise) {
  133.             try {
  134.                 $promise->wait();
  135.             } catch (HttpException $exception) {
  136.                 $exceptions->add(ProxyResponseException::proxyResponse($exception));
  137.             } catch (NetworkException $exception) {
  138.                 $exceptions->add(ProxyUnreachableException::proxyUnreachable($exception));
  139.             } catch (\Exception $exception) {
  140.                 // @codeCoverageIgnoreStart
  141.                 $exceptions->add(new InvalidArgumentException($exception->getMessage(), $exception->getCode(), $exception));
  142.                 // @codeCoverageIgnoreEnd
  143.             }
  144.         }
  145.         if (count($exceptions)) {
  146.             throw $exceptions;
  147.         }
  148.         return count($queue);
  149.     }
  150.     /**
  151.      * Get the list of servers to send invalidation requests to.
  152.      *
  153.      * @return UriInterface[]
  154.      */
  155.     protected function getServers()
  156.     {
  157.         return $this->servers;
  158.     }
  159.     /**
  160.      * Duplicate a request for each caching server.
  161.      *
  162.      * @param RequestInterface $request The request to duplicate for each configured server
  163.      *
  164.      * @return RequestInterface[]
  165.      */
  166.     private function fanOut(RequestInterface $request)
  167.     {
  168.         $requests = [];
  169.         $uri $request->getUri();
  170.         // If a base URI is configured, try to make partial invalidation
  171.         // requests complete.
  172.         if ($this->baseUri) {
  173.             if ($uri->getHost()) {
  174.                 // Absolute URI: does it already have a scheme?
  175.                 if (!$uri->getScheme() && '' !== $this->baseUri->getScheme()) {
  176.                     $uri $uri->withScheme($this->baseUri->getScheme());
  177.                 }
  178.             } else {
  179.                 // Relative URI
  180.                 if ('' !== $this->baseUri->getHost()) {
  181.                     $uri $uri->withHost($this->baseUri->getHost());
  182.                 }
  183.                 if ($this->baseUri->getPort()) {
  184.                     $uri $uri->withPort($this->baseUri->getPort());
  185.                 }
  186.                 // Base path
  187.                 if ('' !== $this->baseUri->getPath()) {
  188.                     $path $this->baseUri->getPath().'/'.ltrim($uri->getPath(), '/');
  189.                     $uri $uri->withPath($path);
  190.                 }
  191.             }
  192.         }
  193.         // Close connections to make sure invalidation (PURGE/BAN) requests
  194.         // will not interfere with content (GET) requests.
  195.         $request $request->withUri($uri)->withHeader('Connection''Close');
  196.         // Create a request to each caching proxy server
  197.         foreach ($this->getServers() as $server) {
  198.             $serverUri $uri
  199.                 ->withScheme($server->getScheme())
  200.                 ->withHost($server->getHost())
  201.                 ->withPort($server->getPort());
  202.             if ($userInfo $server->getUserInfo()) {
  203.                 $userInfoParts explode(':'$userInfo2);
  204.                 $serverUri $serverUri
  205.                     ->withUserInfo($userInfoParts[0], $userInfoParts[1] ?? null);
  206.             }
  207.             $requests[] = $request->withUri($serverUritrue); // Preserve application Host header
  208.         }
  209.         return $requests;
  210.     }
  211.     /**
  212.      * Set caching proxy server URI objects, validating them.
  213.      *
  214.      * @param string[] $servers Caching proxy proxy server hostnames or IP
  215.      *                          addresses, including port if not port 80.
  216.      *                          E.g. ['127.0.0.1:6081']
  217.      *
  218.      * @throws InvalidUrlException If server is invalid or contains URL
  219.      *                             parts other than scheme, host, port
  220.      */
  221.     private function setServers(array $servers)
  222.     {
  223.         $this->servers = [];
  224.         foreach ($servers as $server) {
  225.             $this->servers[] = $this->filterUri($server, ['scheme''user''pass''host''port']);
  226.         }
  227.     }
  228.     /**
  229.      * Set application base URI that will be prefixed to relative purge and
  230.      * refresh requests, and validate it.
  231.      *
  232.      * @param string $uriString Your application’s base URI
  233.      *
  234.      * @throws InvalidUrlException If the base URI is not a valid URI
  235.      */
  236.     private function setBaseUri($uriString null)
  237.     {
  238.         if (!$uriString) {
  239.             $this->baseUri null;
  240.             return;
  241.         }
  242.         $this->baseUri $this->filterUri($uriString);
  243.     }
  244.     /**
  245.      * Filter a URL.
  246.      *
  247.      * Prefix the URL with "http://" if it has no scheme, then check the URL
  248.      * for validity. You can specify what parts of the URL are allowed.
  249.      *
  250.      * @param string   $uriString
  251.      * @param string[] $allowedParts Array of allowed URL parts (optional)
  252.      *
  253.      * @return UriInterface Filtered URI (with default scheme if there was no scheme)
  254.      *
  255.      * @throws InvalidUrlException If URL is invalid, the scheme is not http or
  256.      *                             contains parts that are not expected
  257.      */
  258.     private function filterUri($uriString, array $allowedParts = [])
  259.     {
  260.         if (!is_string($uriString)) {
  261.             throw new \InvalidArgumentException(sprintf(
  262.                 'URI parameter must be a string, %s given',
  263.                 gettype($uriString)
  264.             ));
  265.         }
  266.         // Creating a PSR-7 URI without scheme (with parse_url) results in the
  267.         // original hostname to be seen as path. So first add a scheme if none
  268.         // is given.
  269.         if (false === strpos($uriString'://')) {
  270.             $uriString sprintf('%s://%s''http'$uriString);
  271.         }
  272.         try {
  273.             $uri $this->uriFactory->createUri($uriString);
  274.         } catch (\InvalidArgumentException $e) {
  275.             throw InvalidUrlException::invalidUrl($uriString);
  276.         }
  277.         if (!$uri->getScheme()) {
  278.             throw InvalidUrlException::invalidUrl($uriString'empty scheme');
  279.         }
  280.         if (count($allowedParts) > 0) {
  281.             $parts parse_url((string) $uri);
  282.             $diff array_diff(array_keys($parts), $allowedParts);
  283.             if (count($diff) > 0) {
  284.                 throw InvalidUrlException::invalidUrlParts($uriString$allowedParts);
  285.             }
  286.         }
  287.         return $uri;
  288.     }
  289.     /**
  290.      * Build a request signature based on the request data. Unique for every different request, identical
  291.      * for the same requests.
  292.      *
  293.      * This signature is used to avoid sending the same invalidation request twice.
  294.      *
  295.      * @param RequestInterface $request An invalidation request
  296.      *
  297.      * @return string A signature for this request
  298.      */
  299.     private function getRequestSignature(RequestInterface $request)
  300.     {
  301.         $headers $request->getHeaders();
  302.         ksort($headers);
  303.         return sha1($request->getMethod()."\n".$request->getUri()."\n".var_export($headerstrue));
  304.     }
  305. }