DBLogResource.php 1.48 KB
Newer Older
1 2
<?php

3
namespace Drupal\dblog\Plugin\rest\resource;
4

5
use Drupal\Core\Database\Database;
6 7
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
8
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
9 10 11 12 13
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Provides a resource for database watchdog log entries.
 *
14
 * @RestResource(
15
 *   id = "dblog",
16 17 18 19
 *   label = @Translation("Watchdog database log"),
 *   uri_paths = {
 *     "canonical" = "/dblog/{id}"
 *   }
20 21 22 23 24 25 26 27 28
 * )
 */
class DBLogResource extends ResourceBase {

  /**
   * Responds to GET requests.
   *
   * Returns a watchdog log entry for the specified ID.
   *
29 30 31
   * @param int $id
   *   The ID of the watchdog log entry.
   *
32 33
   * @return \Drupal\rest\ResourceResponse
   *   The response containing the log entry.
34
   *
35 36 37 38
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   *   Thrown when the log entry was not found.
   * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
   *   Thrown when no log entry was provided.
39 40 41
   */
  public function get($id = NULL) {
    if ($id) {
42
      $record = Database::getConnection()->query("SELECT * FROM {watchdog} WHERE wid = :wid", [':wid' => $id])
43
        ->fetchAssoc();
44
      if (!empty($record)) {
45
        return new ResourceResponse($record);
46
      }
47

48
      throw new NotFoundHttpException("Log entry with ID '$id' was not found");
49
    }
50

51
    throw new BadRequestHttpException('No log entry ID was provided');
52
  }
53

54
}