storage = $keyValueFactory->get('{{ plugin_id }}'); } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( $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. * * @param array $data * Data to write into the database. * * @return \Drupal\rest\ModifiedResourceResponse * The HTTP response object. */ public function post(array $data) { $data['id'] = $this->getNextId(); $this->storage->set($data['id'], $data); $this->logger->notice('Create new {{ plugin_label|lower }} record @id.'); // Return the newly created record in the response body. return new ModifiedResourceResponse($data, 201); } /** * Responds to GET requests. * * @param int $id * The ID of the record. * * @return \Drupal\rest\ResourceResponse * The response containing the record. */ public function get($id) { if (!$this->storage->has($id)) { throw new NotFoundHttpException(); } $resource = $this->storage->get($id); return new ResourceResponse($resource); } /** * Responds to PATCH requests. * * @param int $id * The ID of the record. * @param array $data * Data to write into the storage. * * @return \Drupal\rest\ModifiedResourceResponse * The HTTP response object. */ public function patch($id, array $data) { 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.'); return new ModifiedResourceResponse($data, 200); } /** * Responds to DELETE requests. * * @param int $id * The ID of the record. * * @return \Drupal\rest\ModifiedResourceResponse * The HTTP response object. */ public function delete($id) { 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 = 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() { $ids = \array_keys($this->storage->getAll()); return count($ids) > 0 ? max($ids) + 1 : 1; } }