mirror of
https://github.com/codeigniter4/CodeIgniter4.git
synced 2025-02-20 11:44:28 +08:00
Can now add filters on the fly, as long as it is added prior to Filter::initialize is called.
This commit is contained in:
parent
b612bf1bbe
commit
c36d134f4d
@ -210,6 +210,41 @@ class Filters
|
||||
return $this->filters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new alias to the config file.
|
||||
* MUST be called prior to initialize();
|
||||
* Intended for use within routes files.
|
||||
*
|
||||
* @param string $class
|
||||
* @param string|null $alias
|
||||
* @param string $when
|
||||
* @param string $section
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function addFilter(string $class, string $alias = null, string $when = 'before', string $section = 'globals')
|
||||
{
|
||||
$alias = is_null($alias)
|
||||
? md5($class)
|
||||
: $alias;
|
||||
|
||||
if (! isset($this->config->{$section}))
|
||||
{
|
||||
$this->config->{$section} = [];
|
||||
}
|
||||
|
||||
if (! isset($this->config->{$section}[$when]))
|
||||
{
|
||||
$this->config->{$section}[$when] = [];
|
||||
}
|
||||
|
||||
$this->config->aliases[$alias] = $class;
|
||||
|
||||
$this->config->{$section}[$when][] = $alias;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------
|
||||
//--------------------------------------------------------------------
|
||||
// Processors
|
||||
|
@ -475,4 +475,26 @@ class FiltersTest extends \CIUnitTestCase
|
||||
$this->assertEquals($expected, $filters->initialize($uri)->getFilters());
|
||||
}
|
||||
|
||||
public function testAddFilter()
|
||||
{
|
||||
$_SERVER['REQUEST_METHOD'] = 'GET';
|
||||
|
||||
$config = [
|
||||
'aliases' => ['google' => 'CodeIgniter\Filters\fixtures\GoogleMe'],
|
||||
'globals' => [
|
||||
'before' => ['google'],
|
||||
'after' => []
|
||||
]
|
||||
];
|
||||
|
||||
$filters = new Filters((object) $config, $this->request, $this->response);
|
||||
|
||||
$filters = $filters->addFilter('Some\Class', 'some_alias');
|
||||
|
||||
$filters = $filters->initialize('admin/foo/bar');
|
||||
|
||||
$filters = $filters->getFilters();
|
||||
|
||||
$this->assertTrue(in_array('some_alias', $filters['before']));
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user