本文整理汇总了PHP中Magento\Framework\Object::getStoreId方法的典型用法代码示例。如果您正苦于以下问题:PHP Object::getStoreId方法的具体用法?PHP Object::getStoreId怎么用?PHP Object::getStoreId使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Magento\Framework\Object
的用法示例。
在下文中一共展示了Object::getStoreId方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: render
/**
* {@inheritdoc}
*/
public function render(\Magento\Framework\Object $row)
{
if (!$row->getData($this->getColumn()->getIndex())) {
return null;
}
return '<a title="' . __('Edit Store View') . '"
href="' . $this->getUrl('adminhtml/*/editStore', ['store_id' => $row->getStoreId()]) . '">' . $this->escapeHtml($row->getData($this->getColumn()->getIndex())) . '</a>';
}
示例2: render
/**
* Render review type
*
* @param \Magento\Framework\Object $row
* @return string
*/
public function render(\Magento\Framework\Object $row)
{
if ($row->getCustomerId()) {
return __('Customer');
}
if ($row->getStoreId() == \Magento\Store\Model\Store::DEFAULT_STORE_ID) {
return __('Administrator');
}
return __('Guest');
}
示例3: beforeSave
/**
* Before save
*
* @param \Magento\Framework\Object $object
* @return $this
*/
public function beforeSave($object)
{
if ($object->getId()) {
return $this;
}
if (!$object->hasStoreId()) {
$object->setStoreId($this->_storeManager->getStore()->getId());
}
if (!$object->hasData('created_in')) {
$object->setData('created_in', $this->_storeManager->getStore($object->getStoreId())->getName());
}
return $this;
}
示例4: _setAttributeValue
/**
* Set attribute value
*
* @param \Magento\Framework\Object $object
* @return $this
*/
protected function _setAttributeValue($object)
{
$storeId = $object->getStoreId();
$defaultStoreId = \Magento\Store\Model\Store::DEFAULT_STORE_ID;
if (!isset($this->_entityAttributeValues[$object->getId()])) {
return $this;
}
$productValues = $this->_entityAttributeValues[$object->getId()];
if (!isset($productValues[$storeId]) && !isset($productValues[$defaultStoreId])) {
return $this;
}
$value = isset($productValues[$storeId]) ? $productValues[$storeId] : $productValues[$defaultStoreId];
$value = $this->_prepareDatetimeValue($value, $object);
$value = $this->_prepareMultiselectValue($value, $object);
$object->setData($this->getAttribute(), $value);
return $this;
}
示例5: _beforeSave
/**
* Check customer scope, email and confirmation key before saving
*
* @param \Magento\Framework\Object $customer
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function _beforeSave(\Magento\Framework\Object $customer)
{
/** @var \Magento\Customer\Model\Customer $customer */
if ($customer->getStoreId() === null) {
$customer->setStoreId($this->storeManager->getStore()->getId());
}
$customer->getGroupId();
parent::_beforeSave($customer);
if (!$customer->getEmail()) {
throw new ValidatorException(__('Please enter a customer email.'));
}
$adapter = $this->_getWriteAdapter();
$bind = ['email' => $customer->getEmail()];
$select = $adapter->select()->from($this->getEntityTable(), [$this->getEntityIdField()])->where('email = :email');
if ($customer->getSharingConfig()->isWebsiteScope()) {
$bind['website_id'] = (int) $customer->getWebsiteId();
$select->where('website_id = :website_id');
}
if ($customer->getId()) {
$bind['entity_id'] = (int) $customer->getId();
$select->where('entity_id != :entity_id');
}
$result = $adapter->fetchOne($select, $bind);
if ($result) {
throw new AlreadyExistsException(__('A customer with the same email already exists in an associated website.'));
}
// set confirmation key logic
if ($customer->getForceConfirmed()) {
$customer->setConfirmation(null);
} elseif (!$customer->getId() && $customer->isConfirmationRequired()) {
$customer->setConfirmation($customer->getRandomConfirmationKey());
}
// remove customer confirmation key from database, if empty
if (!$customer->getConfirmation()) {
$customer->setConfirmation(null);
}
$this->_validate($customer);
return $this;
}
示例6: setNewIncrementId
/**
* Set new increment id to object
*
* @param \Magento\Framework\Object $object
* @return $this
*/
public function setNewIncrementId(\Magento\Framework\Object $object)
{
if ($object->getIncrementId()) {
return $this;
}
$incrementId = $this->getEntityType()->fetchNewIncrementId($object->getStoreId());
if ($incrementId !== false) {
$object->setIncrementId($incrementId);
}
return $this;
}
示例7: setRequest
/**
* Prepare and set request in property of current instance
*
* @param \Magento\Framework\Object $request
* @return $this
*/
public function setRequest(\Magento\Framework\Object $request)
{
$this->_request = $request;
$this->setStore($request->getStoreId());
$requestObject = new \Magento\Framework\Object();
$requestObject->setIsGenerateLabelReturn($request->getIsGenerateLabelReturn());
$requestObject->setStoreId($request->getStoreId());
if ($request->getLimitMethod()) {
$requestObject->setService($request->getLimitMethod());
}
$requestObject = $this->_addParams($requestObject);
if ($request->getDestPostcode()) {
$requestObject->setDestPostal($request->getDestPostcode());
}
$requestObject->setOrigCountry($this->_getDefaultValue($request->getOrigCountry(), Shipment::XML_PATH_STORE_COUNTRY_ID))->setOrigCountryId($this->_getDefaultValue($request->getOrigCountryId(), Shipment::XML_PATH_STORE_COUNTRY_ID));
$shippingWeight = $request->getPackageWeight();
$requestObject->setValue(round($request->getPackageValue(), 2))->setValueWithDiscount($request->getPackageValueWithDiscount())->setCustomsValue($request->getPackageCustomsValue())->setDestStreet($this->string->substr(str_replace("\n", '', $request->getDestStreet()), 0, 35))->setDestStreetLine2($request->getDestStreetLine2())->setDestCity($request->getDestCity())->setOrigCompanyName($request->getOrigCompanyName())->setOrigCity($request->getOrigCity())->setOrigPhoneNumber($request->getOrigPhoneNumber())->setOrigPersonName($request->getOrigPersonName())->setOrigEmail($this->_scopeConfig->getValue('trans_email/ident_general/email', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $requestObject->getStoreId()))->setOrigCity($request->getOrigCity())->setOrigPostal($request->getOrigPostal())->setOrigStreetLine2($request->getOrigStreetLine2())->setDestPhoneNumber($request->getDestPhoneNumber())->setDestPersonName($request->getDestPersonName())->setDestCompanyName($request->getDestCompanyName());
$originStreet2 = $this->_scopeConfig->getValue(Shipment::XML_PATH_STORE_ADDRESS2, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $requestObject->getStoreId());
$requestObject->setOrigStreet($request->getOrigStreet() ? $request->getOrigStreet() : $originStreet2);
if (is_numeric($request->getOrigState())) {
$requestObject->setOrigState($this->_regionFactory->create()->load($request->getOrigState())->getCode());
} else {
$requestObject->setOrigState($request->getOrigState());
}
if ($request->getDestCountryId()) {
$destCountry = $request->getDestCountryId();
} else {
$destCountry = self::USA_COUNTRY_ID;
}
// for DHL, Puerto Rico state for US will assume as Puerto Rico country
// for Puerto Rico, dhl will ship as international
if ($destCountry == self::USA_COUNTRY_ID && ($request->getDestPostcode() == '00912' || $request->getDestRegionCode() == self::PUERTORICO_COUNTRY_ID)) {
$destCountry = self::PUERTORICO_COUNTRY_ID;
}
$requestObject->setDestCountryId($destCountry)->setDestState($request->getDestRegionCode())->setWeight($shippingWeight)->setFreeMethodWeight($request->getFreeMethodWeight())->setOrderShipment($request->getOrderShipment());
if ($request->getPackageId()) {
$requestObject->setPackageId($request->getPackageId());
}
$requestObject->setBaseSubtotalInclTax($request->getBaseSubtotalInclTax());
$this->setRawRequest($requestObject);
return $this;
}
示例8: registerIds
/**
* Add information about product ids to visitor/customer
*
* @param \Magento\Framework\Object|\Magento\Reports\Model\Product\Index\AbstractIndex $object
* @param array $productIds
* @return $this
*/
public function registerIds(\Magento\Framework\Object $object, $productIds)
{
$row = ['visitor_id' => $object->getVisitorId(), 'customer_id' => $object->getCustomerId(), 'store_id' => $object->getStoreId()];
$addedAt = (new \DateTime())->getTimestamp();
$data = [];
foreach ($productIds as $productId) {
$productId = (int) $productId;
if ($productId) {
$row['product_id'] = $productId;
$row['added_at'] = $this->dateTime->formatDate($addedAt);
$data[] = $row;
}
$addedAt -= $addedAt > 0 ? 1 : 0;
}
$matchFields = ['product_id', 'store_id'];
foreach ($data as $row) {
$this->_resourceHelper->mergeVisitorProductIndex($this->getMainTable(), $row, $matchFields);
}
return $this;
}
示例9: _deleteAttributes
/**
* Delete entity attribute values
*
* @param \Magento\Framework\Object $object
* @param string $table
* @param array $info
* @return $this
*/
protected function _deleteAttributes($object, $table, $info)
{
$adapter = $this->_getWriteAdapter();
$entityIdField = $this->getEntityIdField();
$globalValues = array();
$websiteAttributes = array();
$storeAttributes = array();
/**
* Separate attributes by scope
*/
foreach ($info as $itemData) {
$attribute = $this->getAttribute($itemData['attribute_id']);
if ($attribute->isScopeStore()) {
$storeAttributes[] = (int) $itemData['attribute_id'];
} elseif ($attribute->isScopeWebsite()) {
$websiteAttributes[] = (int) $itemData['attribute_id'];
} elseif ($itemData['value_id'] !== null) {
$globalValues[] = (int) $itemData['value_id'];
}
}
/**
* Delete global scope attributes
*/
if (!empty($globalValues)) {
$adapter->delete($table, array('value_id IN (?)' => $globalValues));
}
$condition = array($entityIdField . ' = ?' => $object->getId(), 'entity_type_id = ?' => $object->getEntityTypeId());
/**
* Delete website scope attributes
*/
if (!empty($websiteAttributes)) {
$storeIds = $object->getWebsiteStoreIds();
if (!empty($storeIds)) {
$delCondition = $condition;
$delCondition['attribute_id IN(?)'] = $websiteAttributes;
$delCondition['store_id IN(?)'] = $storeIds;
$adapter->delete($table, $delCondition);
}
}
/**
* Delete store scope attributes
*/
if (!empty($storeAttributes)) {
$delCondition = $condition;
$delCondition['attribute_id IN(?)'] = $storeAttributes;
$delCondition['store_id = ?'] = (int) $object->getStoreId();
$adapter->delete($table, $delCondition);
}
return $this;
}
示例10: _formShipmentRequest
/**
* Form array with appropriate structure for shipment request
*
* @param \Magento\Framework\Object $request
* @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
protected function _formShipmentRequest(\Magento\Framework\Object $request)
{
if ($request->getReferenceData()) {
$referenceData = $request->getReferenceData() . $request->getPackageId();
} else {
$referenceData = 'Order #' . $request->getOrderShipment()->getOrder()->getIncrementId() . ' P' . $request->getPackageId();
}
$packageParams = $request->getPackageParams();
$customsValue = $packageParams->getCustomsValue();
$height = $packageParams->getHeight();
$width = $packageParams->getWidth();
$length = $packageParams->getLength();
$weightUnits = $packageParams->getWeightUnits() == \Zend_Measure_Weight::POUND ? 'LB' : 'KG';
$dimensionsUnits = $packageParams->getDimensionUnits() == \Zend_Measure_Length::INCH ? 'IN' : 'CM';
$unitPrice = 0;
$itemsQty = 0;
$itemsDesc = [];
$countriesOfManufacture = [];
$productIds = [];
$packageItems = $request->getPackageItems();
foreach ($packageItems as $itemShipment) {
$item = new \Magento\Framework\Object();
$item->setData($itemShipment);
$unitPrice += $item->getPrice();
$itemsQty += $item->getQty();
$itemsDesc[] = $item->getName();
$productIds[] = $item->getProductId();
}
// get countries of manufacture
$productCollection = $this->_productCollectionFactory->create()->addStoreFilter($request->getStoreId())->addFieldToFilter('entity_id', ['in' => $productIds])->addAttributeToSelect('country_of_manufacture');
foreach ($productCollection as $product) {
$countriesOfManufacture[] = $product->getCountryOfManufacture();
}
$paymentType = $request->getIsReturn() ? 'RECIPIENT' : 'SENDER';
$requestClient = ['RequestedShipment' => ['ShipTimestamp' => time(), 'DropoffType' => $this->getConfigData('dropoff'), 'PackagingType' => $request->getPackagingType(), 'ServiceType' => $request->getShippingMethod(), 'Shipper' => ['Contact' => ['PersonName' => $request->getShipperContactPersonName(), 'CompanyName' => $request->getShipperContactCompanyName(), 'PhoneNumber' => $request->getShipperContactPhoneNumber()], 'Address' => ['StreetLines' => [$request->getShipperAddressStreet()], 'City' => $request->getShipperAddressCity(), 'StateOrProvinceCode' => $request->getShipperAddressStateOrProvinceCode(), 'PostalCode' => $request->getShipperAddressPostalCode(), 'CountryCode' => $request->getShipperAddressCountryCode()]], 'Recipient' => ['Contact' => ['PersonName' => $request->getRecipientContactPersonName(), 'CompanyName' => $request->getRecipientContactCompanyName(), 'PhoneNumber' => $request->getRecipientContactPhoneNumber()], 'Address' => ['StreetLines' => [$request->getRecipientAddressStreet()], 'City' => $request->getRecipientAddressCity(), 'StateOrProvinceCode' => $request->getRecipientAddressStateOrProvinceCode(), 'PostalCode' => $request->getRecipientAddressPostalCode(), 'CountryCode' => $request->getRecipientAddressCountryCode(), 'Residential' => (bool) $this->getConfigData('residence_delivery')]], 'ShippingChargesPayment' => ['PaymentType' => $paymentType, 'Payor' => ['AccountNumber' => $this->getConfigData('account'), 'CountryCode' => $this->_scopeConfig->getValue(\Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_COUNTRY_ID, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $request->getStoreId())]], 'LabelSpecification' => ['LabelFormatType' => 'COMMON2D', 'ImageType' => 'PNG', 'LabelStockType' => 'PAPER_8.5X11_TOP_HALF_LABEL'], 'RateRequestTypes' => ['ACCOUNT'], 'PackageCount' => 1, 'RequestedPackageLineItems' => ['SequenceNumber' => '1', 'Weight' => ['Units' => $weightUnits, 'Value' => $request->getPackageWeight()], 'CustomerReferences' => ['CustomerReferenceType' => 'CUSTOMER_REFERENCE', 'Value' => $referenceData], 'SpecialServicesRequested' => ['SpecialServiceTypes' => 'SIGNATURE_OPTION', 'SignatureOptionDetail' => ['OptionType' => $packageParams->getDeliveryConfirmation()]]]]];
// for international shipping
if ($request->getShipperAddressCountryCode() != $request->getRecipientAddressCountryCode()) {
$requestClient['RequestedShipment']['CustomsClearanceDetail'] = ['CustomsValue' => ['Currency' => $request->getBaseCurrencyCode(), 'Amount' => $customsValue], 'DutiesPayment' => ['PaymentType' => $paymentType, 'Payor' => ['AccountNumber' => $this->getConfigData('account'), 'CountryCode' => $this->_scopeConfig->getValue(\Magento\Sales\Model\Order\Shipment::XML_PATH_STORE_COUNTRY_ID, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $request->getStoreId())]], 'Commodities' => ['Weight' => ['Units' => $weightUnits, 'Value' => $request->getPackageWeight()], 'NumberOfPieces' => 1, 'CountryOfManufacture' => implode(',', array_unique($countriesOfManufacture)), 'Description' => implode(', ', $itemsDesc), 'Quantity' => ceil($itemsQty), 'QuantityUnits' => 'pcs', 'UnitPrice' => ['Currency' => $request->getBaseCurrencyCode(), 'Amount' => $unitPrice], 'CustomsValue' => ['Currency' => $request->getBaseCurrencyCode(), 'Amount' => $customsValue]]];
}
if ($request->getMasterTrackingId()) {
$requestClient['RequestedShipment']['MasterTrackingId'] = $request->getMasterTrackingId();
}
// set dimensions
if ($length || $width || $height) {
$requestClient['RequestedShipment']['RequestedPackageLineItems']['Dimensions'] = [];
$dimenssions =& $requestClient['RequestedShipment']['RequestedPackageLineItems']['Dimensions'];
$dimenssions['Length'] = $length;
$dimenssions['Width'] = $width;
$dimenssions['Height'] = $height;
$dimenssions['Units'] = $dimensionsUnits;
}
return $this->_getAuthDetails() + $requestClient;
}
示例11: registerItemSale
/**
* Subtract ordered qty for product
*
* @param \Magento\Framework\Object $item
* @return $this
* @throws \Magento\Framework\Model\Exception
*/
public function registerItemSale(\Magento\Framework\Object $item)
{
$productId = $item->getProductId();
if (!$productId) {
throw new \Magento\Framework\Model\Exception(__('We cannot specify a product identifier for the order item.'));
}
/** @var Item $stockItem */
$stockItem = $this->_stockItemFactory->create()->loadByProduct($productId);
if ($this->stockItemService->isQty($this->getProductType($productId))) {
if ($item->getStoreId()) {
$stockItem->setStoreId($item->getStoreId());
}
if ($stockItem->checkQty($item->getQtyOrdered())) {
$stockItem->subtractQty($item->getQtyOrdered());
$stockItem->save();
}
}
return $this;
}
示例12: getCategoryParentPath
/**
* Retrieve category parent path
*
* @param \Magento\Framework\Object $category
* @return string
*/
public function getCategoryParentPath(\Magento\Framework\Object $category)
{
$store = $this->_storeManager->getStore($category->getStoreId());
if ($category->getId() == $store->getRootCategoryId()) {
return '';
} elseif ($category->getParentId() == 1 || $category->getParentId() == $store->getRootCategoryId()) {
return '';
}
$parentCategory = $this->getCategory($category->getParentId(), $store->getId());
return $parentCategory->getUrlPath() . '/';
}
示例13: getEntityAttributeCodes
/**
* Get codes of all entity type attributes
*
* @param mixed $entityType
* @param \Magento\Framework\Object $object
* @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function getEntityAttributeCodes($entityType, $object = null)
{
$entityType = $this->getEntityType($entityType);
$attributeSetId = 0;
$storeId = 0;
if ($object instanceof \Magento\Framework\Object) {
$attributeSetId = $object->getAttributeSetId() ?: $attributeSetId;
$storeId = $object->getStoreId() ?: $storeId;
}
$cacheKey = self::ATTRIBUTES_CODES_CACHE_ID . $entityType->getId() . '-' . $storeId . '-' . $attributeSetId;
if (isset($this->_attributeCodes[$cacheKey])) {
return $this->_attributeCodes[$cacheKey];
}
if ($this->isCacheEnabled() && ($attributes = $this->_cache->load($cacheKey))) {
$this->_attributeCodes[$cacheKey] = unserialize($attributes);
return $this->_attributeCodes[$cacheKey];
}
if ($attributeSetId) {
$attributesInfo = $this->_universalFactory->create($entityType->getEntityAttributeCollection())->setEntityTypeFilter($entityType)->setAttributeSetFilter($attributeSetId)->addStoreLabel($storeId)->getData();
$attributes = [];
foreach ($attributesInfo as $attributeData) {
$attributes[] = $attributeData['attribute_code'];
$this->_createAttribute($entityType, $attributeData);
}
} else {
$this->_initAttributes($entityType);
$attributes = array_keys($this->_attributeData[$entityType->getEntityTypeCode()]);
}
$this->_attributeCodes[$cacheKey] = $attributes;
if ($this->isCacheEnabled()) {
$this->_cache->save(serialize($attributes), $cacheKey, [\Magento\Eav\Model\Cache\Type::CACHE_TAG, \Magento\Eav\Model\Entity\Attribute::CACHE_TAG]);
}
return $attributes;
}
示例14: _formIntlShipmentRequest
//.........这里部分代码省略.........
$xml->addChild('ToCountry', $this->_getCountryName($request->getRecipientAddressCountryCode()));
$xml->addChild('ToPostalCode', $request->getRecipientAddressPostalCode());
$xml->addChild('ToPOBoxFlag', 'N');
$xml->addChild('ToPhone', $request->getRecipientContactPhoneNumber());
$xml->addChild('ToFax');
$xml->addChild('ToEmail');
if ($method != 'FirstClass') {
$xml->addChild('NonDeliveryOption', 'Return');
}
if ($method == 'FirstClass') {
if (stripos($shippingMethod, 'Letter') !== false) {
$xml->addChild('FirstClassMailType', 'LETTER');
} else {
if (stripos($shippingMethod, 'Flat') !== false) {
$xml->addChild('FirstClassMailType', 'FLAT');
} else {
$xml->addChild('FirstClassMailType', 'PARCEL');
}
}
}
if ($method != 'FirstClass') {
$xml->addChild('Container', $container);
}
$shippingContents = $xml->addChild('ShippingContents');
$packageItems = $request->getPackageItems();
// get countries of manufacture
$countriesOfManufacture = [];
$productIds = [];
foreach ($packageItems as $itemShipment) {
$item = new \Magento\Framework\Object();
$item->setData($itemShipment);
$productIds[] = $item->getProductId();
}
$productCollection = $this->_productCollectionFactory->create()->addStoreFilter($request->getStoreId())->addFieldToFilter('entity_id', ['in' => $productIds])->addAttributeToSelect('country_of_manufacture');
foreach ($productCollection as $product) {
$countriesOfManufacture[$product->getId()] = $product->getCountryOfManufacture();
}
$packagePoundsWeight = $packageOuncesWeight = 0;
// for ItemDetail
foreach ($packageItems as $itemShipment) {
$item = new \Magento\Framework\Object();
$item->setData($itemShipment);
$itemWeight = $item->getWeight() * $item->getQty();
if ($packageParams->getWeightUnits() != \Zend_Measure_Weight::POUND) {
$itemWeight = $this->_carrierHelper->convertMeasureWeight($itemWeight, $packageParams->getWeightUnits(), \Zend_Measure_Weight::POUND);
}
if (!empty($countriesOfManufacture[$item->getProductId()])) {
$countryOfManufacture = $this->_getCountryName($countriesOfManufacture[$item->getProductId()]);
} else {
$countryOfManufacture = '';
}
$itemDetail = $shippingContents->addChild('ItemDetail');
$itemDetail->addChild('Description', $item->getName());
$ceiledQty = ceil($item->getQty());
if ($ceiledQty < 1) {
$ceiledQty = 1;
}
$individualItemWeight = $itemWeight / $ceiledQty;
$itemDetail->addChild('Quantity', $ceiledQty);
$itemDetail->addChild('Value', $item->getCustomsValue() * $item->getQty());
list($individualPoundsWeight, $individualOuncesWeight) = $this->_convertPoundOunces($individualItemWeight);
$itemDetail->addChild('NetPounds', $individualPoundsWeight);
$itemDetail->addChild('NetOunces', $individualOuncesWeight);
$itemDetail->addChild('HSTariffNumber', 0);
$itemDetail->addChild('CountryOfOrigin', $countryOfManufacture);
list($itemPoundsWeight, $itemOuncesWeight) = $this->_convertPoundOunces($itemWeight);
示例15: addNewItem
/**
* Adds new product to wishlist.
* Returns new item or string on error.
*
* @param int|\Magento\Catalog\Model\Product $product
* @param \Magento\Framework\Object|array|string|null $buyRequest
* @param bool $forciblySetQty
* @return Item|string
*/
public function addNewItem($product, $buyRequest = null, $forciblySetQty = false)
{
/*
* Always load product, to ensure:
* a) we have new instance and do not interfere with other products in wishlist
* b) product has full set of attributes
*/
if ($product instanceof \Magento\Catalog\Model\Product) {
$productId = $product->getId();
// Maybe force some store by wishlist internal properties
$storeId = $product->hasWishlistStoreId() ? $product->getWishlistStoreId() : $product->getStoreId();
} else {
$productId = (int) $product;
if (isset($buyRequest) && $buyRequest->getStoreId()) {
$storeId = $buyRequest->getStoreId();
} else {
$storeId = $this->_storeManager->getStore()->getId();
}
}
/* @var $product \Magento\Catalog\Model\Product */
$product = $this->_productFactory->create();
$product->setStoreId($storeId);
$product->load($productId);
if ($buyRequest instanceof \Magento\Framework\Object) {
$_buyRequest = $buyRequest;
} elseif (is_string($buyRequest)) {
$_buyRequest = new \Magento\Framework\Object(unserialize($buyRequest));
} elseif (is_array($buyRequest)) {
$_buyRequest = new \Magento\Framework\Object($buyRequest);
} else {
$_buyRequest = new \Magento\Framework\Object();
}
$cartCandidates = $product->getTypeInstance()->processConfiguration($_buyRequest, $product);
/**
* Error message
*/
if (is_string($cartCandidates)) {
return $cartCandidates;
}
/**
* If prepare process return one object
*/
if (!is_array($cartCandidates)) {
$cartCandidates = array($cartCandidates);
}
$errors = array();
$items = array();
foreach ($cartCandidates as $candidate) {
if ($candidate->getParentProductId()) {
continue;
}
$candidate->setWishlistStoreId($storeId);
$qty = $candidate->getQty() ? $candidate->getQty() : 1;
// No null values as qty. Convert zero to 1.
$item = $this->_addCatalogProduct($candidate, $qty, $forciblySetQty);
$items[] = $item;
// Collect errors instead of throwing first one
if ($item->getHasError()) {
$errors[] = $item->getMessage();
}
}
$this->_eventManager->dispatch('wishlist_product_add_after', array('items' => $items));
return $item;
}