mivita/app/Repositories/ProductRepository.php
2020-01-02 19:22:30 +01:00

147 lines
No EOL
3.5 KiB
PHP

<?php
namespace App\Repositories;
use App\Models\Product;
use App\Models\ProductAttribute;
use App\Models\ProductCategory;
use App\Models\ProductImage;
class ProductRepository extends BaseRepository {
public function __construct(Product $model)
{
$this->model = $model;
}
/**
* refresh.
*/
public function update($data)
{
$data['active'] = isset($data['active']) ? 1 : 0;
if($data['id'] == "new"){
$this->model = Product::create($data);
}
else{
$this->model = $this->getById($data['id']);
$this->model->fill($data);
$this->model->save();
}
$this->updateCategories(isset($data['categories']) ? $data['categories'] : array());
$this->updateAttributes(isset($data['attributes']) ? $data['attributes'] : array());
return $this->model;
}
public function updateCategories($data = array())
{
foreach ($this->model->categories as $category) {
if(($pos = array_search($category->category_id, $data)) !== FALSE){
unset($data[$pos]);
}else{
$category->delete();
}
}
//set attr
if(is_array($data)){
foreach ($data as $id) {
ProductCategory::create([
'product_id' => $this->model->id,
'category_id' => $id,
]);
}
}
return true;
}
public function updateAttributes($data = array())
{
foreach ($this->model->attributes as $attribute) {
if(($pos = array_search($attribute->attribute_id, $data)) !== FALSE){
unset($data[$pos]);
}else{
$attribute->delete();
}
}
//set attr
if(is_array($data)){
foreach ($data as $id) {
ProductAttribute::create([
'product_id' => $this->model->id,
'attribute_id' => $id,
]);
}
}
return true;
}
public function copy($model)
{
$this->model = $model->replicate();
$this->model->name = "Kopie: ".$this->model->name;
$this->model->save();
//categories
foreach ($model->categories as $category){
ProductCategory::create([
'product_id' => $this->model->id,
'category_id' => $category->category_id,
]);
}
//attributes
foreach ($model->attributes as $attribute){
ProductAttribute::create([
'product_id' => $this->model->id,
'attribute_id' => $attribute->attribute_id,
]);
}
//images
foreach ($model->images as $image){
$name = \App\Services\Slim::sanitizeFileName($image->original_name);
$name = uniqid() . '_' . $name;
//copy
$data = \Storage::disk('public')->copy(
'images/product/'.$image->product_id.'/'.$image->filename,
'images/product/'.$this->model->id.'/'.$name
);
ProductImage::create([
'product_id' => $this->model->id,
'filename' => $name,
'original_name' => $image->original_name,
'ext' => $image->ext,
'mine' => $image->mine,
'size' => $image->size
]);
}
return $this->model;
}
public function delete()
{
}
}