Skip to content

Instantly share code, notes, and snippets.

@scott1702
Created January 21, 2020 03:14
Show Gist options
  • Save scott1702/4e241ef795ebe6a3a66d97e6dcaa22f0 to your computer and use it in GitHub Desktop.
Save scott1702/4e241ef795ebe6a3a66d97e6dcaa22f0 to your computer and use it in GitHub Desktop.
Embedded content errors taking down pages
ShortcodeParser::get('default')
->register('embed', [CustomEmbedShortcodeProvider::class, 'handle_shortcode']);
---
Name: app_cache
---
SilverStripe\Core\Injector\Injector:
Psr\SimpleCache\CacheInterface.mycachenamespace:
factory: SilverStripe\Core\Cache\CacheFactory
constructor:
namespace: 'mycachenamespace'
defaultLifetime: 86400
<?php
use Psr\SimpleCache\CacheInterface;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\View\Shortcodes\EmbedShortcodeProvider;
class CustomEmbedShortcodeProvider extends EmbedShortcodeProvider
{
/**
* Override handle_shortcode to catch errors from embedded content (e.g. rate limited by Youtube).
* This will ensure only the video fails to show in the case of an error, rather than throwing a
* server error and taking down the whole page. Also store the result in a cache to reduce the amount
* of calls made to external services.
* https://github.com/silverstripe/silverstripe-framework/issues/9073
*/
public static function handle_shortcode($arguments, $content, $parser, $shortcode, $extra = array())
{
$cache = Injector::inst()->get(CacheInterface::class . '.mycachenamespace');
$cacheKey = 'embed_shortcode_cache_' . preg_replace('/[^a-zA-Z0-9]/', '', implode('-_-', $arguments));
if ($cache->has($cacheKey)) {
return $cache->get($cacheKey);
}
try {
$output = parent::handle_shortcode($arguments, $content, $parser, $shortcode, $extra = array());
$cache->set($cacheKey, $output);
return $output;
} catch (Exception $exception) {
// log error as preferred
}
return '';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment