This is an extension of #1875086: Improve DX of drupal_container()->get(), which leaves us with deprecated, inefficient, and clumsy code like
<?php
if (Drupal::getContainer()->has($context_name)) {
$context = Drupal::service($context_name);
// ...
}
?>
or having to catch exceptions as part of our normal program flow.
I'd like to have something like this instead:
<?php
if ($context = Drupal::service($context_name, TRUE)) {
// ...
}
?>
Symphony's \Symfony\Component\DependencyInjection\ContainerInterface already has the option to call get() with NULL_ON_INVALID_REFERENCE rather than the default EXCEPTION_ON_INVALID_REFERENCE, so this is easy to implement.
In image.inc we currently have this:
<?php
function image_get_info($filepath, ImageToolkitInterface $toolkit = NULL) {
$details = FALSE;
if (!is_file($filepath) && !is_uploaded_file($filepath)) {
return $details;
}
if ($toolkit === NULL) {
$toolkit = Drupal::service('image.toolkit'); // <=== can throw!
}
if ($toolkit) {
$image = new stdClass();
$image->source = $filepath;
$image->toolkit = $toolkit;
$details = $toolkit->getInfo($image);
if (isset($details) && is_array($details)) {
$details['file_size'] = filesize($filepath);
}
}
return $details;
}
?>
... which clearly assumes nothrow behavior. With the following line it will work as expected:
<?php
$toolkit = Drupal::service('image.toolkit', TRUE);
?>