File: D:/HostingSpaces/SBogers93/fitale.nl/workbench/komma/kms/src/Komma/Kms/Images/ImageRepository.php
<?php
namespace Komma\Kms\Images;
use Komma\Kms\Images\Models\Image;
class ImageRepository
{
protected $relatedModel;
/**
* @param String $model
*/
public function setRelatedModel($model)
{
$this->relatedModel = $model;
}
/**
* Delete old images from the database
* Save new images to the database
*
* @param $images
* @param $id
* @param string $attribute_key
*/
public function saveImages($images, $id, $attribute_key = 'images')
{
if (is_array($images)) {
// Loop through each image
foreach ($images as $key => $image) {
// Check if we need to delete an image
if (isset($image->delete) && $image->delete == true) {
// Destroy the image
Image::destroy($image->id);
// Skip import part below
continue;
} // Add a new image
else {
// Find model
$model = Image::find($image->id) ? Image::find($image->id) : new Image();
// Update model data
if (isset($image->original)) $model->original_image_url = $image->original;
if (isset($image->large)) $model->large_image_url = $image->large;
if (isset($image->medium)) $model->medium_image_url = $image->medium;
if (isset($image->small)) $model->small_image_url = $image->small;
if (isset($image->thumb)) $model->thumb_image_url = $image->thumb;
// Set related model and id
$model->imageble_type = $this->relatedModel;
$model->imageble_id = $id;
$model->attribute_key = $attribute_key;
//Set the weight of image the key +1, so it starts with 1
$model->sort_order = $key+1;
// Save image model
$model->save();
}
}
}
}
/**
* Get images from the database
*
* @param $id
* @param string $attributeKey
* @return array
*/
public function getImages($id, $attributeKey = 'images')
{
$images = [];
// Find image record that belong to our related model
$imageRecords = Image::where('imageble_type', $this->relatedModel)
->where('imageble_id', $id)
->where('attribute_key', $attributeKey)
->orderBy('sort_order', 'ASC')
->get();
// Loop through images
foreach ($imageRecords as $record) {
$image = $images[] = new \stdClass();
$image->id = $record->id;
$image->original = $record->original_image_url;
$image->large = $record->large_image_url;
$image->medium = $record->medium_image_url;
$image->small = $record->small_image_url;
$image->thumb = $record->thumb_image_url;
}
return $images;
}
}