/** * @param StoreProduct $product * @param CUploadedFile $image */ public function __construct(StoreProduct $product, CUploadedFile $image) { $name = StoreUploadedImage::createName($product, $image); $fullPath = StoreUploadedImage::getSavePath() . '/' . $name; $image->saveAs($fullPath); @chmod($fullPath, 0666); // Check if product has main image $is_main = (int) StoreProductImage::model()->countByAttributes(array('product_id' => $product->id, 'is_main' => 1)); $imageModel = new StoreProductImage(); $imageModel->product_id = $product->id; $imageModel->name = $name; $imageModel->is_main = $is_main == 0 ? true : false; $imageModel->uploaded_by = Yii::app()->user->getId(); $imageModel->date_uploaded = date('Y-m-d H:i:s'); $imageModel->save(); $this->resize($fullPath); $this->watermark($fullPath); }
/** * Creates copy of product images * * @param StoreProduct $original * @param StoreProduct $copy */ protected function copyImages(StoreProduct $original, StoreProduct $copy) { $images = $original->images; if (!empty($images)) { foreach ($images as $image) { $image_copy = new StoreProductImage(); $image_copy->product_id = $copy->id; $image_copy->name = $image->name . '_' . $copy->id; $image_copy->is_main = $image->is_main; $image_copy->uploaded_by = $image->uploaded_by; $image_copy->title = $image->title; $image_copy->date_uploaded = date('Y-m-d H:i:s'); if ($image_copy->save()) { copy($image->filePath, $image_copy->filePath); } } } }
/** * @param StoreProduct $model */ public function updateMainImage(StoreProduct $model) { if (Yii::app()->request->getPost('mainImageId')) { // Clear current main image StoreProductImage::model()->updateAll(array('is_main' => 0), 'product_id=:pid', array(':pid' => $model->id)); // Set new main image StoreProductImage::model()->updateByPk(Yii::app()->request->getPost('mainImageId'), array('is_main' => 1)); } }
/** * Delete file, etc... */ public function afterDelete() { // Delete file if (file_exists($this->filePath)) { unlink($this->filePath); } // If main image was deleted if ($this->is_main) { // Get first image and set it as main $model = StoreProductImage::model()->find(); if ($model) { $model->is_main = 1; $model->save(false); } } return parent::afterDelete(); }