Created
March 30, 2016 17:03
-
-
Save mattcdavis1/8b30d0dc7950d780c586d938347ebab1 to your computer and use it in GitHub Desktop.
Cache Asset Url
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace Union\Events\OnSaveEntry; | |
use Craft\EntryModel; | |
use Craft\ElementType; | |
use function Craft\craft; | |
class PhotoAlbumsListener | |
{ | |
protected $entry; | |
public function __construct(EntryModel $entry) | |
{ | |
$this->entry = $entry; | |
} | |
public function shouldHandleEvent() | |
{ | |
return true; | |
} | |
public function handleEvent() | |
{ | |
if(CRAFT_ENVIRONMENT !== 'console' && empty($this->entry->referenceId)) { | |
// don't save in console and don't save imported photos which were already watermarked | |
union('service.util.watermark')->saveWatermarkedPhotos($this->entry); | |
} | |
$this->updateAlbumCache(); | |
} | |
protected function updateAlbumCache() | |
{ | |
// get cover photo asset | |
$criteria = craft()->elements->getCriteria(ElementType::Asset); | |
$criteria->id = $this->entry->getContent()->photos; | |
$criteria->order = '(isCoverPhoto = 1) DESC'; | |
$criteria->limit = 1; | |
$coverPhoto = $criteria->first(); | |
// cache cover photo url | |
$cache = json_decode($this->entry->unionCache); | |
if(! $cache) { | |
$cache = (object) []; | |
} | |
if(isset($cache->coverPhotoUrl)) { | |
unset($cache->coverPhotoUrl); | |
} | |
if($coverPhoto) { | |
// get current transform setting so we can set it back when we're done | |
$initialTransformsSetting = craft()->config->get('generateTransformsBeforePageLoad'); | |
// force transform | |
// craft()->config->set('generateTransformsBeforePageLoad', true); | |
$coverPhotoUrl = $coverPhoto->getUrl('gridCover'); | |
$cache->coverPhoto = (object) [ | |
'url' => $coverPhotoUrl, | |
'height' => $coverPhoto->height, | |
'width' => $coverPhoto->width, | |
'id' => $coverPhoto->id, | |
'sourceId' => $coverPhoto->sourceId, | |
'folderId' => $coverPhoto->folderId, | |
'size' => $coverPhoto->size, | |
]; | |
// reset transform setting | |
craft()->config->set('generateTransformsBeforePageLoad', $initialTransformsSetting); | |
// update field outside of craft so we don't trigger endless loop of save events | |
craft()->db->createCommand()->update('content', | |
[ | |
'field_unionCache' => json_encode($cache), | |
], | |
['elementId' => $this->entry->id] | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment