Build a product export
Overview
For the export of products, cross-selling and category assignments, the bundle provides dedicated base classes as of version 12.7.0. They extend the ArrayAdapterAbstract (see "Register a new adapter") and deliver the data in the structure that the ProductModule of the Shopware plugin reads during import (see "Product import").
The product adapter implements the method buildProduct(), which returns the entry of a product or variant as array – like the array of prepare() before. The ProductAdapterAbstract takes care of the structure (main products and variants), adds id and uuid, checks the keys and provides helper methods for translations, prices, visibilities, manufacturers and delivery times. The values are exported exactly as the project returns them: the bundle sets no defaults, applies no fallback and compares no values.
All classes are located in the namespace Twocream\ShopwareConnectorBundle\Transformer\Adapter.
| Class / Interface | Description |
|---|---|
ArrayAdapter\Product\ProductAdapterAbstract | Base class for product adapters, calls buildProduct() per product and variant and checks the keys |
ArrayAdapter\Product\CrossSellingTrait | Collects the cross-selling of the exported products |
CrossSellingProviderInterface | Marks adapters whose cross-selling is exported by the ArrayTransformer as package cross-selling |
ArrayAdapter\Product\CategoryAssignmentAdapterAbstract | Base class for the export of category assignments |
The following steps build a complete product export. A complete example is located at the end of the page.
Answers to frequently asked questions about keys, null values, relations, variants, languages, custom fields, checksums and the migration of existing adapters can be found on the page "Product export: FAQ".
Basic rules
buildProduct()returns the entry: The array corresponds to the export JSON contract.idanduuid(md5(<Pimcore ID>)) are set by the adapter, values returned bybuildProduct()are replaced. A different UUID has to be built by overridinggenerateUuid()- Values unchanged: The bundle sets no values, filters no
nullvalues and does not convert units. A key thatbuildProduct()does not return is missing in the export - Missing key and
null: A missing simple key keeps the current value in Shopware.nullempties the value of simple and main products and inherits the value of the main product for variants (see Inheritance) - Relations always have to be delivered:
properties,visibilities,pricesand, for variants,optionsare always brought to the delivered state in Shopware, a missing key removes all relations of this type (see "State synchronisation") - Shopware requires
product-numberfor every entry andtax,priceandtranslations.<locale>.namefor simple and main products. The import skips entries without these data with a warning - Allowed keys: A key that the importer does not know ends the export with an
ExportException(see Allowed keys)
Pimcore language and Shopware locale
The product export strictly distinguishes between the language in Pimcore and the locale in Shopware. The project only works with Pimcore languages, the mapping to the Shopware locale happens in the helper methods of the ProductAdapterAbstract.
| Pimcore language | Shopware locale | |
|---|---|---|
| Example | de, en, de_CH | de_DE, en_GB, de_CH |
| Defined by | Languages of the Pimcore system settings, restricted per export target by supported_languages | Target of the configuration language_mapping |
| Used in | Parameter of the callback of prepareTranslations(), keys of $descriptions (prepareManufacturer()) and $names (prepareDeliveryTime()), $pimcoreLanguages of applyTranslationFallback() | Keys of translations, manufacturer.description and delivery-time.name in the export |
This results in the following rules:
- The callback of
prepareTranslations()always receives the Pimcore language (e.g.,de) and uses it to read the localized fields, e.g.,$product->getTitle($language) - The helper methods write the values under the Shopware locale from
language_mapping(e.g.,translations.de_DE) - The Pimcore languages of
supported_languagesof the export target are exported. Without a value, these are all languages valid in Pimcore that are not indisabled_languages. Languages insupported_languagesthat are not valid or enabled in Pimcore are ignored (TranslationService::getSupportedLanguageMapping()). This also applies to manufacturer descriptions and names of delivery times - A language without an entry in
language_mappingis written unchanged under its Pimcore key (e.g.,fr)
twocream_shopware_connector:
export_targets:
- key: shop_staging
supported_languages:
- de
- en
- de_CH
language_mapping:
de: de_DE
en: en_GB
de_CH: de_CH
With this configuration, prepareTranslations() calls the callback with de, en and de_CH and writes the results under de_DE, en_GB and de_CH. A further Pimcore language such as fr is not exported for this export target. Without supported_languages, it would be exported under the key fr.
Without language_mapping, prepareTranslations() writes the Pimcore keys unchanged (e.g., de, en). The import only maps the short forms of its own locale mapping (default: de to de_DE, en to en_GB), other keys without a Shopware language are ignored. If a product therefore has no name in the system language, the import skips it. It is recommended to configure language_mapping with the Shopware locales. Other adapters that use mapTranslations() of the TranslationService are not affected by supported_languages and export all languages (see "Handling of translations").
In Shopware, the delivered keys are mapped to the languages via JsonImportConfiguration::getLocaleMapping(): locales with an underscore (e.g., de_CH) are taken over unchanged, short forms such as de are mapped via the mapping of the plugin and keys with a hyphen (e.g., de-DE) are ignored. The mapping can be adjusted in Shopware via the LocaleMappingEvent (see "Which locales are accepted?"). Configuration of the mapping in Pimcore: see "Configure Language Mapping".
Step 1: Create and register the adapter
Product adapters must inherit from the following abstract class: Twocream\ShopwareConnectorBundle\Transformer\Adapter\ArrayAdapter\Product\ProductAdapterAbstract
getTargetClassName() and buildProduct() have to be implemented. The method prepare() is already implemented: it checks isExportable(), calls buildProduct() for the product and its variants and adds id and uuid. The class defines the following defaults, which can be overridden if needed:
- Package name:
products - Dependent adapters:
attributes,attribute-valuesand the own package. Adapters that do not exist are ignored
<?php
namespace App\Component\Export\Adapter\Product;
use Pimcore\Model\DataObject\Concrete;
use Twocream\ShopwareConnectorBundle\Transformer\Adapter\ArrayAdapter\Product\ProductAdapterAbstract;
class ProductAdapter extends ProductAdapterAbstract
{
public function getTargetClassName(): string
{
return 'Product';
}
protected function buildProduct(Concrete $product, ?Concrete $mainProduct): array
{
return [
'product-number' => $product->getArticleNumber(),
'tax' => 19,
'price' => $this->preparePrice($product->getPriceNet(), $product->getPriceGross()),
'translations' => $this->prepareTranslations(fn (string $language) => [
'name' => $product->getTitle($language),
]),
];
}
}
The adapter is registered like every other adapter with the service tag twocream.shopware_connector.adapter, afterwards twocream:shopware-connector:reload-permissions has to be executed (see "Registering the adapter"):
services:
_defaults:
autowire: true
autoconfigure: true
public: false
App\Component\Export\Adapter\Product\ProductAdapter:
public: true
tags: [ 'twocream.shopware_connector.adapter' ]
| Name | Description |
|---|---|
getTargetClassName(): string | Object class name of the products, e.g., "Product" |
buildProduct(Concrete $product, ?Concrete $mainProduct): array | Returns the entry of a product. $mainProduct is null for simple and main products and the main product for variants |
| Optional | |
beforeConvert(): void | Called once before every export (and by the command preview-product), e.g., to preload data for buildProduct() |
prepareListingConditions(string $type): array | Restricts the exported objects, see Step 4 |
isExportable(Concrete $product, ?Concrete $mainProduct = null): bool | Default true. false exports no data for the object or variant, see Step 4 |
getVariants(Concrete $product): ?iterable | Default null. Variants of a main product, see Step 4 |
getAllowedProductKeys(): ?array, getAllowedTranslationKeys(): ?array | Allowed keys, see Allowed keys |
The ProductAttributeService of the Product-Attribute-Bundle is not injected by the base class. If it is needed, it has to be injected via the constructor of the own adapter (see complete example).
Step 2: Build the product entry
buildProduct() returns the keys of the entry with their values (formats see export JSON contract). Helper methods are available for the structured values:
protected function buildProduct(Concrete $product, ?Concrete $mainProduct): array
{
return [
'product-number' => $product->getArticleNumber(),
'ean' => $product->getEan(),
'tax' => 19,
'price' => $this->preparePrice($product->getPriceNet(), $product->getPriceGross()),
'manufacturer' => $this->prepareManufacturer(
(string) $product->getBrand()?->getName(),
$product->getBrand()?->getWebsite(),
['de' => $product->getBrand()?->getDescription('de')]
),
'delivery-time' => $this->prepareDeliveryTime(1, 3, 'day'),
'length' => $this->getQuantityValueRangeSingleValue($product->getLength()),
'weight' => $this->getNumericValue($product->getWeight()),
'properties' => array_values($this->getRelationIdsByFieldName($product, 'properties')),
];
}
Helper methods
The following methods are final protected and available in every product adapter:
| Name | Description |
|---|---|
prepareTranslations(callable $values): array | Calls $values(string $pimcoreLanguage) per exported language and returns the results with the Shopware locale as key, null omits the language, see Step 3 |
applyTranslationFallback(array $translations, array $fields, array $pimcoreLanguages = []): array | Fills empty values of the $fields from the first language of $pimcoreLanguages with a value, otherwise from the first language with a value |
prepareVisibility(string $market, bool $condition = true, int $visibility = 30): ?array | {market, visibility}, null if $condition is false, see Step 5 |
preparePrice($net, $gross): ?array | {net, gross}, null if one of the values is empty |
prepareRulePrice($net, ?string $currency): ?array | {net, currency}, null without net price or currency |
prepareManufacturer(string $name, ?string $link = null, array $descriptions = []): array | {name, link?, description?}, $descriptions with the Pimcore language as key. An empty name returns [] and removes the assignment in Shopware |
prepareDeliveryTime(int $min, int $max, string $unit, array $names = []): array | {min, max, unit, name?}, $names with the Pimcore language as key. Allowed units: hour, day, week, month, year. Alternatively, the UUID of an existing delivery time can be delivered directly |
getNumericValue($value): ?float | Empty string and null result in null, all other values are converted to float |
getQuantityValueRangeSingleValue(?QuantityValueRange $range, bool $preferMaximum = true): float|int|null | Returns the maximum (or, with $preferMaximum = false, the minimum) of a quantity value range, if it is empty, the other value |
In addition, the ArrayAdapterAbstract provides the methods getRelationIds(iterable $relations): array and getRelationIdsByFieldName(Concrete $object, string $fieldName): array (protected, not final). They return [{id, uuid}] for Pimcore objects, ObjectMetadata and arrays with id (and optionally uuid).
getRelationIds() and getRelationIdsByFieldName() return an array with the Pimcore ID as key. For the relations and lists in the export, convert the result with array_values(), as it is otherwise exported as JSON object.
Allowed keys
Every key of a product or variant entry and of translations.<locale> must be part of getAllowedProductKeys() or getAllowedTranslationKeys(). The defaults are the constants ProductAdapterAbstract::PRODUCT_KEYS and ProductAdapterAbstract::TRANSLATION_KEYS, i.e., the keys that the ProductModule reads (see export JSON contract). An unknown key – e.g., a typo such as product-numer – ends the export with an ExportException that names the key, the object ID and the adapter:
Unknown key "product-numer" in the product entry of object 4711 (App\Component\Export\Adapter\Product\ProductAdapter). Return [...parent::getAllowedProductKeys(), 'product-numer'] from getAllowedProductKeys() to allow it or null to disable the check
The contents of product-extension and custom-fields are not checked.
// Own key that a product module of the project reads
protected function getAllowedProductKeys(): ?array
{
return [...parent::getAllowedProductKeys(), 'acme-energy-label'];
}
// Disable the check of the translations
protected function getAllowedTranslationKeys(): ?array
{
return null;
}
Step 3: Translations
prepareTranslations() calls the callback per exported Pimcore language and returns the translations with the Shopware locale as key. If the callback returns null, the language is not exported.
Key in translations.<locale> | Description |
|---|---|
name | Required for simple and main products |
description, keywords, meta-title, meta-description | Texts |
custom-search-keywords | List of search keywords |
pack-unit, pack-unit-plural | Packaging unit |
custom-fields | Translated custom fields, see Step 7 |
'translations' => $this->applyTranslationFallback(
$this->prepareTranslations(fn (string $language) => [
'name' => $product->getTitle($language),
'description' => $product->getLongDescription($language),
'meta-title' => $product->getMetaTitle($language),
]),
['name'],
['de', 'en']
),
Shopware skips simple and main products with an empty name in a delivered language. For such languages, the callback can return null, or the empty values are filled from another language with applyTranslationFallback(). The fallback is optional and only applied if the project calls it – usually not for variants, as a null name inherits the name of the main product (see Inheritance).
Shopware only writes the keys of ProductModule::getProductTranslationKeyMap() (see "Hooks and helper methods").
Step 4: Variants
Without adjustments, every object is a simple product. Main products and variants are created via the following methods:
| Name | Default | Description |
|---|---|---|
getVariants(Concrete $product): ?iterable | null | null = simple product. An iterable (also empty) makes the object a main product with the key variants |
isExportable(Concrete $product, ?Concrete $mainProduct = null): bool | true | Called without for the objects of the listing and with the main product for the variants |
prepareListingConditions(string $type): array | Source folders | Condition of the listing, see below |
- Every published variant from
getVariants()for whichisExportable($variant, $product)returnstrueis built withbuildProduct($variant, $product) - The main product does not have to be the parent object in Pimcore, only
getVariants()defines the variants - Unpublished and non-exportable variants are missing in
variants, Shopware deactivates them as stale variants getVariants()is only called for the objects of the listing. Variants have no own variants- If
isExportable()returnsfalsefor an object of the listing, the adapter exports no data – the object is transferred as deleted like an unpublished object (if the export target hashas_delta_management), Shopware deactivates the product - Shopware only reads
options([{id, uuid}]of the property options) for variants
The check which object is a main product, a variant or a simple product therefore belongs into prepareListingConditions(), isExportable() and getVariants(). In buildProduct(), checking $mainProduct is sufficient.
Every object of the listing is exported as an own entry. Variant objects therefore have to be excluded from the listing via prepareListingConditions(), as they are otherwise exported twice – as own entry and in variants of their main product.
protected function prepareListingConditions(string $type): array
{
[$condition, $params] = parent::prepareListingConditions($type);
return [sprintf('(%s) AND `hierarchyLevel` IN ("master", "single")', $condition), $params];
}
protected function getVariants(Concrete $product): ?iterable
{
return $product->getHierarchyLevel() === 'master' ? $product->getChildren()->getObjects() : null;
}
protected function isExportable(Concrete $product, ?Concrete $mainProduct = null): bool
{
return $product->getState() === 'active';
}
parent::prepareListingConditions() returns the condition of the source folders from the adapter configuration (source_folder_ids) and should therefore always be included.
Inheritance
In Shopware, variants inherit every value they deliver as null from their main product. The bundle compares no values – buildProduct() decides which values a variant inherits:
| Delivered for a variant | Shopware |
|---|---|
null (e.g., tax, price, manufacturer, translations.<locale>.name) | The variant inherits the value of the main product |
[] or missing relation (properties, visibilities, prices) | Own entries are removed, the variant inherits |
custom-fields.<name> = null | The variant inherits the value of the main product per key |
| Key missing | The current value of the variant is kept (a new variant inherits) |
$isVariant = $mainProduct !== null;
$data = [
'product-number' => $product->getArticleNumber(),
'tax' => $isVariant ? null : 19,
'price' => $isVariant ? null : $this->preparePrice($product->getPriceNet(), $product->getPriceGross()),
// ...
];
if ($isVariant) {
$data['options'] = array_values($this->getRelationIdsByFieldName($product, 'options'));
}
return $data;
For simple and main products, Shopware writes a null of a simple field as empty value (except stock), a null of tax, price or name skips the product (see "Product import: Variant inheritance"). To keep a value unchanged, omit the key. If a variant should keep its own name, deliver translations in every exported language – a variant without translations keeps its current names and texts in Shopware.
Step 5: Visibilities and rule prices
Visibilities and rule prices are delivered per market. The market is a freely selectable key, Shopware maps it to a sales channel or a rule via getSalesChannelIdByMarket() or getRuleIdByMarket() (see "Registering the product module").
| Key | Format | Helper method |
|---|---|---|
visibilities | [{market, visibility}] | prepareVisibility() returns null for an inactive market, filter the list with array_values(array_filter([...])) |
prices | {<market>: {net, currency}} | prepareRulePrice() returns null without price, filter the map with array_filter([...]) |
properties | [{id, uuid}] | array_values($this->getRelationIdsByFieldName($product, 'properties')) |
'visibilities' => array_values(array_filter([
$this->prepareVisibility('shop-de', (bool) $product->getActiveShopDe()),
$this->prepareVisibility('shop-at', (bool) $product->getActiveShopAt()),
])),
'prices' => array_filter([
'shop-de' => $this->prepareRulePrice($product->getPriceNetDe(), 'EUR'),
'shop-at' => $this->prepareRulePrice($product->getPriceNetAt(), 'EUR'),
]),
If a market is omitted, Shopware removes an existing rule price or an existing visibility of this market.
The relations are always brought to the delivered state in Shopware. A product without an active market exports "visibilities": [] and loses all visibilities in Shopware. Relations therefore have to be maintained in Pimcore only.
Shopware only writes rule prices in the default currency (e.g., EUR). A rule price in another currency is skipped with Price has no value in the default currency, price is skipped, prices in several currencies are not supported yet (see "Why is a rule price in another currency skipped?").
Step 6: Product extension
Fields of the product extension (in Shopware the entity twocream_product_extension, see "Product extension") are delivered as plain array under product-extension, translated fields under product-extension.translations.<locale>:
'product-extension' => [
'business-area' => $product->getBusinessArea(),
'videos' => array_values($this->getRelationIdsByFieldName($product, 'videos')),
'translations' => $this->prepareTranslations(fn (string $language) => [
'subtitle' => $product->getSubtitle($language),
]),
],
The bundle does not check the contents and exports them unchanged. In Shopware, the keys are mapped to the fields of the product extension via getProductExtensionFieldMap() and getProductExtensionTranslationKeyMap() of the ProductModule. Keys that are not mapped are ignored, nested structures such as videos require an override of getProductExtensionData() (see "Product import: Product extension").
Step 7: Custom fields
Custom fields of the Shopware products are delivered via their technical name in Shopware. No mapping is necessary.
| Key | Meaning |
|---|---|
custom-fields.<name> | Non-translated value |
translations.<locale>.custom-fields.<name> | Translated value |
'custom-fields' => [
'acme_is_new' => (bool) $product->getIsNew(),
'acme_dimensions' => ['a' => $product->getDimensionA(), 'b' => $product->getDimensionB()],
],
'translations' => $this->prepareTranslations(fn (string $language) => [
'name' => $product->getTitle($language),
'custom-fields' => ['acme_claim' => $product->getClaim($language)],
]),
- A value can itself be an array or JSON object. Whether a value is translated is decided only by its position in the export, never by the shape of the value
- If a name is delivered in both places, the translated value applies in Shopware in its language, all other languages receive the non-translated value
nullremoves the value in Shopware, a variant then inherits the value of the main product. A name that is not delivered keeps its value- Shopware checks the value against the type of the custom field, unknown names and invalid values are reported as warning and not written (see "Product import: Custom fields")
Step 8: Cross-selling
The cross-selling is not exported via an own adapter, but via the product adapter. The following steps are necessary:
- Include the trait
ArrayAdapter\Product\CrossSellingTraitin the product adapter - Implement the interface
CrossSellingProviderInterface - Implement the method
getCrossSellingFields(): array - Return
getCrossSellingChecksum($product)ascross-selling-checksuminbuildProduct()– the call also collects the cross-selling of the entry
The trait alone is not sufficient: only the CrossSellingProviderInterface makes the ArrayTransformer take over the collected data as package cross-selling into the export after the conversion of the adapter. Only the cross-selling of the entries for which getCrossSellingChecksum() or prepareCrossSelling() was called is collected.
| Name | Description |
|---|---|
getCrossSellingFields(): array | Mapping of relation field to cross-selling name, e.g., ['accessories' => 'Accessories']. If the mapping is invalid or the field does not exist, an ExportException is thrown |
| Optional | |
prepareAdditionalCrossSelling(Concrete $object): void | Adds further entries to $this->crossSelling[$object->getId()] that cannot be mapped via a relation field |
Provided (final protected) | |
prepareCrossSelling(Concrete $object): array | Collects the cross-selling of an object (including inherited values) and returns it |
getCrossSellingChecksum(Concrete $object): string | Checksum of the result of prepareCrossSelling() |
class ProductAdapter extends ProductAdapterAbstract implements CrossSellingProviderInterface
{
use CrossSellingTrait;
protected function getCrossSellingFields(): array
{
return ['accessories' => 'Accessories'];
}
protected function buildProduct(Concrete $product, ?Concrete $mainProduct): array
{
return [
// ...
'cross-selling-checksum' => $this->getCrossSellingChecksum($product),
];
}
}
prepareCrossSelling() is idempotent per object, calling it multiple times therefore does not create duplicates. The ArrayTransformer calls resetCrossSelling() before every convert() of an adapter with CrossSellingProviderInterface, so the collected cross-selling starts empty in every export.
Delta export
A pure change of the cross-selling does not change the product data itself. As the checksum cross-selling-checksum is part of the product data, the product is nevertheless considered changed when the cross-selling changes and is transferred in the delta export. The importer ignores this field.
| Export | Content of the package cross-selling |
|---|---|
| Delta export | Only the cross-selling of the products exported in this run including their variants |
Full export (--skip-delta) | The cross-selling of all products |
Variants are taken into account via variants[*].id of the product entry. For products that are exported as deleted (.meta.deleted), no cross-selling is transferred, neither in the delta nor in the full export.
Step 9: Category assignments
Adapters for category assignments must inherit from the following abstract class: Twocream\ShopwareConnectorBundle\Transformer\Adapter\ArrayAdapter\Product\CategoryAssignmentAdapterAbstract
The package name is category-assignments by default. With several category trees, getPackageName() can be overridden. The method prepare() is already implemented and creates one entry {id, identifier, products: [{id, uuid}]} per category object via getRelationIds(). Products assigned multiple times are only transferred once.
| Name | Description |
|---|---|
getTargetClassName(): string | Corresponding object class name of the category, e.g., "Category" |
getCategoryIdentifier(Concrete $object): ?string | Identifier of the Shopware category to which the products are assigned. If the identifier is empty, prepare() returns no data and the object is transferred as deleted – like an unpublished object |
getAssignedProducts(Concrete $object): iterable | Returns the product objects (or ObjectMetadata) to be assigned. Rules for hierarchy and variants remain in the project |
| Optional | |
prepareListingConditions(string $type): array | Can be overridden to restrict the exported category objects, e.g., via the path |
<?php
namespace App\Component\Export\Adapter\Product;
use Pimcore\Model\DataObject\Concrete;
use Twocream\ShopwareConnectorBundle\Transformer\Adapter\ArrayAdapter\Product\CategoryAssignmentAdapterAbstract;
class CategoryAssignmentAdapter extends CategoryAssignmentAdapterAbstract
{
public function getTargetClassName(): string
{
return 'Category';
}
protected function getCategoryIdentifier(Concrete $object): ?string
{
return $object->getIdentifier();
}
protected function getAssignedProducts(Concrete $object): iterable
{
return $object->getProducts();
}
}
Step 10: Preview the product
The command twocream:shopware-connector:preview-product prints the entry that the product adapters of the class export for an object – without storing checksums or writing an export file.
php bin/console twocream:shopware-connector:preview-product 4711 --system=shop_staging
--systemis required, asbuildProduct()may use the export target (e.g.,assetHelper())- Errors, e.g., an unknown key, are printed without stack trace and end the command with an error code
- An unpublished object is built anyway with a warning, the export skips it
Arguments and options are described on the page "Commands".
Complete example
The following example shows a product adapter with main products and variants, two markets, properties from the Product-Attribute-Bundle, preloaded positions, product extension, custom fields and cross-selling. The field names of the Pimcore class are examples.
<?php
namespace App\Component\Export\Adapter\Product;
use Pimcore\Db;
use Pimcore\Model\DataObject\Concrete;
use Pimcore\Model\DataObject\ProductAttributeValue;
use Twocream\ProductAttributeBundle\Components\Export\Service\ProductAttributeService;
use Twocream\ShopwareConnectorBundle\Service\AdapterConfigurationService;
use Twocream\ShopwareConnectorBundle\Service\ExportTargetService;
use Twocream\ShopwareConnectorBundle\Service\TranslationService;
use Twocream\ShopwareConnectorBundle\Transformer\Adapter\ArrayAdapter\ConditionManager;
use Twocream\ShopwareConnectorBundle\Transformer\Adapter\ArrayAdapter\Product\CrossSellingTrait;
use Twocream\ShopwareConnectorBundle\Transformer\Adapter\ArrayAdapter\Product\ProductAdapterAbstract;
use Twocream\ShopwareConnectorBundle\Transformer\Adapter\CrossSellingProviderInterface;
class ProductAdapter extends ProductAdapterAbstract implements CrossSellingProviderInterface
{
use CrossSellingTrait;
private array $positions = [];
private ProductAttributeService $productAttributeService;
public function __construct(
TranslationService $translationService,
ExportTargetService $exportTargetService,
AdapterConfigurationService $adapterConfigurationService,
ConditionManager $manager,
ProductAttributeService $productAttributeService
) {
$this->productAttributeService = $productAttributeService;
parent::__construct($translationService, $exportTargetService, $adapterConfigurationService, $manager);
}
public function getTargetClassName(): string
{
return 'Product';
}
protected function beforeConvert(): void
{
$this->positions = Db::get()->fetchAllKeyValue('SELECT `productId`, `position` FROM `app_product_position`');
}
protected function prepareListingConditions(string $type): array
{
[$condition, $params] = parent::prepareListingConditions($type);
return [sprintf('(%s) AND `hierarchyLevel` IN ("master", "single")', $condition), $params];
}
protected function isExportable(Concrete $product, ?Concrete $mainProduct = null): bool
{
return $product->getState() === 'active';
}
protected function getVariants(Concrete $product): ?iterable
{
return $product->getHierarchyLevel() === 'master' ? $product->getChildren()->getObjects() : null;
}
protected function getCrossSellingFields(): array
{
return ['accessories' => 'accessories'];
}
protected function buildProduct(Concrete $product, ?Concrete $mainProduct): array
{
$isVariant = $mainProduct !== null;
$translations = $this->prepareTranslations(fn (string $language) => [
'name' => $isVariant ? $product->getVariantTitle($language) : $product->getTitle($language),
'description' => $isVariant ? null : $product->getLongText($language),
'custom-fields' => ['acme_claim' => $isVariant ? null : $product->getClaim($language)],
]);
$data = [
'product-number' => $isVariant ? $product->getArticleNumber() : 'M-' . $product->getId(),
'ean' => $product->getEan(),
'tax' => $isVariant ? null : 19,
'price' => $isVariant ? null : $this->preparePrice($product->getPriceNet(), $product->getPriceGross()),
'manufacturer' => $isVariant ? null : $this->prepareManufacturer((string) $product->getManufacturerName()),
'weight' => $this->getNumericValue($product->getWeight()),
'properties' => $this->productAttributeService->getArticleAssignmentByProductId(
new ProductAttributeValue\Listing(),
$product->getId()
),
'prices' => $isVariant ? [] : array_filter([
'shop-de' => $this->prepareRulePrice($product->getPriceNetDe(), 'EUR'),
'shop-at' => $this->prepareRulePrice($product->getPriceNetAt(), 'EUR'),
]),
'visibilities' => $isVariant ? [] : array_values(array_filter([
$this->prepareVisibility('shop-de', (bool) $product->getActiveShopDe()),
$this->prepareVisibility('shop-at', (bool) $product->getActiveShopAt()),
])),
'custom-fields' => ['acme_is_new' => $isVariant ? null : (bool) $product->getIsNew()],
'translations' => $isVariant ? $translations : $this->applyTranslationFallback($translations, ['name'], ['de']),
'product-extension' => [
'position' => $this->positions[$isVariant ? $mainProduct->getId() : $product->getId()] ?? 999999,
'videos' => array_values($this->getRelationIdsByFieldName($product, 'videos')),
],
'cross-selling-checksum' => $this->getCrossSellingChecksum($product),
];
if ($isVariant) {
$data['options'] = array_values($this->getRelationIdsByFieldName($product, 'variantOptions'));
}
return $data;
}
}
A main product with one variant results, e.g., in the following entry (with language_mapping de: de_DE, en: en_GB):
{
"id": 4711,
"uuid": "...",
"product-number": "M-4711",
"ean": null,
"tax": 19,
"price": { "net": 100.0, "gross": 119.0 },
"manufacturer": { "name": "ACME" },
"weight": null,
"properties": [{ "id": 301, "uuid": "..." }],
"prices": { "shop-de": { "net": 89.0, "currency": "EUR" } },
"visibilities": [{ "market": "shop-de", "visibility": 30 }],
"custom-fields": { "acme_is_new": true },
"translations": {
"de_DE": { "name": "Bohrmaschine", "description": "…", "custom-fields": { "acme_claim": "Neu" } },
"en_GB": { "name": "Drill", "description": "…", "custom-fields": { "acme_claim": "New" } }
},
"product-extension": { "position": 4, "videos": [] },
"cross-selling-checksum": "...",
"variants": [
{
"id": 4712,
"uuid": "...",
"product-number": "4711-1",
"ean": "4006381333931",
"tax": null,
"price": null,
"manufacturer": null,
"weight": 2.7,
"properties": [{ "id": 302, "uuid": "..." }],
"prices": [],
"visibilities": [],
"custom-fields": { "acme_is_new": null },
"translations": {
"de_DE": { "name": "Bohrmaschine 18 V", "description": null, "custom-fields": { "acme_claim": null } },
"en_GB": { "name": "Drill 18 V", "description": null, "custom-fields": { "acme_claim": null } }
},
"product-extension": { "position": 4, "videos": [] },
"cross-selling-checksum": "...",
"options": [{ "id": 905, "uuid": "..." }]
}
]
}
In Shopware, the variant inherits tax rate, price, manufacturer, description, visibilities, rule prices and the custom fields of the main product. For simple and main products, "ean": null or "weight": null empties the value in Shopware.
The corresponding product module in Shopware maps the markets and the fields of the product extension (see "Product import"), the custom fields are written without mapping via their technical name.
Virtual adapters (groups)
Virtual adapters bundle several adapters into one selectable entry in the export mask. They are not product-specific, see "Virtual adapters (groups)".
Deletion data
If an object is deleted in Pimcore, the deletion data are determined via the adapters registered for the class of the object:
- Virtual adapters and adapters that do not override
getDeletedData()(i.e., inheritAdapterAbstract::getDeletedData()) are skipped - The first result of
getDeletedData($object)of an overriding adapter that is notnullapplies. The registration order is only relevant among the adapters that overridegetDeletedData() - If no adapter returns data,
AdapterAbstract::getDeletedData($object)is used
This way, project-specific implementations of getDeletedData() are taken into account, e.g., if the Shopware UUID is not built from the Pimcore ID.
use Pimcore\Model\DataObject;
public static function getDeletedData(DataObject $object): ?string
{
return json_encode(['uuid' => $object->getAttributeUuid()]);
}
If the deletion data contain a uuid, it is used instead of the generated UUID for the deletion entry.
Export JSON contract
The product export must correspond to the structure that the JSON importer of the Shopware plugin expects:
{
".meta": { "id": "...", "mail": "...", "delta": true },
"<package>": { "<pimcoreId>": { } },
"cross-selling": {
"<pimcoreId>": { "id": 1, "uuid": "...", "items": { "<name>": [ { "id": 2, "uuid": "..." } ] } }
}
}
- The UUID corresponds to
md5(<pimcoreId>), usegenerateUuid()of the adapter for this - Deleted entries:
{ "id", "uuid", ".meta": { "deleted": true } }
products
The keys of the table are the allowed keys (ProductAdapterAbstract::PRODUCT_KEYS and ProductAdapterAbstract::TRANSLATION_KEYS, see Allowed keys).
| Key | Format |
|---|---|
id, uuid | Set by the adapter |
product-number | String, required |
tax | Number, required for simple and main products |
price | {net, gross}, required for simple and main products |
purchase-price | {net, gross} in the default currency |
translations | {<locale>: {name, description, keywords, custom-search-keywords, meta-title, meta-description, pack-unit, pack-unit-plural, custom-fields}}, name required for simple and main products, custom-search-keywords as list |
ean, manufacturer-number, unit | String |
active, is-closeout, shipping-free, mark-as-topseller | Boolean (without active, main products are active, variants inherit) |
stock, min-purchase, max-purchase, purchase-steps, restock-time | Integer |
purchase-unit, reference-unit, length, width, height, weight | Number |
release-date | Date as string |
manufacturer | Name, [] or '' (removes the assignment) or {name, link?, description?} with description per locale |
delivery-time | UUID, null or '' (removes the assignment) or {min, max, unit, name?} with name per locale |
canonical-product | {id, uuid} of another product, null or [] (removes the assignment) |
cms-page, feature-set | UUID of an existing Shopware layout or feature set, null or '' (removes the assignment) |
variant-listing-config (main products only) | {display-parent?, main-variant?{id, uuid}, configurator-group-config?[{uuid, representation, expression-for-listings}]} |
properties, options (variants only) | [{id, uuid}] |
visibilities | [{market, visibility}] |
prices | {<market>: {net, currency}} |
custom-fields | {<technical name>: value}, not checked |
product-extension | {<key>: value, translations?} with translations per locale, not checked |
variants | List of the variant entries (also empty), marks a main product |
cross-selling-checksum | String, ignored by the importer |
- Variants have the same structure. For variants, only
id,uuidandproduct-numberare required,nullinherits the value of the main product (alsotax,priceand names) - As
<locale>,prepareTranslations()writes the target fromlanguage_mapping(see Pimcore language and Shopware locale). Keys with a hyphen (e.g.,de-DE) are ignored in Shopware (see "Which locales are accepted?")
The source system is leading: the relations properties, visibilities, prices, options and variants of an entry are always brought to the state of the export in Shopware. A missing key removes the existing relations, existing variants that are no longer part of the export are deactivated. Every entry therefore has to deliver its complete relations. Missing simple fields, however, are not written (see "State synchronisation").
cross-selling
{ pimcoreId: { id, uuid, items: { name: [ {id, uuid} ] } } }
category-assignments
{ id, identifier, products: [ {id, uuid} ] }