0 follower

Final Class Yiisoft\Validator\Rule\File

InheritanceYiisoft\Validator\Rule\File
ImplementsYiisoft\Validator\DumpedRuleInterface, Yiisoft\Validator\SkipOnEmptyInterface, Yiisoft\Validator\SkipOnErrorInterface, Yiisoft\Validator\WhenInterface
Uses TraitsYiisoft\Validator\Rule\Trait\SkipOnEmptyTrait, Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait, Yiisoft\Validator\Rule\Trait\WhenTrait

Defines validation options to check that a value is a valid file and optionally validate its extension, MIME type and size.

Supported values are:

  • string file paths;
  • {@see \SplFileInfo} instances;
  • {@see \Psr\Http\Message\UploadedFileInterface} instances.

Use {@see \Yiisoft\Validator\Rule\Each} when validating multiple files.

See also Yiisoft\Validator\Rule\FileHandler.

Public Methods

Hide inherited methods

Method Description Defined By
__construct() Yiisoft\Validator\Rule\File
getExtensions() Get allowed file extensions. Yiisoft\Validator\Rule\File
getHandler() Yiisoft\Validator\Rule\File
getMaxSize() Get expected maximum file size in bytes. Yiisoft\Validator\Rule\File
getMessage() Get error message used when the validated value is not a file. Yiisoft\Validator\Rule\File
getMimeTypes() Get allowed file MIME types. Yiisoft\Validator\Rule\File
getMinSize() Get expected minimum file size in bytes. Yiisoft\Validator\Rule\File
getName() Yiisoft\Validator\Rule\File
getNotExactSizeMessage() Get error message used when the file size doesn't exactly equal {@see $size}. Yiisoft\Validator\Rule\File
getOptions() Yiisoft\Validator\Rule\File
getSize() Get expected exact file size in bytes. Yiisoft\Validator\Rule\File
getSkipOnEmpty() Yiisoft\Validator\Rule\File
getTooBigMessage() Get error message used when the file size is greater than {@see $maxSize}. Yiisoft\Validator\Rule\File
getTooSmallMessage() Get error message used when the file size is less than {@see $minSize}. Yiisoft\Validator\Rule\File
getTrustClientMediaType() Whether to use client-provided media type for MIME validation when a validated upload has no real filesystem path. Yiisoft\Validator\Rule\File
getUnableToDetermineSizeMessage() Get error message used when the file size cannot be determined for configured size constraints. Yiisoft\Validator\Rule\File
getUploadFailedMessage() Get error message used when an uploaded file contains an upload error. Yiisoft\Validator\Rule\File
getUploadRequiredMessage() Get error message used when no file was provided. Yiisoft\Validator\Rule\File
getWhen() A getter for $when property. Yiisoft\Validator\Rule\Trait\WhenTrait
getWrongExtensionMessage() Get error message used when the file extension is not allowed. Yiisoft\Validator\Rule\File
getWrongMimeTypeMessage() Get error message used when the file MIME type is not allowed. Yiisoft\Validator\Rule\File
shouldSkipOnError() A getter for $skipOnError property. Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait
skipOnEmpty() An immutable setter to change $skipOnEmpty property. Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait
skipOnError() An immutable setter to change $skipOnError property. Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait
when() An immutable setter to change $when property. Yiisoft\Validator\Rule\Trait\WhenTrait

Method Details

Hide inherited methods

__construct() public method

public mixed __construct ( array|string|null $extensions null, array|string|null $mimeTypes null, integer|null $size null, integer|null $minSize null, integer|null $maxSize null, boolean $trustClientMediaType false, string $message '{Property} must be a file.', string $uploadFailedMessage 'Failed to upload {property}. Error code: {error, number}.', string $uploadRequiredMessage 'Please upload a file.', string $wrongExtensionMessage 'Only files with these extensions are allowed: {extensions}.', string $wrongMimeTypeMessage 'Only files with these MIME types are allowed: {mimeTypes}.', string $notExactSizeMessage 'The size of {property} must be exactly {exactly, number} {exactly, plural, one{byte} other{bytes}}.', string $tooSmallMessage 'The size of {property} cannot be smaller than {limit, number} {limit, plural, one{byte} other{bytes}}.', string $tooBigMessage 'The size of {property} cannot be larger than {limit, number} {limit, plural, one{byte} other{bytes}}.', string $unableToDetermineSizeMessage 'The size of {property} cannot be determined.', boolean|callable|null $skipOnEmpty null, boolean $skipOnError false, Closure|null $when null )
$extensions array|string|null

Allowed file extensions without a leading dot. Values are case-insensitive and may be provided either as an array or as a comma / space separated string. Files without extension will not pass validation if it is configured.

$mimeTypes array|string|null

Allowed MIME types. Values are case-insensitive and may be provided either as an array or as a comma / space separated string. Wildcards like image/* are supported. For in-memory stream uploads without a real file path, MIME validation fails unless {@see $trustClientMediaType} is enabled. If mime_content_type() is unavailable, MIME checks for filesystem-backed files will fail validation.

$size integer|null

Expected exact size of the validated file in bytes. Validation fails if size cannot be determined.

$minSize integer|null

Expected minimum size of the validated file in bytes. Validation fails if size cannot be determined.

$maxSize integer|null

Expected maximum size of the validated file in bytes. Validation fails if size cannot be determined.

$trustClientMediaType boolean

Whether to use client-provided media type for MIME validation when the uploaded file has no real filesystem path. Client-provided media type is not trusted by default.

$message string

A message used when the validated value is not a valid file.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {Property}: the translated label of the property being validated, capitalized.
  • {file}: the validated file name when it is available.
$uploadFailedMessage string

A message used when uploaded file contains an upload error.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {Property}: the translated label of the property being validated, capitalized.
  • {file}: the validated file name when it is available.
  • {error}: the upload error code.
$uploadRequiredMessage string

A message used when no file was provided.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {Property}: the translated label of the property being validated, capitalized.
$wrongExtensionMessage string

A message used when the file extension is not allowed.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {Property}: the translated label of the property being validated, capitalized.
  • {file}: the validated file name when it is available.
  • {extensions}: the list of allowed extensions.
$wrongMimeTypeMessage string

A message used when the file MIME type is not allowed.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {Property}: the translated label of the property being validated, capitalized.
  • {file}: the validated file name when it is available.
  • {mimeTypes}: the list of allowed MIME types.
$notExactSizeMessage string

A message used when the file size doesn't exactly equal {@see $size}.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {Property}: the translated label of the property being validated, capitalized.
  • {file}: the validated file name when it is available.
  • {exactly}: expected exact size in bytes.
$tooSmallMessage string

A message used when the file size is less than {@see $minSize}.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {Property}: the translated label of the property being validated, capitalized.
  • {file}: the validated file name when it is available.
  • {limit}: expected minimum size in bytes.
$tooBigMessage string

A message used when the file size is greater than {@see $maxSize}.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {Property}: the translated label of the property being validated, capitalized.
  • {file}: the validated file name when it is available.
  • {limit}: expected maximum size in bytes.
$unableToDetermineSizeMessage string

A message used when file size constraints are configured, but the file size can't be determined.

You may use the following placeholders in the message:

  • {property}: the translated label of the property being validated.
  • {Property}: the translated label of the property being validated, capitalized.
  • {file}: the validated file name when it is available.
$skipOnEmpty boolean|callable|null

Whether to skip this rule if the validated value is empty. See {@see \Yiisoft\Validator\SkipOnEmptyInterface}.

$skipOnError boolean

Whether to skip this rule if any of the previous rules gave an error. See {@see \Yiisoft\Validator\SkipOnErrorInterface}.

$when Closure|null

A callable to define a condition for applying the rule. See {@see \Yiisoft\Validator\WhenInterface}.

                public function __construct(
    array|string|null $extensions = null,
    array|string|null $mimeTypes = null,
    private ?int $size = null,
    private ?int $minSize = null,
    private ?int $maxSize = null,
    private bool $trustClientMediaType = false,
    private string $message = '{Property} must be a file.',
    private string $uploadFailedMessage = 'Failed to upload {property}. Error code: {error, number}.',
    private string $uploadRequiredMessage = 'Please upload a file.',
    private string $wrongExtensionMessage = 'Only files with these extensions are allowed: {extensions}.',
    private string $wrongMimeTypeMessage = 'Only files with these MIME types are allowed: {mimeTypes}.',
    private string $notExactSizeMessage = 'The size of {property} must be exactly {exactly, number} {exactly, plural, one{byte} other{bytes}}.',
    private string $tooSmallMessage = 'The size of {property} cannot be smaller than {limit, number} {limit, plural, one{byte} other{bytes}}.',
    private string $tooBigMessage = 'The size of {property} cannot be larger than {limit, number} {limit, plural, one{byte} other{bytes}}.',
    private string $unableToDetermineSizeMessage = 'The size of {property} cannot be determined.',
    bool|callable|null $skipOnEmpty = null,
    private bool $skipOnError = false,
    private ?Closure $when = null,
) {
    if ($this->size !== null && ($this->minSize !== null || $this->maxSize !== null)) {
        throw new InvalidArgumentException('Exact size and min / max size can\'t be specified together.');
    }
    foreach (['size' => $this->size, 'minSize' => $this->minSize, 'maxSize' => $this->maxSize] as $name => $value) {
        if ($value !== null && $value < 0) {
            throw new InvalidArgumentException(ucfirst($name) . ' must be greater than or equal to 0.');
        }
    }
    if ($this->minSize !== null && $this->maxSize !== null && $this->minSize > $this->maxSize) {
        throw new InvalidArgumentException('Min size must be less than or equal to max size.');
    }
    $this->extensions = $this->normalizeList($extensions);
    $this->mimeTypes = $this->normalizeList($mimeTypes);
    $this->skipOnEmpty = $skipOnEmpty;
}

            
getExtensions() public method

Get allowed file extensions.

public list|null getExtensions ( )

                public function getExtensions(): ?array
{
    return $this->extensions;
}

            
getHandler() public method

public string getHandler ( )

                public function getHandler(): string
{
    return FileHandler::class;
}

            
getMaxSize() public method

Get expected maximum file size in bytes.

public integer|null getMaxSize ( )
return integer|null

Expected maximum file size in bytes.

                public function getMaxSize(): ?int
{
    return $this->maxSize;
}

            
getMessage() public method

Get error message used when the validated value is not a file.

public string getMessage ( )
return string

Error message.

                public function getMessage(): string
{
    return $this->message;
}

            
getMimeTypes() public method

Get allowed file MIME types.

public list|null getMimeTypes ( )

                public function getMimeTypes(): ?array
{
    return $this->mimeTypes;
}

            
getMinSize() public method

Get expected minimum file size in bytes.

public integer|null getMinSize ( )
return integer|null

Expected minimum file size in bytes.

                public function getMinSize(): ?int
{
    return $this->minSize;
}

            
getName() public method

public string getName ( )

                public function getName(): string
{
    return 'file';
}

            
getNotExactSizeMessage() public method

Get error message used when the file size doesn't exactly equal {@see $size}.

public string getNotExactSizeMessage ( )
return string

Error message.

                public function getNotExactSizeMessage(): string
{
    return $this->notExactSizeMessage;
}

            
getOptions() public method

public array getOptions ( )

                public function getOptions(): array
{
    return [
        'extensions' => $this->extensions,
        'mimeTypes' => $this->mimeTypes,
        'trustClientMediaType' => $this->trustClientMediaType,
        'size' => $this->size,
        'minSize' => $this->minSize,
        'maxSize' => $this->maxSize,
        'message' => [
            'template' => $this->message,
            'parameters' => [],
        ],
        'uploadFailedMessage' => [
            'template' => $this->uploadFailedMessage,
            'parameters' => [],
        ],
        'uploadRequiredMessage' => [
            'template' => $this->uploadRequiredMessage,
            'parameters' => [],
        ],
        'wrongExtensionMessage' => [
            'template' => $this->wrongExtensionMessage,
            'parameters' => [],
        ],
        'wrongMimeTypeMessage' => [
            'template' => $this->wrongMimeTypeMessage,
            'parameters' => [],
        ],
        'notExactSizeMessage' => [
            'template' => $this->notExactSizeMessage,
            'parameters' => [],
        ],
        'tooSmallMessage' => [
            'template' => $this->tooSmallMessage,
            'parameters' => [],
        ],
        'tooBigMessage' => [
            'template' => $this->tooBigMessage,
            'parameters' => [],
        ],
        'unableToDetermineSizeMessage' => [
            'template' => $this->unableToDetermineSizeMessage,
            'parameters' => [],
        ],
        'skipOnEmpty' => $this->getSkipOnEmptyOption(),
        'skipOnError' => $this->skipOnError,
    ];
}

            
getSize() public method

Get expected exact file size in bytes.

public integer|null getSize ( )
return integer|null

Expected exact file size in bytes.

                public function getSize(): ?int
{
    return $this->size;
}

            
getSkipOnEmpty() public method

public bool|callable|null getSkipOnEmpty ( )

                public function getSkipOnEmpty(): bool|callable|null
{
    if ($this->skipOnEmpty === true || $this->skipOnEmpty instanceof WhenEmpty) {
        $emptyCondition = $this->skipOnEmpty === true ? new WhenEmpty() : $this->skipOnEmpty;
        return static fn(mixed $value, bool $isPropertyMissing): bool => self::isUploadMissing($value)
            || $emptyCondition($value, $isPropertyMissing);
    }
    return $this->skipOnEmpty;
}

            
getTooBigMessage() public method

Get error message used when the file size is greater than {@see $maxSize}.

public string getTooBigMessage ( )
return string

Error message.

                public function getTooBigMessage(): string
{
    return $this->tooBigMessage;
}

            
getTooSmallMessage() public method

Get error message used when the file size is less than {@see $minSize}.

public string getTooSmallMessage ( )
return string

Error message.

                public function getTooSmallMessage(): string
{
    return $this->tooSmallMessage;
}

            
getTrustClientMediaType() public method

Whether to use client-provided media type for MIME validation when a validated upload has no real filesystem path.

public boolean getTrustClientMediaType ( )

                public function getTrustClientMediaType(): bool
{
    return $this->trustClientMediaType;
}

            
getUnableToDetermineSizeMessage() public method

Get error message used when the file size cannot be determined for configured size constraints.

public string getUnableToDetermineSizeMessage ( )
return string

Error message.

                public function getUnableToDetermineSizeMessage(): string
{
    return $this->unableToDetermineSizeMessage;
}

            
getUploadFailedMessage() public method

Get error message used when an uploaded file contains an upload error.

public string getUploadFailedMessage ( )
return string

Error message.

                public function getUploadFailedMessage(): string
{
    return $this->uploadFailedMessage;
}

            
getUploadRequiredMessage() public method

Get error message used when no file was provided.

public string getUploadRequiredMessage ( )
return string

Error message.

                public function getUploadRequiredMessage(): string
{
    return $this->uploadRequiredMessage;
}

            
getWhen() public method

Defined in: Yiisoft\Validator\Rule\Trait\WhenTrait::getWhen()

A getter for $when property.

public Closure|null getWhen ( )
return Closure|null

Current value:

  • null - always apply the validation.
  • callable - apply the validation depending on a return value: true - apply, false - do not apply.

                public function getWhen(): ?Closure
{
    return $this->when;
}

            
getWrongExtensionMessage() public method

Get error message used when the file extension is not allowed.

public string getWrongExtensionMessage ( )
return string

Error message.

                public function getWrongExtensionMessage(): string
{
    return $this->wrongExtensionMessage;
}

            
getWrongMimeTypeMessage() public method

Get error message used when the file MIME type is not allowed.

public string getWrongMimeTypeMessage ( )
return string

Error message.

                public function getWrongMimeTypeMessage(): string
{
    return $this->wrongMimeTypeMessage;
}

            
shouldSkipOnError() public method

Defined in: Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait::shouldSkipOnError()

A getter for $skipOnError property.

public boolean shouldSkipOnError ( )
return boolean

Current value. true means to skip the current rule when the previous one errored and false - do not skip.

                public function shouldSkipOnError(): bool
{
    return $this->skipOnError;
}

            
skipOnEmpty() public method

Defined in: Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait::skipOnEmpty()

An immutable setter to change $skipOnEmpty property.

public $this skipOnEmpty ( boolean|callable|null $value )
$value boolean|callable|null

A new value.

return $this

The new instance with a changed value.

                public function skipOnEmpty(bool|callable|null $value): static
{
    $new = clone $this;
    $new->skipOnEmpty = $value;
    return $new;
}

            
skipOnError() public method

Defined in: Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait::skipOnError()

An immutable setter to change $skipOnError property.

public $this skipOnError ( boolean $value )
$value boolean

A new value. true means to skip the current rule when the previous one errored and false - do not skip.

return $this

The new instance with a changed value.

                public function skipOnError(bool $value): static
{
    $new = clone $this;
    $new->skipOnError = $value;
    return $new;
}

            
when() public method

Defined in: Yiisoft\Validator\Rule\Trait\WhenTrait::when()

An immutable setter to change $when property.

public $this when ( Closure|null $value )
$value Closure|null

A new value:

  • null - always apply the validation.
  • callable - apply the validation depending on a return value: true - apply, false - do not apply.
return $this

The new instance with a changed value.

                public function when(?Closure $value): static
{
    $new = clone $this;
    $new->when = $value;
    return $new;
}