/** * Copies the image to the assets folder and save's it in the database. * * @param string $absolutePath The path were the image is uploaded * @param bool $isMain A flag to determine if the image is the main image * @param string $identifier The index that has to be set for the image in the database * @return bool|Image * @throws \Exception */ public function attachImage($absolutePath, $isMain = false, $identifier = '') { if (!preg_match('#http#', $absolutePath)) { if (!file_exists($absolutePath)) { throw new \Exception('File not exist! :' . $absolutePath); } } else { //nothing } if (!$this->owner->primaryKey) { throw new \Exception('Owner must have primaryKey when you attach image!'); } $pictureFileName = basename($absolutePath); $pictureSubDir = $this->getModule()->getModelSubDir($this->owner); $storePath = $this->getModule()->getStorePath($this->owner); $newAbsolutePath = $storePath . DIRECTORY_SEPARATOR . $pictureSubDir . DIRECTORY_SEPARATOR . $pictureFileName; BaseFileHelper::createDirectory($storePath . DIRECTORY_SEPARATOR . $pictureSubDir, 0775, true); copy($absolutePath, $newAbsolutePath); unlink($absolutePath); if (!file_exists($newAbsolutePath)) { throw new \Exception('Cant copy file! ' . $absolutePath . ' to ' . $newAbsolutePath); } $image = new Image(); $image->itemId = $this->owner->primaryKey; $image->filePath = $pictureSubDir . '/' . $pictureFileName; $image->modelName = $this->getModule()->getShortClass($this->owner); $image->urlAlias = $this->getAlias($image); $image->identifier = $identifier; $image->name = substr(yii\helpers\Inflector::slug($pictureFileName), 0, -3); // Get the highest position // @todo Create function $owner = $this->owner; $query = (new yii\db\Query())->select('MAX(`position`)')->from(Image::tableName())->where(['modelName' => yii\helpers\StringHelper::basename($owner::className())]); $command = $query->createCommand(); $image->position = $command->queryOne(\PDO::FETCH_COLUMN) + 1; if (!$image->save()) { return false; } // Add the translations foreach (Yii::$app->params['languages'] as $language => $data) { $imageLang = new ImageLang(); $imageLang->language = $language; $image->link('translations', $imageLang); } if (count($image->getErrors()) > 0) { $ar = array_shift($image->getErrors()); unlink($newAbsolutePath); throw new \Exception(array_shift($ar)); } $img = $this->owner->getImage(); $this->setMainImage($image); return $image; }