AbstractPostSerializable.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. <?php
  2. namespace DNB;
  3. use Reflection;
  4. use ReflectionClass;
  5. use ReflectionFunction;
  6. abstract class AbstractPostSerializable implements PostSerializableInterface {
  7. public static function fromPostParams(array $post): PostSerializableInterface {
  8. $vars = [];
  9. foreach (static::getPostParams() as $key => $required) {
  10. $vars[$key] = isset($post[$key]) && ((bool)$post[$key]) && strtolower((string)$post[$key]) != "off" ? htmlspecialchars($post[$key], ENT_QUOTES | ENT_SUBSTITUTE) : null;
  11. if ($vars[$key] == null && $required)
  12. throw new \Symfony\Component\HttpClient\Exception\InvalidArgumentException(
  13. sprintf("Missing required argmuent: %s", $key)
  14. );
  15. }
  16. return new static(...array_values($vars));
  17. }
  18. final public static function getPostParams(): array {
  19. $vars = [];
  20. foreach ((new ReflectionClass(static::class))->getConstructor()->getParameters() as $param)
  21. $vars[$param->getName()] = !($param->isOptional() || $param->allowsNull());
  22. return $vars;
  23. }
  24. }