Skip to content

Instantly share code, notes, and snippets.

@ohnotnow
Created October 7, 2016 11:54
Show Gist options
  • Save ohnotnow/697cf121525602c9c63abe46dbdcd53f to your computer and use it in GitHub Desktop.
Save ohnotnow/697cf121525602c9c63abe46dbdcd53f to your computer and use it in GitHub Desktop.
Testing/mocking stdlib function
<?php
/*
This is a contrived example - but I'm working on a large PHPv4 style legacy codebase
and it's full of this kind of code (only much, much worse - c70,000 lines of raw
mysql calls etc).
So in this case I could use the 'namespace' mocking trick to mock all of the
functions - but to test things like "everything passes", "connection works, but TLS
fails", "password is wrong" etc, seems hard to do without the tests
getting really quite nasty. Combined with all the raw mysql* function calls it
makes writing tests/refactoring much more, ahem, 'exciting' than I'd like ;-)
*/
function auth_ldap($username, $password, $server, $ou)
{
$ldapconn = ldap_connect($server);
if (!$ldapconn) {
return "Could not connect to server!";
}
if (! ldap_start_tls($ldapconn)) {
return "Could not start TLS connection to server!";
}
$ldapbind = @ldap_bind($ldapconn);
$search = ldap_search($ldapconn, $ou, "uid={$username}");
if (ldap_count_entries($ldapconn, $search) != 1) {
ldap_unbind($ldapconn);
return "Could not find user!";
}
$info = ldap_get_entries($ldapconn, $search);
$ldapbind = @ldap_bind($ldapconn, $info[0]['dn'], $password);
if (!$ldapbind) {
ldap_unbind($ldapconn);
return "Could not authenticate user!";
}
$search = ldap_search($ldapconn, $ou, "uid={$username}");
$info = ldap_get_entries($ldapconn, $search);
$userData = array(
'username' => $username,
'surname' => $info[0]['sn'][0],
'forenames' => $info[0]['givenname'][0],
'email' => $info[0]['mail'][0],
);
ldap_unbind($ldapconn);
return $userData;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment