Sequence.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\SalesSequence\Model;
  7. use Magento\Framework\App\ResourceConnection as AppResource;
  8. use Magento\Framework\DB\Sequence\SequenceInterface;
  9. /**
  10. * Class Sequence represents sequence in logic
  11. *
  12. * @api
  13. * @since 100.0.2
  14. */
  15. class Sequence implements SequenceInterface
  16. {
  17. /**
  18. * Default pattern for Sequence
  19. */
  20. const DEFAULT_PATTERN = "%s%'.09d%s";
  21. /**
  22. * @var string
  23. */
  24. private $lastIncrementId;
  25. /**
  26. * @var Meta
  27. */
  28. private $meta;
  29. /**
  30. * @var false|\Magento\Framework\DB\Adapter\AdapterInterface
  31. */
  32. private $connection;
  33. /**
  34. * @var string
  35. */
  36. private $pattern;
  37. /**
  38. * @param Meta $meta
  39. * @param AppResource $resource
  40. * @param string $pattern
  41. */
  42. public function __construct(
  43. Meta $meta,
  44. AppResource $resource,
  45. $pattern = self::DEFAULT_PATTERN
  46. ) {
  47. $this->meta = $meta;
  48. $this->connection = $resource->getConnection('sales');
  49. $this->pattern = $pattern;
  50. }
  51. /**
  52. * Retrieve current value
  53. *
  54. * @return string
  55. */
  56. public function getCurrentValue()
  57. {
  58. if (!isset($this->lastIncrementId)) {
  59. return null;
  60. }
  61. return sprintf(
  62. $this->pattern,
  63. $this->meta->getActiveProfile()->getPrefix(),
  64. $this->calculateCurrentValue(),
  65. $this->meta->getActiveProfile()->getSuffix()
  66. );
  67. }
  68. /**
  69. * Retrieve next value
  70. *
  71. * @return string
  72. */
  73. public function getNextValue()
  74. {
  75. $this->connection->insert($this->meta->getSequenceTable(), []);
  76. $this->lastIncrementId = $this->connection->lastInsertId($this->meta->getSequenceTable());
  77. return $this->getCurrentValue();
  78. }
  79. /**
  80. * Calculate current value depends on start value
  81. *
  82. * @return string
  83. */
  84. private function calculateCurrentValue()
  85. {
  86. return ($this->lastIncrementId - $this->meta->getActiveProfile()->getStartValue())
  87. * $this->meta->getActiveProfile()->getStep() + $this->meta->getActiveProfile()->getStartValue();
  88. }
  89. }