-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #249 from statikbe/issue-145
#145 implement twig tests to validate if a query or id is valid
- Loading branch information
Showing
4 changed files
with
71 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
<?php | ||
|
||
namespace modules\statik\web\twig; | ||
|
||
use Twig\Extension\AbstractExtension; | ||
use Twig\TwigTest; | ||
|
||
use function is_numeric; | ||
|
||
class ValidateInputExtension extends AbstractExtension | ||
{ | ||
private const COMMON_QUERY_CHARACTERS_REGEX = "/^[a-zA-Z0-9.!?'\"]+$/"; | ||
|
||
public function getTests(): array | ||
{ | ||
return [ | ||
new TwigTest('valid_id', [$this, 'validateIdInput']), | ||
new TwigTest('valid_query', [$this, 'validateQueryInput']), | ||
]; | ||
} | ||
|
||
// Validates a string representing an id or an array of strings representing ids | ||
public function validateIdInput(null|array|string $input): bool | ||
{ | ||
if ($input === null) { | ||
return false; | ||
} | ||
|
||
if(!is_array($input)) { | ||
return is_numeric($input); | ||
} | ||
|
||
foreach($input as $value) { | ||
if (!$this->validateIdInput($value)) { | ||
return false; | ||
} | ||
} | ||
|
||
return true; | ||
} | ||
|
||
// Validates that query string or array of query strings only contains valid characters | ||
public function validateQueryInput(null|array|string $input): bool | ||
{ | ||
if ($input === null) { | ||
return false; | ||
} | ||
|
||
if (!is_array($input)) { | ||
return preg_match(self::COMMON_QUERY_CHARACTERS_REGEX, $input); | ||
} | ||
|
||
foreach($input as $value) { | ||
if (!$this->validateQueryInput($value)) { | ||
return false; | ||
} | ||
} | ||
|
||
return true; | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters