diff --git a/src/Encrypt.php b/src/Encrypt.php index 479a12bd..a9d83697 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -38,9 +38,41 @@ public function __construct($options = null) $this->setAdapter($options); } + /** + * Returns the adapter instance + * + * @throws Exception\RuntimeException + * @throws Exception\InvalidArgumentException + * @return Encrypt\EncryptionAlgorithmInterface + */ + public function getAdapterInstance() + { + if ($this->adapter instanceof Encrypt\EncryptionAlgorithmInterface) { + return $this->adapter; + } + + $adapter = $this->adapter; + $options = $this->getOptions(); + if (!class_exists($adapter)) { + $adapter = 'Zend\\Filter\\Encrypt\\' . ucfirst($adapter); + if (!class_exists($adapter)) { + throw new Exception\RuntimeException(sprintf( + '%s unable to load adapter; class "%s" not found', + __METHOD__, + $this->adapter + )); + } + } + + $this->adapter = new $adapter($options); + if (!$this->adapter instanceof Encrypt\EncryptionAlgorithmInterface) { + throw new Exception\InvalidArgumentException("Encryption adapter '" . $adapter . "' does not implement Zend\\Filter\\Encrypt\\EncryptionAlgorithmInterface"); + } + return $this->adapter; + } + /** * Returns the name of the set adapter - * @todo inconsitent: get adapter should return the adapter and not the name * * @return string */ diff --git a/test/DecryptTest.php b/test/DecryptTest.php index a6719783..43fd4eab 100644 --- a/test/DecryptTest.php +++ b/test/DecryptTest.php @@ -116,9 +116,11 @@ public function testSettingAdapterManually() $filter = new DecryptFilter(); $filter->setAdapter('Openssl'); $this->assertEquals('Openssl', $filter->getAdapter()); + $this->assertInstanceOf('Zend\Filter\Encrypt\EncryptionAlgorithmInterface', $filter->getAdapterInstance()); $filter->setAdapter('BlockCipher'); $this->assertEquals('BlockCipher', $filter->getAdapter()); + $this->assertInstanceOf('Zend\Filter\Encrypt\EncryptionAlgorithmInterface', $filter->getAdapterInstance()); $this->setExpectedException('\Zend\Filter\Exception\InvalidArgumentException', 'does not implement'); $filter->setAdapter('\\ZendTest\\Filter\\TestAdapter'); diff --git a/test/EncryptTest.php b/test/EncryptTest.php index 07d524ac..98e44db4 100644 --- a/test/EncryptTest.php +++ b/test/EncryptTest.php @@ -126,9 +126,11 @@ public function testSettingAdapterManually() $filter = new EncryptFilter(); $filter->setAdapter('Openssl'); $this->assertEquals('Openssl', $filter->getAdapter()); + $this->assertInstanceOf('Zend\Filter\Encrypt\EncryptionAlgorithmInterface', $filter->getAdapterInstance()); $filter->setAdapter('BlockCipher'); $this->assertEquals('BlockCipher', $filter->getAdapter()); + $this->assertInstanceOf('Zend\Filter\Encrypt\EncryptionAlgorithmInterface', $filter->getAdapterInstance()); $this->setExpectedException('Zend\Filter\Exception\InvalidArgumentException', 'does not implement'); $filter->setAdapter('\ZendTest\Filter\TestAdapter2');