@@ -118,9 +118,9 @@ public function applyRule(string $rule, string $key, $value): Result
118118
119119 $ removed = null ;
120120
121- if ($ rule === 'rename ' ) {
122- $ removed = $ key ;
123- $ key = $ this -> data_rule -> getAttribute ( ' new_key_name_ ' . $ key );
121+ if ($ rule === 'modify_ ' . $ key ) {
122+ $ callback = $ this -> data_rule -> getAttribute ( ' callback_function_ ' . $ key) ;
123+ $ value = call_user_func ( $ callback , $ key, $ value );
124124 }
125125
126126 return new Result ($ key , $ value , $ removed );
@@ -154,12 +154,60 @@ public function optimize(DataRulesInterface $rules): array
154154 unset($ item [$ result ->getRemoved ()]);
155155 }
156156 }
157+ if ($ this ->data_rule ->hasAttribute ('rename_ ' . $ key )) {
158+ $ item [$ this ->data_rule ->getAttribute ('new_key_name_ ' . $ key )] = $ value ;
159+ unset($ item [$ this ->data_rule ->getAttribute ('rename_ ' . $ key )]);
160+ }
161+ }
162+
163+ if ($ this ->data_rule ->hasAttribute ('add_keys ' )) { {
164+ foreach ($ this ->data_rule ->getAttribute ('add_keys ' ) as $ k => $ v ) {
165+ $ item [$ k ] = $ v ;
166+ }
167+ }
157168 }
158169
159- $ data [] = $ item ;
170+ for ($ i = 1 ; $ i < $ this ->data_rule ->getIncrement () + 1 ; $ i ++) {
171+ if ($ this ->data_rule ->hasAttribute ('add_keys_by_using_item_ ' . $ i )) {
172+ $ v = call_user_func ($ this ->data_rule ->getAttribute ('add_keys_by_using_item_callback_ ' . $ i ), $ item );
173+ $ item [$ this ->data_rule ->getAttribute ('add_keys_by_using_item_ ' . $ i )] = $ v ;
174+ }
175+ }
176+
177+ if ($ this ->data_rule ->hasAttribute ('remove_keys ' )) {
178+ foreach ($ this ->data_rule ->getAttribute ('remove_keys ' ) as $ k ) {
179+ unset($ item [$ k ]);
180+ }
181+ }
182+ if ($ this ->data_rule ->hasAttribute ('sort ' )) {
183+ $ data [] = $ this ->sortByKeys ($ item , $ this ->data_rule ->getAttribute ('sort ' ));
184+ } else {
185+ $ data [] = $ item ;
186+ }
160187 }
161188 }
162189
163190 return $ data ;
164191 }
192+
193+ /**
194+ * sort keys of array using list of keys
195+ * @param array $array array you want sort
196+ * @param array $keysToSortBy list of keys
197+ * @return array sorted array
198+ */
199+ private function sortByKeys (array $ array , array $ keysToSortBy ): array
200+ {
201+ $ keyPositions = array_flip ($ keysToSortBy );
202+
203+ // Sort the array based on key positions
204+ uksort ($ array , function ($ key1 , $ key2 ) use ($ keyPositions ) {
205+ $ position1 = $ keyPositions [$ key1 ] ?? PHP_INT_MAX ;
206+ $ position2 = $ keyPositions [$ key2 ] ?? PHP_INT_MAX ;
207+
208+ return $ position1 - $ position2 ;
209+ });
210+
211+ return $ array ;
212+ }
165213}
0 commit comments