vlw.se/endpoints/work/PATCH.php

109 lines
No EOL
3.1 KiB
PHP

<?php
use Reflect\Call;
use Reflect\{Response, Path};
use ReflectRules\{Ruleset, Rules, Type};
use VLW\API\Endpoints;
use VLW\Database\Database;
use VLW\Database\Tables\Work\{
WorkTable,
PermalinksTable
};
require_once Path::root("src/Endpoints.php");
require_once Path::root("src/Database/Database.php");
require_once Path::root("src/Database/Models/Work/Work.php");
require_once Path::root("src/Database/Models/Work/WorkPermalinks.php");
class PATCH_Work extends Database {
protected Ruleset $ruleset;
public function __construct() {
$this->ruleset = new Ruleset(strict: true);
$this->ruleset->GET([
(new Rules(WorkTable::ID->value))
->required()
->type(Type::STRING)
->min(1)
->max(parent::MYSQL_VARCHAR_MAX_LENGTH)
]);
$this->ruleset->POST([
(new Rules(WorkTable::TITLE->value))
->type(Type::STRING)
->min(3)
->max(parent::MYSQL_VARCHAR_MAX_LENGTH),
(new Rules(WorkTable::SUMMARY->value))
->type(Type::STRING)
->min(1)
->max(parent::MYSQL_TEXT_MAX_LENGTH),
(new Rules(WorkTable::IS_LISTED->value))
->type(Type::BOOLEAN),
(new Rules(WorkTable::DATE_MODIFIED->value))
->type(Type::NUMBER)
->min(1)
->max(parent::MYSQL_INT_MAX_LENGTH)
->default(time()),
(new Rules(WorkTable::DATE_CREATED->value))
->type(Type::NUMBER)
->min(1)
->max(parent::MYSQL_INT_MAX_LENGTH)
]);
parent::__construct();
}
// Generate a slug URL from string
private static function gen_slug(string $input): string {
return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $input)));
}
// Compute and return modeled year, month, and day from Unix timestamp in request body
private static function gen_date_created(): array {
return [
WorkTable::DATE_YEAR->value => date("Y", $_POST[WorkTable::DATE_CREATED->value]),
WorkTable::DATE_MONTH ->value => date("n", $_POST[WorkTable::DATE_CREATED->value]),
WorkTable::DATE_DAY->value => date("j", $_POST[WorkTable::DATE_CREATED->value])
];
}
private function get_entity_by_id(string $id): Response {
return (new Call(Endpoints::WORK->value))->params([
WorkTable::ID->value => $id
])->get();
}
public function main(): Response {
// Use copy of request body as entity
$entity = $_POST;
// Generate a new slug id from title if changed
if ($_POST[WorkTable::TITLE->value]) {
$slug = $_POST[WorkTable::TITLE->value];
// Bail out if the slug generated from the new tite already exist
if ($this->get_entity_by_id($slug)) {
return new Response("An entity with this title already exist", 409);
}
// Add the new slug to update entity
$entity[WorkTable::ID] = $slug;
}
// Generate new work date fields from timestamp
if ($_POST[WorkTable::DATE_CREATED->value]) {
array_merge($entity, self::gen_date_created());
}
// Update entity by existing id
return $this->db->for(WorkTable::NAME)->where([WorkTable::ID->value => $_GET[WorkTable::ID->value]])->update($entity) === true
? new Response($_GET[WorkTable::ID->value])
: new Response("Failed to update entity", 500);
}
}