PredefinedId.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\Framework\Model\ResourceModel;
  8. use Magento\Framework\Exception\LocalizedException;
  9. use Magento\Framework\Model\AbstractModel;
  10. /**
  11. * Provides possibility of saving entity with predefined/pre-generated id
  12. *
  13. * The choice to use trait instead of inheritance was made to prevent the introduction of new layer super type on
  14. * the module basis as well as better code reusability, as potentially current trait not coupled to Inventory module
  15. * and other modules could re-use this approach.
  16. */
  17. trait PredefinedId
  18. {
  19. /**
  20. * Overwrite default \Magento\Framework\Model\ResourceModel\Db\AbstractDb implementation of the isObjectNew
  21. * @see \Magento\Framework\Model\ResourceModel\Db\AbstractDb::isObjectNew()
  22. *
  23. * Adding the possibility to check whether record already exists in DB or not
  24. *
  25. * @param AbstractModel $object
  26. * @return bool
  27. */
  28. protected function isObjectNotNew(AbstractModel $object)
  29. {
  30. $connection = $this->getConnection();
  31. $select = $connection->select()
  32. ->from($this->getMainTable(), [$this->getIdFieldName()])
  33. ->where($this->getIdFieldName() . ' = ?', $object->getId())
  34. ->limit(1);
  35. return (bool)$connection->fetchOne($select);
  36. }
  37. /**
  38. * Save New Object
  39. *
  40. * Overwrite default \Magento\Framework\Model\ResourceModel\Db\AbstractDb implementation of the saveNewObject
  41. * @see \Magento\Framework\Model\ResourceModel\Db\AbstractDb::saveNewObject()
  42. *
  43. * @param \Magento\Framework\Model\AbstractModel $object
  44. * @throws LocalizedException
  45. * @return void
  46. */
  47. protected function saveNewObject(\Magento\Framework\Model\AbstractModel $object)
  48. {
  49. $bind = $this->_prepareDataForSave($object);
  50. $this->getConnection()->insert($this->getMainTable(), $bind);
  51. if ($this->_isPkAutoIncrement) {
  52. $object->setId($this->getConnection()->lastInsertId($this->getMainTable()));
  53. }
  54. if ($this->_useIsObjectNew) {
  55. $object->isObjectNew(false);
  56. }
  57. }
  58. }