本文整理汇总了PHP中Magento\Catalog\Model\ProductFactory类的典型用法代码示例。如果您正苦于以下问题:PHP ProductFactory类的具体用法?PHP ProductFactory怎么用?PHP ProductFactory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ProductFactory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: setUp
protected function setUp()
{
$this->productBuilder = $this->getMock('Magento\\Catalog\\Controller\\Adminhtml\\Product\\Builder', ['build'], [], '', false);
$this->product = $this->getMockBuilder('Magento\\Catalog\\Model\\Product')->disableOriginalConstructor()->setMethods(['addData', 'getSku', 'getTypeId', 'getStoreId', '__sleep', '__wakeup', 'getAttributes', 'setAttributeSetId'])->getMock();
$this->product->expects($this->any())->method('getTypeId')->will($this->returnValue('simple'));
$this->product->expects($this->any())->method('getStoreId')->will($this->returnValue('1'));
$this->product->expects($this->any())->method('getAttributes')->will($this->returnValue([]));
$this->productBuilder->expects($this->any())->method('build')->will($this->returnValue($this->product));
$this->resultPage = $this->getMockBuilder('Magento\\Backend\\Model\\View\\Result\\Page')->disableOriginalConstructor()->getMock();
$resultPageFactory = $this->getMockBuilder('Magento\\Framework\\View\\Result\\PageFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock();
$resultPageFactory->expects($this->any())->method('create')->willReturn($this->resultPage);
$this->resultForward = $this->getMockBuilder('Magento\\Backend\\Model\\View\\Result\\Forward')->disableOriginalConstructor()->getMock();
$resultForwardFactory = $this->getMockBuilder('Magento\\Backend\\Model\\View\\Result\\ForwardFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock();
$resultForwardFactory->expects($this->any())->method('create')->willReturn($this->resultForward);
$this->resultPage->expects($this->any())->method('getLayout')->willReturn($this->layout);
$this->resultRedirectFactory = $this->getMock('Magento\\Backend\\Model\\View\\Result\\RedirectFactory', ['create'], [], '', false);
$this->resultRedirect = $this->getMock('Magento\\Backend\\Model\\View\\Result\\Redirect', [], [], '', false);
$this->resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->resultRedirect);
$this->initializationHelper = $this->getMock('Magento\\Catalog\\Controller\\Adminhtml\\Product\\Initialization\\Helper', [], [], '', false);
$this->productFactory = $this->getMockBuilder('Magento\\Catalog\\Model\\ProductFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock();
$this->productFactory->expects($this->any())->method('create')->willReturn($this->product);
$this->resultJson = $this->getMock('Magento\\Framework\\Controller\\Result\\Json', [], [], '', false);
$this->resultJsonFactory = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\JsonFactory')->disableOriginalConstructor()->setMethods(['create'])->getMock();
$this->resultJsonFactory->expects($this->any())->method('create')->willReturn($this->resultJson);
$additionalParams = ['resultRedirectFactory' => $this->resultRedirectFactory];
$this->action = (new ObjectManagerHelper($this))->getObject('Magento\\Catalog\\Controller\\Adminhtml\\Product\\Validate', ['context' => $this->initContext($additionalParams), 'productBuilder' => $this->productBuilder, 'resultPageFactory' => $resultPageFactory, 'resultForwardFactory' => $resultForwardFactory, 'initializationHelper' => $this->initializationHelper, 'resultJsonFactory' => $this->resultJsonFactory, 'productFactory' => $this->productFactory]);
}
示例2: setUp
protected function setUp()
{
$this->product = $this->getMock('Magento\\Catalog\\Model\\Product', [], [], '', false);
$this->productFactory = $this->getMock('Magento\\Catalog\\Model\\ProductFactory', ['create'], [], '', false);
$this->productFactory->expects($this->any())->method('create')->will($this->returnValue($this->product));
$this->visibility = $this->getMock('Magento\\Catalog\\Model\\Product\\Visibility', [], [], '', false);
$this->timezone = $this->getMock('Magento\\Framework\\Stdlib\\DateTime\\Timezone', [], [], '', false);
$this->objectManagerHelper = new ObjectManagerHelper($this);
$this->newProducts = $this->objectManagerHelper->getObject('Magento\\Catalog\\Model\\Rss\\Product\\NewProducts', ['productFactory' => $this->productFactory, 'visibility' => $this->visibility, 'localeDate' => $this->timezone]);
}
示例3: _getProduct
/**
* Get or create new instance of product
*
* @return \Magento\Catalog\Model\Product
*/
private function _getProduct()
{
if (!$this->hasData('product')) {
$this->setProduct($this->_productFactory->create());
}
return $this->getProduct();
}
示例4: _validateProductVariations
/**
* Product variations attributes validation
*
* @param Product $parentProduct
* @param array $products
* @param RequestInterface $request
* @return array
*/
protected function _validateProductVariations(Product $parentProduct, array $products, RequestInterface $request)
{
$this->eventManager->dispatch('catalog_product_validate_variations_before', ['product' => $parentProduct, 'variations' => $products]);
$validationResult = [];
foreach ($products as $productData) {
$product = $this->productFactory->create();
$product->setData('_edit_mode', true);
$storeId = $request->getParam('store');
if ($storeId) {
$product->setStoreId($storeId);
}
$product->setAttributeSetId($parentProduct->getAttributeSetId());
$product->addData($this->getRequiredDataFromProduct($parentProduct));
$product->addData($productData);
$product->setCollectExceptionMessages(true);
$configurableAttribute = [];
$encodedData = $productData['configurable_attribute'];
if ($encodedData) {
$configurableAttribute = $this->jsonHelper->jsonDecode($encodedData);
}
$configurableAttribute = implode('-', $configurableAttribute);
$errorAttributes = $product->validate();
if (is_array($errorAttributes)) {
foreach ($errorAttributes as $attributeCode => $result) {
if (is_string($result)) {
$key = 'variations-matrix-' . $configurableAttribute . '-' . $attributeCode;
$validationResult[$key] = $result;
}
}
}
}
return $validationResult;
}
示例5: _toHtml
/**
* @return string
*/
protected function _toHtml()
{
$storeId = $this->_getStoreId();
$storeModel = $this->_storeManager->getStore($storeId);
$newUrl = $this->_urlBuilder->getUrl('rss/catalog/new/store_id/' . $storeId);
$title = __('New Products from %1', $storeModel->getFrontendName());
$lang = $this->_scopeConfig->getValue('general/locale/code', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeModel);
/** @var $rssObj \Magento\Rss\Model\Rss */
$rssObj = $this->_rssFactory->create();
$rssObj->_addHeader(array('title' => $title, 'description' => $title, 'link' => $newUrl, 'charset' => 'UTF-8', 'language' => $lang));
/** @var $product \Magento\Catalog\Model\Product */
$product = $this->_productFactory->create();
$todayStartOfDayDate = $this->_localeDate->date()->setTime('00:00:00')->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT);
$todayEndOfDayDate = $this->_localeDate->date()->setTime('23:59:59')->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT);
/** @var $products \Magento\Catalog\Model\Resource\Product\Collection */
$products = $product->getCollection();
$products->setStoreId($storeId);
$products->addStoreFilter()->addAttributeToFilter('news_from_date', array('or' => array(0 => array('date' => true, 'to' => $todayEndOfDayDate), 1 => array('is' => new \Zend_Db_Expr('null')))), 'left')->addAttributeToFilter('news_to_date', array('or' => array(0 => array('date' => true, 'from' => $todayStartOfDayDate), 1 => array('is' => new \Zend_Db_Expr('null')))), 'left')->addAttributeToFilter(array(array('attribute' => 'news_from_date', 'is' => new \Zend_Db_Expr('not null')), array('attribute' => 'news_to_date', 'is' => new \Zend_Db_Expr('not null'))))->addAttributeToSort('news_from_date', 'desc')->addAttributeToSelect(array('name', 'short_description', 'description'), 'inner')->addAttributeToSelect(array('price', 'special_price', 'special_from_date', 'special_to_date', 'msrp_enabled', 'msrp_display_actual_price_type', 'msrp', 'thumbnail'), 'left')->applyFrontendPriceLimitations();
$products->setVisibility($this->_visibility->getVisibleInCatalogIds());
/*
using resource iterator to load the data one by one
instead of loading all at the same time. loading all data at the same time can cause the big memory allocation.
*/
$this->_resourceIterator->walk($products->getSelect(), array(array($this, 'addNewItemXmlCallback')), array('rssObj' => $rssObj, 'product' => $product));
return $rssObj->createRssXml();
}
示例6: create
/**
* Populate product with variation of attributes
*
* @param \Magento\Catalog\Api\Data\ProductInterface $product
* @param array $attributes
* @return \Magento\Catalog\Api\Data\ProductInterface[]
*/
public function create(\Magento\Catalog\Api\Data\ProductInterface $product, $attributes)
{
$variations = $this->variationMatrix->getVariations($attributes);
$products = [];
foreach ($variations as $variation) {
$price = $product->getPrice();
/** @var \Magento\Catalog\Model\Product $item */
$item = $this->productFactory->create();
$item->setData($product->getData());
$suffix = '';
foreach ($variation as $attributeId => $valueInfo) {
$suffix .= '-' . $valueInfo['value'];
$customAttribute = $this->customAttributeFactory->create()->setAttributeCode($attributes[$attributeId]['attribute_code'])->setValue($valueInfo['value']);
$customAttributes = array_merge($item->getCustomAttributes(), [$attributes[$attributeId]['attribute_code'] => $customAttribute]);
$item->setData('custom_attributes', $customAttributes);
$priceInfo = $valueInfo['price'];
$price += (!empty($priceInfo['is_percent']) ? $product->getPrice() / 100.0 : 1.0) * $priceInfo['pricing_value'];
}
$item->setPrice($price);
$item->setName($product->getName() . $suffix);
$item->setSku($product->getSku() . $suffix);
$item->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE);
$products[] = $item;
}
return $products;
}
示例7: copy
/**
* Create product duplicate
*
* @param \Magento\Catalog\Model\Product $product
* @return \Magento\Catalog\Model\Product
*/
public function copy(\Magento\Catalog\Model\Product $product)
{
$product->getWebsiteIds();
$product->getCategoryIds();
$duplicate = $this->productFactory->create();
$duplicate->setData($product->getData());
$duplicate->setIsDuplicate(true);
$duplicate->setOriginalId($product->getId());
$duplicate->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
$duplicate->setCreatedAt(null);
$duplicate->setUpdatedAt(null);
$duplicate->setId(null);
$duplicate->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID);
$this->copyConstructor->build($product, $duplicate);
$isDuplicateSaved = false;
do {
$urlKey = $duplicate->getUrlKey();
$urlKey = preg_match('/(.*)-(\\d+)$/', $urlKey, $matches) ? $matches[1] . '-' . ($matches[2] + 1) : $urlKey . '-1';
$duplicate->setUrlKey($urlKey);
try {
$duplicate->save();
$isDuplicateSaved = true;
} catch (DuplicateEntryException $e) {
}
} while (!$isDuplicateSaved);
$product->getOptionInstance()->duplicate($product->getId(), $duplicate->getId());
$product->getResource()->duplicate($product->getId(), $duplicate->getId());
return $duplicate;
}
示例8: getLoadedProductCollection
/**
* Products collection.
*
* @return array
*/
public function getLoadedProductCollection()
{
$productsToDisplay = [];
$mode = $this->getRequest()->getActionName();
$customerId = $this->getRequest()->getParam('customer_id');
$limit = $this->recommnededHelper->getDisplayLimitByMode($mode);
//login customer to receive the recent products
$session = $this->sessionFactory->create();
$isLoggedIn = $session->loginById($customerId);
$collection = $this->viewed;
$productItems = $collection->getItemsCollection()->setPageSize($limit);
//get the product ids from items collection
$productIds = $productItems->getColumnValues('product_id');
//get product collection to check for salable
$productCollection = $this->productFactory->create()->getCollection()->addAttributeToSelect('*')->addFieldToFilter('entity_id', ['in' => $productIds]);
//show products only if is salable
foreach ($productCollection as $product) {
if ($product->isSalable()) {
$productsToDisplay[$product->getId()] = $product;
}
}
$this->helper->log('Recentlyviewed customer : ' . $customerId . ', mode ' . $mode . ', limit : ' . $limit . ', items found : ' . count($productItems) . ', is customer logged in : ' . $isLoggedIn . ', products :' . count($productsToDisplay));
$session->logout();
return $productsToDisplay;
}
示例9: execute
/**
* Get associated grouped products grid popup
*
* @return void
*/
public function execute()
{
$productId = (int) $this->getRequest()->getParam('id');
/** @var $product \Magento\Catalog\Model\Product */
$product = $this->factory->create();
$product->setStoreId($this->getRequest()->getParam('store', 0));
$typeId = $this->getRequest()->getParam('type');
if (!$productId && $typeId) {
$product->setTypeId($typeId);
}
$product->setData('_edit_mode', true);
if ($productId) {
try {
$product->load($productId);
} catch (\Exception $e) {
$product->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE);
$this->logger->logException($e);
}
}
$setId = (int) $this->getRequest()->getParam('set');
if ($setId) {
$product->setAttributeSetId($setId);
}
$this->registry->register('current_product', $product);
$this->_view->loadLayout(false);
$this->_view->renderLayout();
}
示例10: getTreeArray
/**
* Get categories tree as recursive array
*
* @param int $parentId
* @param bool $asJson
* @param int $recursionLevel
* @return array
*/
public function getTreeArray($parentId = null, $asJson = false, $recursionLevel = 3)
{
$productId = $this->_request->getParam('product');
if ($productId) {
$product = $this->_productFactory->create()->setId($productId);
$this->_allowedCategoryIds = $product->getCategoryIds();
unset($product);
}
$result = [];
if ($parentId) {
try {
$category = $this->categoryRepository->get($parentId);
} catch (NoSuchEntityException $e) {
$category = null;
}
if ($category) {
$tree = $this->_getNodesArray($this->getNode($category, $recursionLevel));
if (!empty($tree) && !empty($tree['children'])) {
$result = $tree['children'];
}
}
} else {
$result = $this->_getNodesArray($this->getRoot(null, $recursionLevel));
}
if ($asJson) {
return $this->_jsonEncoder->encode($result);
}
$this->_allowedCategoryIds = [];
return $result;
}
示例11: copy
/**
* Create product duplicate
*
* @param \Magento\Catalog\Model\Product $product
* @return \Magento\Catalog\Model\Product
*/
public function copy(\Magento\Catalog\Model\Product $product)
{
$product->getWebsiteIds();
$product->getCategoryIds();
/** @var \Magento\Catalog\Model\Product $duplicate */
$duplicate = $this->productFactory->create();
$duplicate->setData($product->getData());
$duplicate->setOptions([]);
$duplicate->setIsDuplicate(true);
$duplicate->setOriginalId($product->getEntityId());
$duplicate->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
$duplicate->setCreatedAt(null);
$duplicate->setUpdatedAt(null);
$duplicate->setId(null);
$duplicate->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID);
$this->copyConstructor->build($product, $duplicate);
$isDuplicateSaved = false;
do {
$urlKey = $duplicate->getUrlKey();
$urlKey = preg_match('/(.*)-(\\d+)$/', $urlKey, $matches) ? $matches[1] . '-' . ($matches[2] + 1) : $urlKey . '-1';
$duplicate->setUrlKey($urlKey);
try {
$duplicate->save();
$isDuplicateSaved = true;
} catch (\Magento\Framework\Exception\AlreadyExistsException $e) {
}
} while (!$isDuplicateSaved);
$this->getOptionRepository()->duplicate($product, $duplicate);
$metadata = $this->getMetadataPool()->getMetadata(ProductInterface::class);
$product->getResource()->duplicate($product->getData($metadata->getLinkField()), $duplicate->getData($metadata->getLinkField()));
return $duplicate;
}
示例12: execute
/**
* Get associated grouped products grid popup
*
* @return \Magento\Framework\View\Result\Layout
*/
public function execute()
{
$productId = (int) $this->getRequest()->getParam('id');
/** @var $product \Magento\Catalog\Model\Product */
$product = $this->factory->create();
$product->setStoreId($this->getRequest()->getParam('store', 0));
$typeId = $this->getRequest()->getParam('type');
if (!$productId && $typeId) {
$product->setTypeId($typeId);
}
$product->setData('_edit_mode', true);
if ($productId) {
try {
$product->load($productId);
} catch (\Exception $e) {
$product->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE);
$this->logger->critical($e);
}
}
$setId = (int) $this->getRequest()->getParam('set');
if ($setId) {
$product->setAttributeSetId($setId);
}
$this->registry->register('current_product', $product);
/** @var \Magento\Framework\View\Result\Layout $resultLayout */
$resultLayout = $this->resultFactory->create(ResultFactory::TYPE_LAYOUT);
return $resultLayout;
}
示例13: build
/**
* Build product based on user request
*
* @param RequestInterface $request
* @return \Magento\Catalog\Model\Product
*/
public function build(RequestInterface $request)
{
$productId = (int) $request->getParam('id');
/** @var $product \Magento\Catalog\Model\Product */
$product = $this->productFactory->create();
$product->setStoreId($request->getParam('store', 0));
$typeId = $request->getParam('type');
if (!$productId && $typeId) {
$product->setTypeId($typeId);
}
$product->setData('_edit_mode', true);
if ($productId) {
try {
$product->load($productId);
} catch (\Exception $e) {
$product->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE);
$this->logger->critical($e);
}
}
$setId = (int) $request->getParam('set');
if ($setId) {
$product->setAttributeSetId($setId);
}
$this->registry->register('product', $product);
$this->registry->register('current_product', $product);
$this->wysiwygConfig->setStoreId($request->getParam('store'));
return $product;
}
示例14: run
/**
* {@inheritdoc}
*/
public function run()
{
$this->logger->log('Installing product links:');
$entityFileAssociation = ['related', 'upsell', 'crosssell'];
foreach ($this->postInstaller->getInstalledModuleList() as $moduleName) {
foreach ($entityFileAssociation as $linkType) {
$fileName = substr($moduleName, strpos($moduleName, "_") + 1) . '/Links/' . $linkType . '.csv';
$fileName = $this->fixtureHelper->getPath($fileName);
if (!$fileName) {
continue;
}
/** @var \Magento\SampleData\Helper\Csv\ReaderFactory $csvReader */
$csvReader = $this->csvReaderFactory->create(['fileName' => $fileName, 'mode' => 'r']);
foreach ($csvReader as $row) {
/** @var \Magento\Catalog\Model\Product $product */
$product = $this->productFactory->create();
$productId = $product->getIdBySku($row['sku']);
if (!$productId) {
continue;
}
$product->setId($productId);
$links = [$linkType => []];
foreach (explode("\n", $row['linked_sku']) as $linkedProductSku) {
$linkedProductId = $product->getIdBySku($linkedProductSku);
if ($linkedProductId) {
$links[$linkType][$linkedProductId] = [];
}
}
$this->linksInitializer->initializeLinks($product, $links);
$product->getLinkInstance()->saveProductRelations($product);
$this->logger->logInline('.');
}
}
}
}
示例15: getMediaAttributes
/**
* @return array
*/
public function getMediaAttributes()
{
static $simple;
if (empty($simple)) {
$simple = $this->productFactory->create()->setTypeId(Type::TYPE_SIMPLE)->getMediaAttributes();
}
return $simple;
}