Skip to content

Commit c36d134

Browse files
committed
Can now add filters on the fly, as long as it is added prior to Filter::initialize is called.
1 parent b612bf1 commit c36d134

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

system/Filters/Filters.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,41 @@ public function getFilters()
210210
return $this->filters;
211211
}
212212

213+
/**
214+
* Adds a new alias to the config file.
215+
* MUST be called prior to initialize();
216+
* Intended for use within routes files.
217+
*
218+
* @param string $class
219+
* @param string|null $alias
220+
* @param string $when
221+
* @param string $section
222+
*
223+
* @return $this
224+
*/
225+
public function addFilter(string $class, string $alias = null, string $when = 'before', string $section = 'globals')
226+
{
227+
$alias = is_null($alias)
228+
? md5($class)
229+
: $alias;
230+
231+
if (! isset($this->config->{$section}))
232+
{
233+
$this->config->{$section} = [];
234+
}
235+
236+
if (! isset($this->config->{$section}[$when]))
237+
{
238+
$this->config->{$section}[$when] = [];
239+
}
240+
241+
$this->config->aliases[$alias] = $class;
242+
243+
$this->config->{$section}[$when][] = $alias;
244+
245+
return $this;
246+
}
247+
213248
//--------------------------------------------------------------------
214249
//--------------------------------------------------------------------
215250
// Processors

tests/system/Filters/FiltersTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -475,4 +475,26 @@ public function testAfterExceptInapplicable()
475475
$this->assertEquals($expected, $filters->initialize($uri)->getFilters());
476476
}
477477

478+
public function testAddFilter()
479+
{
480+
$_SERVER['REQUEST_METHOD'] = 'GET';
481+
482+
$config = [
483+
'aliases' => ['google' => 'CodeIgniter\Filters\fixtures\GoogleMe'],
484+
'globals' => [
485+
'before' => ['google'],
486+
'after' => []
487+
]
488+
];
489+
490+
$filters = new Filters((object) $config, $this->request, $this->response);
491+
492+
$filters = $filters->addFilter('Some\Class', 'some_alias');
493+
494+
$filters = $filters->initialize('admin/foo/bar');
495+
496+
$filters = $filters->getFilters();
497+
498+
$this->assertTrue(in_array('some_alias', $filters['before']));
499+
}
478500
}

0 commit comments

Comments
 (0)