11<?php
22/**
3- * Filter to filter values on a specific field.
3+ * Filter values on a specific field.
44 * Ex: show only users with a specific father.
55 * Both father or father_id can be used (the composed field or the unique attribute).
66 *
1717
1818use Illuminate \Support \Collection ;
1919use Laramore \Contracts \Eloquent \LaramoreBuilder ;
20- use Laramore \Contracts \Field \ComposedField ;
20+ use Laramore \Contracts \Field \{
21+ Field , ComposedField ,
22+ RelationField
23+ };
2124use Laramore \Contracts \Http \Filters \BuilderFilter ;
25+ use Laramore \Elements \OperatorElement ;
2226use Laramore \Traits \Http \Filters \HasOperatorParameter ;
2327
24- class Filter extends BaseFilter implements BuilderFilter
28+ class Related extends BaseFilter implements BuilderFilter
2529{
2630 use HasOperatorParameter;
2731
@@ -35,7 +39,7 @@ public function getDefaultParams(): array
3539 ];
3640 }
3741
38- public function getField ()
42+ public function getField (): Field
3943 {
4044 $ this ->needsToBeOwned ();
4145
@@ -49,21 +53,37 @@ protected function owned()
4953 $ meta = $ this ->getOwner ()->getMeta ();
5054
5155 $ this ->field = $ meta ->getField ($ this ->getName ());
56+
57+ if (! ($ this ->field instanceof RelationField)) {
58+ throw new \Exception ("The field {$ this ->getName ()} is not a relation field " );
59+ }
5260 }
5361
54- public function checkValue ($ value =null )
62+ public function checkValue ($ value =null , Collection $ params = null )
5563 {
56- // TODO.
57-
5864 if ($ this ->getField () instanceof ComposedField) {
59- return explode (', ' , $ value );
65+ if ($ params ->get ('operator ' )->needs (OperatorElement::COLLECTION_TYPE )) {
66+ return $ value ->map (function ($ subValue ) {
67+ return new Collection (explode (', ' , $ subValue ));
68+ });
69+ }
70+
71+ return new Collection (explode (', ' , $ value ));
6072 }
6173
6274 return $ value ;
6375 }
6476
6577 public function filterBuilder (LaramoreBuilder $ builder , Collection $ params ): ?LaramoreBuilder
6678 {
67- return $ this ->getField ()->where ($ builder , $ params ->get ('operator ' ), $ params ->get ('value ' ));
79+ $ field = $ this ->getField ();
80+ $ operator = $ params ->get ('operator ' );
81+ $ method = $ operator ->getWhereMethod ();
82+
83+ if (method_exists ($ field , $ method ) || $ field ::hasMacro ($ method )) {
84+ return \call_user_func ([$ field , $ method ], $ builder , collect ($ params ->get ('value ' )));
85+ }
86+
87+ return $ field ->where ($ builder , $ operator , $ params ->get ('value ' ));
6888 }
6989}
0 commit comments