Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit 73b9e45

Browse files
committed
feat: add helper methods to quickly get custom attribute values from models
1 parent c048e82 commit 73b9e45

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/Models/MagentoProduct.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Grayloon\Magento\Models;
44

55
use Illuminate\Database\Eloquent\Model;
6+
use Illuminate\Support\Facades\Storage;
67

78
class MagentoProduct extends Model
89
{
@@ -63,4 +64,33 @@ public function categories()
6364
{
6465
return $this->hasManyThrough(MagentoCategory::class, MagentoProductCategory::class, 'magento_product_id', 'id');
6566
}
67+
68+
/**
69+
* Helper to quickly get a value from a custom attribute.
70+
*
71+
* @param string $key
72+
* @return mixed
73+
*/
74+
public function customAttributeValue($key)
75+
{
76+
$attribute = $this->customAttributes->where('attribute_type', $key)->first();
77+
78+
return $attribute ? $attribute->value : null;
79+
}
80+
81+
/**
82+
* Helper to easily get the product image.
83+
*
84+
* @return null|string
85+
*/
86+
public function productImage($key)
87+
{
88+
$attribute = $this->customAttributes->where('attribute_type', 'image')->first();
89+
90+
if (Storage::exists('public/product/'. $attribute->value)) {
91+
return 'product/'. $attribute->value;
92+
}
93+
94+
return null;
95+
}
6696
}

tests/Models/MagentoProductModelTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,4 +96,32 @@ public function test_magento_product_can_get_categories()
9696
$this->assertNotEmpty($categories);
9797
$this->assertEquals(10, $categories->count());
9898
}
99+
100+
public function test_custom_attribute_value_helper_returns_value_of_custom_attribute()
101+
{
102+
$product = factory(MagentoProduct::class)->create();
103+
104+
factory(MagentoCustomAttribute::class)->create([
105+
'attributable_type' => MagentoProduct::class,
106+
'attributable_id' => $product->id,
107+
'attribute_type' => 'foo',
108+
'value' => 'bar',
109+
]);
110+
111+
$product = $product->with('customAttributes')->first();
112+
113+
$this->assertEquals(1, $product->customAttributes()->count());
114+
$this->assertEquals('bar', $product->customAttributeValue('foo'));
115+
}
116+
117+
118+
public function test_custom_attribute_value_helper_returns_null_of_invalid_custom_attribute()
119+
{
120+
$product = factory(MagentoProduct::class)->create();
121+
122+
$product = $product->with('customAttributes')->first();
123+
124+
$this->assertEquals(0, $product->customAttributes()->count());
125+
$this->assertNull($product->customAttributeValue('foo'));
126+
}
99127
}

0 commit comments

Comments
 (0)