2024-08-06 08:19:28 +00:00
< ? php
namespace Appwrite\Functions\Validator ;
2024-10-08 07:54:40 +00:00
use Utopia\Validator ;
2024-08-06 08:19:28 +00:00
/**
* Headers .
*
* Validates user provided headers
*/
class Headers extends Validator
{
2024-08-20 09:19:31 +00:00
public function __construct ( protected bool $allowEmpty = true , protected int $maxKeys = 100 , protected int $maxSize = 16384 )
2024-08-06 08:19:28 +00:00
{
}
/**
* Get Description .
*
* Returns validator description
*
* @ return string
*/
public function getDescription () : string
{
2024-08-20 09:19:31 +00:00
return 'Invalid headers: Alphanumeric characters or hyphens only, cannot start with "x-appwrite", maximum ' . $this -> maxKeys . ' keys, and total size ' . $this -> maxSize . '.' ;
2024-08-06 08:19:28 +00:00
}
/**
* Is valid .
*
* @ param mixed $value
*
* @ return bool
*/
public function isValid ( $value ) : bool
{
if ( $this -> allowEmpty && empty ( $value )) {
return true ;
}
2024-08-11 12:45:10 +00:00
if ( ! \is_array ( $value )) {
return false ;
}
2024-09-04 18:52:01 +00:00
if ( \count ( $value ) > $this -> maxKeys ) {
2024-08-20 09:19:31 +00:00
return false ;
}
2024-08-10 20:55:03 +00:00
2024-08-20 09:19:31 +00:00
$size = 0 ;
foreach ( $value as $key => $val ) {
$length = \strlen ( $key );
// Reject non-string keys
if ( ! \is_string ( $key ) || $length === 0 ) {
return false ;
}
2024-08-10 20:55:03 +00:00
2024-08-20 09:19:31 +00:00
$size += $length + \strlen ( $val );
2024-09-04 18:52:01 +00:00
if ( $size >= $this -> maxSize ) {
2024-08-20 09:19:31 +00:00
return false ;
}
// Check first and last character
if ( ! ctype_alnum ( $key [ 0 ]) || ! ctype_alnum ( $key [ $length - 1 ])) {
return false ;
}
2024-08-12 10:09:35 +00:00
2024-08-20 09:19:31 +00:00
// Check middle characters
for ( $i = 1 ; $i < $length - 1 ; $i ++ ) {
if ( ! ctype_alnum ( $key [ $i ]) && $key [ $i ] !== '-' ) {
2024-08-11 13:02:14 +00:00
return false ;
2024-08-06 08:19:28 +00:00
}
}
2024-08-20 09:19:31 +00:00
// Check for x-appwrite- prefix
if ( str_starts_with ( $key , 'x-appwrite-' )) {
return false ;
}
2024-08-06 08:19:28 +00:00
}
2024-08-20 09:19:31 +00:00
return true ;
2024-08-06 08:19:28 +00:00
}
/**
* Is array
*
* Function will return true if object is array .
*
* @ return bool
*/
public function isArray () : bool
{
return false ;
}
/**
* Get Type
*
* Returns validator type .
*
* @ return string
*/
public function getType () : string
{
return self :: TYPE_OBJECT ;
}
}