Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / vendor / chi-teck / drupal-code-generator / templates / d8 / service / param-converter.twig
diff --git a/vendor/chi-teck/drupal-code-generator/templates/d8/service/param-converter.twig b/vendor/chi-teck/drupal-code-generator/templates/d8/service/param-converter.twig
new file mode 100644 (file)
index 0000000..771506d
--- /dev/null
@@ -0,0 +1,65 @@
+<?php
+
+namespace Drupal\{{ machine_name }};
+
+use Drupal\Core\Database\Connection;
+use Drupal\Core\ParamConverter\ParamConverterInterface;
+use Symfony\Component\Routing\Route;
+
+/**
+ * Converts parameters for upcasting database record IDs to full std objects.
+ *
+ * @DCG
+ * To use this converter specify parameter type in a relevant route as follows:
+ * @code
+ * {{ machine_name }}.{{ parameter_type }}_parameter_converter:
+ *   path: example/{record}
+ *   defaults:
+ *     _controller: '\Drupal\{{ machine_name }}\Controller\{{ controller_class }}::build'
+ *   requirements:
+ *     _access: 'TRUE'
+ *   options:
+ *     parameters:
+ *       record:
+ *        type: {{ parameter_type }}
+ * @endcode
+ *
+ * Note that for entities you can make use of existing parameter converter
+ * provided by Drupal core.
+ * @see \Drupal\Core\ParamConverter\EntityConverter
+ */
+class {{ class }} implements ParamConverterInterface {
+
+  /**
+   * The database connection.
+   *
+   * @var \Drupal\Core\Database\Connection
+   */
+  protected $connection;
+
+  /**
+   * Constructs a new {{ class }}.
+   *
+   * @param \Drupal\Core\Database\Connection $connection
+   *   The default database connection.
+   */
+  public function __construct(Connection $connection) {
+    $this->connection = $connection;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function convert($value, $definition, $name, array $defaults) {
+    // Return NULL if record not found to trigger 404 HTTP error.
+    return $this->connection->query('SELECT * FROM {table_name} WHERE id = ?', [$value])->fetch() ?: NULL;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function applies($definition, $name, Route $route) {
+    return !empty($definition['type']) && $definition['type'] == '{{ parameter_type }}';
+  }
+
+}