11
11
use Lmc \ApiFilter \Filters \FiltersInterface ;
12
12
use Lmc \ApiFilter \Service \FilterApplicator ;
13
13
use Lmc \ApiFilter \Service \FilterFactory ;
14
+ use Lmc \ApiFilter \Service \FunctionCreator ;
14
15
use Lmc \ApiFilter \Service \Functions ;
15
16
use Lmc \ApiFilter \Service \QueryParametersParser ;
16
17
@@ -22,13 +23,16 @@ class ApiFilter
22
23
private $ parser ;
23
24
/** @var FilterApplicator */
24
25
private $ applicator ;
26
+ /** @var FunctionCreator */
27
+ private $ functionCreator ;
25
28
26
29
public function __construct ()
27
30
{
28
31
$ filterFactory = new FilterFactory ();
29
32
$ this ->functions = new Functions ();
30
33
$ this ->parser = new QueryParametersParser ($ filterFactory , $ this ->functions );
31
34
$ this ->applicator = new FilterApplicator ();
35
+ $ this ->functionCreator = new FunctionCreator ($ filterFactory );
32
36
33
37
if (class_exists ('Doctrine\ORM\QueryBuilder ' )) {
34
38
$ this ->registerApplicator (new QueryBuilderApplicator (), Priority::MEDIUM );
@@ -168,6 +172,44 @@ public function registerApplicator(ApplicatorInterface $applicator, int $priorit
168
172
return $ this ;
169
173
}
170
174
175
+ /**
176
+ * Declare a function to specify a name for several parameters which must be given together.
177
+ *
178
+ * ApiFilter::applyFilters() method will be used with all declared parameters.
179
+ * If you want to have a custom callback, not just abstract a name for few parameters, use registerFunction method instead
180
+ *
181
+ * Note:
182
+ * It is not allowed to register more functions with same parameter (not matter of their order).
183
+ *
184
+ * @example
185
+ * How to abstract first and last name into a fullName function and still benefit from ApiFilter features
186
+ * $apiFilter->declareFunction('fullName', ['first', 'last']);
187
+ *
188
+ * @see ApiFilter::registerFunction()
189
+ * @see ApiFilter::executeFunction()
190
+ *
191
+ * Parameters might be defined as
192
+ * - array of single values (names)
193
+ * - array of array values (definitions)
194
+ * - array of ParameterDefinition
195
+ *
196
+ * @param array $parameters names or definition of needed parameters (parameters will be passed to function in given order)
197
+ * @throws ApiFilterExceptionInterface
198
+ */
199
+ public function declareFunction (string $ functionName , array $ parameters )
200
+ {
201
+ $ parameters = $ this ->functionCreator ->normalizeParameters ($ parameters );
202
+
203
+ $ this ->functions ->register (
204
+ $ functionName ,
205
+ $ this ->functionCreator ->getParameterNames ($ parameters ),
206
+ $ this ->functionCreator ->createByParameters ($ this ->applicator , $ parameters ),
207
+ $ this ->functionCreator ->getParameterDefinitions ($ parameters )
208
+ );
209
+
210
+ return $ this ;
211
+ }
212
+
171
213
/**
172
214
* Add a custom function to express any intention you can have
173
215
*
0 commit comments