/** * {@inheritdoc} */ public function read(\Magento\Catalog\Model\Product\Option $option) { $fields = [Metadata::PRICE => $option->getPrice(), Metadata::PRICE_TYPE => $option->getPriceType(), Metadata::SKU => $option->getSku()]; $fields = array_merge($fields, $this->getCustomAttributes($option)); $value = $this->valueBuilder->populateWithArray($fields)->create(); return [$value]; }
/** * Prepare item info * * @return void */ protected function _prepareLayout() { parent::_prepareLayout(); $this->_shouldRenderInfo = true; $key = 'order_item_info'; foreach (array('name' => __('Product Name'), 'sku' => __('SKU'), 'qty' => __('Quantity')) as $itemKey => $label) { $value = $this->_recurringPayment->getInfoValue($key, $itemKey); if ($value) { $this->_addInfo(array('label' => $label, 'value' => $value)); } } $request = $this->_recurringPayment->getInfoValue($key, 'info_buyRequest'); if (empty($request)) { return; } $request = unserialize($request); if (empty($request['options'])) { return; } $options = $this->_option->getCollection()->addIdsToFilter(array_keys($request['options']))->addTitleToResult($this->_recurringPayment->getInfoValue($key, 'store_id'))->addValuesToResult(); foreach ($options as $option) { $quoteItemOption = $this->_quoteItemOptionFactory->create()->setId($option->getId()); $group = $option->groupFactory($option->getType())->setOption($option)->setRequest(new \Magento\Framework\Object($request))->setProduct($this->_product)->setUseQuotePath(true)->setQuoteItemOption($quoteItemOption)->validateUserValue($request['options']); $skipHtmlEscaping = false; if ('file' == $option->getType()) { $skipHtmlEscaping = true; $downloadParams = array('id' => $this->_recurringPayment->getId(), 'option_id' => $option->getId(), 'key' => $request['options'][$option->getId()]['secret_key']); $group->setCustomOptionDownloadUrl('sales/download/downloadProfileCustomOption')->setCustomOptionUrlParams($downloadParams); } $optionValue = $group->prepareForCart(); $this->_addInfo(array('label' => $option->getTitle(), 'value' => $group->getFormattedOptionValue($optionValue), 'skip_html_escaping' => $skipHtmlEscaping)); } }
/** * Get option html block * * @param \Magento\Catalog\Model\Product\Option $option * * @return string */ public function getOptionHtml(\Magento\Catalog\Model\Product\Option $option) { $type = $this->getGroupOfOption($option->getType()); $renderer = $this->getChildBlock($type); $renderer->setSkipJsReloadPrice(1)->setProduct($this->getProduct())->setOption($option); return $this->getChildHtml($type, false); }
/** * {@inheritdoc} */ public function read(\Magento\Catalog\Model\Product\Option $option) { $output = []; foreach ($option->getValues() as $value) { $output[] = $this->metadataBuilder->populateWithArray([Metadata::PRICE => $value->getPrice(), Metadata::PRICE_TYPE => $value->getPriceType(), Metadata::SKU => $value->getSku(), Metadata::TITLE => $value->getTitle(), Metadata::SORT_ORDER => $value->getSortOrder(), Metadata::OPTION_TYPE_ID => $value->getId()])->create(); } return $output; }
/** * @expectedException \Magento\Framework\Exception\LocalizedException * @expectedExceptionMessage The file 'File Title' for 'Option Title' has an invalid extension. */ public function testValidateWithInvalidFile() { $relativePath = '/custom_options/quote/file'; $optionValues = ['quote_path' => '/custom_options/quote/file', 'title' => 'File Title']; $this->prepare(); $this->directoryRead->expects($this->once())->method('isReadable')->with($relativePath)->willReturn(false); $this->option->expects($this->once())->method('getTitle')->willReturn('Option Title'); $this->zendValidator->expects($this->at(2))->method('getErrors')->willReturn(true); $this->zendValidator->expects($this->at(3))->method('getErrors')->willReturn([\Zend_Validate_File_ExcludeExtension::FALSE_EXTENSION]); $this->validator->validate($optionValues, $this->option); }
/** * Test for `save` method */ public function testSave() { $this->model->setIsDuplicate(false); $this->configureSaveTest(); $this->optionInstanceMock->expects($this->any())->method('setProduct')->will($this->returnSelf()); $this->optionInstanceMock->expects($this->once())->method('saveOptions')->will($this->returnSelf()); $this->model->save(); }
/** * Test for `save` method */ public function testSave() { $this->imageCache->expects($this->once())->method('generate')->with($this->model); $this->imageCacheFactory->expects($this->once())->method('create')->willReturn($this->imageCache); $this->model->setIsDuplicate(false); $this->configureSaveTest(); $this->optionInstanceMock->expects($this->any())->method('setProduct')->will($this->returnSelf()); $this->optionInstanceMock->expects($this->once())->method('saveOptions')->will($this->returnSelf()); $this->model->beforeSave(); $this->model->afterSave(); }
/** * Validate option type fields * * @param Option $option * @return bool */ protected function validateOptionValue(Option $option) { $values = $option->getData('values'); if (!is_array($values) || $this->isEmpty($values)) { return false; } //forbid removal of last value for option if ($this->checkAllValuesRemoved($values)) { return false; } foreach ($option->getData('values') as $value) { $type = isset($value['price_type']) ? $value['price_type'] : ''; $price = isset($value['price']) ? $value['price'] : 0; $title = isset($value['title']) ? $value['title'] : ''; if (!$this->isInRange($type, $this->priceTypes) || $this->isNegative($price) || $this->isEmpty($title)) { return false; } } return true; }
/** * Validate option type fields * * @param Option $option * @return bool * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ protected function validateOptionValue(Option $option) { $values = $option->getValues() ?: $option->getData('values'); if (!is_array($values) || $this->isEmpty($values)) { return false; } //forbid removal of last value for option if ($this->checkAllValuesRemoved($values)) { return false; } $storeId = \Magento\Store\Model\Store::DEFAULT_STORE_ID; if ($option->getProduct()) { $storeId = $option->getProduct()->getStoreId(); } foreach ($values as $value) { $type = isset($value['price_type']) ? $value['price_type'] : null; $price = isset($value['price']) ? $value['price'] : null; $title = isset($value['title']) ? $value['title'] : null; if (!$this->isValidOptionPrice($type, $price, $storeId) || !$this->isValidOptionTitle($title, $storeId)) { return false; } } return true; }
public function testExecuteBadSecretKey() { $this->itemOptionMock->expects($this->once())->method('load')->willReturnSelf(); $this->itemOptionMock->expects($this->once())->method('getId')->willReturn(self::OPTION_ID); $this->itemOptionMock->expects($this->any())->method('getCode')->willReturn(self::OPTION_CODE); $this->itemOptionMock->expects($this->any())->method('getProductId')->willReturn(self::OPTION_PRODUCT_ID); $this->itemOptionMock->expects($this->any())->method('getValue')->willReturn(self::OPTION_VALUE); $this->productOptionMock->expects($this->once())->method('load')->willReturnSelf(); $this->productOptionMock->expects($this->any())->method('getId')->willReturn(self::OPTION_ID); $this->productOptionMock->expects($this->any())->method('getProductId')->willReturn(self::OPTION_PRODUCT_ID); $this->productOptionMock->expects($this->any())->method('getType')->willReturn(self::OPTION_TYPE); $this->unserializeMock->expects($this->once())->method('unserialize')->with(self::OPTION_VALUE)->willReturn([self::SECRET_KEY => 'bad_test_secret_key']); $this->resultForwardMock->expects($this->once())->method('forward')->with('noroute')->willReturn(true); $this->objectMock->execute(); }
public function testGetRegularPrice() { $priceInfoMock = $this->getMockForAbstractClass('Magento\\Framework\\Pricing\\PriceInfoInterface', [], '', false, false, true, ['getAmount', 'getPrice']); $priceInfoMock->expects($this->once())->method('getPrice')->willReturnSelf(); $amountMock = $this->getMockForAbstractClass('Magento\\Framework\\Pricing\\Amount\\AmountInterface'); $priceInfoMock->expects($this->once())->method('getAmount')->willReturn($amountMock); $this->productMock->expects($this->once())->method('getPriceInfo')->willReturn($priceInfoMock); $amountMock->expects($this->once())->method('getValue')->willReturn(50); $this->model->setPrice(50); $this->model->setPriceType(\Magento\Catalog\Model\Product\Option\Value::TYPE_PERCENT); $this->assertEquals(25, $this->model->getRegularPrice()); $this->model->setPriceType(null); $this->assertEquals(50, $this->model->getRegularPrice()); }
/** * @param \Zend_File_Transfer_Adapter_Http|\Zend_Validate $object * @param \Magento\Catalog\Model\Product\Option $option * @param array $fileFullPath * @return \Zend_File_Transfer_Adapter_Http|\Zend_Validate $object * @throws \Magento\Framework\Exception\InputException */ protected function buildImageValidator($object, $option, $fileFullPath = null) { $dimensions = []; if ($option->getImageSizeX() > 0) { $dimensions['maxwidth'] = $option->getImageSizeX(); } if ($option->getImageSizeY() > 0) { $dimensions['maxheight'] = $option->getImageSizeY(); } if (count($dimensions) > 0) { if ($fileFullPath !== null && !$this->isImage($fileFullPath)) { throw new \Magento\Framework\Exception\InputException(__('File \'%1\' is not an image.', $option->getTitle())); } $object->addValidator(new \Zend_Validate_File_ImageSize($dimensions)); } // File extension $allowed = $this->parseExtensionsString($option->getFileExtension()); if ($allowed !== null) { $object->addValidator(new \Zend_Validate_File_Extension($allowed)); } else { $forbidden = $this->parseExtensionsString($this->getConfigData('forbidden_extensions')); if ($forbidden !== null) { $object->addValidator(new \Zend_Validate_File_ExcludeExtension($forbidden)); } } $object->addValidator(new \Zend_Validate_File_FilesSize(['max' => $this->fileSize->getMaxFileSize()])); return $object; }
/** * Create option data object * * @param \Magento\Catalog\Model\Product\Option $option * @return \Magento\Catalog\Service\V1\Product\CustomOptions\Data\Option array */ protected function _createOptionDataObject(\Magento\Catalog\Model\Product\Option $option) { $data = array(Data\Option::OPTION_ID => $option->getId(), Data\Option::TITLE => $option->getTitle(), Data\Option::TYPE => $option->getType(), Data\Option::IS_REQUIRE => $option->getIsRequire(), Data\Option::SORT_ORDER => $option->getSortOrder(), Data\Option::METADATA => $this->optionMetadataReader->read($option)); return $this->optionBuilder->populateWithArray($data)->create(); }
/** * @param \PHPUnit_Framework_MockObject_MockObject|DefaultType $group * @param \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product\Option $option * @param \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Object $buyRequest * @param \PHPUnit_Framework_MockObject_MockObject|\Magento\Catalog\Model\Product $product */ protected function parentClass($group, $option, $buyRequest, $product) { $group->expects($this->once())->method('setOption')->willReturnSelf(); $group->expects($this->once())->method('setProduct')->willReturnSelf(); $group->expects($this->once())->method('setRequest')->willReturnSelf(); $group->expects($this->once())->method('setProcessMode')->willReturnSelf(); $group->expects($this->once())->method('validateUserValue')->willReturnSelf(); $group->expects($this->once())->method('prepareForCart')->willReturn('someString'); $option->expects($this->once())->method('getType'); $option->expects($this->once())->method('groupFactory')->willReturn($group); $option->expects($this->at(0))->method('getId')->willReturn(333); $buyRequest->expects($this->once())->method('getData'); $buyRequest->expects($this->once())->method('getOptions'); $buyRequest->expects($this->once())->method('getSuperProductConfig')->willReturn([]); $buyRequest->expects($this->any())->method('unsetData')->willReturnSelf(); $buyRequest->expects($this->any())->method('getQty'); $product->expects($this->once())->method('getOptions')->willReturn([$option]); $product->expects($this->once())->method('prepareCustomOptions'); $product->expects($this->any())->method('addCustomOption')->willReturnSelf(); $product->expects($this->any())->method('setCartQty')->willReturnSelf(); $product->expects($this->once())->method('setQty'); $this->catalogProduct->expects($this->once())->method('getSkipSaleableCheck')->willReturn(false); }
/** * {@inheritdoc} */ protected function getCustomAttributes(\Magento\Catalog\Model\Product\Option $option) { return [Metadata::MAX_CHARACTERS => $option->getMaxCharacters()]; }
/** * Validate option type fields * * @param Option $option * @return bool */ protected function validateOptionValue(Option $option) { return $this->isInRange($option->getPriceType(), $this->priceTypes) && !$this->isNegative($option->getPrice()); }
/** * Retrieve option values or false for options which has no values * * @param \Magento\Catalog\Model\Product\Option $option * @return array|bool */ protected function getOptionValues(\Magento\Catalog\Model\Product\Option $option) { $values = $option->getValues(); if (!empty($values)) { $result = []; /** @var $value \Magento\Catalog\Model\Product\Option\Value */ foreach ($values as $value) { $optionData = []; foreach ($this->_assertOptionValues as $assertKey) { if ($value->hasData($assertKey)) { $optionData[$assertKey] = $value->getData($assertKey); } } $result[] = $optionData; } return $result; } return false; }
/** * Duplicate custom options for product * * @param \Magento\Catalog\Model\Product\Option $object * @param int $oldProductId * @param int $newProductId * @return \Magento\Catalog\Model\Product\Option */ public function duplicate(\Magento\Catalog\Model\Product\Option $object, $oldProductId, $newProductId) { $connection = $this->getConnection(); $optionsCond = []; $optionsData = []; // read and prepare original product options $select = $connection->select()->from($this->getTable('catalog_product_option'))->where('product_id = ?', $oldProductId); $query = $connection->query($select); while ($row = $query->fetch()) { $optionsData[$row['option_id']] = $row; $optionsData[$row['option_id']]['product_id'] = $newProductId; unset($optionsData[$row['option_id']]['option_id']); } // insert options to duplicated product foreach ($optionsData as $oId => $data) { $connection->insert($this->getMainTable(), $data); $optionsCond[$oId] = $connection->lastInsertId($this->getMainTable()); } // copy options prefs foreach ($optionsCond as $oldOptionId => $newOptionId) { // title $table = $this->getTable('catalog_product_option_title'); $select = $this->getConnection()->select()->from($table, [new \Zend_Db_Expr($newOptionId), 'store_id', 'title'])->where('option_id = ?', $oldOptionId); $insertSelect = $connection->insertFromSelect($select, $table, ['option_id', 'store_id', 'title'], \Magento\Framework\DB\Adapter\AdapterInterface::INSERT_ON_DUPLICATE); $connection->query($insertSelect); // price $table = $this->getTable('catalog_product_option_price'); $select = $connection->select()->from($table, [new \Zend_Db_Expr($newOptionId), 'store_id', 'price', 'price_type'])->where('option_id = ?', $oldOptionId); $insertSelect = $connection->insertFromSelect($select, $table, ['option_id', 'store_id', 'price', 'price_type'], \Magento\Framework\DB\Adapter\AdapterInterface::INSERT_ON_DUPLICATE); $connection->query($insertSelect); $object->getValueInstance()->duplicate($oldOptionId, $newOptionId); } return $object; }
/** * Enter description here... * * @param Option $option * @return \Magento\Catalog\Model\Resource\Product\Option\Value\Collection */ public function getValuesCollection(Option $option) { $collection = $this->_valueCollectionFactory->create()->addFieldToFilter('option_id', $option->getId())->getValues($option->getStoreId()); return $collection; }
/** * @param \Magento\Framework\Object $processingParams * @param \Magento\Catalog\Model\Product\Option $option * @return array * @throws LocalizedException * @throws ProductException * @throws \Exception * @throws \Magento\Framework\Exception\InputException * @throws \Magento\Framework\Validator\Exception * @throws \Zend_File_Transfer_Exception * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function validate($processingParams, $option) { $upload = $this->httpFactory->create(); $file = $processingParams->getFilesPrefix() . 'options_' . $option->getId() . '_file'; try { $runValidation = $option->getIsRequire() || $upload->isUploaded($file); if (!$runValidation) { throw new \Magento\Framework\Validator\Exception(__('Validation failed. Required options were not filled or file was not uploaded.')); } $fileInfo = $upload->getFileInfo($file)[$file]; $fileInfo['title'] = $fileInfo['name']; } catch (\Magento\Framework\Validator\Exception $e) { throw $e; } catch (\Exception $e) { // when file exceeds the upload_max_filesize, $_FILES is empty if ($this->validateContentLength()) { $value = $this->fileSize->getMaxFileSizeInMb(); throw new LocalizedException(__('The file you uploaded is larger than %1 Megabytes allowed by server', $value)); } else { throw new ProductException(__('Option required.')); } } /** * Option Validations */ $upload = $this->buildImageValidator($upload, $option); /** * Upload process */ $this->initFilesystem(); $userValue = []; if ($upload->isUploaded($file) && $upload->isValid($file)) { $extension = pathinfo(strtolower($fileInfo['name']), PATHINFO_EXTENSION); $fileName = \Magento\MediaStorage\Model\File\Uploader::getCorrectFileName($fileInfo['name']); $dispersion = \Magento\MediaStorage\Model\File\Uploader::getDispretionPath($fileName); $filePath = $dispersion; $tmpDirectory = $this->filesystem->getDirectoryRead(DirectoryList::SYS_TMP); $fileHash = md5($tmpDirectory->readFile($tmpDirectory->getRelativePath($fileInfo['tmp_name']))); $filePath .= '/' . $fileHash . '.' . $extension; $fileFullPath = $this->mediaDirectory->getAbsolutePath($this->quotePath . $filePath); $upload->addFilter(new \Zend_Filter_File_Rename(['target' => $fileFullPath, 'overwrite' => true])); if ($this->product !== null) { $this->product->getTypeInstance()->addFileQueue(['operation' => 'receive_uploaded_file', 'src_name' => $file, 'dst_name' => $fileFullPath, 'uploader' => $upload, 'option' => $this]); } $_width = 0; $_height = 0; if ($tmpDirectory->isReadable($tmpDirectory->getRelativePath($fileInfo['tmp_name']))) { $imageSize = getimagesize($fileInfo['tmp_name']); if ($imageSize) { $_width = $imageSize[0]; $_height = $imageSize[1]; } } $uri = $this->filesystem->getUri(DirectoryList::MEDIA); $userValue = ['type' => $fileInfo['type'], 'title' => $fileInfo['name'], 'quote_path' => $uri . $this->quotePath . $filePath, 'order_path' => $uri . $this->orderPath . $filePath, 'fullpath' => $fileFullPath, 'size' => $fileInfo['size'], 'width' => $_width, 'height' => $_height, 'secret_key' => substr($fileHash, 0, 20)]; } elseif ($upload->getErrors()) { $errors = $this->getValidatorErrors($upload->getErrors(), $fileInfo, $option); if (count($errors) > 0) { throw new LocalizedException(__(implode("\n", $errors))); } } else { throw new LocalizedException(__('Please specify the product\'s required option(s).')); } return $userValue; }
/** * {@inheritdoc} */ protected function getCustomAttributes(\Magento\Catalog\Model\Product\Option $option) { return [Metadata::FILE_EXTENSION => $option->getFileExtension(), Metadata::IMAGE_SIZE_X => $option->getImageSizeX(), Metadata::IMAGE_SIZE_Y => $option->getImageSizeY()]; }
/** * Retrieve additional searchable data from type instance * Using based on product id and store_id data * * @param \Magento\Catalog\Model\Product $product * @return array */ public function getSearchableData($product) { $searchData = []; if ($product->getHasOptions()) { $searchData = $this->_catalogProductOption->getSearchableData($product->getEntityId(), $product->getStoreId()); } return $searchData; }
public function testGetProductSku() { $productSku = 'product-sku'; $this->productMock->expects($this->once())->method('getSku')->willReturn($productSku); $this->assertEquals($productSku, $this->model->getProductSku()); }
/** * Add option to array of product options * * @param Product\Option $option * @return \Magento\Catalog\Model\Product */ public function addOption(Product\Option $option) { $options = (array) $this->getData('options'); $options[] = $option; $option->setProduct($this); $this->setData('options', $options); return $this; }
/** * Retrieve option instance * * @return Product\Option */ public function getOptionInstance() { if (!isset($this->optionInstance)) { $this->optionInstance = $this->optionFactory->create(); $this->optionInstance->setProduct($this); } return $this->optionInstance; }
/** * Add option to array of product options * * @param Product\Option $option * @return \Magento\Catalog\Model\Product */ public function addOption(Product\Option $option) { $this->_options[$option->getId()] = $option; return $this; }
/** * Load option value * * @param \Magento\Catalog\Model\Product\Option $option * @return Metadata[] */ public function read(\Magento\Catalog\Model\Product\Option $option) { $type = $option->getType(); $reader = isset($this->valueReaders[$type]) ? $this->valueReaders[$type] : $this->valueReaders['default']; return $reader->read($option); }