ParserPlugin.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Artful\Plugin;
  4. use Closure;
  5. use Psr\Http\Message\ResponseInterface;
  6. use Yansongda\Artful\Contract\PluginInterface;
  7. use Yansongda\Artful\Exception\Exception;
  8. use Yansongda\Artful\Exception\InvalidParamsException;
  9. use Yansongda\Artful\Logger;
  10. use Yansongda\Artful\Rocket;
  11. use function Yansongda\Artful\get_direction;
  12. use function Yansongda\Artful\get_packer;
  13. class ParserPlugin implements PluginInterface
  14. {
  15. /**
  16. * @throws InvalidParamsException
  17. */
  18. public function assembly(Rocket $rocket, Closure $next): Rocket
  19. {
  20. /* @var Rocket $rocket */
  21. $rocket = $next($rocket);
  22. Logger::debug('[ParserPlugin] 插件开始装载', ['rocket' => $rocket]);
  23. $response = $rocket->getDestination();
  24. $direction = get_direction($rocket->getDirection());
  25. $packer = get_packer($rocket->getPacker());
  26. $payload = $rocket->getPayload();
  27. if (!is_null($response) && !($response instanceof ResponseInterface)) {
  28. throw new InvalidParamsException(Exception::PARAMS_PARSER_DIRECTION_INVALID, '参数异常: 解析插件中 `Rocket` 的 `destination` 只能是 `null` 或者 `ResponseInterface`');
  29. }
  30. $rocket->setDestination($direction->guide($packer, $response, $payload?->all() ?? []));
  31. Logger::debug('[ParserPlugin] 插件装载完毕', ['rocket' => $rocket]);
  32. return $rocket;
  33. }
  34. }