FilesystemRepository.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Repository;
  12. use Composer\Json\JsonFile;
  13. use Composer\Package\Loader\ArrayLoader;
  14. use Composer\Package\Dumper\ArrayDumper;
  15. /**
  16. * Filesystem repository.
  17. *
  18. * @author Konstantin Kudryashov <ever.zet@gmail.com>
  19. * @author Jordi Boggiano <j.boggiano@seld.be>
  20. */
  21. class FilesystemRepository extends WritableArrayRepository
  22. {
  23. private $file;
  24. /**
  25. * Initializes filesystem repository.
  26. *
  27. * @param JsonFile $repositoryFile repository json file
  28. */
  29. public function __construct(JsonFile $repositoryFile)
  30. {
  31. $this->file = $repositoryFile;
  32. }
  33. /**
  34. * Initializes repository (reads file, or remote address).
  35. */
  36. protected function initialize()
  37. {
  38. parent::initialize();
  39. if (!$this->file->exists()) {
  40. return;
  41. }
  42. try {
  43. $packages = $this->file->read();
  44. if (!is_array($packages)) {
  45. throw new \UnexpectedValueException('Could not parse package list from the repository');
  46. }
  47. } catch (\Exception $e) {
  48. throw new InvalidRepositoryException('Invalid repository data in '.$this->file->getPath().', packages could not be loaded: ['.get_class($e).'] '.$e->getMessage());
  49. }
  50. $loader = new ArrayLoader();
  51. foreach ($packages as $packageData) {
  52. $package = $loader->load($packageData);
  53. $this->addPackage($package);
  54. }
  55. }
  56. public function reload()
  57. {
  58. $this->packages = null;
  59. $this->initialize();
  60. }
  61. /**
  62. * Writes writable repository.
  63. */
  64. public function write()
  65. {
  66. $data = array();
  67. $dumper = new ArrayDumper();
  68. foreach ($this->getCanonicalPackages() as $package) {
  69. $data[] = $dumper->dump($package);
  70. }
  71. $this->file->write($data);
  72. }
  73. }