Created
December 9, 2012 18:52
-
-
Save mattattui/4246470 to your computer and use it in GitHub Desktop.
Custom validators (regex and callback) with the Symfony HTTP Foundation component
This file contains hidden or 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
<?php | |
require_once __DIR__.'/vendor/autoload.php'; | |
use Symfony\Component\HttpFoundation\Request; | |
// Real request data | |
// $request = Request::createFromGlobals(); | |
// Or fake it (for testing) | |
// e.g. http://example.com/script.php?page=home | |
$request = Request::create('/script.php', 'GET', array( | |
'page' => 'home', | |
'search' => 'grumpycat', | |
)); | |
/* e.g. script.php?search=grumpycat | |
* If 'search' contains anything that isn't letters, numbers, or spaces this | |
* validator will return false. If search is empty, it returns 'default'. | |
*/ | |
$query = $request->query->filter('search', 'default', false, FILTER_VALIDATE_REGEXP, | |
array('options' => array( | |
'regexp' => '/^[a-z0-9 ]+$/i', | |
) | |
); | |
/* e.g. script.php?page=home | |
* Check if the page exists | |
* This could be a database lookup instead, and instead of returning | |
* the value or false, it could load your page object and return it. | |
* The callback shown here is an anonymous function, but you could also | |
* use 'trim' or array($pageHandler, 'load') to call the 'load' method | |
* on the $pageHandler object. | |
*/ | |
$contentDir = __DIR__.'/content'; | |
$page = $request->query->filter('page', 'default', false, FILTER_CALLBACK, array('options' => function($input) use ($contentDir) { | |
// Resolve any sneaky ../ stuff | |
$path = realpath($contentDir.DIRECTORY_SEPARATOR.$input.'.html'); | |
// Make sure the path still points to your content directory | |
// And check the file exists | |
if ((strpos($path, $contentDir) === 0) && is_file($path)) { | |
return $path; | |
} | |
// File doesn't exist or is invalid | |
return false; | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment