openquestions-1.0.x-dev/src/Model/VoteDataByQuestionBasic.php

src/Model/VoteDataByQuestionBasic.php
<?php

namespace Drupal\openquestions\Model;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Plugin\Context\Context;
use Drupal\Core\Plugin\Context\ContextProviderInterface;
use Drupal\Core\Plugin\Context\EntityContext;
use Drupal\Core\Plugin\Context\EntityContextDefinition;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\openquestions\Entity\Term;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Logger\LoggerChannelInterface;

/**
 * Represents the votes on a specific item and specific question, organized
 * by author.
 *
 * If an author has multiple votes on the same item+question combo, their
 * votes are sorted with the latest votes being first.
 *
 * @see VoteDataBasic
 */
class VoteDataByQuestionBasic {

  /**
   * The data.
   *
   * @var array
   */
  protected $votesByAuthor;

  /**
   * Constructs a new VoteDataByQuestionBasic.
   */
  public function __construct() {
    $this->votesByAuthor = [];
  }

  /**
   * Return the average vote value on this question.
   */
  public function getAverage() {
    $cc = 0;
    $total = 0;
    foreach ($this->votesByAuthor as $votes) {
      $vote = array_shift($votes);
      if ($vote->get('status')->value) {
        $total += $vote->get('vote_value')->value;
        $cc++;
      }
    }

    return $total / $cc;
  }

  /**
   * Return an array of the votes for a specific uid, or NULL.
   */
  public function getVotesForAccountId($uid) {
    if (!empty($this->votesByAuthor[$uid])) {
      return $this->votesByAuthor[$uid];
    }

    return NULL;
  }

  /**
   * Adds a vote to the data.
   */
  public function add($vote) {
    $authorID = $this->getReferencedEntityId($vote->uid->referencedEntities());

    if (!empty($this->votesByAuthor[$authorID])) {
      $this->votesByAuthor[$authorID][] = $vote;
    }
    else {
      $this->votesByAuthor[$authorID] = [$vote];
    }

    if (count($this->votesByAuthor[$authorID]) > 1) {
      usort($this->votesByAuthor[$authorID], function ($a, $b) {
        return $b->get('created')->value <=> $a->get('created')->value;
      });
    }
  }

  /**
   * Get the first ID from an array of entities.
   */
  protected function getReferencedEntityId($entities) {
    foreach ($entities as $entity) {
      $entityID = $entity->id();
      if ($entityID) {
        return $entityID;
      }
    }

    return 0;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc