FilesystemRepository.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. // forward compatibility for composer v2 installed.json
  46. if (isset($packages['packages'])) {
  47. $packages = $packages['packages'];
  48. }
  49. if (!is_array($packages)) {
  50. throw new \UnexpectedValueException('Could not parse package list from the repository');
  51. }
  52. } catch (\Exception $e) {
  53. throw new InvalidRepositoryException('Invalid repository data in '.$this->file->getPath().', packages could not be loaded: ['.get_class($e).'] '.$e->getMessage());
  54. }
  55. $loader = new ArrayLoader(null, true);
  56. foreach ($packages as $packageData) {
  57. $package = $loader->load($packageData);
  58. $this->addPackage($package);
  59. }
  60. }
  61. public function reload()
  62. {
  63. $this->packages = null;
  64. $this->initialize();
  65. }
  66. /**
  67. * Writes writable repository.
  68. */
  69. public function write()
  70. {
  71. $data = array();
  72. $dumper = new ArrayDumper();
  73. foreach ($this->getCanonicalPackages() as $package) {
  74. $data[] = $dumper->dump($package);
  75. }
  76. usort($data, function ($a, $b) {
  77. return strcmp($a['name'], $b['name']);
  78. });
  79. $this->file->write($data);
  80. }
  81. }