MultiConstraint.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. <?php
  2. /*
  3. * This file is part of composer/semver.
  4. *
  5. * (c) Composer <https://github.com/composer>
  6. *
  7. * For the full copyright and license information, please view
  8. * the LICENSE file that was distributed with this source code.
  9. */
  10. namespace Composer\Semver\Constraint;
  11. /**
  12. * Defines a conjunctive or disjunctive set of constraints.
  13. */
  14. class MultiConstraint implements ConstraintInterface
  15. {
  16. /** @var ConstraintInterface[] */
  17. protected $constraints;
  18. /** @var string */
  19. protected $prettyString;
  20. /** @var bool */
  21. protected $conjunctive;
  22. /**
  23. * @param ConstraintInterface[] $constraints A set of constraints
  24. * @param bool $conjunctive Whether the constraints should be treated as conjunctive or disjunctive
  25. */
  26. public function __construct(array $constraints, $conjunctive = true)
  27. {
  28. $this->constraints = $constraints;
  29. $this->conjunctive = $conjunctive;
  30. }
  31. /**
  32. * @return ConstraintInterface[]
  33. */
  34. public function getConstraints()
  35. {
  36. return $this->constraints;
  37. }
  38. /**
  39. * @return bool
  40. */
  41. public function isConjunctive()
  42. {
  43. return $this->conjunctive;
  44. }
  45. /**
  46. * @return bool
  47. */
  48. public function isDisjunctive()
  49. {
  50. return !$this->conjunctive;
  51. }
  52. /**
  53. * @param ConstraintInterface $provider
  54. *
  55. * @return bool
  56. */
  57. public function matches(ConstraintInterface $provider)
  58. {
  59. if (false === $this->conjunctive) {
  60. foreach ($this->constraints as $constraint) {
  61. if ($constraint->matches($provider)) {
  62. return true;
  63. }
  64. }
  65. return false;
  66. }
  67. foreach ($this->constraints as $constraint) {
  68. if (!$constraint->matches($provider)) {
  69. return false;
  70. }
  71. }
  72. return true;
  73. }
  74. /**
  75. * @param string $prettyString
  76. */
  77. public function setPrettyString($prettyString)
  78. {
  79. $this->prettyString = $prettyString;
  80. }
  81. /**
  82. * @return string
  83. */
  84. public function getPrettyString()
  85. {
  86. if ($this->prettyString) {
  87. return $this->prettyString;
  88. }
  89. return (string) $this;
  90. }
  91. /**
  92. * @return string
  93. */
  94. public function __toString()
  95. {
  96. $constraints = array();
  97. foreach ($this->constraints as $constraint) {
  98. $constraints[] = (string) $constraint;
  99. }
  100. return '[' . implode($this->conjunctive ? ' ' : ' || ', $constraints) . ']';
  101. }
  102. }