streamFor example

/** * Tests that provider discovery fails if the provider database is empty. * * @param string $content * The expected JSON content of the provider database. * * @dataProvider providerEmptyProviderList */
  public function testEmptyProviderList($content) {
    $response = $this->prophesize('\GuzzleHttp\Psr7\Response');
    $response->getBody()->willReturn(Utils::streamFor($content));

    $client = $this->createMock('\GuzzleHttp\Client');
    $client->method('request')->withAnyParameters()->willReturn($response->reveal());
    $this->container->set('http_client', $client);

    $this->expectException(ProviderException::class);
    $this->expectExceptionMessage('Remote oEmbed providers database returned invalid or empty list.');
    $this->container->get('media.oembed.provider_repository')->getAll();
  }

  /** * Data provider for testEmptyProviderList(). * * @see ::testEmptyProviderList() * * @return array */

        $stream = new AppendStream();

        foreach ($elements as $element) {
            if (!is_array($element)) {
                throw new \UnexpectedValueException('An array is expected');
            }
            $this->addElement($stream$element);
        }

        // Add the trailing boundary with CRLF         $stream->addStream(Utils::streamFor("--{$this->boundary}--\r\n"));

        return $stream;
    }

    private function addElement(AppendStream $stream, array $element): void
    {
        foreach (['contents', 'name'] as $key) {
            if (!array_key_exists($key$element)) {
                throw new \InvalidArgumentException("A '{$key}' key is required");
            }
        }

        
int $status = 200,
        array $headers = [],
        $body = null,
        string $version = '1.1',
        string $reason = null
    ) {
        $this->assertStatusCodeRange($status);

        $this->statusCode = $status;

        if ($body !== '' && $body !== null) {
            $this->stream = Utils::streamFor($body);
        }

        $this->setHeaders($headers);
        if ($reason == '' && isset(self::PHRASES[$this->statusCode])) {
            $this->reasonPhrase = self::PHRASES[$this->statusCode];
        } else {
            $this->reasonPhrase = (string) $reason;
        }

        $this->protocol = $version;
    }

    
$this->lastHeaders = [];

        try {
            [$ver$status$reason$headers] = HeaderProcessor::parseHeaders($hdrs);
        } catch (\Exception $e) {
            return P\Create::rejectionFor(
                new RequestException('An error was encountered while creating the response', $request, null, $e)
            );
        }

        [$stream$headers] = $this->checkDecode($options$headers$stream);
        $stream = Psr7\Utils::streamFor($stream);
        $sink = $stream;

        if (\strcasecmp('HEAD', $request->getMethod())) {
            $sink = $this->createSink($stream$options);
        }

        try {
            $response = new Psr7\Response($status$headers$sink$ver$reason);
        } catch (\Exception $e) {
            return P\Create::rejectionFor(
                new RequestException('An error was encountered while creating the response', $request, null, $e)
            );
// Mock the resource fetcher so that it will return our fake resource.     $resource_fetcher = $this->prophesize(ResourceFetcherInterface::class);
    $resource_fetcher->fetchResource(Argument::any())
      ->willReturn($resource);
    $this->container->set('media.oembed.resource_fetcher', $resource_fetcher->reveal());

    // The source plugin will try to fetch the remote thumbnail, so mock the     // HTTP client to ensure that request returns a response with some valid     // image data.     $data = Utils::tryFopen($this->getDrupalRoot() . '/core/misc/druplicon.png', 'r');
    $response = new Response(200, $thumbnail_headers, Utils::streamFor($data));
    $handler = new MockHandler([$response]);
    $client = new Client([
      'handler' => new HandlerStack($handler),
    ]);
    $this->container->set('http_client', $client);

    $media_type = $this->createMediaType('oembed:video');
    $source = $media_type->getSource();

    // Add some HTML to the global site slogan, and use the site:slogan token in     // the thumbnail path, in order to prove that the final thumbnail path is
                // to overwrite this implicit header with an empty one.                 $conf[\CURLOPT_HTTPHEADER][] = 'Accept-Encoding:';
            }
        }

        if (!isset($options['sink'])) {
            // Use a default temp stream if no sink was set.             $options['sink'] = \GuzzleHttp\Psr7\Utils::tryFopen('php://temp', 'w+');
        }
        $sink = $options['sink'];
        if (!\is_string($sink)) {
            $sink = \GuzzleHttp\Psr7\Utils::streamFor($sink);
        } elseif (!\is_dir(\dirname($sink))) {
            // Ensure that the directory exists before failing in curl.             throw new \RuntimeException(\sprintf('Directory %s does not exist for sink value of %s', \dirname($sink)$sink));
        } else {
            $sink = new LazyOpenStream($sink, 'w+');
        }
        $easy->sink = $sink;
        $conf[\CURLOPT_WRITEFUNCTION] = static function D$ch$write) use ($sink): int {
            return $sink->write($write);
        };

        
&& $options['decode_content'] !== true
        ) {
            // Ensure that we don't have the header in different case and set the new value.             $options['_conditional'] = Psr7\Utils::caselessRemove(['Accept-Encoding']$options['_conditional']);
            $modify['set_headers']['Accept-Encoding'] = $options['decode_content'];
        }

        if (isset($options['body'])) {
            if (\is_array($options['body'])) {
                throw $this->invalidBody();
            }
            $modify['body'] = Psr7\Utils::streamFor($options['body']);
            unset($options['body']);
        }

        if (!empty($options['auth']) && \is_array($options['auth'])) {
            $value = $options['auth'];
            $type = isset($value[2]) ? \strtolower($value[2]) : 'basic';
            switch ($type) {
                case 'basic':
                    // Ensure that we don't have the header in different case and set the new value.                     $modify['set_headers'] = Psr7\Utils::caselessRemove(['Authorization']$modify['set_headers']);
                    $modify['set_headers']['Authorization'] = 'Basic '
                        .
$this->method = strtoupper($method);
        $this->uri = $uri;
        $this->setHeaders($headers);
        $this->protocol = $version;

        if (!isset($this->headerNames['host'])) {
            $this->updateHostFromUri();
        }

        if ($body !== '' && $body !== null) {
            $this->stream = Utils::streamFor($body);
        }
    }

    public function getRequestTarget(): string
    {
        if ($this->requestTarget !== null) {
            return $this->requestTarget;
        }

        $target = $this->uri->getPath();
        if ($target === '') {
            
$header = $this->headerNames[$normalized];

        $new = clone $this;
        unset($new->headers[$header]$new->headerNames[$normalized]);

        return $new;
    }

    public function getBody(): StreamInterface
    {
        if (!$this->stream) {
            $this->stream = Utils::streamFor('');
        }

        return $this->stream;
    }

    public function withBody(StreamInterface $body): MessageInterface
    {
        if ($body === $this->stream) {
            return $this;
        }

        
 elseif ($resource instanceof \Iterator) {
                    return new PumpStream(function D) use ($resource) {
                        if (!$resource->valid()) {
                            return false;
                        }
                        $result = $resource->current();
                        $resource->next();

                        return $result;
                    }$options);
                } elseif (method_exists($resource, '__toString')) {
                    return self::streamFor((string) $resource$options);
                }
                break;
            case 'NULL':
                return new Stream(self::tryFopen('php://temp', 'r+')$options);
        }

        if (is_callable($resource)) {
            return new PumpStream($resource$options);
        }

        throw new \InvalidArgumentException('Invalid resource type: '.gettype($resource));
    }
string $clientMediaType = null
    ): UploadedFileInterface {
        if ($size === null) {
            $size = $stream->getSize();
        }

        return new UploadedFile($stream$size$error$clientFilename$clientMediaType);
    }

    public function createStream(string $content = ''): StreamInterface
    {
        return Utils::streamFor($content);
    }

    public function createStreamFromFile(string $file, string $mode = 'r'): StreamInterface
    {
        try {
            $resource = Utils::tryFopen($file$mode);
        } catch (\RuntimeException $e) {
            if ('' === $mode || false === \in_array($mode[0]['r', 'w', 'a', 'x', 'c'], true)) {
                throw new \InvalidArgumentException(sprintf('Invalid file opening mode "%s"', $mode), 0, $e);
            }

            
// unsetting the property forces the first access to go through         // __get().         unset($this->stream);
    }

    /** * Creates the underlying stream lazily when required. */
    protected function createStream(): StreamInterface
    {
        return Utils::streamFor(Utils::tryFopen($this->filename, $this->mode));
    }
}
Home | Imprint | This part of the site doesn't use cookies.