CoalescingDirectoryResource.php 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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\Factory\Resource;
  11. /**
  12. * Coalesces multiple directories together into one merged resource.
  13. *
  14. * @author Kris Wallsmith <kris.wallsmith@gmail.com>
  15. */
  16. class CoalescingDirectoryResource implements IteratorResourceInterface
  17. {
  18. private $directories;
  19. public function __construct($directories)
  20. {
  21. $this->directories = array();
  22. foreach ($directories as $directory) {
  23. $this->addDirectory($directory);
  24. }
  25. }
  26. public function addDirectory(IteratorResourceInterface $directory)
  27. {
  28. $this->directories[] = $directory;
  29. }
  30. public function isFresh($timestamp)
  31. {
  32. foreach ($this->getFileResources() as $file) {
  33. if (!$file->isFresh($timestamp)) {
  34. return false;
  35. }
  36. }
  37. return true;
  38. }
  39. public function getContent()
  40. {
  41. $parts = array();
  42. foreach ($this->getFileResources() as $file) {
  43. $parts[] = $file->getContent();
  44. }
  45. return implode("\n", $parts);
  46. }
  47. /**
  48. * Returns a string to uniquely identify the current resource.
  49. *
  50. * @return string An identifying string
  51. */
  52. public function __toString()
  53. {
  54. $parts = array();
  55. foreach ($this->directories as $directory) {
  56. $parts[] = (string) $directory;
  57. }
  58. return implode(',', $parts);
  59. }
  60. public function getIterator()
  61. {
  62. return new \ArrayIterator($this->getFileResources());
  63. }
  64. /**
  65. * Returns the relative version of a filename.
  66. *
  67. * @param ResourceInterface $file The file
  68. * @param ResourceInterface $directory The directory
  69. *
  70. * @return string The name to compare with files from other directories
  71. */
  72. protected function getRelativeName(ResourceInterface $file, ResourceInterface $directory)
  73. {
  74. return substr((string) $file, strlen((string) $directory));
  75. }
  76. /**
  77. * Performs the coalesce.
  78. *
  79. * @return array An array of file resources
  80. */
  81. private function getFileResources()
  82. {
  83. $paths = array();
  84. foreach ($this->directories as $directory) {
  85. foreach ($directory as $file) {
  86. $relative = $this->getRelativeName($file, $directory);
  87. if (!isset($paths[$relative])) {
  88. $paths[$relative] = $file;
  89. }
  90. }
  91. }
  92. return array_values($paths);
  93. }
  94. }