1<?php 2/** 3 * This file is part of the FreeDSx LDAP package. 4 * 5 * (c) Chad Sikorra <Chad.Sikorra@gmail.com> 6 * 7 * For the full copyright and license information, please view the LICENSE 8 * file that was distributed with this source code. 9 */ 10 11namespace FreeDSx\Ldap\Entry; 12 13use FreeDSx\Ldap\Exception\InvalidArgumentException; 14 15/** 16 * Represents a collection of entry objects. 17 * 18 * @author Chad Sikorra <Chad.Sikorra@gmail.com> 19 */ 20class Entries implements \Countable, \IteratorAggregate 21{ 22 /** 23 * @var Entry[] 24 */ 25 protected $entries = []; 26 27 /** 28 * @param Entry ...$entries 29 */ 30 public function __construct(Entry ...$entries) 31 { 32 $this->entries = $entries; 33 } 34 35 /** 36 * @param Entry ...$entries 37 * @return $this 38 */ 39 public function add(Entry ...$entries) 40 { 41 $this->entries = \array_merge($this->entries, $entries); 42 43 return $this; 44 } 45 46 /** 47 * @param Entry ...$entries 48 * @return $this 49 */ 50 public function remove(Entry ...$entries) 51 { 52 foreach ($entries as $entry) { 53 if (($index = \array_search($entry, $this->entries, true)) !== false) { 54 unset($this->entries[$index]); 55 } 56 } 57 58 return $this; 59 } 60 61 /** 62 * Check whether or not an entry (either an Entry object or string DN) exists within the entries. 63 * 64 * @param Entry|Dn|string $entry 65 * @return bool 66 */ 67 public function has($entry): bool 68 { 69 if ($entry instanceof Entry) { 70 return (\array_search($entry, $this->entries, true) !== false); 71 } 72 73 foreach ($this->entries as $entryObj) { 74 if ((string) $entry === $entryObj->getDn()->toString()) { 75 return true; 76 } 77 } 78 79 return false; 80 } 81 82 /** 83 * Get an entry from the collection by its DN. 84 * 85 * @param string $dn 86 * @return Entry|null 87 */ 88 public function get(string $dn): ?Entry 89 { 90 foreach ($this->entries as $entry) { 91 if ($entry->getDn()->toString() === $dn) { 92 return $entry; 93 } 94 } 95 96 return null; 97 } 98 99 /** 100 * Get the first entry object, if one exists. 101 * 102 * @return Entry|null 103 */ 104 public function first(): ?Entry 105 { 106 $entry = \reset($this->entries); 107 108 return $entry === false ? null : $entry; 109 } 110 111 /** 112 * Get the last entry object, if one exists. 113 * 114 * @return Entry|null 115 */ 116 public function last(): ?Entry 117 { 118 $entry = \end($this->entries); 119 \reset($this->entries); 120 121 return $entry === false ? null : $entry; 122 } 123 124 /** 125 * @return Entry[] 126 */ 127 public function toArray(): array 128 { 129 return $this->entries; 130 } 131 132 /** 133 * @return \ArrayIterator 134 */ 135 public function getIterator() 136 { 137 return new \ArrayIterator($this->entries); 138 } 139 140 /** 141 * @return int 142 */ 143 public function count() 144 { 145 return \count($this->entries); 146 } 147} 148