|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace Loki\AdminComponents\Filter; |
| 4 | + |
| 5 | +use Loki\AdminComponents\Component\Form\FormRepository; |
| 6 | +use Loki\AdminComponents\Component\Form\FormViewModel; |
| 7 | +use Loki\AdminComponents\Form\Field\Field; |
| 8 | +use Loki\Components\Component\ComponentInterface; |
| 9 | +use Loki\Components\Filter\FilterInterface; |
| 10 | +use Loki\Components\Filter\FilterScope; |
| 11 | + |
| 12 | +class Security implements FilterInterface |
| 13 | +{ |
| 14 | + public function filter(mixed $value, FilterScope $scope): mixed |
| 15 | + { |
| 16 | + if (is_object($value)) { |
| 17 | + return $value; |
| 18 | + } |
| 19 | + |
| 20 | + $value = (string)$value; |
| 21 | + if ($this->allowStripTags($value, $scope)) { |
| 22 | + $value = strip_tags($value); |
| 23 | + } |
| 24 | + |
| 25 | + $value = htmlspecialchars_decode($value); |
| 26 | + return $value; |
| 27 | + } |
| 28 | + |
| 29 | + private function allowStripTags(string $value, FilterScope $scope): bool |
| 30 | + { |
| 31 | + $component = $scope->getComponent(); |
| 32 | + if (false === $component instanceof ComponentInterface) { |
| 33 | + return true; |
| 34 | + } |
| 35 | + |
| 36 | + $repository = $component->getRepository(); |
| 37 | + if (false === $repository instanceof FormRepository) { |
| 38 | + return true; |
| 39 | + } |
| 40 | + |
| 41 | + $property = $scope->getProperty(); |
| 42 | + if (empty($property)) { |
| 43 | + return true; |
| 44 | + } |
| 45 | + |
| 46 | + $field = $this->getFieldByPropertyName($repository, $property); |
| 47 | + if (empty($field)) { |
| 48 | + return true; |
| 49 | + } |
| 50 | + |
| 51 | + return !$field->allowHtml(); |
| 52 | + } |
| 53 | + |
| 54 | + private function getFieldByPropertyName(FormRepository $repository, string $propertyName): ?Field |
| 55 | + { |
| 56 | + /** @var FormViewModel $viewModel */ |
| 57 | + $viewModel = $repository->getComponent()->getViewModel(); |
| 58 | + $fields = $viewModel->getFields(); |
| 59 | + foreach ($fields as $field) { |
| 60 | + if ($field->getCode() === $propertyName) { |
| 61 | + return $field; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + return null; |
| 66 | + } |
| 67 | +} |
0 commit comments