File upload

To handle file uploads AssegaiPHP provides a specialized interface called FileInterceptor and a parameter attribute, UploadedFile

To use the FileInterceptor interceptor to handle a file upload, apply it to the route handler and use the #[UploadedFile] attribute to extract the file from the request.

Here's a basic exmaple:

#[Post('upload')]
#[UseInterceptors(new FileInterceptor('file'))]
function uploadFile(#[UploadedFile] object $file)
{
  error_log($file);
}

The FileInterceptor attribute is used to intercept incoming file requests and handle them in a specified way. It takes two arguments:

Name Description
fieldName A string that specifies the name of the field in the HTML form that holds the file.
options (optional) An object of type FileInterceptorOptions that provides additional parameters for handling the file.

The FileInterceptorOptions class has the following parameters in its constructor:

Name Description
dest (string) The destination folder for the file. The default value is <PROJECT_PATH>/uploads.
storage (string) The folder where the file will be temporarily stored before it is moved to its final destination. The default value is <PROJECT_PATH>/uploads.
fileFilter (Closure) A closure that allows you to specify a custom filter for the file. The default value is null.
limits (array) An array of file size limits. The default value is an empty array.
preservePath (bool) A boolean value that specifies whether the file's original path should be preserved. The default value is false.

File validation

Sometimes it is useful to validate the metadata of an incoming file, such as its size or type. You can create a Pipe and bind it to a parameter that has been attributed with the #[UploadedFile] attribute to do this. The following is an example of how to implement a basic file size validator pipe:

src/Util/Validation/FileSizeValidationPipe.php
use Assegai\Core\Interfaces\IPipeTransform;
use stdClass;

#[Injectable]
class FileSizeValidationPipe implements IPipeTransform
{
  function transform(mixed $value, array|stdClass|null $metadata = null): mixed
  {
    // `value` contains the file\'s attributes & metadata
    $oneKb = 1000;
    $fileSize = filesize($value->tmp_name);

    return $fileSize < $oneKb;
  }
}

The FileSizeValidationPipe class is an implementation of the IPipeTransform interface. It has a transform method that takes in a $value and $metadata as parameters, both of which are of mixed type. The value is expected to be an object containing the file's attributes and metadata, and the metadata is optional and can be an array, stdClass, or null.

The transform method calculates the file size of the file represented by the value by using the filesize() function, and checks if it is less than 1000 bytes. If it is, it returns true, otherwise it returns false.