nyholm/psr7 Documentation

repository·master·Indexed 23 days ago

https://github.com/nyholm/psr7

A lightweight, strict, and high-performance PHP implementation of the PSR-7 (HTTP Message Interface) and PSR-17 (HTTP Factories) specifications. It provides concrete implementations for Request, Response, ServerRequest, and Stream, along with the Psr17Factory for creating PSR-7 compliant objects. The library emphasizes immutability and the use of composition over inheritance.

Tokens
4.3K
Snippets
5
Records
32
Agent score
79%

What's inside nyholm/psr7

  1. Create server requests from PHP superglobals

    master

    To convert PHP superglobals (like $_SERVER, $_GET, etc.) into PSR-7 server requests, use the nyholm/psr7-server package. You must provide the necessary factories to the ServerRequestCreator.

    // Requires composer require nyholm/psr7-server
    $psr17Factory = new \Nyholm\Psr7\Factory\Psr17Factory();
    
    $creator = new \Nyholm\Psr7Server\ServerRequestCreator(
        $psr17Factory, // ServerRequestFactory
        $psr17Factory, // UriFactory
        $psr17Factory, // UploadedFileFactory
        $psr17Factory  // StreamFactory
    );
    
    $serverRequest = $creator->fromGlobals();
  2. Mocking PSR-7 classes

    master
    Since PSR-7 classes are designed as value objects, they can typically be used directly in your tests without the need for mocking. If you encounter a specific scenario that requires a mock, you should mock the interface (e.g., Psr ing equest-interface) rather than attempting to mock the concrete implementation classes.
  3. Send a request using a PSR-18 client

    master

    You can send PSR-7 requests using any PSR-18 compliant HTTP client (such as Buzz). Pass the Psr17Factory to the client to handle request creation and compatibility.

    $psr17Factory = new \Nyholm\Psr7\Factory\Psr17Factory();
    $psr18Client = new \Buzz\Client\Curl($psr17Factory);
    
    $request = $psr17Factory->createRequest('GET', 'http://tnyholm.se');
    $response = $psr18Client->sendRequest($request);
  4. Emit a PSR-7 response

    master

    To send a PSR-7 response to the client (e.g., via SAPI), use an emitter such as laminas/laminas-httphandlerrunner.

    // Requires composer require laminas/laminas-httphandlerrunner
    $psr17Factory = new \Nyholm\Psr7\Factory\Psr17Factory();
    
    $responseBody = $psr17Factory->createStream('Hello world');
    $response = $psr17Factory->createResponse(200)->withBody($responseBody);
    (new \Laminas\HttpHandlerRunner\Emitter\SapiEmitter())->emit($response);
  5. Create PSR-7 objects using Psr17Factory

    master

    To create PSR-7 objects such as requests, streams, and URIs, use the Nyholm\Psr7\Factory\Psr17Factory. This factory implements the PSR-17 standard, ensuring compatibility with other PSR-compliant libraries.

    $psr17Factory = new \Nyholm\Psr7\Factory\Psr17Factory();
    $request = $psr17Factory->createRequest('GET', 'http://tnyholm.se');
    $stream = $psr17Factory->createStream('foobar');
  6. Create Streams with Psr17Factory

    master

    The Psr17Factory provides three ways to create a StreamInterface:

    1. createStream(string $content = ''): Creates a stream from a string.
    2. createStreamFromFile(string $filename, string $mode = 'r'): Creates a stream from a file. Throws RuntimeException if the path is empty or the file cannot be opened, and InvalidArgumentException if the mode is invalid.
    3. createStreamFromResource($resource): Creates a stream from an existing PHP resource.
  7. Create a Response with Psr17Factory::createResponse()

    master

    Use createResponse() to instantiate a new ResponseInterface.

    • If you provide only the $code, the $reasonPhrase will be set to null (allowing the Response class to use its own default logic).
    • If you provide both $code and $reasonPhrase, the response will use the specified phrase.
  8. Create new URI instances with 'with' methods

    master

    Since Uri implements UriInterface, it follows the PSR-7 immutability pattern. Methods prefixed with with do not modify the existing object; instead, they return a new instance with the specified change. If the new value is identical to the current value, the original instance is returned.

    Available methods:

    • withScheme(string $scheme): UriInterface
    • withUserInfo(string $user, string $password = null): UriInterface
    • withHost(string $host): UriInterface
    • withPort(int $port): UriInterface
    • withPath(string $path): UriInterface
    • withQuery(string $query): UriInterface
    • withFragment(string $fragment): UriInterface

    Note on Ports: If you set a port that is the default for the current scheme (e.g., 80 for http), the getPort() method will return null to comply with PSR-7 standards.

  9. Instantiate UploadedFile

    master

    The Nyholm\Psr7\UploadedFile class implements Psr\Http\Message\UploadedFileInterface. It is used to represent files uploaded via an HTTP request.

    Constructor Parameters

    • $streamOrFile: A StreamInterface, a string (path to file), or a PHP resource.
    • $size: An integer representing the file size in bytes.
    • $errorStatus: An integer representing the upload error status. This must be one of the standard PHP UPLOAD_ERR_* constants (e.g., \UPLOAD_ERR_OK).
    • $clientFilename (optional): A string representing the filename provided by the client.
    • $clientMediaType (optional): A string representing the media type provided by the client.

    Error Handling

    • If $errorStatus is not a valid UPLOAD_ERR_* constant, an \InvalidArgumentException is thrown.
    • If $size is not an integer, an \InvalidArgumentException is thrown.
    • If the provided $streamOrFile is invalid for the given error status, an \InvalidArgumentException is thrown.
  10. Create a new Response with a different status using withStatus()

    master

    Since Response implements ResponseInterface, it follows the PSR-7 immutability pattern. To change the status code, use the withStatus() method, which returns a new instance of the response with the updated status and reason phrase.

    Method Signature: public function withStatus($code, $reasonPhrase = ''): ResponseInterface

    • $code: An integer or string representing the status code. Must be between 100 and 599.
    • $reasonPhrase: An optional string for a custom reason phrase. If empty, the default phrase for the status code is used.

    Throws:

    • \InvalidArgumentException if the status code is not an integer/string or is outside the range 100-599.