'/api/{{ plugin_id|u2h }}/{id}', 'create' => '/api/{{ plugin_id|u2h }}', ], )] final class {{ class }} extends ResourceBase { /** * The key-value storage. */ private readonly KeyValueStoreInterface $storage; /** * {@inheritdoc} */ public function __construct( array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, KeyValueFactoryInterface $keyValueFactory, ) { parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger); $this->storage = $keyValueFactory->get('{{ plugin_id }}'); } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): self { return new self( $configuration, $plugin_id, $plugin_definition, $container->getParameter('serializer.formats'), $container->get('logger.factory')->get('rest'), $container->get('keyvalue') ); } /** * Responds to POST requests and saves the new record. */ public function post(array $data): ModifiedResourceResponse { $data['id'] = $this->getNextId(); $this->storage->set($data['id'], $data); $this->logger->notice('Created new {{ plugin_label|lower }} record @id.', ['@id' => $data['id']]); // Return the newly created record in the response body. return new ModifiedResourceResponse($data, 201); } /** * Responds to GET requests. */ public function get($id): ResourceResponse { if (!$this->storage->has($id)) { throw new NotFoundHttpException(); } $resource = $this->storage->get($id); return new ResourceResponse($resource); } /** * Responds to PATCH requests. */ public function patch($id, array $data): ModifiedResourceResponse { if (!$this->storage->has($id)) { throw new NotFoundHttpException(); } $stored_data = $this->storage->get($id); $data += $stored_data; $this->storage->set($id, $data); $this->logger->notice('The {{ plugin_label|lower }} record @id has been updated.', ['@id' => $id]); return new ModifiedResourceResponse($data, 200); } /** * Responds to DELETE requests. */ public function delete($id): ModifiedResourceResponse { if (!$this->storage->has($id)) { throw new NotFoundHttpException(); } $this->storage->delete($id); $this->logger->notice('The {{ plugin_label|lower }} record @id has been deleted.', ['@id' => $id]); // Deleted responses have an empty body. return new ModifiedResourceResponse(NULL, 204); } /** * {@inheritdoc} */ protected function getBaseRoute($canonical_path, $method): Route { $route = parent::getBaseRoute($canonical_path, $method); // Set ID validation pattern. if ($method !== 'POST') { $route->setRequirement('id', '\d+'); } return $route; } /** * Returns next available ID. */ private function getNextId(): int { $ids = \array_keys($this->storage->getAll()); return count($ids) > 0 ? max($ids) + 1 : 1; } }