AbstractPostSerializable.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace DNB;
  3. use ReflectionClass;
  4. abstract class AbstractPostSerializable implements PostSerializableInterface {
  5. public static function fromPostParams(array $post): PostSerializableInterface {
  6. $vars = [];
  7. foreach (static::getPostParams() as $key => $param) {
  8. $vars[$key] = isset($post[$key]) && ((bool)$post[$key]) && strtolower((string)$post[$key]) != "off" ? htmlspecialchars($post[$key], ENT_QUOTES | ENT_SUBSTITUTE) : null;
  9. if ($vars[$key] == null && $param->required)
  10. throw new \Symfony\Component\HttpClient\Exception\InvalidArgumentException(
  11. json_encode([
  12. $key => sprintf("%s is a required field.", $key)
  13. ])
  14. );
  15. }
  16. return new static(...array_values($vars));
  17. }
  18. protected static function removePrefix(string $param): string {
  19. return ltrim(strstr($param, '-'), '-');
  20. }
  21. final public static function getPostParams(bool $short = false): array {
  22. $vars = [];
  23. foreach ((new ReflectionClass(static::class))->getConstructor()->getParameters() as $param) {
  24. if ($short)
  25. $vars[$param->getName()] = (object)[
  26. 'type' => !is_null($param->getType()) ? $param->getType()->getName() : 'mixed',
  27. 'required' => !($param->isOptional() || $param->allowsNull())
  28. ];
  29. else
  30. $vars[sprintf('%s-%s', static::namespace(), $param->getName())] = (object)[
  31. 'type' => !is_null($param->getType()) ? $param->getType()->getName() : 'mixed',
  32. 'required' => !($param->isOptional() || $param->allowsNull())
  33. ];
  34. }
  35. return $vars;
  36. }
  37. public static function namespace(): string {
  38. return strtolower(basename(str_replace('\\', DIRECTORY_SEPARATOR, static::class)));
  39. }
  40. }