Skip to main content

Filtres

Créer un filtre

php spark make:filter MyFilter

Filtre créé dans app/Filters/MyFilter.php

<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

/**
* This filter bloc the access if the domain is not the same as the one passed as argument
*/
class AllowDomain implements FilterInterface
{
/**
* Do whatever processing this filter needs to do.
* By default it should not return anything during
* normal execution. However, when an abnormal state
* is found, it should return an instance of
* CodeIgniter\HTTP\Response. If it does, script
* execution will end and that Response will be
* sent back to the client, allowing for error pages,
* redirects, etc.
*
* @param RequestInterface $request
* @param array|null $arguments
*
* @return RequestInterface|ResponseInterface|string|void
*/
public function before(RequestInterface $request, $arguments = null)
{

if (isset($arguments) && count($arguments) > 0) {
if ($request->getUri()->getHost() != $arguments[0]) {
return response()->setStatusCode(403)->setBody('Forbidden');
}
} else {
return response()->setStatusCode(403)->setBody('Forbidden');
}
}

/**
* Allows After filters to inspect and modify the response
* object as needed. This method does not allow any way
* to stop execution of other after filters, short of
* throwing an Exception or Error.
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @param array|null $arguments
*
* @return ResponseInterface|void
*/
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
//
}
}




Ajouter le filtre

Dans app/Config/Filters.php ajouter le filtre avec son alias

public $aliases = [
...
'allowDomain' => \App\Filters\AllowDomain::class
];

Utiliser le filtre

Utiliser le filtre pour une route

Dans app/Config/Routes.php ajouter le filtre à une route

$routes->get('admin', 'Admin::index', ['filter' => 'allowDomain:example.com']);

Vérifier les filtres sur les routes

php spark routes