/** * Validate * * @param \Magento\Framework\Model\AbstractModel $model * @return bool * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function validate(\Magento\Framework\Model\AbstractModel $model) { $all = $this->getAggregator() === 'all'; $true = (bool) $this->getValue(); $found = false; foreach ($model->getAllItems() as $item) { $found = $all; foreach ($this->getConditions() as $cond) { $validated = $cond->validate($item); if ($all && !$validated || !$all && $validated) { $found = $validated; break; } } if ($found && $true || !$true && $found) { break; } } // found an item and we're looking for existing one if ($found && $true) { return true; } elseif (!$found && !$true) { // not found and we're making sure it doesn't exist return true; } return false; }
/** * Returns true if and only if $value meets the validation requirements. * * @param \Magento\Framework\Model\AbstractModel $entity * @return bool * @throws \InvalidArgumentException */ public function isValid($entity) { $this->_messages = []; if (!$entity instanceof \Magento\Framework\Model\AbstractModel) { throw new \InvalidArgumentException('Model must be extended from \\Magento\\Framework\\Model\\AbstractModel'); } /** @var \Magento\Eav\Model\Entity\AbstractEntity $resource */ $resource = $entity->getResource(); if (!$resource instanceof \Magento\Eav\Model\Entity\AbstractEntity) { throw new \InvalidArgumentException('Model resource must be extended from \\Magento\\Eav\\Model\\Entity\\AbstractEntity'); } $resource->loadAllAttributes($entity); $attributes = $resource->getAttributesByCode(); /** @var \Magento\Eav\Model\Entity\Attribute $attribute */ foreach ($attributes as $attribute) { $backend = $attribute->getBackend(); if (!method_exists($backend, 'validate') || !is_callable([$backend, 'validate'])) { continue; } try { $result = $backend->validate($entity); if (false === $result) { $this->_messages[$attribute->getAttributeCode()][] = __('The value of attribute "%1" is invalid', $attribute->getAttributeCode()); } elseif (is_string($result)) { $this->_messages[$attribute->getAttributeCode()][] = $result; } } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->_messages[$attribute->getAttributeCode()][] = $e->getMessage(); } } return 0 == count($this->_messages); }
/** * Retrieve max sort order * * @param \Magento\Framework\Model\AbstractModel $object * @return int */ protected function _getMaxSortOrder($object) { $adapter = $this->_getReadAdapter(); $bind = [':attribute_set_id' => $object->getAttributeSetId()]; $select = $adapter->select()->from($this->getMainTable(), new \Zend_Db_Expr("MAX(sort_order)"))->where('attribute_set_id = :attribute_set_id'); return $adapter->fetchOne($select, $bind); }
/** * Update the status of a queue record and check to confirm the exclusive change * * @param \Magento\Framework\Model\AbstractModel $object * @return bool */ public function changeQueueStatusWithLocking(AbstractModel $object) { /* @var $object \ClassyLlama\AvaTax\Model\Queue */ $object->setUpdatedAt($this->dateTime->gmtDate()); $data = $this->prepareDataForUpdate($object); $originalQueueStatus = $object->getOrigData(self::QUEUE_STATUS_FIELD_NAME); $originalUpdatedAt = $object->getOrigData(self::UPDATED_AT_FIELD_NAME); // A conditional update does a read lock on update so we use the condition on the old // queue status here to guarantee that nothing else has modified the status for processing $condition = array(); // update only the queue record identified by Id $condition[] = $this->getConnection()->quoteInto($this->getIdFieldName() . '=?', $object->getId()); // only update the record if it is still pending $condition[] = $this->getConnection()->quoteInto(self::QUEUE_STATUS_FIELD_NAME . '=?', $originalQueueStatus); // only update the record if nothing else has updated it if ($originalUpdatedAt === null) { $condition[] = self::UPDATED_AT_FIELD_NAME . ' IS NULL'; } else { $condition[] = $this->getConnection()->quoteInto(self::UPDATED_AT_FIELD_NAME . '=?', $originalUpdatedAt); } // update the record and get the number of affected records $affectedRowCount = $this->getConnection()->update($this->getMainTable(), $data, $condition); $result = false; if ($affectedRowCount > 0) { $object->setHasDataChanges(false); $result = true; } return $result; }
/** * Save entity types after save form type * * @see \Magento\Framework\Model\ModelResource\Db\AbstractDb#_afterSave($object) * * @param FormType|AbstractModel $object * @return $this */ protected function _afterSave(AbstractModel $object) { if ($object->hasEntityTypes()) { $new = $object->getEntityTypes(); $old = $this->getEntityTypes($object); $insert = array_diff($new, $old); $delete = array_diff($old, $new); $connection = $this->getConnection(); if (!empty($insert)) { $data = []; foreach ($insert as $entityId) { if (empty($entityId)) { continue; } $data[] = ['entity_type_id' => (int) $entityId, 'type_id' => $object->getId()]; } if ($data) { $connection->insertMultiple($this->getTable('eav_form_type_entity'), $data); } } if (!empty($delete)) { $where = ['entity_type_id IN (?)' => $delete, 'type_id = ?' => $object->getId()]; $connection->delete($this->getTable('eav_form_type_entity'), $where); } } return parent::_afterSave($object); }
/** * Check if Entity is Empty * * @return $this * @throws \InvalidArgumentException */ protected function _checkEntityIsEmpty() { if (!$this->_entity->getId()) { throw new \InvalidArgumentException('The model is empty'); } return $this; }
public function testProcessRelations() { $this->relationProcessorMock->expects($this->once())->method('processRelation')->with($this->modelMock); $this->modelMock->expects($this->once())->method('getEventPrefix')->willReturn('custom_event_prefix'); $this->eventManagerMock->expects($this->once())->method('dispatch')->with('custom_event_prefix_process_relation', ['object' => $this->modelMock]); $this->entityRelationComposite->processRelations($this->modelMock); }
/** * {@inheritdoc} * * @param \Magento\Framework\Model\AbstractModel $change * @return $this */ protected function _beforeSave(\Magento\Framework\Model\AbstractModel $change) { if (!$change->getChangeTime()) { $change->setChangeTime($this->dateTime->formatDate(true)); } return $this; }
/** * Perform actions before object save * * @param \Smart2Pay\GlobalPay\Model\ConfiguredMethods $object * @return $this * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object) { if ($existing_arr = $this->checkMethodCountryID($object->getMethodID(), $object->getCountryID())) { $this->getConnection()->delete($this->getMainTable(), $this->getConnection()->quoteInto($this->getIdFieldName() . '=?', $existing_arr[$this->getIdFieldName()])); } return parent::_beforeSave($object); }
/** * Save relations for Order * * @param \Magento\Framework\Model\AbstractModel $object * @return void * @throws \Exception */ public function processRelation(\Magento\Framework\Model\AbstractModel $object) { /** @var \Magento\Sales\Model\Order $object */ if (null !== $object->getItems()) { /** @var \Magento\Sales\Model\Order\Item $item */ foreach ($object->getItems() as $item) { $item->setOrderId($object->getId()); $item->setOrder($object); $this->orderItemRepository->save($item); } } if (null !== $object->getPayment()) { $payment = $object->getPayment(); $payment->setParentId($object->getId()); $payment->setOrder($object); $this->orderPaymentResource->save($payment); } if (null !== $object->getStatusHistories()) { /** @var \Magento\Sales\Model\Order\Status\History $statusHistory */ foreach ($object->getStatusHistories() as $statusHistory) { $statusHistory->setParentId($object->getId()); $statusHistory->setOrder($object); $this->orderStatusHistoryResource->save($statusHistory); } } if (null !== $object->getRelatedObjects()) { foreach ($object->getRelatedObjects() as $relatedObject) { $relatedObject->setOrder($object); $relatedObject->save(); } } $this->addressHandler->removeEmptyAddresses($object); $this->addressHandler->process($object); }
/** * Delete all Nonce entries associated with the consumer * * @param \Magento\Framework\Model\AbstractModel $object * @return $this */ public function _afterDelete(\Magento\Framework\Model\AbstractModel $object) { $connection = $this->getConnection(); $connection->delete($this->getTable('oauth_nonce'), ['consumer_id' => $object->getId()]); $connection->delete($this->getTable('oauth_token'), ['consumer_id' => $object->getId()]); return parent::_afterDelete($object); }
/** * Reindex on product delete * * @param \Magento\Catalog\Model\ResourceModel\Product $productResource * @param \Closure $proceed * @param \Magento\Framework\Model\AbstractModel $product * @return \Magento\Catalog\Model\ResourceModel\Product * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundDelete(\Magento\Catalog\Model\ResourceModel\Product $productResource, \Closure $proceed, \Magento\Framework\Model\AbstractModel $product) { $productResource->addCommitCallback(function () use($product) { $this->reindexRow($product->getEntityId()); }); return $proceed($product); }
/** * Delete all Nonce entries associated with the consumer * * @param \Magento\Framework\Model\AbstractModel $object * @return $this */ public function _afterDelete(\Magento\Framework\Model\AbstractModel $object) { $adapter = $this->_getWriteAdapter(); $adapter->delete($this->getTable('oauth_nonce'), array('consumer_id' => $object->getId())); $adapter->delete($this->getTable('oauth_token'), array('consumer_id' => $object->getId())); return parent::_afterDelete($object); }
/** * Perform actions after object save * * @param \Magento\Framework\Model\AbstractModel $object * @return $this */ protected function _afterSave(\Magento\Framework\Model\AbstractModel $object) { /** @var \Magento\Sales\Model\Order\Invoice\Item $object */ if (null == !$object->getOrderItem()) { $object->getOrderItem()->save(); } return parent::_afterSave($object); }
protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object) { if (!$object->getId()) { $object->setCreatedAt($this->_date->gmtDate()); } $object->setUpdatedAt($this->_date->gmtDate()); return $this; }
/** * Set created date * * @param \Magento\Framework\Model\AbstractModel $object * @return $this */ public function beforeSave($object) { $attributeCode = $this->getAttribute()->getAttributeCode(); if ($object->isObjectNew() && $object->getData($attributeCode) === null) { $object->setData($attributeCode, gmdate(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT)); } return $this; }
/** * Method to run after load * * @param \Magento\Framework\Model\AbstractModel $object * @return $this */ protected function _afterLoad(\Magento\Framework\Model\AbstractModel $object) { $select = $this->getConnection()->select()->from($this->getTable('checkout_agreement_store'), ['store_id'])->where('agreement_id = :agreement_id'); if ($stores = $this->getConnection()->fetchCol($select, [':agreement_id' => $object->getId()])) { $object->setData('store_id', $stores); } return parent::_afterLoad($object); }
/** * Before save handler * * @param \Magento\Cms\Model\ResourceModel\Page $subject * @param \Magento\Framework\Model\AbstractModel $object * * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function beforeSave(\Magento\Cms\Model\ResourceModel\Page $subject, \Magento\Framework\Model\AbstractModel $object) { /** @var $object \Magento\Cms\Model\Page */ $urlKey = $object->getData('identifier'); if ($urlKey === '' || $urlKey === null) { $object->setData('identifier', $this->cmsPageUrlPathGenerator->generateUrlKey($object)); } }
/** * @magentoDataFixture Magento/Security/_files/password_reset_request_events.php */ public function testDeleteRecordsOlderThen() { /** @var \Magento\Security\Model\PasswordResetRequestEvent $passwordResetRequestEvent */ $countBefore = $this->model->getCollection()->count(); $this->resourceModel->deleteRecordsOlderThen(strtotime('2016-01-20 12:00:00')); $countAfter = $this->model->getCollection()->count(); $this->assertLessThan($countBefore, $countAfter); }
/** * {@inheritdoc} */ protected function _beforeSave(AbstractModel $tag) { /** @var \Mirasvit\Blog\Model\Tag $tag */ if (!$tag->getData('url_key')) { $tag->setData('url_key', $this->filter->translitUrl($tag->getName())); } return parent::_beforeSave($tag); }
/** * Prepare data to be saved to database * @param \Magento\Framework\Model\AbstractModel|\Magento\Framework\Object $object * * @return $this */ protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object) { if ($object->isObjectNew()) { $object->setCreatedAt($this->dateTime->formatDate(true)); } $object->setUpdatedAt($this->dateTime->formatDate(true)); return $this; }
/** * @param \Magento\Framework\Model\AbstractModel $object * @param string $dateIdentifier * @return void */ private function resolveDate(\Magento\Framework\Model\AbstractModel $object, $dateIdentifier) { $date = $object->getData($dateIdentifier); if ($date instanceof \DateTime) { $object->setData($dateIdentifier, $date->format('Y-m-d H:i:s')); } elseif (!is_string($date) || empty($date)) { $object->setData($dateIdentifier, null); } }
/** * Set template type, added at and modified at time * * @param \Magento\Framework\Model\AbstractModel $object * @return $this */ protected function _beforeSave(AbstractModel $object) { if ($object->isObjectNew()) { $object->setAddedAt($this->dateTime->formatDate(true)); } $object->setModifiedAt($this->dateTime->formatDate(true)); $object->setTemplateType((int) $object->getTemplateType()); return parent::_beforeSave($object); }
/** * Perform operations after object load * * @param \Magento\Framework\Model\AbstractModel $object * @return $this */ protected function _afterLoad(\Magento\Framework\Model\AbstractModel $object) { if ($object->getId()) { $productIds = $this->lookupProductIds($object->getId()); $productId = implode(',', $productIds); $object->setData('product_id', $productId); } return parent::_afterLoad($object); }
/** * Invalidate indexer on store group save * * @param \Magento\Store\Model\Resource\Group $subject * @param \Closure $proceed * @param \Magento\Framework\Model\AbstractModel $group * * @return \Magento\Store\Model\Resource\Group * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundSave(\Magento\Store\Model\Resource\Group $subject, \Closure $proceed, \Magento\Framework\Model\AbstractModel $group) { $needInvalidation = !$group->isObjectNew() && $group->dataHasChangedFor('website_id'); $result = $proceed($group); if ($needInvalidation) { $this->indexerRegistry->get(Fulltext::INDEXER_ID)->invalidate(); } return $result; }
/** * Set created date * * @param \Magento\Framework\Model\AbstractModel $object * @return $this */ public function beforeSave($object) { $attributeCode = $this->getAttribute()->getAttributeCode(); if ($object->isObjectNew() && $object->getData($attributeCode) === null) { //$object->setData($attributeCode, $this->dateTime->gmtDate()); $object->setData($attributeCode, gmdate('Y-m-d H:i:s')); } return $this; }
/** * Invalidate indexer on store view save * * @param \Magento\Store\Model\ResourceModel\Store $subject * @param \Closure $proceed * @param \Magento\Framework\Model\AbstractModel $store * * @return \Magento\Store\Model\ResourceModel\Store * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundSave(\Magento\Store\Model\ResourceModel\Store $subject, \Closure $proceed, \Magento\Framework\Model\AbstractModel $store) { $needInvalidation = $store->isObjectNew(); $result = $proceed($store); if ($needInvalidation) { $this->indexerRegistry->get(Fulltext::INDEXER_ID)->invalidate(); } return $result; }
/** * Decorate status column values * * @param string $value * @param \Magento\Framework\Model\AbstractModel $row * @param \Magento\Backend\Block\Widget\Grid\Column $column * @param bool $isExport * @return string */ public function decorateStatus($value, $row, $column, $isExport) { if ($row->getIsActive() || $row->getStatus()) { $cell = '<span class="grid-severity-notice"><span>' . $value . '</span></span>'; } else { $cell = '<span class="grid-severity-critical"><span>' . $value . '</span></span>'; } return $cell; }
/** * Invalidate indexer on searchable attribute delete * * @param \Magento\Catalog\Model\Resource\Attribute $subject * @param \Closure $proceed * @param \Magento\Framework\Model\AbstractModel $attribute * * @return \Magento\Catalog\Model\Resource\Attribute * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundDelete(\Magento\Catalog\Model\Resource\Attribute $subject, \Closure $proceed, \Magento\Framework\Model\AbstractModel $attribute) { $needInvalidation = !$attribute->isObjectNew() && $attribute->getIsSearchable(); $result = $proceed($attribute); if ($needInvalidation) { $this->indexerRegistry->get(Fulltext::INDEXER_ID)->invalidate(); } return $result; }
/** * Update a "layout update link" if relevant data is provided * * @param \Magento\Widget\Model\Layout\Update|\Magento\Framework\Model\AbstractModel $object * @return $this */ protected function _afterSave(\Magento\Framework\Model\AbstractModel $object) { $data = $object->getData(); if (isset($data['store_id']) && isset($data['theme_id'])) { $this->getConnection()->insertOnDuplicate($this->getTable('layout_link'), ['store_id' => $data['store_id'], 'theme_id' => $data['theme_id'], 'layout_update_id' => $object->getId(), 'is_temporary' => (int) $object->getIsTemporary()]); } $this->_cache->clean(); return parent::_afterSave($object); }