Can now add filters on the fly, as long as it is added prior to Filter::initialize is called.

This commit is contained in:
Lonnie Ezell 2018-08-26 23:18:34 -05:00
parent b612bf1bbe
commit c36d134f4d
No known key found for this signature in database
GPG Key ID: 8EB408F8D82F5002
2 changed files with 57 additions and 0 deletions

View File

@ -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

View File

@ -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']));
}
}