RepositoryFactory.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. /**
  13. * @author Konstantin Kudryashiv <ever.zet@gmail.com>
  14. */
  15. class RepositoryFactory
  16. {
  17. private $classes = array();
  18. public function __construct(array $classes)
  19. {
  20. foreach ($classes as $class) {
  21. $this->registerRepositoryClass($class);
  22. }
  23. }
  24. public function registerRepositoryClass($class)
  25. {
  26. $reflection = new \ReflectionClass($class);
  27. if (!$reflection->implementsInterface('Composer\Repository\RepositoryInterface')) {
  28. throw new \InvalidArgumentException(
  29. 'Repository class should implement "RepositoryInterface", but "'.$class.'"'.
  30. 'given'
  31. );
  32. }
  33. $this->classes[] = $class;
  34. }
  35. public function classWhichSupports($type, $name = '', $url = '')
  36. {
  37. foreach ($this->classes as $class) {
  38. if ($class::supports($type, $name, $url)) {
  39. return $class;
  40. }
  41. }
  42. throw new \UnexpectedValueException(sprintf(
  43. "Can not find repository class, which supports:\n%s",
  44. json_encode(array($name => array($type => $url)))
  45. ));
  46. }
  47. public function create($type, $name = '', $url = '')
  48. {
  49. $class = $this->classWhichSupports($type, $name, $url);
  50. return $class::create($type, $name, $url);
  51. }
  52. }