You are here

class VoteResultFunctionManager in Voting API 8.3

Manages vote result plugins.

Hierarchy

Expanded class hierarchy of VoteResultFunctionManager

See also

hook_vote_result_info_alter()

\Drupal\image\Annotation\ImageEffect

\Drupal\image\ConfigurableImageEffectInterface

\Drupal\image\ConfigurableImageEffectBase

\Drupal\image\ImageEffectInterface

\Drupal\image\ImageEffectBase

Plugin API

1 string reference to 'VoteResultFunctionManager'
votingapi.services.yml in ./votingapi.services.yml
votingapi.services.yml
1 service uses VoteResultFunctionManager
plugin.manager.votingapi.resultfunction in ./votingapi.services.yml
Drupal\votingapi\VoteResultFunctionManager

File

src/VoteResultFunctionManager.php, line 24

Namespace

Drupal\votingapi
View source
class VoteResultFunctionManager extends DefaultPluginManager {

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * The entity_type.manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The datetime.time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $datetime;

  /**
   * Constructs a new VoteResultFunctionManager.
   *
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   Cache backend instance to use.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity_type.manager service.
   * @param \Drupal\Component\Datetime\TimeInterface $datetime
   *   The datetime.time service.
   */
  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, Connection $database, EntityTypeManagerInterface $entity_type_manager, TimeInterface $datetime) {
    parent::__construct('Plugin/VoteResultFunction', $namespaces, $module_handler, VoteResultFunctionInterface::class, VoteResultFunction::class);
    $this
      ->alterInfo('vote_result_info');
    $this
      ->setCacheBackend($cache_backend, 'vote_result_plugins');
    $this->database = $database;
    $this->entityTypeManager = $entity_type_manager;
    $this->datetime = $datetime;
  }

  /**
   * Get the voting results for an entity.
   *
   * @param string $entity_type_id
   *   The type of entity, e.g. 'node'.
   * @param int $entity_id
   *   The ID of the entity.
   *
   * @return array
   *   A nested array
   */
  public function getResults($entity_type_id, $entity_id) {
    $results = [];
    $result = $this->database
      ->select('votingapi_result', 'v')
      ->fields('v', [
      'type',
      'function',
      'value',
    ])
      ->condition('entity_type', $entity_type_id)
      ->condition('entity_id', $entity_id)
      ->execute();
    while ($row = $result
      ->fetchAssoc()) {
      $results[$row['type']][$row['function']] = $row['value'];
    }
    return $results;
  }

  /**
   * Recalculates the aggregate voting results of all votes for a given entity.
   *
   * Loads all votes for a given piece of content, then calculates and caches
   * the aggregate vote results. This is only intended for modules that have
   * assumed responsibility for the full voting cycle: the votingapi_set_vote()
   * function recalculates automatically.
   *
   * @param string $entity_type_id
   *   A string identifying the type of content being rated. Node, comment,
   *   aggregator item, etc.
   * @param string $entity_id
   *   The key ID of the content being rated.
   * @param string $vote_type
   *   The type of vote cast.
   */
  public function recalculateResults($entity_type_id, $entity_id, $vote_type) {
    $this->database
      ->delete('votingapi_result')
      ->condition('entity_type', $entity_type_id)
      ->condition('entity_id', $entity_id)
      ->condition('type', $vote_type)
      ->execute();
    $vote_storage = $this->entityTypeManager
      ->getStorage('vote');
    $vote_ids = $vote_storage
      ->getQuery()
      ->condition('entity_type', $entity_type_id)
      ->condition('entity_id', $entity_id)
      ->condition('type', $vote_type)
      ->sort('type')
      ->execute();
    if (!empty($vote_ids)) {
      $votes = [];
      $vote_type = '';
      foreach ($vote_ids as $vote_id) {
        $vote = $vote_storage
          ->load($vote_id);

        // Votes are sorted by vote type, so when we hit a new type, we can run
        // find the results of the current set and then start over.
        if (!empty($vote_type) && $vote_type != $vote
          ->bundle()) {
          $this
            ->performAndStore($votes);
          $vote_type = $vote
            ->bundle();
          $votes = [];
        }
        $votes[] = $vote;
      }

      // Still one last set to process.
      $this
        ->performAndStore($votes);
    }
  }

  /**
   * Perform the result calculations on a set of votes and store the results.
   *
   * @param array $votes
   *   The set of votes to perform the calculations on. All votes in the set are
   *   expected to be the same vote type and for the same entity.
   */
  protected function performAndStore(array $votes) {
    $entity_type_id = $votes[0]
      ->getVotedEntityType();
    $entity_id = $votes[0]
      ->getVotedEntityId();
    $vote_type = $votes[0]
      ->bundle();
    foreach ($this
      ->getDefinitions() as $plugin_id => $definition) {
      $plugin = $this
        ->createInstance($plugin_id);
      $vote_results[] = [
        'entity_id' => $entity_id,
        'entity_type' => $entity_type_id,
        'type' => $vote_type,
        'function' => $plugin_id,
        'value' => $plugin
          ->calculateResult($votes),
        'value_type' => $votes[0]
          ->get('value_type')->value,
        'timestamp' => $this->datetime
          ->getRequestTime(),
      ];
    }

    // Give other modules a chance to act on the results of vote calculations.
    $this->moduleHandler
      ->alter('votingapi_results', $vote_results, $entity_type_id, $entity_id);
    foreach ($vote_results as $id => $vote_result) {
      if (!empty($vote_result)) {
        $this->database
          ->insert('votingapi_result')
          ->fields($vote_result)
          ->execute();
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DefaultPluginManager::$additionalAnnotationNamespaces protected property Additional namespaces the annotation discovery mechanism should scan for annotation definitions.
DefaultPluginManager::$alterHook protected property Name of the alter hook if one should be invoked.
DefaultPluginManager::$cacheKey protected property The cache key.
DefaultPluginManager::$cacheTags protected property An array of cache tags to use for the cached definitions.
DefaultPluginManager::$defaults protected property A set of defaults to be referenced by $this->processDefinition() if additional processing of plugins is necessary or helpful for development purposes. 9
DefaultPluginManager::$moduleHandler protected property The module handler to invoke the alter hook. 1
DefaultPluginManager::$namespaces protected property An object that implements \Traversable which contains the root paths keyed by the corresponding namespace to look for plugin implementations.
DefaultPluginManager::$pluginDefinitionAnnotationName protected property The name of the annotation that contains the plugin definition.
DefaultPluginManager::$pluginInterface protected property The interface each plugin should implement. 1
DefaultPluginManager::$subdir protected property The subdirectory within a namespace to look for plugins, or FALSE if the plugins are in the top level of the namespace.
DefaultPluginManager::alterDefinitions protected function Invokes the hook to alter the definitions if the alter hook is set. 1
DefaultPluginManager::alterInfo protected function Sets the alter hook name.
DefaultPluginManager::clearCachedDefinitions public function Clears static and persistent plugin definition caches. Overrides CachedDiscoveryInterface::clearCachedDefinitions 5
DefaultPluginManager::extractProviderFromDefinition protected function Extracts the provider from a plugin definition.
DefaultPluginManager::findDefinitions protected function Finds plugin definitions. 7
DefaultPluginManager::fixContextAwareDefinitions private function Fix the definitions of context-aware plugins.
DefaultPluginManager::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts
DefaultPluginManager::getCachedDefinitions protected function Returns the cached plugin definitions of the decorated discovery class.
DefaultPluginManager::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge
DefaultPluginManager::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags
DefaultPluginManager::getDefinitions public function Gets the definition of all plugins for this type. Overrides DiscoveryTrait::getDefinitions 2
DefaultPluginManager::getDiscovery protected function Gets the plugin discovery. Overrides PluginManagerBase::getDiscovery 12
DefaultPluginManager::getFactory protected function Gets the plugin factory. Overrides PluginManagerBase::getFactory
DefaultPluginManager::processDefinition public function Performs extra processing on plugin definitions. 13
DefaultPluginManager::providerExists protected function Determines if the provider of a definition exists. 3
DefaultPluginManager::setCacheBackend public function Initialize the cache backend.
DefaultPluginManager::setCachedDefinitions protected function Sets a cache of plugin definitions for the decorated discovery class.
DefaultPluginManager::useCaches public function Disable the use of caches. Overrides CachedDiscoveryInterface::useCaches 1
DiscoveryCachedTrait::$definitions protected property Cached definitions array. 1
DiscoveryCachedTrait::getDefinition public function Overrides DiscoveryTrait::getDefinition 3
DiscoveryTrait::doGetDefinition protected function Gets a specific plugin definition.
DiscoveryTrait::hasDefinition public function
PluginManagerBase::$discovery protected property The object that discovers plugins managed by this manager.
PluginManagerBase::$factory protected property The object that instantiates plugins managed by this manager.
PluginManagerBase::$mapper protected property The object that returns the preconfigured plugin instance appropriate for a particular runtime condition.
PluginManagerBase::createInstance public function Creates a pre-configured instance of a plugin. Overrides FactoryInterface::createInstance 12
PluginManagerBase::getInstance public function Gets a preconfigured instance of a plugin. Overrides MapperInterface::getInstance 7
PluginManagerBase::handlePluginNotFound protected function Allows plugin managers to specify custom behavior if a plugin is not found. 1
UseCacheBackendTrait::$cacheBackend protected property Cache backend instance.
UseCacheBackendTrait::$useCaches protected property Flag whether caches should be used or skipped.
UseCacheBackendTrait::cacheGet protected function Fetches from the cache backend, respecting the use caches flag. 1
UseCacheBackendTrait::cacheSet protected function Stores data in the persistent cache, respecting the use caches flag.
VoteResultFunctionManager::$database protected property The database connection.
VoteResultFunctionManager::$datetime protected property The datetime.time service.
VoteResultFunctionManager::$entityTypeManager protected property The entity_type.manager service.
VoteResultFunctionManager::getResults public function Get the voting results for an entity.
VoteResultFunctionManager::performAndStore protected function Perform the result calculations on a set of votes and store the results.
VoteResultFunctionManager::recalculateResults public function Recalculates the aggregate voting results of all votes for a given entity.
VoteResultFunctionManager::__construct public function Constructs a new VoteResultFunctionManager. Overrides DefaultPluginManager::__construct