/** * Validate user credentials * * @param string $username * @param string $password * @throws InputException * @return void */ public function validate($username, $password) { $exception = new InputException(); if (!is_string($username) || strlen($username) == 0) { $exception->addError(__('%fieldName is a required field.', ['fieldName' => 'username'])); } if (!is_string($password) || strlen($password) == 0) { $exception->addError(__('%fieldName is a required field.', ['fieldName' => 'password'])); } if ($exception->wasErrorAdded()) { throw $exception; } }
/** * Validate user credentials * * @param string $username * @param string $password * @throws InputException * @return void */ public function validateCredentials($username, $password) { $exception = new InputException(); if (!is_string($username) || strlen($username) == 0) { $exception->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'username']); } if (!is_string($username) || strlen($password) == 0) { $exception->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'password']); } if ($exception->wasErrorAdded()) { throw $exception; } }
/** * {@inheritdoc} */ public function getList($entityTypeCode, \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria) { if (!$entityTypeCode) { throw InputException::requiredField('entity_type_code'); } /** @var \Magento\Eav\Model\Resource\Entity\Attribute\Collection $attributeCollection */ $attributeCollection = $this->attributeCollectionFactory->create(); $attributeCollection->addFieldToFilter('entity_type_code', ['eq' => $entityTypeCode]); $attributeCollection->join(['entity_type' => $attributeCollection->getTable('eav_entity_type')], 'main_table.entity_type_id = entity_type.entity_type_id', []); $attributeCollection->join(['eav_entity_attribute' => $attributeCollection->getTable('eav_entity_attribute')], 'main_table.attribute_id = eav_entity_attribute.attribute_id', []); $attributeCollection->join(['additional_table' => $attributeCollection->getTable('catalog_eav_attribute')], 'main_table.attribute_id = additional_table.attribute_id', []); //Add filters from root filter group to the collection foreach ($searchCriteria->getFilterGroups() as $group) { $this->addFilterGroupToCollection($group, $attributeCollection); } /** @var \Magento\Framework\Api\SortOrder $sortOrder */ foreach ((array) $searchCriteria->getSortOrders() as $sortOrder) { $attributeCollection->addOrder($sortOrder->getField(), $sortOrder->getDirection() == SearchCriteriaInterface::SORT_ASC ? 'ASC' : 'DESC'); } $totalCount = $attributeCollection->getSize(); // Group attributes by id to prevent duplicates with different attribute sets $attributeCollection->addAttributeGrouping(); $attributeCollection->setCurPage($searchCriteria->getCurrentPage()); $attributeCollection->setPageSize($searchCriteria->getPageSize()); $attributes = []; /** @var \Magento\Eav\Api\Data\AttributeInterface $attribute */ foreach ($attributeCollection as $attribute) { $attributes[] = $this->get($entityTypeCode, $attribute->getAttributeCode()); } $searchResults = $this->searchResultsFactory->create(); $searchResults->setSearchCriteria($searchCriteria); $searchResults->setItems($attributes); $searchResults->setTotalCount($totalCount); return $searchResults; }
/** * {@inheritdoc} */ public function save(\Magento\Quote\Api\Data\CartItemInterface $cartItem) { $qty = $cartItem->getQty(); if (!is_numeric($qty) || $qty <= 0) { throw InputException::invalidFieldValue('qty', $qty); } $cartId = $cartItem->getQuoteId(); /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); $itemId = $cartItem->getItemId(); try { /** update item qty */ if (isset($itemId)) { $cartItem = $quote->getItemById($itemId); if (!$cartItem) { throw new NoSuchEntityException(__('Cart %1 doesn\'t contain item %2', $cartId, $itemId)); } $product = $this->productRepository->get($cartItem->getSku()); $cartItem->setData('qty', $qty); } else { $product = $this->productRepository->get($cartItem->getSku()); $quote->addProduct($product, $qty); } $this->quoteRepository->save($quote->collectTotals()); } catch (\Exception $e) { if ($e instanceof NoSuchEntityException) { throw $e; } throw new CouldNotSaveException(__('Could not save quote')); } return $quote->getItemByProduct($product); }
/** * Assert for presence of Input exception messages * * @param InputException $e */ private function assertInputExceptionMessages($e) { $this->assertEquals(InputException::DEFAULT_MESSAGE, $e->getMessage()); $errors = $e->getErrors(); $this->assertCount(2, $errors); $this->assertEquals('username is a required field.', $errors[0]->getLogMessage()); $this->assertEquals('password is a required field.', $errors[1]->getLogMessage()); }
/** * Assert for presence of Input exception messages * * @param InputException $e */ private function assertInputExceptionMessages($e) { $this->assertEquals('One or more input exceptions have occurred.', $e->getMessage()); $errors = $e->getErrors(); $this->assertCount(2, $errors); $this->assertEquals('username is a required field.', $errors[0]->getLogMessage()); $this->assertEquals('password is a required field.', $errors[1]->getLogMessage()); }
/** * {@inheritdoc} */ public function inputException($wrappedErrorParameters) { $exception = new InputException(); if ($wrappedErrorParameters) { foreach ($wrappedErrorParameters as $error) { $exception->addError(__('Invalid value of "%value" provided for the %fieldName field.', ['fieldName' => $error->getFieldName(), 'value' => $error->getValue()])); } } throw $exception; }
/** * {@inheritdoc} */ public function inputException($wrappedErrorParameters) { $exception = new InputException(); if ($wrappedErrorParameters) { foreach ($wrappedErrorParameters as $error) { $exception->addError(__(InputException::INVALID_FIELD_VALUE, ['fieldName' => $error->getFieldName(), 'value' => $error->getValue()])); } } throw $exception; }
/** * {@inheritdoc} * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function save(\Magento\Quote\Api\Data\CartItemInterface $cartItem) { $qty = $cartItem->getQty(); if (!is_numeric($qty) || $qty <= 0) { throw InputException::invalidFieldValue('qty', $qty); } $cartId = $cartItem->getQuoteId(); /** @var \Magento\Quote\Model\Quote $quote */ $quote = $this->quoteRepository->getActive($cartId); $itemId = $cartItem->getItemId(); try { /** update item */ if (isset($itemId)) { $item = $quote->getItemById($itemId); if (!$item) { throw new NoSuchEntityException(__('Cart %1 doesn\'t contain item %2', $cartId, $itemId)); } $productType = $item->getProduct()->getTypeId(); $buyRequestData = $this->getBuyRequest($productType, $cartItem); if (is_object($buyRequestData)) { /** update item product options */ /** @var \Magento\Quote\Model\Quote\Item $cartItem */ $cartItem = $quote->updateItem($itemId, $buyRequestData); } else { /** update item qty */ $item->setData('qty', $qty); } } else { /** add item to shopping cart */ $product = $this->productRepository->get($cartItem->getSku()); $productType = $product->getTypeId(); /** @var \Magento\Quote\Model\Quote\Item|string $cartItem */ $cartItem = $quote->addProduct($product, $this->getBuyRequest($productType, $cartItem)); if (is_string($cartItem)) { throw new \Magento\Framework\Exception\LocalizedException(__($cartItem)); } } $this->quoteRepository->save($quote->collectTotals()); } catch (\Exception $e) { if ($e instanceof NoSuchEntityException || $e instanceof LocalizedException) { throw $e; } throw new CouldNotSaveException(__('Could not save quote')); } $itemId = $cartItem->getId(); foreach ($quote->getAllItems() as $quoteItem) { if ($itemId == $quoteItem->getId()) { $cartItem = $this->addProductOptions($productType, $quoteItem); return $this->applyCustomOptions($cartItem); } } throw new CouldNotSaveException(__('Could not save quote')); }
/** * @param CartInterface $quote * @param CartItemInterface $item * @return CartItemInterface * @throws CouldNotSaveException * @throws InputException * @throws LocalizedException * @throws NoSuchEntityException * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function save(CartInterface $quote, CartItemInterface $item) { /** @var \Magento\Quote\Model\Quote $quote */ $qty = $item->getQty(); if (!is_numeric($qty) || $qty <= 0) { throw InputException::invalidFieldValue('qty', $qty); } $cartId = $item->getQuoteId(); $itemId = $item->getItemId(); try { /** Update existing item */ if (isset($itemId)) { $currentItem = $quote->getItemById($itemId); if (!$currentItem) { throw new NoSuchEntityException(__('Cart %1 does not contain item %2', $cartId, $itemId)); } $productType = $currentItem->getProduct()->getTypeId(); $buyRequestData = $this->cartItemOptionProcessor->getBuyRequest($productType, $item); if (is_object($buyRequestData)) { /** Update item product options */ $item = $quote->updateItem($itemId, $buyRequestData); } else { if ($item->getQty() !== $currentItem->getQty()) { $currentItem->setQty($qty); } } } else { /** add new item to shopping cart */ $product = $this->productRepository->get($item->getSku()); $productType = $product->getTypeId(); $item = $quote->addProduct($product, $this->cartItemOptionProcessor->getBuyRequest($productType, $item)); if (is_string($item)) { throw new LocalizedException(__($item)); } } } catch (NoSuchEntityException $e) { throw $e; } catch (LocalizedException $e) { throw $e; } catch (\Exception $e) { throw new CouldNotSaveException(__('Could not save quote')); } $itemId = $item->getId(); foreach ($quote->getAllItems() as $quoteItem) { /** @var \Magento\Quote\Model\Quote\Item $quoteItem */ if ($itemId == $quoteItem->getId()) { $item = $this->cartItemOptionProcessor->addProductOptions($productType, $quoteItem); return $this->cartItemOptionProcessor->applyCustomOptions($item); } } throw new CouldNotSaveException(__('Could not save quote')); }
/** * Constructor * * @param \Magento\Framework\Phrase $phrase * @param \Exception $cause * @param array $messages Validation error messages */ public function __construct(Phrase $phrase = null, \Exception $cause = null, array $messages = []) { if (!empty($messages)) { $message = ''; foreach ($messages as $propertyMessages) { foreach ($propertyMessages as $propertyMessage) { if ($message) { $message .= PHP_EOL; } $message .= $propertyMessage; $this->addMessage(new Error($propertyMessage)); } } $phrase = new Phrase($message); } parent::__construct($phrase, $cause); }
/** * Constructor * * @param string $message * @param [] $params * @param \Exception $cause * @param array $messages Validation error messages */ public function __construct($message = self::DEFAULT_MESSAGE, $params = [], \Exception $cause = null, array $messages = []) { if (!empty($messages)) { $this->_messages = $messages; $message = ''; foreach ($this->_messages as $propertyMessages) { foreach ($propertyMessages as $propertyMessage) { if ($message) { $message .= PHP_EOL; } $message .= $propertyMessage; } } } else { $this->_messages = [$message]; } parent::__construct($message, $params, $cause); }
/** * {@inheritdoc} */ public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria) { $attributeSetId = $this->retrieveAttributeSetIdFromSearchCriteria($searchCriteria); if (!$attributeSetId) { throw InputException::requiredField('attribute_set_id'); } try { $this->setRepository->get($attributeSetId); } catch (\Exception $exception) { throw NoSuchEntityException::singleField('attributeSetId', $attributeSetId); } $collection = $this->groupListFactory->create(); $collection->setAttributeSetFilter($attributeSetId); $collection->setSortOrder(); $searchResult = $this->searchResultsFactory->create(); $searchResult->setSearchCriteria($searchCriteria); $searchResult->setItems($collection->getItems()); $searchResult->setTotalCount($collection->getSize()); return $searchResult; }
/** * {@inheritdoc} */ public function updateItem($cartId, $itemId, \Magento\Checkout\Service\V1\Data\Cart\Item $data) { $qty = $data->getQty(); if (!is_numeric($qty) || $qty <= 0) { throw InputException::invalidFieldValue('qty', $qty); } /** @var \Magento\Sales\Model\Quote $quote */ $quote = $this->quoteRepository->get($cartId); $quoteItem = $quote->getItemById($itemId); if (!$quoteItem) { throw new NoSuchEntityException("Cart {$cartId} doesn't contain item {$itemId}"); } $quoteItem->setData('qty', $qty); try { $quote->collectTotals()->save(); } catch (\Exception $e) { throw new CouldNotSaveException('Could not update quote item'); } return true; }
/** * {@inheritdoc} */ public function create($entityTypeCode, AttributeSetInterface $attributeSet, $skeletonId) { /** @var \Magento\Eav\Model\Entity\Attribute\Set $attributeSet */ if ($attributeSet->getId() !== null) { throw InputException::invalidFieldValue('id', $attributeSet->getId()); } if ($skeletonId == 0) { throw InputException::invalidFieldValue('skeletonId', $skeletonId); } // Make sure that skeleton attribute set is valid (try to load it) $this->repository->get($skeletonId); try { $attributeSet->setEntityTypeId($this->eavConfig->getEntityType($entityTypeCode)->getId()); $attributeSet->validate(); } catch (\Exception $exception) { throw new InputException(__($exception->getMessage())); } $this->repository->save($attributeSet); $attributeSet->initFromSkeleton($skeletonId); return $this->repository->save($attributeSet); }
/** * {@inheritdoc} */ public function setProductLinks($sku, array $items) { $linkTypes = $this->linkTypeProvider->getLinkTypes(); // Check if product link type is set and correct if (!empty($items)) { foreach ($items as $newLink) { $type = $newLink->getLinkType(); if ($type == null) { throw InputException::requiredField("linkType"); } if (!isset($linkTypes[$type])) { throw new NoSuchEntityException(__('Provided link type "%1" does not exist', $type)); } } } $product = $this->productRepository->get($sku); // Replace only links of the specified type $existingLinks = $product->getProductLinks(); $newLinks = []; if (!empty($existingLinks)) { foreach ($existingLinks as $link) { if ($link->getLinkType() != $type) { $newLinks[] = $link; } } $newLinks = array_merge($newLinks, $items); } else { $newLinks = $items; } $product->setProductLinks($newLinks); try { $this->productRepository->save($product); } catch (\Exception $exception) { throw new CouldNotSaveException(__('Invalid data provided for linked products')); } return true; }
/** * {@inheritdoc} * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function save(\Magento\Catalog\Api\Data\ProductInterface $product, $saveOptions = false) { if ($saveOptions) { $productOptions = $product->getProductOptions(); } $isDeleteOptions = $product->getIsDeleteOptions(); $tierPrices = $product->getData('tier_price'); $productId = $this->resourceModel->getIdBySku($product->getSku()); $ignoreLinksFlag = $product->getData('ignore_links_flag'); $productDataArray = $this->extensibleDataObjectConverter->toNestedArray($product, [], 'Magento\\Catalog\\Api\\Data\\ProductInterface'); $productLinks = null; if (!$ignoreLinksFlag && $ignoreLinksFlag !== null) { $productLinks = $product->getProductLinks(); } $product = $this->initializeProductData($productDataArray, empty($productId)); if (isset($productDataArray['options'])) { if (!empty($productDataArray['options']) || $isDeleteOptions) { $this->processOptions($product, $productDataArray['options']); $product->setCanSaveCustomOptions(true); } } $this->processLinks($product, $productLinks); if (isset($productDataArray['media_gallery_entries'])) { $this->processMediaGallery($product, $productDataArray['media_gallery_entries']); } $validationResult = $this->resourceModel->validate($product); if (true !== $validationResult) { throw new \Magento\Framework\Exception\CouldNotSaveException(__('Invalid product data: %1', implode(',', $validationResult))); } try { if ($saveOptions) { $product->setProductOptions($productOptions); $product->setCanSaveCustomOptions(true); } if ($tierPrices !== null) { $product->setData('tier_price', $tierPrices); } $this->resourceModel->save($product); } catch (\Magento\Eav\Model\Entity\Attribute\Exception $exception) { throw \Magento\Framework\Exception\InputException::invalidFieldValue($exception->getAttributeCode(), $product->getData($exception->getAttributeCode()), $exception); } catch (\Exception $e) { throw new \Magento\Framework\Exception\CouldNotSaveException(__('Unable to save product')); } unset($this->instances[$product->getSku()]); unset($this->instancesById[$product->getId()]); return $this->get($product->getSku()); }
/** * Validate tax rate * * @param \Magento\Tax\Api\Data\TaxRateInterface $taxRate * @throws InputException * @return void * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ private function validate(\Magento\Tax\Api\Data\TaxRateInterface $taxRate) { $exception = new InputException(); $countryCode = $taxRate->getTaxCountryId(); if (!\Zend_Validate::is($countryCode, 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'country_id'])); } elseif (!\Zend_Validate::is($this->countryFactory->create()->loadByCode($countryCode)->getId(), 'NotEmpty')) { $exception->addError(__(InputException::INVALID_FIELD_VALUE, ['fieldName' => 'country_id', 'value' => $countryCode])); } $regionCode = $taxRate->getTaxRegionId(); // if regionCode eq 0 (all regions *), do not validate with existing region list if (\Zend_Validate::is($regionCode, 'NotEmpty') && $regionCode != "0" && !\Zend_Validate::is($this->regionFactory->create()->load($regionCode)->getId(), 'NotEmpty')) { $exception->addError(__(InputException::INVALID_FIELD_VALUE, ['fieldName' => 'region_id', 'value' => $regionCode])); } if (!\Zend_Validate::is($taxRate->getRate(), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'percentage_rate'])); } if (!\Zend_Validate::is(trim($taxRate->getCode()), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'code'])); } if ($taxRate->getZipIsRange()) { $zipRangeFromTo = ['zip_from' => $taxRate->getZipFrom(), 'zip_to' => $taxRate->getZipTo()]; foreach ($zipRangeFromTo as $key => $value) { if (!is_numeric($value) || $value < 0) { $exception->addError(__(InputException::INVALID_FIELD_VALUE, ['fieldName' => $key, 'value' => $value])); } } if ($zipRangeFromTo['zip_from'] > $zipRangeFromTo['zip_to']) { $exception->addError(__('Range To should be equal or greater than Range From.')); } } else { if (!\Zend_Validate::is(trim($taxRate->getTaxPostcode()), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'postcode'])); } } if ($exception->wasErrorAdded()) { throw $exception; } }
/** * Validate customer attribute values. * * @param \Magento\Customer\Api\Data\CustomerInterface $customer * @throws InputException * @return void * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ private function validate(\Magento\Customer\Api\Data\CustomerInterface $customer) { $exception = new InputException(); if (!\Zend_Validate::is(trim($customer->getFirstname()), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'firstname'])); } if (!\Zend_Validate::is(trim($customer->getLastname()), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'lastname'])); } $isEmailAddress = \Zend_Validate::is($customer->getEmail(), 'EmailAddress'); if (!$isEmailAddress) { $exception->addError(__(InputException::INVALID_FIELD_VALUE, ['fieldName' => 'email', 'value' => $customer->getEmail()])); } $dob = $this->getAttributeMetadata('dob'); if ($dob !== null && $dob->isRequired() && '' == trim($customer->getDob())) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'dob'])); } $taxvat = $this->getAttributeMetadata('taxvat'); if ($taxvat !== null && $taxvat->isRequired() && '' == trim($customer->getTaxvat())) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'taxvat'])); } $gender = $this->getAttributeMetadata('gender'); if ($gender !== null && $gender->isRequired() && '' == trim($customer->getGender())) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'gender'])); } if ($exception->wasErrorAdded()) { throw $exception; } }
/** * Validate Slider Item values. * * @param \Stepzerosolutions\Tbslider\Api\Data\SlideritemsInterface $slider * @throws InputException * @return void * * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ private function _validate($slider) { $exception = new InputException(); if (!\Zend_Validate::is($slider->getSlideritemTitle(), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'slideritem_title'])); } if ($exception->wasErrorAdded()) { throw $exception; } }
/** * {@inheritdoc} */ public function update($id, \Magento\Catalog\Service\V1\Data\Product $product) { $productModel = $this->productLoader->load($id); try { $this->productMapper->toModel($product, $productModel); $this->initializationHelper->initialize($productModel); $this->productTypeManager->processProduct($productModel); $productModel->validate(); $productModel->save(); } catch (\Magento\Eav\Model\Entity\Attribute\Exception $exception) { throw \Magento\Framework\Exception\InputException::invalidFieldValue($exception->getAttributeCode(), $productModel->getData($exception->getAttributeCode()), $exception); } return $productModel->getSku(); }
/** * Validate TaxClass Data * * @param \Magento\Tax\Api\Data\TaxClassInterface $taxClass * @return void * @throws InputException */ protected function validateTaxClassData(\Magento\Tax\Api\Data\TaxClassInterface $taxClass) { $exception = new InputException(); if (!\Zend_Validate::is(trim($taxClass->getClassName()), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => TaxClassInterface::KEY_NAME])); } $classType = $taxClass->getClassType(); if (!\Zend_Validate::is(trim($classType), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => TaxClassInterface::KEY_TYPE])); } elseif ($classType !== TaxClassManagementInterface::TYPE_CUSTOMER && $classType !== TaxClassManagementInterface::TYPE_PRODUCT) { $exception->addError(__(InputException::INVALID_FIELD_VALUE, ['fieldName' => TaxClassInterface::KEY_TYPE, 'value' => $classType])); } if ($exception->wasErrorAdded()) { throw $exception; } }
public function testValidateAddressesOneInvalidNoKeys() { $invalidAddress = $this->_addressBuilder->setFirstname('Freddy')->setLastname('Mercury')->create(); try { $this->_service->validateAddresses(array_merge($this->_expectedAddresses, array($invalidAddress))); $this->fail("InputException was expected but not thrown"); } catch (InputException $actualException) { $expectedException = new InputException(); $expectedException->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'street', 'index' => 2]); $expectedException->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'city', 'index' => 2]); $expectedException->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'telephone', 'index' => 2]); $expectedException->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'postcode', 'index' => 2]); $expectedException->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'countryId', 'index' => 2]); $this->assertEquals($expectedException, $actualException); } }
public function testValidateAddressesBoth() { // Setup address mock, no first name $mockBadAddress = $this->_createAddress(1, ''); // Setup address mock, with first name $mockAddress = $this->_createAddress(1, 'John'); $addressBad = $this->_addressBuilder->create(); $addressGood = $this->_addressBuilder->create(); $this->_addressConverterMock->expects($this->any())->method('createAddressModel')->will($this->returnValueMap(array(array($addressBad, $mockBadAddress), array($addressGood, $mockAddress)))); $customerService = $this->_createService(); try { $customerService->validateAddresses(array($addressBad, $addressGood)); $this->fail("InputException was expected but not thrown"); } catch (InputException $actualException) { $expectedException = new InputException(); $expectedException->addError(InputException::REQUIRED_FIELD, ['fieldName' => 'firstname', 'index' => 0]); $this->assertEquals($expectedException, $actualException); } }
/** * Validate tax rule * * @param TaxRule $rule * @return void * @throws InputException * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ private function validate(TaxRule $rule) { $exception = new InputException(); if (!\Zend_Validate::is(trim($rule->getSortOrder()), 'GreaterThan', [-1])) { $exception->addError(InputException::INVALID_FIELD_MIN_VALUE, ['fieldName' => TaxRule::SORT_ORDER, 'value' => $rule->getSortOrder(), 'minValue' => 0]); } if (!\Zend_Validate::is(trim($rule->getPriority()), 'GreaterThan', [-1])) { $exception->addError(InputException::INVALID_FIELD_MIN_VALUE, ['fieldName' => TaxRule::PRIORITY, 'value' => $rule->getPriority(), 'minValue' => 0]); } // Code is required if (!\Zend_Validate::is(trim($rule->getCode()), 'NotEmpty')) { $exception->addError(InputException::REQUIRED_FIELD, ['fieldName' => TaxRule::CODE]); } // customer tax class ids is required if ($rule->getCustomerTaxClassIds() === null || !$rule->getCustomerTaxClassIds()) { $exception->addError(InputException::REQUIRED_FIELD, ['fieldName' => TaxRule::CUSTOMER_TAX_CLASS_IDS]); } // product tax class ids is required if ($rule->getProductTaxClassIds() === null || !$rule->getProductTaxClassIds()) { $exception->addError(InputException::REQUIRED_FIELD, ['fieldName' => TaxRule::PRODUCT_TAX_CLASS_IDS]); } // tax rate ids is required if ($rule->getTaxRateIds() === null || !$rule->getTaxRateIds()) { $exception->addError(InputException::REQUIRED_FIELD, ['fieldName' => TaxRule::TAX_RATE_IDS]); } // throw exception if errors were found if ($exception->wasErrorAdded()) { throw $exception; } }
/** * {@inheritdoc} */ public function remove($attributeSetId) { $id = intval($attributeSetId); if (0 == $id) { throw InputException::invalidFieldValue('id', $id); } /** @var \Magento\Eav\Model\Entity\Attribute\Set $attributeSet */ $attributeSet = $this->setFactory->create()->load($id); $defaultAttributeSetId = $this->eavConfig->getEntityType(\Magento\Catalog\Model\Product::ENTITY)->getDefaultAttributeSetId(); $loadedData = $attributeSet->getData(); if (empty($loadedData)) { throw NoSuchEntityException::singleField('id', $attributeSetId); } $productEntityId = $this->eavConfig->getEntityType(\Magento\Catalog\Model\Product::ENTITY)->getId(); if ($attributeSet->getEntityTypeId() != $productEntityId) { throw InputException::invalidFieldValue('id', $attributeSetId); } if ($attributeSetId == $defaultAttributeSetId) { throw new StateException('Default attribute set can not be deleted'); } $attributeSet->delete(); return true; }
/** * Validate Frontend Input Type * * @param string $frontendInput * @return void * @throws \Magento\Framework\Exception\InputException */ protected function validateFrontendInput($frontendInput) { /** @var \Magento\Eav\Model\Adminhtml\System\Config\Source\Inputtype\Validator $validator */ $validator = $this->inputtypeValidatorFactory->create(); if (!$validator->isValid($frontendInput)) { throw InputException::invalidFieldValue('frontend_input', $frontendInput); } }
private function validate(PostInterface $post) { $exception = new InputException(); if (!\Zend_Validate::is(trim($post->getTitle()), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'title'])); } if (!\Zend_Validate::is(trim($post->getUrlKey()), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'url_key'])); } $id = $this->_resourceModel->checkUrlKey($post->getUrlKey()); if ($id && $id != $post->getId()) { $exception->addError(__(InputException::DEFAULT_MESSAGE)); } if ($exception->wasErrorAdded()) { throw $exception; } }
/** * Validate thesaurus values * * @param \Smile\ElasticsuiteThesaurus\Api\Data\ThesaurusInterface $thesaurus the thesaurus to validate * * @return void * @throws \Magento\Framework\Exception\InputException */ protected function validate(\Smile\ElasticsuiteThesaurus\Api\Data\ThesaurusInterface $thesaurus) { $exception = new \Magento\Framework\Exception\InputException(); $validator = new \Zend_Validate(); if (!$validator->is(trim($thesaurus->getName()), 'NotEmpty')) { $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'name'])); } if ($exception->wasErrorAdded()) { throw $exception; } }
/** * Process an input error * * @param array $inputError * @return void * @throws InputException */ protected function processInputError($inputError) { if (!empty($inputError)) { $exception = new InputException(); foreach ($inputError as $errorParamField) { $exception->addError(new Phrase(InputException::REQUIRED_FIELD, ['fieldName' => $errorParamField])); } if ($exception->wasErrorAdded()) { throw $exception; } } }