appwrite/src/Appwrite/Functions/Validator/Headers.php

104 lines
2.2 KiB
PHP
Raw Normal View History

2024-08-06 08:19:28 +00:00
<?php
namespace Appwrite\Functions\Validator;
use Utopia\Validator;
/**
* Headers.
*
* Validates user provided headers
*/
class Headers extends Validator
{
protected bool $allowEmpty;
public function __construct(bool $allowEmpty = true)
{
$this->allowEmpty = $allowEmpty;
}
/**
* Get Description.
*
* Returns validator description
*
* @return string
*/
public function getDescription(): string
{
return 'Invalid header format. Header keys can only contain alphanumeric characters, underscores, and hyphens. Header keys cannot start with "x-appwrite-" prefix.';
}
/**
* 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-08-11 13:02:14 +00:00
if (\is_array($value)) {
foreach ($value as $key => $val) {
2024-08-12 10:09:35 +00:00
$length = \strlen($key);
2024-08-11 13:02:14 +00:00
// Reject non-string keys
2024-08-12 10:09:35 +00:00
if (!\is_string($key) || $length === 0) {
2024-08-11 13:02:14 +00:00
return false;
}
2024-08-10 20:55:03 +00:00
2024-08-12 10:09:35 +00:00
// Check first and last character
if (!ctype_alnum($key[0]) || !ctype_alnum($key[$length - 1])) {
2024-08-11 13:02:14 +00:00
return false;
}
2024-08-10 20:55:03 +00:00
2024-08-12 10:09:35 +00:00
// Check middle characters
for ($i = 1; $i < $length - 1; $i++) {
if (!ctype_alnum($key[$i]) && $key[$i] !== '-') {
return false;
}
2024-08-11 13:02:14 +00:00
}
2024-08-12 10:09:35 +00:00
2024-08-11 13:02:14 +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-10 20:55:03 +00:00
return true;
2024-08-06 08:19:28 +00:00
}
2024-08-11 13:02:14 +00:00
return false;
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;
}
}