AbstractSet.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. /**
  3. * This file is part of the ramsey/collection library
  4. *
  5. * For the full copyright and license information, please view the LICENSE
  6. * file that was distributed with this source code.
  7. *
  8. * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
  9. * @license http://opensource.org/licenses/MIT MIT
  10. */
  11. declare(strict_types=1);
  12. namespace Ramsey\Collection;
  13. /**
  14. * This class contains the basic implementation of a collection that does not
  15. * allow duplicated values (a set), to minimize the effort required to implement
  16. * this specific type of collection.
  17. *
  18. * @template T
  19. * @extends AbstractCollection<T>
  20. */
  21. abstract class AbstractSet extends AbstractCollection
  22. {
  23. public function add(mixed $element): bool
  24. {
  25. if ($this->contains($element)) {
  26. return false;
  27. }
  28. // Call offsetSet() on the parent instead of add(), since calling
  29. // parent::add() will invoke $this->offsetSet(), which will call
  30. // $this->contains() a second time. This can cause performance issues
  31. // with extremely large collections. For more information, see
  32. // https://github.com/ramsey/collection/issues/68.
  33. parent::offsetSet(null, $element);
  34. return true;
  35. }
  36. public function offsetSet(mixed $offset, mixed $value): void
  37. {
  38. if ($this->contains($value)) {
  39. return;
  40. }
  41. parent::offsetSet($offset, $value);
  42. }
  43. }