$callbacks) { if (!$callbacks) { continue; } $callbacks = is_array($callbacks) ? $callbacks : [$callbacks]; if (str_contains($key, '*')) { $expandedRules = array_merge( $expandedRules, static::substituteWildcardKeys( [$key => $callbacks], $key, $data ) ); } else { $expandedRules[$key] = $callbacks; } } // Apply sanitization foreach ($expandedRules as $k => $callbacks) { $callbacks = static::mayBeFixCallbacks($callbacks); if (($value = Arr::get($data, $k)) !== null) { foreach ($callbacks as $cb) { if ($cb = static::getCallback($cb)) { $value = $cb($value); } } Arr::Set($data, $k, $value); } } return $data; } public static function substituteWildcardKeys($array, $field, $data) { $callback = $array[$field]; unset($array[$field]); $expand = function ( $data, $segments, $prefix = '' ) use ( &$expand, $callback, &$array ) { $segment = array_shift($segments); if ($segment === null) { $array[$prefix] = $callback; return; } if ($segment === '*') { if (!is_array($data)) return; foreach ($data as $key => $child) { $newPrefix = $prefix === '' ? $key : $prefix . '.' . $key; $expand($child, $segments, $newPrefix); } } else { if (is_array($data) && array_key_exists($segment, $data)) { $newPrefix = $prefix === '' ? $segment : $prefix . '.' . $segment; $expand($data[$segment], $segments, $newPrefix); } } }; $segments = explode('.', $field); $expand($data, $segments); return $array; } /** * Check and fix if callbacks are given * as: callback1|callback2\callback3. * * @param array|string $callbacks * @return array */ public static function mayBeFixCallbacks($callbacks) { $normalized = []; foreach ((array)$callbacks as $cb) { if (is_string($cb)) { $normalized = array_merge($normalized, explode('|', $cb)); } elseif (is_callable($cb)) { $normalized[] = $cb; } } return $normalized; } /** * Get the callback function. * * @param callable|string $callback * @return callable|null * @throws \InvalidArgumentException If the rule resolves to nothing callable. */ protected static function getCallback($callback) { if ($callback) { if ($callback instanceof Closure) return $callback; if ($cb = static::methodExists($callback)) { $callback = $cb; } elseif (!is_callable($callback)) { throw new InvalidArgumentException(sprintf( 'Unknown sanitizer rule: %s.', is_string($callback) ? $callback : gettype($callback) )); } } return $callback; } /** * Check if the method exists. * * @param string $method * @return callable|null */ protected static function methodExists($method) { $suffix = ''; if (Str::endsWith($method, '__')) { $suffix = '__'; } $method = Str::camel($method) . $suffix; if (method_exists(static::class, $method)) { return [static::class, $method]; } } }