Created
January 21, 2020 03:14
-
-
Save scott1702/4e241ef795ebe6a3a66d97e6dcaa22f0 to your computer and use it in GitHub Desktop.
Embedded content errors taking down pages
This file contains hidden or 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
ShortcodeParser::get('default') | |
->register('embed', [CustomEmbedShortcodeProvider::class, 'handle_shortcode']); |
This file contains hidden or 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
--- | |
Name: app_cache | |
--- | |
SilverStripe\Core\Injector\Injector: | |
Psr\SimpleCache\CacheInterface.mycachenamespace: | |
factory: SilverStripe\Core\Cache\CacheFactory | |
constructor: | |
namespace: 'mycachenamespace' | |
defaultLifetime: 86400 |
This file contains hidden or 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 | |
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