You are here

public function DownloadLogger::getDownloadCounts in Commerce File 8.2

Gets the download counts for the given license and its files.

Note that the download counts are returned for the license owner since we we only record downloads from the license owner.

Parameters

\Drupal\commerce_license\Entity\LicenseInterface $license: The license.

Return value

array The download counts, keyed by fid.

Throws

\InvalidArgumentException Thrown when the given license references a purchased entity that does not reference any file.

Overrides DownloadLoggerInterface::getDownloadCounts

File

src/DownloadLogger.php, line 83

Class

DownloadLogger
Provides a service responsible for logging licensed file downloads.

Namespace

Drupal\commerce_file

Code

public function getDownloadCounts(LicenseInterface $license) {
  if (isset($this->downloadCounts[$license
    ->id()])) {
    return $this->downloadCounts[$license
      ->id()];
  }
  $purchased_entity = $license
    ->getPurchasedEntity();
  if (!$purchased_entity
    ->hasField('commerce_file') || $purchased_entity
    ->get('commerce_file')
    ->isEmpty()) {
    throw new \InvalidArgumentException("The purchased entity referenced by the given license does not reference any file.");
  }

  // Collect the file IDS.
  $fids = array_column($purchased_entity
    ->get('commerce_file')
    ->getValue(), 'target_id');
  $query = $this->connection
    ->select(self::TABLE_NAME);
  $query
    ->addField(self::TABLE_NAME, 'fid');
  $query
    ->addExpression("COUNT(fid)", 'count');
  $query
    ->condition('uid', $license
    ->getOwnerId())
    ->condition('license_id', $license
    ->id())
    ->condition('fid', $fids, 'IN')
    ->groupBy(self::TABLE_NAME . '.fid');
  $results = $query
    ->execute()
    ->fetchAllKeyed();

  // Default the download count to 0, in case no downloads were ever logged.
  foreach ($fids as $fid) {
    $this->downloadCounts[$license
      ->id()][$fid] = $results[$fid] ?? 0;
  }
  return $this->downloadCounts[$license
    ->id()];
}