SimpleProductsFixture.php 12.6 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magento\Setup\Fixtures;

use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\ProductFactory;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\CollectionFactory;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory as AttributeSetCollectionFactory;
use Magento\Setup\Model\FixtureGenerator\ProductGenerator;
use Magento\Setup\Model\SearchTermDescriptionGeneratorFactory;

/**
 * Generate simple products based on profile configuration
 * Support the following format:
 * <simple_products>{products amount}</simple_products>
 * Products will be distributed per Default and pre-defined
 * attribute sets (@see setup/performance-toolkit/config/attributeSets.xml)
 *
 * If extra attribute set is specified in profile as: <product_attribute_sets>{sets amount}</product_attribute_sets>
 * then products also will be distributed per additional attribute sets
 *
 * Products will be uniformly distributed per categories and websites
 * If node "assign_entities_to_all_websites" from profile is set to "1" then products will be assigned to all websites
 *
 * @see setup/performance-toolkit/profiles/ce/small.xml
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class SimpleProductsFixture extends Fixture
{
    /**
     * Simple product sku pattern
     */
    const SKU_PATTERN = 'product_dynamic_%s';

    /**
     * @var int
     */
    protected $priority = 31;

    /**
     * @var array
     */
    private $descriptionConfig;

    /**
     * @var array
     */
    private $shortDescriptionConfig;

    /**
     * @var ProductFactory
     */
    private $productFactory;

    /**
     * @var ProductGenerator
     */
    private $productGenerator;

    /**
     * @var int
     */
    private $defaultAttributeSetId;

    /**
     * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection
     */
    private $attributeCollectionFactory;

    /**
     * @var AttributeSetCollectionFactory
     */
    private $attributeSetCollectionFactory;

    /**
     * @var SearchTermDescriptionGeneratorFactory
     */
    private $descriptionGeneratorFactory;

    /**
     * @var ProductsAmountProvider
     */
    private $productsAmountProvider;

    /**
     * @var WebsiteCategoryProvider
     */
    private $websiteCategoryProvider;

    /**
     * @var PriceProvider
     */
    private $priceProvider;

    /**
     * @param FixtureModel $fixtureModel
     * @param ProductFactory $productFactory
     * @param ProductGenerator $productGenerator
     * @param CollectionFactory $attributeCollectionFactory
     * @param AttributeSetCollectionFactory $attributeSetCollectionFactory
     * @param SearchTermDescriptionGeneratorFactory $descriptionGeneratorFactory
     * @param WebsiteCategoryProvider $websiteCategoryProvider
     * @param ProductsAmountProvider $productsAmountProvider
     * @param PriceProvider $priceProvider
     * @internal param FixtureConfig $fixtureConfig
     */
    public function __construct(
        FixtureModel $fixtureModel,
        ProductFactory $productFactory,
        ProductGenerator $productGenerator,
        CollectionFactory $attributeCollectionFactory,
        AttributeSetCollectionFactory $attributeSetCollectionFactory,
        SearchTermDescriptionGeneratorFactory $descriptionGeneratorFactory,
        WebsiteCategoryProvider $websiteCategoryProvider,
        ProductsAmountProvider $productsAmountProvider,
        PriceProvider $priceProvider
    ) {
        parent::__construct($fixtureModel);
        $this->productFactory = $productFactory;
        $this->productGenerator = $productGenerator;
        $this->attributeCollectionFactory = $attributeCollectionFactory;
        $this->attributeSetCollectionFactory = $attributeSetCollectionFactory;
        $this->descriptionGeneratorFactory = $descriptionGeneratorFactory;
        $this->productsAmountProvider = $productsAmountProvider;
        $this->websiteCategoryProvider = $websiteCategoryProvider;
        $this->priceProvider = $priceProvider;
    }

    /**
     * {@inheritdoc}
     */
    public function getActionTitle()
    {
        return 'Generating simple products';
    }

    /**
     * {@inheritdoc}
     */
    public function introduceParamLabels()
    {
        return [
            'simple_products' => 'Simple products'
        ];
    }

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD)
     */
    public function execute()
    {
        $simpleProductsCount = $this->productsAmountProvider->getAmount(
            $this->fixtureModel->getValue('simple_products', 0),
            $this->getSkuPattern()
        );

        if (!$simpleProductsCount) {
            return;
        }

        $defaultAttributeSets = $this->getDefaultAttributeSets();
        $searchTermsConfig = $this->getSearchTerms();

        /** @var \Magento\Setup\Model\SearchTermDescriptionGenerator $descriptionGenerator */
        $descriptionGenerator = $this->descriptionGeneratorFactory->create(
            $this->getDescriptionConfig(),
            $searchTermsConfig,
            $simpleProductsCount,
            'Full simple product Description %s'
        );

        /** @var \Magento\Setup\Model\SearchTermDescriptionGenerator $shortDescriptionGenerator */
        $shortDescriptionGenerator = $this->descriptionGeneratorFactory->create(
            $this->getShortDescriptionConfig(),
            $searchTermsConfig,
            $simpleProductsCount,
            'Short simple product Description %s'
        );

        $additionalAttributeSets = $this->getAdditionalAttributeSets();
        $attributeSet = function ($index) use ($defaultAttributeSets, $additionalAttributeSets) {
            mt_srand($index);
            $attributeSetCount = count(array_keys($defaultAttributeSets));
            if ($attributeSetCount > (($index - 1) % (int)$this->fixtureModel->getValue('categories', 30))) {
                return array_keys($defaultAttributeSets)[mt_rand(0, count(array_keys($defaultAttributeSets)) - 1)];
            } else {
                $customSetsAmount = count($additionalAttributeSets);
                return $customSetsAmount
                    ? $additionalAttributeSets[$index % count($additionalAttributeSets)]['attribute_set_id']
                    : $this->getDefaultAttributeSetId();
            }
        };

        $additionalAttributes = function (
            $attributeSetId,
            $index
        ) use (
            $defaultAttributeSets,
            $additionalAttributeSets
        ) {
            $attributeValues = [];
            mt_srand($index);
            if (isset($defaultAttributeSets[$attributeSetId])) {
                foreach ($defaultAttributeSets[$attributeSetId] as $attributeCode => $values) {
                    $attributeValues[$attributeCode] = $values[mt_rand(0, count($values) - 1)];
                }
            }

            return $attributeValues;
        };

        $fixtureMap = [
            'name' => function ($productId) {
                return sprintf('Simple Product %s', $productId);
            },
            'sku' => function ($productId) {
                return sprintf($this->getSkuPattern(), $productId);
            },
            'price' => function ($index, $entityNumber) {
                return $this->priceProvider->getPrice($entityNumber);
            },
            'url_key' => function ($productId) {
                return sprintf('simple-product-%s', $productId);
            },
            'description' => function ($index) use ($descriptionGenerator) {
                return $descriptionGenerator->generate($index);
            },
            'short_description' => function ($index) use ($shortDescriptionGenerator) {
                return $shortDescriptionGenerator->generate($index);
            },
            'website_ids' => function ($index, $entityNumber) {
                return $this->websiteCategoryProvider->getWebsiteIds($index);
            },
            'category_ids' => function ($index, $entityNumber) {
                return $this->websiteCategoryProvider->getCategoryId($index);
            },
            'attribute_set_id' => $attributeSet,
            'additional_attributes' => $additionalAttributes,
            'status' => function () {
                return Status::STATUS_ENABLED;
            }
        ];
        $this->productGenerator->generate($simpleProductsCount, $fixtureMap);
    }

    /**
     * Get simple product sku pattern
     *
     * @return string
     */
    private function getSkuPattern()
    {
        return self::SKU_PATTERN;
    }

    /**
     * Get default attribute set id
     *
     * @return int
     */
    private function getDefaultAttributeSetId()
    {
        if (null === $this->defaultAttributeSetId) {
            $this->defaultAttributeSetId = (int)$this->productFactory->create()->getDefaultAttributeSetId();
        }

        return $this->defaultAttributeSetId;
    }

    /**
     * Get default attribute sets with attributes
     *
     * @see config/attributeSets.xml
     * @return array
     */
    private function getDefaultAttributeSets()
    {
        $attributeSets = $this->fixtureModel->getValue('attribute_sets', null);
        $attributes = [];

        if ($attributeSets !== null && array_key_exists('attribute_set', $attributeSets)) {
            foreach ($attributeSets['attribute_set'] as $attributeSet) {
                $attributesData = array_key_exists(0, $attributeSet['attributes']['attribute'])
                    ? $attributeSet['attributes']['attribute'] : [$attributeSet['attributes']['attribute']];

                $attributeCollection = $this->attributeCollectionFactory->create();

                $attributeCollection->setAttributeSetFilterBySetName($attributeSet['name'], Product::ENTITY);
                $attributeCollection->addFieldToFilter(
                    'attribute_code',
                    array_column($attributesData, 'attribute_code')
                );
                /** @var \Magento\Eav\Model\Entity\Attribute $attribute */
                foreach ($attributeCollection as $attribute) {
                    $values = [];
                    $options = $attribute->getOptions();
                    foreach (($options ?: []) as $option) {
                        if ($option->getValue()) {
                            $values[] = $option->getValue();
                        }
                    }
                    $attributes[$attribute->getAttributeSetId()][$attribute->getAttributeCode()] = $values;
                }
            }
        }
        $attributes[$this->getDefaultAttributeSetId()] = [];

        return $attributes;
    }

    /**
     * Get search terms config which used for product description generation
     *
     * @return array
     */
    private function getSearchTerms()
    {
        $searchTerms = $this->fixtureModel->getValue('search_terms', []);
        if (!empty($searchTerms)) {
            $searchTerms = array_key_exists(0, $searchTerms['search_term'])
                ? $searchTerms['search_term'] : [$searchTerms['search_term']];
        }

        return $searchTerms;
    }

    /**
     * Get description config
     *
     * @return array
     */
    private function getDescriptionConfig()
    {
        if (null === $this->descriptionConfig) {
            $this->descriptionConfig = $this->readDescriptionConfig('description');
        }

        return $this->descriptionConfig;
    }

    /**
     * Get short description config
     *
     * @return array
     */
    private function getShortDescriptionConfig()
    {
        if (null === $this->shortDescriptionConfig) {
            $this->shortDescriptionConfig = $this->readDescriptionConfig('short-description');
        }

        return $this->shortDescriptionConfig;
    }

    /**
     * Get description config from fixture
     *
     * @param string $configSrc
     * @return array
     */
    private function readDescriptionConfig($configSrc)
    {
        $configData = $this->fixtureModel->getValue($configSrc, []);

        if (isset($configData['mixin']['tags'])) {
            $configData['mixin']['tags'] = explode('|', $configData['mixin']['tags']);
        }

        return $configData;
    }

    /**
     * Get additional attribute sets
     *
     * @return \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection[]
     */
    private function getAdditionalAttributeSets()
    {
        /** @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\Collection $sets */
        $sets = $this->attributeSetCollectionFactory->create();
        $sets->addFieldToFilter('attribute_set_name', ['like' => AttributeSetsFixture::PRODUCT_SET_NAME . '%']);

        return $sets->getData();
    }
}