Oihana PHP

FileEncryptionTrait uses trait:short

Provides helpers to encrypt/decrypt files and stream them as PSR-7 download responses, delegating the cryptography to a configured `oihana\files\openssl\OpenSSLFileEncryption`.

The encryption instance is supplied through self::initializeFileEncryption() (from an init array or a PSR-11 container), so the passphrase lives in the DI configuration and never in this trait.

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0

Table of Contents

Constants

FILE_ENCRYPTION  : string = 'fileEncryption'
The key used to initialize the file encryption instance from an array.

Properties

$fileEncryption  : OpenSSLFileEncryption|null
The file encryption helper (optional). When unset, the helpers below fail.

Methods

decryptFile()  : string
Decrypts a file and returns the path of the produced (clear) file.
decryptFileResponse()  : ResponseInterface
Decrypts a file and streams the clear content as a download response.
encryptedFileResponse()  : ResponseInterface
Encrypts a file and streams the encrypted content as a download response.
encryptFile()  : string
Encrypts a file and returns the path of the produced (encrypted) file.
fail()  : ResponseInterface|null
Generates a structured error response with an HTTP status code and optional detailed messages.
initializeFileEncryption()  : static
Initializes the internal file encryption helper.
response()  : ResponseInterface
Return a response in the format accepted by the client : JSON by default or CBOR.
status()  : ResponseInterface|null
Outputs a generic HTTP status message in a JSON response.
success()  : mixed
Outputs a success message with optional JSON metadata.
successWithNewBody()  : mixed
Same as {@see self::success()} but guarantees a fresh response body stream before writing the envelope.
withFreshBody()  : ResponseInterface|null
Returns the same response with a fresh, empty body stream.
requireFileEncryption()  : OpenSSLFileEncryption
Returns the configured encryption helper or throws if none was provided.
streamProducedFile()  : ResponseInterface
Emits the download headers for a produced file, streams it into the response body, then removes the temporary file.

Constants

FILE_ENCRYPTION

The key used to initialize the file encryption instance from an array.

public string FILE_ENCRYPTION = 'fileEncryption'

Properties

$fileEncryption

The file encryption helper (optional). When unset, the helpers below fail.

protected OpenSSLFileEncryption|null $fileEncryption = null

Methods

decryptFile()

Decrypts a file and returns the path of the produced (clear) file.

public decryptFile(string $input[, string|null $output = null ]) : string
Parameters
$input : string

Path of the encrypted file.

$output : string|null = null

Optional output path (defaults to $input without its .enc suffix).

Tags
throws
FileException

If the input file is missing/unreadable or the decryption fails.

Return values
string

The path of the decrypted file.

decryptFileResponse()

Decrypts a file and streams the clear content as a download response.

public decryptFileResponse(ServerRequestInterface|null $request, ResponseInterface $response, string $file[, array<string|int, mixed> $options = [] ]) : ResponseInterface
Parameters
$request : ServerRequestInterface|null

Optional PSR-7 Request object (used to build the failure response).

$response : ResponseInterface

The PSR-7 Response object to write the file into.

$file : string

Path of the encrypted file.

$options : array<string|int, mixed> = []

Optional header switches (see FileResponseOption).

Return values
ResponseInterface

The response carrying the decrypted file, or a 500 failure response on error.

encryptedFileResponse()

Encrypts a file and streams the encrypted content as a download response.

public encryptedFileResponse(ServerRequestInterface|null $request, ResponseInterface $response, string $file[, array<string|int, mixed> $options = [] ]) : ResponseInterface
Parameters
$request : ServerRequestInterface|null

Optional PSR-7 Request object (used to build the failure response).

$response : ResponseInterface

The PSR-7 Response object to write the file into.

$file : string

Path of the plaintext file.

$options : array<string|int, mixed> = []

Optional header switches (see FileResponseOption).

Return values
ResponseInterface

The response carrying the encrypted file, or a 500 failure response on error.

encryptFile()

Encrypts a file and returns the path of the produced (encrypted) file.

public encryptFile(string $input[, string|null $output = null ]) : string
Parameters
$input : string

Path of the plaintext file.

$output : string|null = null

Optional output path (defaults to $input with a .enc suffix).

Tags
throws
DirectoryException

If the output directory cannot be created or written.

FileException

If the input file is missing/unreadable or the encryption fails.

Return values
string

The path of the encrypted file.

fail()

Generates a structured error response with an HTTP status code and optional detailed messages.

public fail(ServerRequestInterface|null $request, ResponseInterface|null $response[, int|string|null $code = 400 ][, string|null $details = null ][, array<string|int, mixed> $options = [] ][, string|null $accept = null ]) : ResponseInterface|null

Automatically logs the error if logging is enabled.

Parameters
$request : ServerRequestInterface|null

Optional PSR-7 Request object.

$response : ResponseInterface|null

The PSR-7 Response object.

$code : int|string|null = 400

The HTTP status code (default: 400).

$details : string|null = null

Optional detailed error message to override default description.

$options : array<string|int, mixed> = []

Optional array of additional data to include (e.g., errors).

$accept : string|null = null

The header accepted by the client : 'application/cbor' or by default 'application/json'

Tags
example
return $this->fail(
    $response,
    406,
    'fields validation failed',
    [
        'firstName' => 'firstName is required',
        'lastName'  => 'lastName must be a string'
    ]
);
Return values
ResponseInterface|null

Returns a PSR-7 Response object with JSON content or null if $response is not provided.

initializeFileEncryption()

Initializes the internal file encryption helper.

public initializeFileEncryption([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static

Priority order:

  1. $init[FileEncryptionTrait::FILE_ENCRYPTION]
  2. $container->get(OpenSSLFileEncryption::class) if available.
Parameters
$init : array<string|int, mixed> = []

Optional initialization array.

$container : ContainerInterface|null = null

Optional PSR-11 container.

Tags
throws
ContainerExceptionInterface

If the container encounters an error while retrieving an entry.

NotFoundExceptionInterface

If no entry was found in the container for the given identifier.

Return values
static

Returns the current instance for method chaining.

response()

Return a response in the format accepted by the client : JSON by default or CBOR.

public response(ResponseInterface $response[, mixed $data = null ][, int $status = 200 ][, string|null $accept = null ]) : ResponseInterface

Checks the Accept header in the request to determine the preferred format.

Parameters
$response : ResponseInterface

PSR-7 Response object to write to.

$data : mixed = null

Data to send in the response.

$status : int = 200

HTTP status code (default: 200).

$accept : string|null = null

The header accepted by the client : 'application/cbor' or by default 'application/json'

Tags
see
FileMimeType::JSON
FileMimeType::CBOR
FileMimeType::CBOR_SEQ
Return values
ResponseInterface

The response encoded as CBOR or JSON according to the negotiated format.

status()

Outputs a generic HTTP status message in a JSON response.

public status(ServerRequestInterface|null $request, ResponseInterface|null $response[, mixed $message = Char::EMPTY ][, int|string|null $code = 200 ][, array<string|int, mixed>|null $options = null ][, string|null $accept = null ]) : ResponseInterface|null
Parameters
$request : ServerRequestInterface|null

Optional PSR-7 Request object.

$response : ResponseInterface|null

PSR-7 Response object to send output.

$message : mixed = Char::EMPTY

The message content.

$code : int|string|null = 200

The HTTP status code (default: 200).

$options : array<string|int, mixed>|null = null

Optional array of additional output properties.

$accept : string|null = null

The header accepted by the client : 'application/cbor' or by default 'application/json'

Tags
example
return $this->status($response, 'bad request', 405);
Return values
ResponseInterface|null

Returns a PSR-7 Response object with JSON content or null if $response is not provided.

success()

Outputs a success message with optional JSON metadata.

public success(ServerRequestInterface|null $request, ResponseInterface|null $response[, mixed $data = null ][, array<string|int, mixed>|null $init = null ][, string|null $accept = null ]) : mixed

If $response is null, returns the $data directly. Supports optional initialization properties like count, limit, offset, owner, URL, status, total, position, options.

Parameters
$request : ServerRequestInterface|null

Optional PSR-7 Request object.

$response : ResponseInterface|null

Optional PSR-7 Response object.

$data : mixed = null

The main payload or data to return.

$init : array<string|int, mixed>|null = null

Optional associative array with keys:

  • count (int): Number of elements
  • limit (int): Pagination limit
  • offset (int): Pagination offset
  • params (array): Parameters for getCurrentPath()
  • status (int): HTTP status code
  • total (int): Total elements
  • url (string): URL to include in response
  • owner (array|object): Owner reference
  • options (array): Additional properties
  • position (int): Optional position in list
$accept : string|null = null

The header accepted by the client : 'application/cbor' or by default 'application/json'

Tags
example
return $this->success(
    $request,
    $response,
    $data,
    [Output::COUNT => count($data), Output::PARAMS => $request->getQueryParams()]
);
Return values
mixed

Returns a PSR-7 Response object with JSON if $response is provided, otherwise returns $data directly.

successWithNewBody()

Same as {@see self::success()} but guarantees a fresh response body stream before writing the envelope.

public successWithNewBody(ServerRequestInterface|null $request, ResponseInterface|null $response[, mixed $data = null ][, array<string|int, mixed>|null $init = null ][, string|null $accept = null ]) : mixed

Use this only when an upstream actor (typically a sub-controller called from the current controller method) may have already written into the shared PSR-7 body stream. Calling the plain success() in that case would concatenate two JSON envelopes — invalid JSON for any strict parser (NextJS RSC, modern fetch, etc.).

Implementation: swaps the response body for an empty stream via self::withFreshBody(), then delegates to success(). Whatever was previously written is discarded; the resulting body contains exactly one envelope.

Parameters
$request : ServerRequestInterface|null

Optional PSR-7 Request object.

$response : ResponseInterface|null

Optional PSR-7 Response object.

$data : mixed = null

The main payload or data to return.

$init : array<string|int, mixed>|null = null

Same keys as success().

$accept : string|null = null

The header accepted by the client.

Tags
example
// POST /users where dispatchAutoInvitation() writes into the shared body
public function post( ?Request $request , ?Response $response , array $args , array $init ) :mixed
{
    $result = parent::post( $request , $response , $args , $init ) ;
    $this->dispatchAutoInvitation( $request , $response , $userKey ) ;

    return $this->successWithNewBody
    (
        $request ,
        $result  ,
        $this->refetchHydratedUser( $userKey )
    ) ;
}
see
success()

Plain variant when the body has not been touched.

Return values
mixed

Same return contract as success().

withFreshBody()

Returns the same response with a fresh, empty body stream.

public withFreshBody(ResponseInterface|null $response) : ResponseInterface|null

Use to discard whatever an upstream actor (sub-controller, middleware) may have already written, then chain into any other response helper.

Parameters
$response : ResponseInterface|null

Optional PSR-7 Response object.

Tags
example
return $this->fail( $request , $this->withFreshBody( $response ) , 502 , 'zitadel_sync_failed' ) ;
Return values
ResponseInterface|null

The same response with a fresh empty body, or null if $response was null.

requireFileEncryption()

Returns the configured encryption helper or throws if none was provided.

private requireFileEncryption() : OpenSSLFileEncryption
Tags
throws
RuntimeException

If no encryption helper has been initialized.

Return values
OpenSSLFileEncryption

The configured file encryption helper.

streamProducedFile()

Emits the download headers for a produced file, streams it into the response body, then removes the temporary file.

private streamProducedFile(ResponseInterface $response, string $produced[, array<string|int, mixed> $options = [] ]) : ResponseInterface
Parameters
$response : ResponseInterface

The PSR-7 Response object to write the file into.

$produced : string

Path of the produced (encrypted or decrypted) file.

$options : array<string|int, mixed> = []

Optional header switches (see FileResponseOption).

Return values
ResponseInterface

The response carrying the file body.

On this page

Search results