Skip to content

Instantly share code, notes, and snippets.

@renaatdemuynck
Created September 24, 2015 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renaatdemuynck/5fccfb6b4900e8347fa3 to your computer and use it in GitHub Desktop.
Save renaatdemuynck/5fccfb6b4900e8347fa3 to your computer and use it in GitHub Desktop.
Chainable authentication adapters in Zend Framework
<?php
namespace My\Authentication\Adapter;
use Zend\Authentication\Adapter\AbstractAdapter;
use Zend\Authentication\Adapter\Exception\InvalidArgumentException;
use Zend\Authentication\Adapter\ValidatableAdapterInterface;
use Zend\Authentication\Result;
class AdapterChain extends AbstractAdapter
{
private $adapters;
public function __construct(array $adapters)
{
if (count($adapters) < 1) {
throw new InvalidArgumentException('There must be at least one authentication adapter');
}
foreach ($adapters as $adapter) {
if (!($adapter instanceof ValidatableAdapterInterface)) {
throw new InvalidArgumentException('All adapters must implement ValidatableAdapterInterface');
}
}
$this->adapters = $adapters;
}
public function authenticate()
{
if (!$this->identity) {
return new Result(Result::FAILURE_IDENTITY_NOT_FOUND, '', [
'A username is required'
]);
}
if (!$this->credential) {
return new Result(Result::FAILURE_CREDENTIAL_INVALID, '', [
'A password is required'
]);
}
// try all adapters in the chain
foreach ($this->adapters as $adapter) {
$adapter->setIdentity($this->identity);
$adapter->setCredential($this->credential);
$result = $adapter->authenticate();
// try the next adapter if the identity is not found
if ($result->getCode() === Result::FAILURE_IDENTITY_NOT_FOUND) {
continue;
}
return $result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment