DownloadManager.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. /*
  3. * This file is part of Packagist.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. * Nils Adermann <naderman@naderman.de>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Packagist\WebBundle\Model;
  12. use Packagist\WebBundle\Entity\Package;
  13. use Packagist\WebBundle\Entity\Version;
  14. use Predis\Client;
  15. /**
  16. * Manages the download counts for packages.
  17. */
  18. class DownloadManager
  19. {
  20. protected $redis;
  21. public function __construct(Client $redis)
  22. {
  23. $this->redis = $redis;
  24. }
  25. /**
  26. * Gets the total, monthly, and daily download counts for a package.
  27. *
  28. * @param \Packagist\WebBundle\Entity\Package|int $package
  29. * @return array
  30. */
  31. public function getDownloads($package)
  32. {
  33. if ($package instanceof Package) {
  34. $package = $package->getId();
  35. }
  36. $counts = $this->redis->mget(
  37. 'dl:' . $package,
  38. 'dl:' . $package.':'.date('Ym'),
  39. 'dl:' . $package.':'.date('Ymd')
  40. );
  41. return array(
  42. 'total' => (int) $counts[0] ?: 0,
  43. 'monthly' => (int) $counts[1] ?: 0,
  44. 'daily' => (int)$counts[2] ?: 0,
  45. );
  46. }
  47. /**
  48. * Gets total download counts for multiple package IDs.
  49. *
  50. * @param array $packageIds
  51. * @return array a map of package ID to download count
  52. */
  53. public function getPackagesDownloads(array $packageIds)
  54. {
  55. $keys = array();
  56. foreach ($packageIds as $id) {
  57. $keys[$id] = 'dl:'.$id;
  58. }
  59. $res = array_map('intval', $this->redis->mget(array_values($keys)));
  60. return array_combine(array_keys($keys), $res);
  61. }
  62. /**
  63. * Tracks a new download by updating the relevant keys.
  64. *
  65. * @param \Packagist\WebBundle\Entity\Package|int $package
  66. * @param \Packagist\WebBundle\Entity\Version|int $version
  67. */
  68. public function addDownload($package, $version)
  69. {
  70. $redis = $this->redis;
  71. if ($package instanceof Package) {
  72. $package = $package->getId();
  73. }
  74. if ($version instanceof Version) {
  75. $version = $version->getId();
  76. }
  77. $redis->incr('downloads');
  78. $redis->incr('dl:'.$package);
  79. $redis->incr('dl:'.$package.':'.date('Ym'));
  80. $redis->incr('dl:'.$package.':'.date('Ymd'));
  81. $redis->incr('dl:'.$package.'-'.$version);
  82. $redis->incr('dl:'.$package.'-'.$version.':'.date('Ym'));
  83. $redis->incr('dl:'.$package.'-'.$version.':'.date('Ymd'));
  84. }
  85. }