771506d6052d69c37b2535b4e64e37efa2e22513
[yaffs-website] / vendor / chi-teck / drupal-code-generator / templates / d8 / service / param-converter.twig
1 <?php
2
3 namespace Drupal\{{ machine_name }};
4
5 use Drupal\Core\Database\Connection;
6 use Drupal\Core\ParamConverter\ParamConverterInterface;
7 use Symfony\Component\Routing\Route;
8
9 /**
10  * Converts parameters for upcasting database record IDs to full std objects.
11  *
12  * @DCG
13  * To use this converter specify parameter type in a relevant route as follows:
14  * @code
15  * {{ machine_name }}.{{ parameter_type }}_parameter_converter:
16  *   path: example/{record}
17  *   defaults:
18  *     _controller: '\Drupal\{{ machine_name }}\Controller\{{ controller_class }}::build'
19  *   requirements:
20  *     _access: 'TRUE'
21  *   options:
22  *     parameters:
23  *       record:
24  *        type: {{ parameter_type }}
25  * @endcode
26  *
27  * Note that for entities you can make use of existing parameter converter
28  * provided by Drupal core.
29  * @see \Drupal\Core\ParamConverter\EntityConverter
30  */
31 class {{ class }} implements ParamConverterInterface {
32
33   /**
34    * The database connection.
35    *
36    * @var \Drupal\Core\Database\Connection
37    */
38   protected $connection;
39
40   /**
41    * Constructs a new {{ class }}.
42    *
43    * @param \Drupal\Core\Database\Connection $connection
44    *   The default database connection.
45    */
46   public function __construct(Connection $connection) {
47     $this->connection = $connection;
48   }
49
50   /**
51    * {@inheritdoc}
52    */
53   public function convert($value, $definition, $name, array $defaults) {
54     // Return NULL if record not found to trigger 404 HTTP error.
55     return $this->connection->query('SELECT * FROM {table_name} WHERE id = ?', [$value])->fetch() ?: NULL;
56   }
57
58   /**
59    * {@inheritdoc}
60    */
61   public function applies($definition, $name, Route $route) {
62     return !empty($definition['type']) && $definition['type'] == '{{ parameter_type }}';
63   }
64
65 }