1
1
Fork 0
mirror of https://code.mensbeam.com/MensBeam/Arsse.git synced 2024-12-23 09:02:41 +00:00
Arsse/lib/REST/AbstractHandler.php

86 lines
2.8 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
2017-03-28 04:12:12 +00:00
namespace JKingWeb\Arsse\REST;
2017-08-29 14:50:31 +00:00
use JKingWeb\Arsse\Misc\Date;
use JKingWeb\Arsse\Misc\ValueInfo;
abstract class AbstractHandler implements Handler {
2017-08-29 14:50:31 +00:00
abstract public function __construct();
abstract public function dispatch(Request $req): Response;
protected function fieldMapNames(array $data, array $map): array {
$out = [];
2017-08-29 14:50:31 +00:00
foreach ($map as $to => $from) {
if (array_key_exists($from, $data)) {
$out[$to] = $data[$from];
}
}
return $out;
2017-08-29 14:50:31 +00:00
}
protected function fieldMapTypes(array $data, array $map, string $dateFormat = "sql"): array {
2017-08-29 14:50:31 +00:00
foreach ($map as $key => $type) {
if (array_key_exists($key, $data)) {
if ($type=="datetime" && $dateFormat != "sql") {
$data[$key] = Date::transform($data[$key], $dateFormat, "sql");
} else {
settype($data[$key], $type);
}
}
}
return $data;
}
protected function NormalizeInput(array $data, array $types, string $dateFormat = null): array {
$out = [];
2017-08-29 14:50:31 +00:00
foreach ($data as $key => $value) {
if (!isset($types[$key])) {
$out[$key] = $value;
continue;
}
2017-08-29 14:50:31 +00:00
if (is_null($value)) {
$out[$key] = null;
continue;
}
2017-08-29 14:50:31 +00:00
switch ($types[$key]) {
case "int":
if (valueInfo::int($value) & ValueInfo::VALID) {
2017-07-21 02:40:09 +00:00
$out[$key] = (int) $value;
}
break;
case "string":
2017-09-28 13:01:43 +00:00
if (is_bool($value)) {
$out[$key] = var_export($value, true);
} elseif (!is_scalar($value)) {
break;
} else {
$out[$key] = (string) $value;
}
break;
case "bool":
$test = filter_var($value, \FILTER_VALIDATE_BOOLEAN, \FILTER_NULL_ON_FAILURE);
if (!is_null($test)) {
$out[$key] = $test;
}
break;
case "float":
$test = filter_var($value, \FILTER_VALIDATE_FLOAT);
if ($test !== false) {
$out[$key] = $test;
2017-07-21 02:40:09 +00:00
}
break;
case "datetime":
$t = Date::normalize($value, $dateFormat);
2017-08-29 14:50:31 +00:00
if ($t) {
2017-07-21 02:40:09 +00:00
$out[$key] = $t;
}
break;
default:
throw new Exception("typeUnknown", $types[$key]);
}
}
return $out;
}
2017-08-29 14:50:31 +00:00
}