You are here

public function FileResponseSubscriber::logFileDownload in Commerce File 8.2

Logs file downloads for license owners.

Parameters

\Symfony\Component\HttpKernel\Event\PostResponseEvent $event: The event object.

File

src/EventSubscriber/FileResponseSubscriber.php, line 79

Class

FileResponseSubscriber
A subscriber to log downloads of licensed files.

Namespace

Drupal\commerce_file\EventSubscriber

Code

public function logFileDownload(PostResponseEvent $event) {

  // Not a successful response, nothing to do on our side.
  if (!$event
    ->getResponse()
    ->isSuccessful()) {
    return;
  }
  $headers = $event
    ->getResponse()->headers
    ->all();

  // Check if the custom headers added by our logic in
  // See commerce_file_file_download() are present.
  // If these headers are present, this means a licensed file is being
  // downloaded, therefore we should log the download.
  if (!isset($headers['x-commerce-file-id'], $headers['x-commerce-license-id'])) {
    return;
  }

  /** @var \Drupal\commerce_license\Entity\LicenseInterface $license */
  $license = $this->entityTypeManager
    ->getStorage('commerce_license')
    ->load($headers['x-commerce-license-id'][0]);

  /** @var \Drupal\file\FileInterface $file */
  $file = $this->entityTypeManager
    ->getStorage('file')
    ->load($headers['x-commerce-file-id'][0]);

  // The license or the file could not be loaded, stop here.
  if (!$license || !$file) {
    return;
  }

  // We skip logging file downloads if the download is not initiated by
  // the license owner.
  // When this happens, that means the download was initiated by an admin
  // user who's not affected by file download limits, therefore it is
  // pointless to log a file download that isn't going to be used.
  if (!$this->licenseFileManager
    ->shouldLogDownload($license)) {
    return;
  }
  $this->downloadLogger
    ->log($license, $file);
}