1
1
Fork 0
mirror of https://code.mensbeam.com/MensBeam/Arsse.git synced 2024-12-22 21:22:40 +00:00
Arsse/lib/REST/AbstractHandler.php
J. King e74a3ae3cb Fix numerous bugs when adding or changing folders
- Specifying a non-integer parent no longer silently casts to 0 or 1
- Specifying a folder ID of 0 now always converts to null automatically
- Performing both a rename and move to root in the same operation no longer results in potential duplicates
- Calling folderSetProperties with an empty data array no peforms an update; it now returns false before the update call
- Modification timestamps are now actually updated when a folder is modified
- Constraint violation exceptions triggered by code (rather than the database) now print a message
- Renaming a folder or subscription to a non-string value (e.g. an array) throws an exception rather than silently casting
- Added tests to better cover all the above
- Centralized the normalization of integers and title strings into a new ValueInfo static class
2017-09-26 16:45:41 -04:00

94 lines
3.1 KiB
PHP

<?php
declare(strict_types=1);
namespace JKingWeb\Arsse\REST;
use JKingWeb\Arsse\Misc\Date;
use JKingWeb\Arsse\Misc\ValueInfo;
abstract class AbstractHandler implements Handler {
abstract public function __construct();
abstract public function dispatch(Request $req): Response;
protected function fieldMapNames(array $data, array $map): array {
$out = [];
foreach ($map as $to => $from) {
if (array_key_exists($from, $data)) {
$out[$to] = $data[$from];
}
}
return $out;
}
protected function fieldMapTypes(array $data, array $map, string $dateFormat = "sql"): array {
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 validateInt($id): bool {
return (bool) (ValueInfo::int($id) & ValueInfo::VALID);
}
protected function NormalizeInput(array $data, array $types, string $dateFormat = null): array {
$out = [];
foreach ($data as $key => $value) {
if (!isset($types[$key])) {
$out[$key] = $value;
continue;
}
if (is_null($value)) {
$out[$key] = null;
continue;
}
switch ($types[$key]) {
case "int":
if ($this->validateInt($value)) {
$out[$key] = (int) $value;
}
break;
case "string":
$out[$key] = (string) $value;
break;
case "bool":
if (is_bool($value)) {
$out[$key] = $value;
} elseif ($this->validateInt($value)) {
$value = (int) $value;
if ($value > -1 && $value < 2) {
$out[$key] = $value;
}
} elseif (is_string($value)) {
$value = trim(strtolower($value));
if ($value=="false") {
$out[$key] = false;
}
if ($value=="true") {
$out[$key] = true;
}
}
break;
case "float":
if (is_numeric($value)) {
$out[$key] = (float) $value;
}
break;
case "datetime":
$t = Date::normalize($value, $dateFormat);
if ($t) {
$out[$key] = $t;
}
break;
default:
throw new Exception("typeUnknown", $types[$key]);
}
}
return $out;
}
}