Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
SwatchesGenerator.php
Go to the documentation of this file.
1 <?php
7 
10 
15 {
22 
29 
35  const GENERATED_SWATCH_TMP_NAME = 'tmp_swatch.jpg';
36 
40  private $swatchHelper;
41 
45  private $imagesGeneratorFactory;
46 
50  private $imagesGenerator;
51 
56  public function __construct(
57  \Magento\Swatches\Helper\Media $swatchHelper,
58  \Magento\Setup\Fixtures\ImagesGenerator\ImagesGeneratorFactory $imagesGeneratorFactory
59  ) {
60  $this->swatchHelper = $swatchHelper;
61  $this->imagesGeneratorFactory = $imagesGeneratorFactory;
62  }
63 
72  public function generateSwatchData($optionCount, $data, $type)
73  {
74  if ($type === null) {
75  return [];
76  }
77 
78  $attribute['swatch_input_type'] = Swatch::SWATCH_INPUT_TYPE_VISUAL;
79  $attribute['swatchvisual']['value'] = array_reduce(
80  range(1, $optionCount),
81  function ($values, $index) use ($optionCount, $data, $type) {
82  if ($type === 'image') {
83  $values['option_' . $index] = $this->generateSwatchImage($data . $index);
84  }
85  if ($type === 'color') {
86  $values['option_' . $index] = $this->generateSwatchColor($index / $optionCount);
87  }
88  return $values;
89  },
90  []
91  );
92  $attribute['optionvisual']['value'] = array_reduce(
93  range(1, $optionCount),
94  function ($values, $index) use ($optionCount) {
95  $values['option_' . $index] = ['option ' . $index];
96  return $values;
97  },
98  []
99  );
100 
101  return $attribute;
102  }
103 
112  private function generateSwatchColor($index)
113  {
114  return '#' . str_repeat(dechex(255 * $index), 3);
115  }
116 
126  private function generateSwatchImage($data)
127  {
128  if ($this->imagesGenerator === null) {
129  $this->imagesGenerator = $this->imagesGeneratorFactory->create();
130  }
131 
132  $imageName = md5($data) . '.jpg';
133  $this->imagesGenerator->generate([
134  'image-width' => self::GENERATED_SWATCH_WIDTH,
135  'image-height' => self::GENERATED_SWATCH_HEIGHT,
136  'image-name' => $imageName
137  ]);
138 
139  $imagePath = substr($this->swatchHelper->moveImageFromTmp($imageName), 1);
140  $this->swatchHelper->generateSwatchVariations($imagePath);
141 
142  return $imagePath;
143  }
144 }
$values
Definition: options.phtml:88
$type
Definition: item.phtml:13
$index
Definition: list.phtml:44
__construct(\Magento\Swatches\Helper\Media $swatchHelper, \Magento\Setup\Fixtures\ImagesGenerator\ImagesGeneratorFactory $imagesGeneratorFactory)