I have a curious issue that when an ActiveRecord row is deleted, the image file whose path was stored in that row is also deleted.
I’m using oEmbed to validate a video url and retrieve the thumbnail. The thumbnail is saved to disk and a copy is made (imgA.png and imgA-original.png)
$thumbnailUrl = $this->getVideo('thumbnail');
$thumbnail = new Image($thumbnailUrl); // using Treinetic\ImageArtist
// crop and scale the thumbnail
// Save this image and later overlay a play button
$thumbnail->save($this->thumbnailBaseFilename . '.png', IMAGETYPE_PNG);
// Save the original image
copy($this->thumbnailBaseFilename . '.png', $this->thumbnailBaseFilename . '-original.png');
// Save path to db
$this->updateAttributes(['video_thumbnail' => $this->thumbnailFilename . '.png']);
Note that only the path for imgA.png is saved to db. Later on, if I delete the AR row with $block->delete()
, imgA.png is also deleted, but imgA-original.png is left.
Another strange thing happens if I duplicate the AR row, copy both images to new filenames (e.g. imgB.png and imgB-original.png), and save the new filename (imgB.png) to the new row. Now if I delete this new AR row, the image from the first AR is deleted (imgA.png). The other three images are left (imgA-original.png, imgB.png, imgB-original.png).
public function duplicateBlock()
{
// new block
$block = $this->block;
$blockAttr = $block->attributes;
unset($blockAttr[$block->primaryKey()[0]]);
$blockClassName = $block::className();
$newBlock = new $blockClassName();
$newBlock->save();
$newBlock->updateAttributes($blockAttr);
//
$newBlock->duplicateVideoThumbnail($block->id);
}
public function duplicateVideoThumbnail($bid)
{
$oldBlock = self::findOne($bid);
$oldFilename = Yii::getAlias('@webroot') . self::UPLOAD_PATH . $oldBlock->hasBlock->id . '-' . $oldBlock->id;
$newFilename = Yii::getAlias('@webroot') . self::UPLOAD_PATH . $this->hasBlock->id . '-' . $this->id;
if (file_exists($oldFilename . '.png')) {
copy($oldFilename . '.png', $newFilename . '.png');
}
if (file_exists($oldFilename . '-original.png')) {
copy($oldFilename . '-original.png', $newFilename . '-original.png');
}
}