|
4 | 4 |
|
5 | 5 | use Grayloon\Magento\Magento; |
6 | 6 | use Grayloon\Magento\Models\MagentoCategory; |
| 7 | +use Grayloon\Magento\Models\MagentoCustomAttributeType; |
7 | 8 |
|
8 | 9 | class MagentoCategories extends PaginatableMagentoService |
9 | 10 | { |
@@ -94,15 +95,67 @@ protected function findAttributeByKey($key, $attributes) |
94 | 95 | protected function syncCustomAttributes($attributes, $category) |
95 | 96 | { |
96 | 97 | foreach ($attributes as $attribute) { |
97 | | - if (is_array($attribute['value'])) { |
98 | | - $attribute['value'] = json_encode($attribute['value']); |
99 | | - } |
| 98 | + $type = $this->resolveCustomAttributeType($attribute['attribute_code']); |
| 99 | + $value = $this->resolveCustomAttributeValue($type, $attribute['value']); |
100 | 100 |
|
101 | | - $category->customAttributes()->updateOrCreate(['attribute_type' => $attribute['attribute_code']], [ |
102 | | - 'value' => $attribute['value'], |
103 | | - ]); |
| 101 | + $category |
| 102 | + ->customAttributes() |
| 103 | + ->updateOrCreate(['attribute_type_id' => $type->id], [ |
| 104 | + 'attribute_type' => $attribute['attribute_code'], |
| 105 | + 'value' => $value, |
| 106 | + ]); |
104 | 107 | } |
105 | 108 |
|
106 | 109 | return $this; |
107 | 110 | } |
| 111 | + |
| 112 | + /** |
| 113 | + * Resolve the Custom Attribute Type by the Attribute Code. |
| 114 | + * |
| 115 | + * @param string $attributeCode |
| 116 | + * @return \Grayloon\Magento\Models\MagentoCustomAttributeType |
| 117 | + */ |
| 118 | + protected function resolveCustomAttributeType($attributeCode) |
| 119 | + { |
| 120 | + $type = MagentoCustomAttributeType::where('name', $attributeCode) |
| 121 | + ->first(); |
| 122 | + |
| 123 | + if (! $type) { |
| 124 | + $api = (new Magento())->api('productAttributes') |
| 125 | + ->show($attributeCode) |
| 126 | + ->json(); |
| 127 | + |
| 128 | + $type = MagentoCustomAttributeType::create([ |
| 129 | + 'name' => $attributeCode, |
| 130 | + 'display_name' => $api['default_frontend_label'] ?? $attributeCode, |
| 131 | + 'options' => $api['options'] ?? [], |
| 132 | + ]); |
| 133 | + } |
| 134 | + |
| 135 | + return $type; |
| 136 | + } |
| 137 | + |
| 138 | + /** |
| 139 | + * Resolve the Custom Attribute Value by the provided options. |
| 140 | + * |
| 141 | + * @param \Grayloon\Magento\Models\MagentoCustomAttributeType $type |
| 142 | + * @param string $value; |
| 143 | + * @return string|null |
| 144 | + */ |
| 145 | + protected function resolveCustomAttributeValue($type, $value) |
| 146 | + { |
| 147 | + if ($type->options) { |
| 148 | + foreach ($type->options as $option) { |
| 149 | + if ($option['value'] == $value) { |
| 150 | + return $option['label']; |
| 151 | + } |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + if (is_array($value)) { |
| 156 | + $value = json_encode($value); |
| 157 | + } |
| 158 | + |
| 159 | + return $value; |
| 160 | + } |
108 | 161 | } |
0 commit comments