LockValidator.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\ConfigurableProduct\Model\Attribute;
  7. use Magento\Catalog\Api\Data\ProductInterface;
  8. use Magento\Catalog\Model\Attribute\LockValidatorInterface;
  9. use Magento\Framework\App\ObjectManager;
  10. use Magento\Framework\App\ResourceConnection;
  11. use Magento\Framework\EntityManager\MetadataPool;
  12. /**
  13. * Class LockValidator
  14. */
  15. class LockValidator implements LockValidatorInterface
  16. {
  17. /**
  18. * @var Resource
  19. */
  20. protected $resource;
  21. /**
  22. * @var MetadataPool
  23. */
  24. private $metadataPool;
  25. /**
  26. * Constructor
  27. *
  28. * @param ResourceConnection $resource
  29. */
  30. public function __construct(
  31. ResourceConnection $resource
  32. ) {
  33. $this->resource = $resource;
  34. }
  35. /**
  36. * Check attribute lock state
  37. *
  38. * @param \Magento\Framework\Model\AbstractModel $object
  39. * @param null $attributeSet
  40. * @throws \Magento\Framework\Exception\LocalizedException
  41. * @return void
  42. */
  43. public function validate(\Magento\Framework\Model\AbstractModel $object, $attributeSet = null)
  44. {
  45. $metadata = $this->getMetadataPool()->getMetadata(ProductInterface::class);
  46. $connection = $this->resource->getConnection();
  47. $bind = ['attribute_id' => $object->getAttributeId()];
  48. $select = clone $connection->select();
  49. $select->reset()
  50. ->from(
  51. ['main_table' => $this->resource->getTableName('catalog_product_super_attribute')],
  52. ['psa_count' => 'COUNT(product_super_attribute_id)']
  53. )->join(
  54. ['entity' => $this->resource->getTableName('catalog_product_entity')],
  55. 'main_table.product_id = entity.' . $metadata->getLinkField()
  56. )->where('main_table.attribute_id = :attribute_id')
  57. ->group('main_table.attribute_id')
  58. ->limit(1);
  59. if ($attributeSet !== null) {
  60. $bind['attribute_set_id'] = $attributeSet;
  61. $select->where('entity.attribute_set_id = :attribute_set_id');
  62. }
  63. if ($connection->fetchOne($select, $bind)) {
  64. throw new \Magento\Framework\Exception\LocalizedException(
  65. __('This attribute is used in configurable products.')
  66. );
  67. }
  68. }
  69. /**
  70. * Get MetadataPool instance
  71. * @return MetadataPool
  72. */
  73. private function getMetadataPool()
  74. {
  75. if (!$this->metadataPool) {
  76. $this->metadataPool = ObjectManager::getInstance()->get(MetadataPool::class);
  77. }
  78. return $this->metadataPool;
  79. }
  80. }