HttpAsset.php 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /*
  3. * This file is part of the Assetic package, an OpenSky project.
  4. *
  5. * (c) 2010-2011 OpenSky Project Inc
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Assetic\Asset;
  11. use Assetic\Filter\FilterInterface;
  12. /**
  13. * Represents an asset loaded via an HTTP request.
  14. *
  15. * @author Kris Wallsmith <kris.wallsmith@gmail.com>
  16. */
  17. class HttpAsset extends BaseAsset
  18. {
  19. private $sourceUrl;
  20. private $ignoreErrors;
  21. /**
  22. * Constructor.
  23. *
  24. * @param string $sourceUrl The source URL
  25. * @param array $filters An array of filters
  26. *
  27. * @throws InvalidArgumentException If the first argument is not an URL
  28. */
  29. public function __construct($sourceUrl, $filters = array(), $ignoreErrors = false)
  30. {
  31. if (0 === strpos($sourceUrl, '//')) {
  32. $sourceUrl = 'http:'.$sourceUrl;
  33. } elseif (false === strpos($sourceUrl, '://')) {
  34. throw new \InvalidArgumentException(sprintf('"%s" is not a valid URL.', $sourceUrl));
  35. }
  36. $this->sourceUrl = $sourceUrl;
  37. $this->ignoreErrors = $ignoreErrors;
  38. list($scheme, $url) = explode('://', $sourceUrl, 2);
  39. list($host, $path) = explode('/', $url, 2);
  40. parent::__construct($filters, $scheme.'://'.$host, $path);
  41. }
  42. public function load(FilterInterface $additionalFilter = null)
  43. {
  44. if (false === $content = @file_get_contents($this->sourceUrl)) {
  45. if ($this->ignoreErrors) {
  46. return;
  47. } else {
  48. throw new \RuntimeException(sprintf('Unable to load asset from URL "%s"', $this->sourceUrl));
  49. }
  50. }
  51. $this->doLoad($content, $additionalFilter);
  52. }
  53. public function getLastModified()
  54. {
  55. if (false !== @file_get_contents($this->sourceUrl, false, stream_context_create(array('http' => array('method' => 'HEAD'))))) {
  56. foreach ($http_response_header as $header) {
  57. if (0 === stripos($header, 'Last-Modified: ')) {
  58. list(, $mtime) = explode(':', $header, 2);
  59. return strtotime(trim($mtime));
  60. }
  61. }
  62. }
  63. }
  64. }