ruleset = new Ruleset(strict: true); $this->ruleset->POST([ (new Rules(WorkTable::TITLE->value)) ->type(Type::STRING) ->min(3) ->max(parent::MYSQL_VARCHAR_MAX_LENGTH) ->default(null), (new Rules(WorkTable::SUMMARY->value)) ->type(Type::STRING) ->min(1) ->max(parent::MYSQL_TEXT_MAX_LENGTH) ->default(null), (new Rules(WorkTable::IS_LISTED->value)) ->type(Type::BOOLEAN) ->default(false), (new Rules(WorkTable::DATE_CREATED->value)) ->type(Type::NUMBER) ->min(1) ->max(parent::MYSQL_INT_MAX_LENGTH) ->default(time()) ]); $ruleset->validate_or_exit(); 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 a Unix timestamp private static function gen_date_created(): array { // Use provided timestamp in request $date_created = $_POST[WorkTable::DATE_CREATED->value]; return [ WorkTable::DATE_YEAR->value => date("Y", $date_created), WorkTable::DATE_MONTH ->value => date("n", $date_created), WorkTable::DATE_DAY->value => date("j", $date_created) ]; } 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 URL slug from title text or UUID if undefined $entity[WorkTable::ID->value] = $_POST[WorkTable::TITLE->value] ? self::gen_slug($_POST[WorkTable::TITLE->value]) : parent::gen_uuid4(); // Bail out here if a work entry with id had been created already if ($this->get_entity_by_id($entity[WorkTable::ID->value])->ok) { return new Response("An entity with id '{$slug}' already exist", 409); } // Generate the necessary date fields array_merge($entity, self::gen_date_created()); // Let's try to insert the new entity if (!$this->db->for(WorkTable::NAME)->insert($entity)) { return new Response("Failed to insert work entry", 500); } // Generate permalink for new entity return (new Call(Endpoints::WORK_PERMALINKS->value))->post([ PermalinksTable::ID => $entity[WorkTable::ID->value], PermalinksTable::REF_WORK_ID => $entity[WorkTable::ID->value], PermalinksTable::DATE_CREATED => time() ]); } }