Skip to content
Snippets Groups Projects

Don't save aggregated vote results for fields that do not exist on the entity type

Files
4
+ 75
0
<?php
declare(strict_types=1);
namespace Drupal\votingapi_widgets\Hook;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Hook\Attribute\Hook;
/**
* Implementations of Voting API module hooks.
*/
final class VotingApiWidgetsVotingApiHooks {
/**
* Constructs a new VotingApiWidgetsVotingApiHooks service.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
* The entity_type.manager service.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entityFieldManager
* The entity_field.manager service.
*/
public function __construct(
protected EntityTypeManagerInterface $entityTypeManager,
protected EntityFieldManagerInterface $entityFieldManager,
) {
}
/**
* Implements hook_votingapi_results_alter().
*
* Removes aggregated vote results for votingapi_widget fields that do not
* exist on the entity type, preventing unnecessary data storage.
*/
#[Hook('votingapi_results_alter')]
public function votingapiResultsAlter(array &$vote_results, string $entity_type, string|int $entity_id): void {
$instances = $this->entityFieldManager->getFieldMapByFieldType('voting_api_field');
foreach ($vote_results as $key => $result) {
$function_id = explode(':', $result['function']);
// A votingapi_widget field function starts with 'vote_field_'.
if (str_starts_with($function_id[0], 'vote_field_') && isset($function_id[1])) {
// The second part is the derivative id 'ENTITY_TYPE.FIELD_NAME'.
$derivative_id = explode('.', $function_id[1]);
if ($entity_type != $derivative_id[0]) {
// This entity_type does not match.
unset($vote_results[$key]);
}
elseif (empty($instances[$entity_type][$derivative_id[1]])) {
// This field_name does not exist for the entity.
unset($vote_results[$key]);
}
else {
$bundles = $instances[$entity_type][$derivative_id[1]]['bundles'];
$entity = $this->entityTypeManager->getStorage($entity_type)->load($entity_id);
if (!$entity || !isset($bundles[$entity->bundle()])) {
// The field is not present on this bundle.
unset($vote_results[$key]);
}
else {
// Check for vote types not matching the one set for this field.
$field_storage = $this->entityFieldManager->getFieldStorageDefinitions($entity_type);
if (isset($field_storage[$derivative_id[1]])) {
$field_settings = $field_storage[$derivative_id[1]]->getSettings();
if ($result['type'] != $field_settings['vote_type']) {
unset($vote_results[$key]);
}
}
}
}
}
}
}
}
Loading