123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- <?php
- namespace DNB;
- use ReflectionClass;
- abstract class AbstractPostSerializable implements PostSerializableInterface {
- public static function fromPostParams(array $post): PostSerializableInterface {
- $vars = [];
- foreach (static::getPostParams() as $key => $param) {
- $vars[$key] = isset($post[$key]) && ((bool)$post[$key]) && strtolower((string)$post[$key]) != "off" ? htmlspecialchars($post[$key], ENT_QUOTES | ENT_SUBSTITUTE) : null;
- if ($vars[$key] == null && $param->required)
- throw new \Symfony\Component\HttpClient\Exception\InvalidArgumentException(
- json_encode([
- $key => sprintf("%s is a required field.", $key)
- ])
- );
- }
- return new static(...array_values($vars));
- }
- protected static function removePrefix(string $param): string {
- return ltrim(strstr($param, '-'), '-');
- }
- final public static function getPostParams(bool $short = false): array {
-
- $vars = [];
- foreach ((new ReflectionClass(static::class))->getConstructor()->getParameters() as $param) {
- if ($short)
- $vars[$param->getName()] = (object)[
- 'type' => !is_null($param->getType()) ? $param->getType()->getName() : 'mixed',
- 'required' => !($param->isOptional() || $param->allowsNull())
- ];
- else
- $vars[sprintf('%s-%s', static::namespace(), $param->getName())] = (object)[
- 'type' => !is_null($param->getType()) ? $param->getType()->getName() : 'mixed',
- 'required' => !($param->isOptional() || $param->allowsNull())
- ];
- }
- return $vars;
- }
- public static function namespace(): string {
- return strtolower(basename(str_replace('\\', DIRECTORY_SEPARATOR, static::class)));
- }
- }
|