ulmus-ldap/src/Common/LdapObject.php

125 lines
3.1 KiB
PHP

<?php
namespace Ulmus\Ldap\Common;
use function ldap_set_option, ldap_start_tls, ldap_bind, ldap_unbind, ldap_connect, ldap_close, ldap_get_entries, ldap_count_entries;
class LdapObject {
public static ? string $dump = null;
public $connection;
public $search;
public int $rowCount = 0;
public int $bufferedRows = 0;
public string $dn;
public bool $binded = false;
public function __destruct()
{
isset($this->connection) and ldap_close($this->connection);
}
public function connect(string $host, string $baseDn) : bool
{
$this->connection = ldap_connect($host);
$this->dn = $baseDn;
return $this->connection !== false;
}
public function setOptions(array $options, $useConnectionRessource = true) : void
{
foreach($options as $field => $value) {
ldap_set_option($useConnectionRessource ? $this->connection : null, $field, $value);
}
}
public function startTLS() : void
{
ldap_start_tls($this->connection);
}
public function bind(? string $dn, ? string $password) : bool
{
if ($this->binded) {
throw new \Exception("LdapObject is already binded with a user. Use the unbind() method to release it.");
}
return $this->binded = ldap_bind($this->connection, $dn, $password);
}
public function unbind() : void
{
if ($this->binded) {
$this->binded = ! ldap_unbind($this->connection);
}
}
public function select(array $filter, array $fields = [])
{
static::$dump && call_user_func_array(static::$dump, [ $filter, $fields ]);
$this->search = ldap_search($this->connection, $this->dn, $filter['filters'], $filter['fields'], 0, 0);
$this->rowCount = $this->bufferedRows = ldap_count_entries($this->connection, $this->search);
return $this;
}
public function fetch() /* : bool|array */
{
static $result;
if (! $this->search ) {
throw new \Exception('Impossible to fetch from LdapObject from which select() was not called first.');
}
if ( ! $this->bufferedRows ) {
return $result = false;
}
if ( $this->rowCount === $this->bufferedRows ) {
$result = ldap_first_entry($this->connection, $this->search);
}
else {
$result = ldap_next_entry($this->connection, $result);
}
if ($result) {
$this->bufferedRows--;
$dataset = [];
if ( $attributes = ldap_get_attributes($this->connection, $result) ) {
for ($i = 0; $i < $attributes['count']; $i++) {
$key = $attributes[$i];
$dataset[strtolower($key)] = $attributes[$key][0];
}
}
return $dataset;
}
return false;
}
public function rowCount() : int
{
return $this->rowCount;
}
public function fetchAll()
{
return ldap_get_entries($this->connection, $result);
}
public function closeCursor() : void {}
}