WebOrbiton
v1.0.0.0

StocketBase

45 lines · 1.6 KB
  1. <?php
  2. ​
  3. declare(strict_types=1);
  4. ​
  5. require_once __DIR__ . '/database.php';
  6. require_once __DIR__ . '/digital-files.php';
  7. ​
  8. final class ProductStats
  9. {
  10. public static function buyersCount(int $productId): int
  11. {
  12. try {
  13. $usersDb = Database::users();
  14. $placeholders = implode(',', array_fill(0, count(DigitalFiles::PAID_ORDER_STATUSES), '?'));
  15. ​
  16. $orderStatement = $usersDb->prepare(
  17. "SELECT COUNT(DISTINCT CASE WHEN o.user_account_id IS NOT NULL THEN CONCAT('u', o.user_account_id) ELSE CONCAT('g', LOWER(o.guest_email)) END)
  18. FROM orders o JOIN order_items oi ON oi.order_id = o.id
  19. WHERE oi.product_id = ? AND o.status IN ({$placeholders})"
  20. );
  21. $orderStatement->execute(array_merge([$productId], DigitalFiles::PAID_ORDER_STATUSES));
  22. $buyers = (int) $orderStatement->fetchColumn();
  23. ​
  24. $subscriptionStatement = $usersDb->prepare('SELECT COUNT(DISTINCT user_account_id) FROM subscriptions WHERE product_id = :id');
  25. $subscriptionStatement->execute(['id' => $productId]);
  26. ​
  27. return $buyers + (int) $subscriptionStatement->fetchColumn();
  28. } catch (PDOException $exception) {
  29. return 0;
  30. }
  31. }
  32. ​
  33. public static function downloadsCount(int $productId): int
  34. {
  35. try {
  36. $statement = Database::site()->prepare('SELECT COALESCE(SUM(download_count), 0) FROM product_files WHERE product_id = :id');
  37. $statement->execute(['id' => $productId]);
  38. ​
  39. return (int) $statement->fetchColumn();
  40. } catch (PDOException $exception) {
  41. return 0;
  42. }
  43. }
  44. }
  45. ​