I have the below class to connect to ldap server to check whether the user belongs to a group or not. i want to write unit test for this class. how do i achieve this. how to mock the ldap php native functions. can some one please help me with a bit of sample code.
<?php
namespace ABC\Admin\Login;
use Doctrine\ORM\EntityManagerInterface;
/**
* Class Authenticate AD Login
* @package Adp\Admin\Login
*/
class LdapAuthentication
{
/**
* @var string host
*/
private $ldapHost;
/**
* @var string Admin
*/
private $ldapDomain;
/**
* @var string DN
*/
private $baseDn;
/**
* @var EntityManagerInterface
*/
private $entityManager;
public function validateUser($user, $password)
{
$ad = ldap_connect("$this->ldapHost") or die('Could not connect to LDAP server.');
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ad, LDAP_OPT_REFERRALS, 0);
if (!ldap_bind($ad, "{$user}@{$this->ldapDomain}", $password)) {
return false;
}
$userDn = $this->getDN($ad, $user, $this->baseDn);
return $this->checkGroupEx($ad, $userDn, $groups);
ldap_unbind($ad);
}
/**
* @param $ad
* @param $samAccountName
* @param $baseDn
* @return string
*/
private function getDN($ad, $samAccountName, $baseDn)
{
$attributes = array('dn');
$result = ldap_search(
$ad,
$baseDn,
"(samaccountname={$samAccountName})",
$attributes
);
if ($result === false) {
return '';
}
$entries = ldap_get_entries($ad, $result);
if ($entries['count'] > 0) {
return $entries[0]['dn'];
}
return '';
}
/**
* @param $ad
* @param $userDn
* @param $groups
* @param $roles
* @return bool
*/
private function checkGroupEx($ad, $userDn, $groups)
{
$attributes = array('cn','memberof', 'mail');
$result = ldap_read($ad, $userDn, '(objectclass=*)', $attributes);
if ($result === false) {
return false;
};
$entries = ldap_get_entries($ad, $result);
$response = array();
$name = explode(',', $entries[0]['cn'][0]);
$response['firstName'] = $name[0];
$response['lastName'] = $name[1];
$response['email'] = $entries[0]['mail'][0];
if ($entries['count'] <= 0) {
return false;
};
if (empty($entries[0]['memberof'])) {
return false;
}
for ($i = 0; $i < $entries[0]['memberof']['count']; $i++) {
$groupName = explode(',', $entries[0]['memberof'][$i]);
$pos = array_search(strtolower(substr($groupName[0], 3)), $groups);
if (!empty($pos)) {
return $response;
}
}
return false;
}
/**
* @return string
*/
public function getBaseDn()
{
return $this->baseDn;
}
/**
* @param string $baseDn
*/
public function setBaseDn($baseDn)
{
$this->baseDn = $baseDn;
}
/**
* @return string
*/
public function getLdapDomain()
{
return $this->ldapDomain;
}
/**
* @param string $ldapDomain
*/
public function setLdapDomain($ldapDomain)
{
$this->ldapDomain = $ldapDomain;
}
/**
* @return string
*/
public function getLdapHost()
{
return $this->ldapHost;
}
/**
* @param string $ldapHost
*/
public function setLdapHost($ldapHost)
{
$this->ldapHost = $ldapHost;
}