api de gestion de ticket, basé sur php-crud-api. Le but est de décorrélé les outils de gestion des données, afin
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IpAddressMiddleware.php 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace Tqdev\PhpCrudApi\Middleware;
  3. use Psr\Http\Message\ResponseInterface;
  4. use Psr\Http\Message\ServerRequestInterface;
  5. use Psr\Http\Server\RequestHandlerInterface;
  6. use Tqdev\PhpCrudApi\Column\Reflection\ReflectedTable;
  7. use Tqdev\PhpCrudApi\Column\ReflectionService;
  8. use Tqdev\PhpCrudApi\Controller\Responder;
  9. use Tqdev\PhpCrudApi\Middleware\Base\Middleware;
  10. use Tqdev\PhpCrudApi\Middleware\Router\Router;
  11. use Tqdev\PhpCrudApi\RequestUtils;
  12. class IpAddressMiddleware extends Middleware
  13. {
  14. private $reflection;
  15. public function __construct(Router $router, Responder $responder, array $properties, ReflectionService $reflection)
  16. {
  17. parent::__construct($router, $responder, $properties);
  18. $this->reflection = $reflection;
  19. }
  20. private function callHandler($record, string $operation, ReflectedTable $table) /*: object */
  21. {
  22. $context = (array) $record;
  23. $columnNames = $this->getProperty('columns', '');
  24. if ($columnNames) {
  25. foreach (explode(',', $columnNames) as $columnName) {
  26. if ($table->hasColumn($columnName)) {
  27. if ($operation == 'create') {
  28. $context[$columnName] = $_SERVER['REMOTE_ADDR'];
  29. } else {
  30. unset($context[$columnName]);
  31. }
  32. }
  33. }
  34. }
  35. return (object) $context;
  36. }
  37. public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface
  38. {
  39. $operation = RequestUtils::getOperation($request);
  40. if (in_array($operation, ['create', 'update', 'increment'])) {
  41. $tableNames = $this->getProperty('tables', '');
  42. $tableName = RequestUtils::getPathSegment($request, 2);
  43. if (!$tableNames || in_array($tableName, explode(',', $tableNames))) {
  44. if ($this->reflection->hasTable($tableName)) {
  45. $record = $request->getParsedBody();
  46. if ($record !== null) {
  47. $table = $this->reflection->getTable($tableName);
  48. if (is_array($record)) {
  49. foreach ($record as &$r) {
  50. $r = $this->callHandler($r, $operation, $table);
  51. }
  52. } else {
  53. $record = $this->callHandler($record, $operation, $table);
  54. }
  55. $request = $request->withParsedBody($record);
  56. }
  57. }
  58. }
  59. }
  60. return $next->handle($request);
  61. }
  62. }