Usage.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\SalesRule\Model\ResourceModel\Coupon;
  7. /**
  8. * SalesRule Model Resource Coupon_Usage
  9. *
  10. * @author Magento Core Team <core@magentocommerce.com>
  11. */
  12. class Usage extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
  13. {
  14. /**
  15. * Constructor
  16. *
  17. * @return void
  18. */
  19. protected function _construct()
  20. {
  21. $this->_init('salesrule_coupon_usage', 'coupon_id');
  22. }
  23. /**
  24. * Increment times_used counter
  25. *
  26. * @param int $customerId
  27. * @param mixed $couponId
  28. * @return void
  29. */
  30. public function updateCustomerCouponTimesUsed($customerId, $couponId)
  31. {
  32. $connection = $this->getConnection();
  33. $select = $connection->select();
  34. $select->from(
  35. $this->getMainTable(),
  36. ['times_used']
  37. )->where(
  38. 'coupon_id = :coupon_id'
  39. )->where(
  40. 'customer_id = :customer_id'
  41. );
  42. $timesUsed = $connection->fetchOne($select, [':coupon_id' => $couponId, ':customer_id' => $customerId]);
  43. if ($timesUsed > 0) {
  44. $this->getConnection()->update(
  45. $this->getMainTable(),
  46. ['times_used' => $timesUsed + 1],
  47. ['coupon_id = ?' => $couponId, 'customer_id = ?' => $customerId]
  48. );
  49. } else {
  50. $this->getConnection()->insert(
  51. $this->getMainTable(),
  52. ['coupon_id' => $couponId, 'customer_id' => $customerId, 'times_used' => 1]
  53. );
  54. }
  55. }
  56. /**
  57. * Load an object by customer_id & coupon_id
  58. *
  59. * @param \Magento\Framework\DataObject $object
  60. * @param int $customerId
  61. * @param mixed $couponId
  62. * @return $this
  63. */
  64. public function loadByCustomerCoupon(\Magento\Framework\DataObject $object, $customerId, $couponId)
  65. {
  66. $connection = $this->getConnection();
  67. if ($connection && $couponId && $customerId) {
  68. $select = $connection->select()->from(
  69. $this->getMainTable()
  70. )->where(
  71. 'customer_id =:customer_id'
  72. )->where(
  73. 'coupon_id = :coupon_id'
  74. );
  75. $data = $connection->fetchRow($select, [':coupon_id' => $couponId, ':customer_id' => $customerId]);
  76. if ($data) {
  77. $object->setData($data);
  78. }
  79. }
  80. if ($object instanceof \Magento\Framework\Model\AbstractModel) {
  81. $this->_afterLoad($object);
  82. }
  83. return $this;
  84. }
  85. }