前言
在保存数据库前,我们需要对某些字段做处理,如下
1. 对一些特殊字符串过滤掉 如 * \ /等
2. 对js的脚本代码过滤掉
下面简单的例子
/* 过滤特殊字符串 */ class RemoveWord { public function handle($content, Closure $next) { $content = str_replace(['*', '.'] , '', $content); return $next($content); } } /* 删除js脚本 */ class RemoveScript { public function handle($content, Closure $next) { return $next(strip_tags($content)); } } $data = (new PipeLine)->send('<script>alert("\\\你好啊*!!")') //要被处理的字符串 ->through([ RemoveWord::class, RemoveScript::class ]) ->then(function($content) { //保存数据库 return $content; }); /* 模拟array_reduce执行原理的方法 */ function custom_array_reduce($arr, callable $callback, $init = null) { $ret = $init; foreach ($arr as $item) { $ret = $callback($ret, $item); } return $ret; } /* 自个儿写的类似laravel的管道类 */ class PipeLine { protected $method = 'handle'; public $passable; public function send($passable) { $this->passable = $passable; return $this; } public function through($pipes) { $this->pipes = is_array($pipes) ? $pipes : func_get_args(); return $this; } public function then($destination) { $pipeline = custom_array_reduce( array_reverse($this->pipes), $this->carry(), $this->prepareDestination($destination) ); return $pipeline($this->passable); } public function carry() { return function ($stack, $pipe) { return function ($passable) use ($stack, $pipe) { if (is_callable($pipe)) { // If the pipe is a callable, then we will call it directly, but otherwise we // will resolve the pipes out of the dependency container and call it with // the appropriate method and arguments, returning the results back out. return $pipe($passable, $stack); } elseif (! is_object($pipe)) { list($name, $parameters) = $this->parsePipeString($pipe); $pipe = new $pipe; $parameters = array_merge([$passable, $stack], $parameters); } else { // If the pipe is already an object we'll just make a callable and pass it to // the pipe as-is. There is no need to do any extra parsing and formatting // since the object we're given was already a fully instantiated object. $parameters = [$passable, $stack]; } $carry = method_exists($pipe, $this->method) ? $pipe->{$this->method}(...$parameters) : $pipe(...$parameters); return $carry; }; }; } /** * Get the final piece of the Closure onion. * * @param \Closure $destination * @return \Closure */ protected function prepareDestination(Closure $destination) { return function ($passable) use ($destination) { return $destination($passable); }; } /** * Parse full pipe string to get name and parameters. * * @param string $pipe * @return array */ protected function parsePipeString($pipe) { list($name, $parameters)= array_pad(explode(':', $pipe, 2), 2, []); if (is_string($parameters)) { $parameters = explode(',', $parameters); } return [$name, $parameters]; } }
laravel 利用pipe管道解耦逻辑代码
最新推荐文章于 2023-05-11 10:37:52 发布