SimpleLdapConnection.php in Simple LDAP 8
File
src/SimpleLdapConnection.php
View source
<?php
namespace Drupal\simple_ldap;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\simple_ldap\SimpleLdapException;
use Drupal\simple_ldap\SimpleLdapConnectionInterface;
class SimpleLdapConnection implements SimpleLdapConnectionInterface {
protected $config;
protected $connection_string;
private $connection;
public function __construct(ConfigFactoryInterface $config_factory) {
$this->config = $config_factory
->get('simple_ldap.server');
$connection_prefix = $this->config
->get('encryption') === 'ssl' ? 'ldaps://' : 'ldap://';
$this->connection_string = $connection_prefix . $this->config
->get('host') . ':' . $this->config
->get('port');
}
public function __destruct() {
$this
->disconnect();
}
public function connect() {
if ($this->connection) {
return;
}
$this->connection = @ldap_connect($this->connection_string);
@ldap_set_option($this->connection, LDAP_OPT_NETWORK_TIMEOUT, 10);
if ($this->connection === FALSE) {
throw new SimpleLdapException('Could not connect to LDAP server: ', $this->connection);
}
if ($this->config
->get('encryption') === 'tls' && ldap_start_tls($this->connection) === FALSE) {
throw new SimpleLdapException('Could not start TLS connection: ', $this->connection);
}
@ldap_set_option($this->connection, LDAP_OPT_PROTOCOL_VERSION, 3);
@ldap_set_option($this->connection, LDAP_OPT_REFERRALS, (int) $this->config
->get('opt_referrals'));
}
public function disconnect() {
if ($this->connection && is_resource($this->connection)) {
ldap_close($this->connection);
}
$this->connection = NULL;
}
public function getResource() {
return $this->connection;
}
}