FilesystemRepository.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. parent::__construct();
  32. $this->file = $repositoryFile;
  33. }
  34. /**
  35. * Initializes repository (reads file, or remote address).
  36. */
  37. protected function initialize()
  38. {
  39. parent::initialize();
  40. if (!$this->file->exists()) {
  41. return;
  42. }
  43. try {
  44. $packages = $this->file->read();
  45. if (!is_array($packages)) {
  46. throw new \UnexpectedValueException('Could not parse package list from the repository');
  47. }
  48. } catch (\Exception $e) {
  49. throw new InvalidRepositoryException('Invalid repository data in '.$this->file->getPath().', packages could not be loaded: ['.get_class($e).'] '.$e->getMessage());
  50. }
  51. $loader = new ArrayLoader(null, true);
  52. foreach ($packages as $packageData) {
  53. $package = $loader->load($packageData);
  54. $this->addPackage($package);
  55. }
  56. }
  57. public function reload()
  58. {
  59. $this->packages = null;
  60. $this->initialize();
  61. }
  62. /**
  63. * Writes writable repository.
  64. */
  65. public function write()
  66. {
  67. $data = array();
  68. $dumper = new ArrayDumper();
  69. foreach ($this->getCanonicalPackages() as $package) {
  70. $data[] = $dumper->dump($package);
  71. }
  72. $this->file->write($data);
  73. }
  74. }