Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Attribute.php
Go to the documentation of this file.
1 <?php
8 
13 
14 class Attribute
15 {
19  protected $resource;
20 
24  protected $connection;
25 
29  protected $eventManager;
30 
35  public function __construct(
37  EventManager $eventManager
38  ) {
39  $this->resource = $resource;
40  $this->eventManager = $eventManager;
41  }
42 
46  protected function getConnection()
47  {
48  if (!$this->connection) {
49  $this->connection = $this->resource->getConnection('sales');
50  }
51  return $this->connection;
52  }
53 
61  protected function _beforeSaveAttribute(AbstractModel $object, $attribute)
62  {
63  if ($object->getEventObject() && $object->getEventPrefix()) {
64  $this->eventManager->dispatch(
65  $object->getEventPrefix() . '_save_attribute_before',
66  [
67  $object->getEventObject() => $this,
68  'object' => $object,
69  'attribute' => $attribute
70  ]
71  );
72  }
73  return $this;
74  }
75 
84  public function saveAttribute(AbstractModel $object, $attribute)
85  {
86  if ($attribute instanceof AbstractAttribute) {
87  $attributes = $attribute->getAttributeCode();
88  } elseif (is_string($attribute)) {
90  } else {
92  }
93  if (is_array($attributes) && !empty($attributes)) {
94  $this->getConnection()->beginTransaction();
95  $data = array_intersect_key($object->getData(), array_flip($attributes));
96  try {
97  $this->_beforeSaveAttribute($object, $attributes);
98  if ($object->getId() && !empty($data)) {
99  $this->getConnection()->update(
100  $object->getResource()->getMainTable(),
101  $data,
102  [$object->getResource()->getIdFieldName() . '= ?' => (int)$object->getId()]
103  );
104  $object->addData($data);
105  }
106  $this->_afterSaveAttribute($object, $attributes);
107  $this->getConnection()->commit();
108  } catch (\Exception $e) {
109  $this->getConnection()->rollBack();
110  throw $e;
111  }
112  }
113  return $this;
114  }
115 
123  protected function _afterSaveAttribute(AbstractModel $object, $attribute)
124  {
125  if ($object->getEventObject() && $object->getEventPrefix()) {
126  $this->eventManager->dispatch(
127  $object->getEventPrefix() . '_save_attribute_after',
128  [
129  $object->getEventObject() => $this,
130  'object' => $object,
131  'attribute' => $attribute
132  ]
133  );
134  }
135  return $this;
136  }
137 }
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
saveAttribute(AbstractModel $object, $attribute)
Definition: Attribute.php:84
$attributes
Definition: matrix.phtml:13
_afterSaveAttribute(AbstractModel $object, $attribute)
Definition: Attribute.php:123
__construct(AppResource $resource, EventManager $eventManager)
Definition: Attribute.php:35
_beforeSaveAttribute(AbstractModel $object, $attribute)
Definition: Attribute.php:61