Skip to content

Commit 92e2a4a

Browse files
committed
feat: do not instantiate the same filter class more than once
1 parent e0bfc54 commit 92e2a4a

File tree

1 file changed

+27
-4
lines changed

1 file changed

+27
-4
lines changed

system/Filters/Filters.php

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,13 @@ class Filters
118118
'after' => [],
119119
];
120120

121+
/**
122+
* List of filter class instances.
123+
*
124+
* @var array<class-string, FilterInterface> [classname => instance]
125+
*/
126+
protected array $filterClassInstances = [];
127+
121128
/**
122129
* Any arguments to be passed to filters.
123130
*
@@ -230,7 +237,17 @@ private function runBefore(array $filterClassList)
230237
$className = $filterClassInfo[0];
231238
$arguments = ($filterClassInfo[1] === []) ? null : $filterClassInfo[1];
232239

233-
$class = new $className();
240+
if (isset($this->filterClassInstances[$className])) {
241+
$class = $this->filterClassInstances[$className];
242+
} else {
243+
$class = new $className();
244+
245+
if (! $class instanceof FilterInterface) {
246+
throw FilterException::forIncorrectInterface($class::class);
247+
}
248+
249+
$this->filterClassInstances[$className] = $class;
250+
}
234251

235252
if (! $class instanceof FilterInterface) {
236253
throw FilterException::forIncorrectInterface($class::class);
@@ -271,10 +288,16 @@ private function runAfter(array $filterClassList): ResponseInterface
271288
$className = $filterClassInfo[0];
272289
$arguments = ($filterClassInfo[1] === []) ? null : $filterClassInfo[1];
273290

274-
$class = new $className();
291+
if (isset($this->filterClassInstances[$className])) {
292+
$class = $this->filterClassInstances[$className];
293+
} else {
294+
$class = new $className();
275295

276-
if (! $class instanceof FilterInterface) {
277-
throw FilterException::forIncorrectInterface($class::class);
296+
if (! $class instanceof FilterInterface) {
297+
throw FilterException::forIncorrectInterface($class::class);
298+
}
299+
300+
$this->filterClassInstances[$className] = $class;
278301
}
279302

280303
$result = $class->after($this->request, $this->response, $arguments);

0 commit comments

Comments
 (0)