vendor/liip/imagine-bundle/Binary/Loader/StreamLoader.php line 63

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the `liip/LiipImagineBundle` project.
  4.  *
  5.  * (c) https://github.com/liip/LiipImagineBundle/graphs/contributors
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE.md
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Liip\ImagineBundle\Binary\Loader;
  11. use Liip\ImagineBundle\Exception\Binary\Loader\NotLoadableException;
  12. class StreamLoader implements LoaderInterface
  13. {
  14.     /**
  15.      * The wrapper prefix to append to the path to be loaded.
  16.      *
  17.      * @var string
  18.      */
  19.     protected $wrapperPrefix;
  20.     /**
  21.      * A stream context resource to use.
  22.      *
  23.      * @var resource|null
  24.      */
  25.     protected $context;
  26.     /**
  27.      * @param string        $wrapperPrefix
  28.      * @param resource|null $context
  29.      *
  30.      * @throws \InvalidArgumentException
  31.      */
  32.     public function __construct($wrapperPrefix, $context = null)
  33.     {
  34.         $this->wrapperPrefix = $wrapperPrefix;
  35.         if ($context && !\is_resource($context)) {
  36.             throw new \InvalidArgumentException('The given context is no valid resource.');
  37.         }
  38.         $this->context = empty($context) ? null : $context;
  39.     }
  40.     /**
  41.      * {@inheritdoc}
  42.      */
  43.     public function find($path)
  44.     {
  45.         $name = $this->wrapperPrefix.$path;
  46.         /*
  47.          * This looks strange, but at least in PHP 5.3.8 it will raise an E_WARNING if the 4th parameter is null.
  48.          * fopen() will be called only once with the correct arguments.
  49.          *
  50.          * The error suppression is solely to determine whether the file exists.
  51.          * file_exists() is not used as not all wrappers support stat() to actually check for existing resources.
  52.          */
  53.         if (($this->context && !$resource = @fopen($name, 'rb', false, $this->context)) || !$resource = @fopen($name, 'rb')) {
  54.             throw new NotLoadableException(sprintf('Source image %s not found.', $name));
  55.         }
  56.         // Closing the opened stream to avoid locking of the resource to find.
  57.         fclose($resource);
  58.         try {
  59.             $content = file_get_contents($name, false, $this->context);
  60.         } catch (\Exception $e) {
  61.             throw new NotLoadableException(sprintf('Source image %s could not be loaded.', $name), $e->getCode(), $e);
  62.         }
  63.         if (false === $content) {
  64.             throw new NotLoadableException(sprintf('Source image %s could not be loaded.', $name));
  65.         }
  66.         return $content;
  67.     }
  68. }