Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PCC-59: Views integration with pcc site entity. #4

Merged
merged 2 commits into from
May 17, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 130 additions & 0 deletions pcx_connect.views.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
<?php

/**
* @file
* Views hook implementations for the PCX Connect module.
*/

use Drupal\pcx_connect\Entity\PccSite;
use Drupal\pcx_connect\PccSiteViewHelper;

/**
* Implements hook_views_data().
*/
function pcx_connect_views_data() {
$data = [];

$pcc_sites = PccSite::loadMultiple();
if ($pcc_sites) {
foreach ($pcc_sites as $pcc_site) {
$id = $pcc_site->getEntityTypeId();
$name = $pcc_site->label();
$table = &$data[$pcc_site->id()];
// Base data.
$table['table']['group'] = t('PCC Site - @name', ['@name' => $name]);
$table['table']['provider'] = $id;
gauravgoyal marked this conversation as resolved.
Show resolved Hide resolved

// Locate the config entity type's ID.
$entityType = \Drupal::entityTypeManager()
->getStorage($id)
->getEntityType();
$id_key = $entityType->getKey('id');

// Get entity fields.
$fields = PccSiteViewHelper::getMapping($id);
if (empty($fields[$id_key])) {
continue;
}
if (empty($fields[$id_key]['label'])) {
continue;
}

$table['table']['base'] = [
'field' => strtolower($fields[$id_key]['label']),
'index' => strtolower($fields[$id_key]['label']),
'title' => t('PCC Site - @name', ['@name' => $name]),
'help' => t('Use the ConfigEntity @name to view the data.', ['@name' => $name]),
gauravgoyal marked this conversation as resolved.
Show resolved Hide resolved
'query_id' => 'pcc_site_view_query',
];

$table['title'] = [
'title' => t('Title'),
'help' => t('Article title'),
gauravgoyal marked this conversation as resolved.
Show resolved Hide resolved
'field' => [
'id' => 'standard',
'click sortable' => TRUE,
],
'sort' => [
'id' => 'standard',
],
'filter' => [
'id' => 'string',
],
'argument' => [
'id' => 'string',
],
];

$table['content'] = [
'title' => t('Content'),
'help' => t('Article Content'),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace the t() function with \Drupal::translation()->translate() for better performance.

-  $table['content'] = [
-    'title' => t('Content'),
-    'help' => t('Article Content'),
-    'field' => [
-      'id' => 'standard',
-      'click sortable' => FALSE,
-    ],
-    'filter' => [
-      'id' => 'string',
-    ],
-  ];
+  $table['content'] = [
+    'title' => \Drupal::translation()->translate('Content'),
+    'help' => \Drupal::translation()->translate('Article Content'),
+    'field' => [
+      'id' => 'standard',
+      'click sortable' => FALSE,
+    ],
+    'filter' => [
+      'id' => 'string',
+    ],
+  ];

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
'title' => t('Content'),
'help' => t('Article Content'),
'title' => \Drupal::translation()->translate('Content'),
'help' => \Drupal::translation()->translate('Article Content'),

'field' => [
'id' => 'standard',
'click sortable' => FALSE,
],
'filter' => [
'id' => 'string',
],
];

$table['snippet'] = [
'title' => t('Snippet'),
'help' => t('Article Snippet'),
gauravgoyal marked this conversation as resolved.
Show resolved Hide resolved
'field' => [
'id' => 'standard',
'click sortable' => FALSE,
],
'filter' => [
'id' => 'string',
],
];

$table['publishedAt'] = [
'title' => t('Published At'),
'help' => t('Article publish time'),
gauravgoyal marked this conversation as resolved.
Show resolved Hide resolved
'field' => [
'id' => 'date',
'click sortable' => TRUE,
],
'filter' => [
'id' => 'date',
],
'sort' => [
'id' => 'date',
],
'argument' => [
'id' => 'date',
],
];

$table['updatedAt'] = [
'title' => t('Updated At'),
'help' => t('Article update time'),
'field' => [
'id' => 'date',
'click sortable' => TRUE,
],
'filter' => [
'id' => 'date',
],
'sort' => [
'id' => 'date',
],
'argument' => [
'id' => 'date',
],
];
}
}
return array_filter($data);
}
5 changes: 3 additions & 2 deletions src/Controller/ApiStatusController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,18 @@
use Symfony\Component\HttpFoundation\JsonResponse;

/**
* Api Status Controller responsible for returning response for pcc site status endpoint.
* Api Status Controller for returning response for pcc site status endpoint.
*/
class ApiStatusController extends ControllerBase {

/**
* Returns empty response.
*
* @return JsonResponse
* @return \Symfony\Component\HttpFoundation\JsonResponse
* Empty JSON response.
*/
public function emptyResponse() {
return new JsonResponse();
}

}
15 changes: 15 additions & 0 deletions src/Entity/PccSite.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
namespace Drupal\pcx_connect\Entity;

use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\pcx_connect\PccSiteInterface;
use Drupal\views\Views;

/**
* Defines the PCC Site entity.
Expand Down Expand Up @@ -54,4 +56,17 @@ class PccSite extends ConfigEntityBase implements PccSiteInterface {
*/
protected $label;

/**
* {@inheritdoc}
*/
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
parent::postSave($storage, $update);

// Clear cache to populate the PCC site in views.
if (\Drupal::moduleHandler()->moduleExists('views')) {
Views::viewsData()->clear();
\Drupal::cache('discovery')->delete('views:wizard');
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use dependency injection for better testability and adherence to Drupal best practices.

-  if (\Drupal::moduleHandler()->moduleExists('views')) {
-    Views::viewsData()->clear();
-    \Drupal::cache('discovery')->delete('views:wizard');
-  }
+  $module_handler = \Drupal::service('module_handler');
+  $views_data = \Drupal::service('views.views_data');
+  $cache_discovery = \Drupal::service('cache.discovery');
+  if ($module_handler->moduleExists('views')) {
+    $views_data->clear();
+    $cache_discovery->delete('views:wizard');
+  }

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
parent::postSave($storage, $update);
// Clear cache to populate the PCC site in views.
if (\Drupal::moduleHandler()->moduleExists('views')) {
Views::viewsData()->clear();
\Drupal::cache('discovery')->delete('views:wizard');
}
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
parent::postSave($storage, $update);
// Clear cache to populate the PCC site in views.
$module_handler = \Drupal::service('module_handler');
$views_data = \Drupal::service('views.views_data');
$cache_discovery = \Drupal::service('cache.discovery');
if ($module_handler->moduleExists('views')) {
$views_data->clear();
$cache_discovery->delete('views:wizard');
}

}

}
81 changes: 81 additions & 0 deletions src/PccSiteViewHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

namespace Drupal\pcx_connect;

/**
* Helper methods for adding custom behavior to the view.
*/
class PccSiteViewHelper {

/**
* Retrieves mapping for Config Entity.
*
* @param string $id
* Config Entity id.
*
* @return array|null
* Returns array of Entity attributes.
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update the return type in the docblock to reflect the actual return type.

-  * @return array|null
+  * @return array

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
* @return array|null
* Returns array of Entity attributes.
* @return array
* Returns array of Entity attributes.

*
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public static function getMapping(string $id): ?array {
$config_type_all = self::getConfigTypedDefinitions();
$config_prefix = self::getConfigPrefix($id);

foreach ($config_type_all as $key => $value) {
if (isset($value['type']) && $value['type'] == 'config_entity') {
if (strpos($key, $config_prefix) === 0) {
return ($value['mapping'] ?? NULL);
}
}
}

// Return an empty array to avoid PHP errors when field definitions.
// That haven't been loaded yet or there is no mapping for the config
// entity.
return [];
}

/**
* Gets provider and config prefix for Config Entity.
*
* @param string $id
* Config Entity id.
*
* @return string
* Returns config prefix.
*
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
protected static function getConfigPrefix(string $id): string {
return \Drupal::entityTypeManager()->getDefinition($id)->getConfigPrefix();
}
gauravgoyal marked this conversation as resolved.
Show resolved Hide resolved

/**
* Gets the config.typed service.
*
* @return mixed
* Definitions of config.typed service.
*/
protected static function getConfigTypedDefinitions() {
return \Drupal::service('config.typed')->getDefinitions();
}

/**
* Gets the Config Entity Label.
*
* @param string $id
* Config Entity iD.
*
* @return string
* Config Entity label used in the group list.
*
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public static function getConfigLabel(string $id): string {
return (string) \Drupal::entityTypeManager()
->getDefinition($id)
->getLabel();
}

}
93 changes: 93 additions & 0 deletions src/Plugin/views/query/PccSiteViewQuery.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php

namespace Drupal\pcx_connect\Plugin\views\query;

use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;
use GuzzleHttp\ClientInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
* Defines a Views query class for Config Entities.
*
* @ViewsQuery(
* id = "pcc_site_view_query",
* title = @Translation("Configuration Entity"),
* help = @Translation("Configuration Entity Query")
* )
*/
class PccSiteViewQuery extends QueryPluginBase {

/**
* Constructs a PccSiteViewQuery object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The database-specific date handler.
* @param \GuzzleHttp\ClientInterface $httpClient
* The HTTP client.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, public ClientInterface $httpClient) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('http_client')
);
}

/**
* Ensures a table exists in the query.
*
* @return string
* An empty string.
*/
public function ensureTable(): string {
return '';
}

/**
* Adds a field to the table.
*
* @param string|null $table
* Ignored.
* @param string $field
* The combined property path of the property that should be retrieved.
* @param string $alias
* (optional) Ignored.
* @param array $params
* (optional) Ignored.
*
* @return string
* The name that this field can be referred to as (always $field).
*
* @see \Drupal\views\Plugin\views\query\Sql::addField()
*/
public function addField($table, $field, $alias = '', $params = []): string {
return $field;
}

/**
* {@inheritdoc}
*/
public function execute(ViewExecutable $view): void {
// @todo This will need in coming tickets, so keep it now.
// $base_table = $view->storage->get('base_table');
// Load current pcc site.
// $pcc_site = PccSite::load($base_table);
$row = [];
$view->result[] = new ResultRow($row);
}

}