Browse Source

Merge pull request #4437 from cakephp/3.0-exceptions

Update exceptions used in cache engines.
José Lorenzo Rodríguez 11 years ago
parent
commit
8bff03dcdc

+ 37 - 16
src/Cache/Engine/FileEngine.php

@@ -16,8 +16,9 @@ namespace Cake\Cache\Engine;
 
 use Cake\Cache\CacheEngine;
 use Cake\Core\Configure;
-use Cake\Core\Exception\Exception;
 use Cake\Utility\Inflector;
+use Exception;
+use LogicException;
 
 /**
  * File Storage engine for cache. Filestorage is the slowest cache storage
@@ -147,7 +148,9 @@ class FileEngine extends CacheEngine {
 		}
 
 		$this->_File->rewind();
-		$success = $this->_File->ftruncate(0) && $this->_File->fwrite($contents) && $this->_File->fflush();
+		$success = $this->_File->ftruncate(0) &&
+			$this->_File->fwrite($contents) &&
+			$this->_File->fflush();
 
 		if ($this->_config['lock']) {
 			$this->_File->flock(LOCK_UN);
@@ -161,7 +164,8 @@ class FileEngine extends CacheEngine {
  * Read a key from the cache
  *
  * @param string $key Identifier for the data
- * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
+ * @return mixed The cached data, or false if the data doesn't exist, has
+ *   expired, or if there was an error fetching it
  */
 	public function read($key) {
 		$key = $this->_key($key);
@@ -178,7 +182,9 @@ class FileEngine extends CacheEngine {
 		$time = time();
 		$cachetime = intval($this->_File->current());
 
-		if ($cachetime !== false && ($cachetime < $time || ($time + $this->_config['duration']) < $cachetime)) {
+		if ($cachetime !== false &&
+			($cachetime < $time || ($time + $this->_config['duration']) < $cachetime)
+		) {
 			if ($this->_config['lock']) {
 				$this->_File->flock(LOCK_UN);
 			}
@@ -211,7 +217,8 @@ class FileEngine extends CacheEngine {
  * Delete a key from the cache
  *
  * @param string $key Identifier for the data
- * @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
+ * @return bool True if the value was successfully deleted, false if it didn't
+ *   exist or couldn't be removed
  */
 	public function delete($key) {
 		$key = $this->_key($key);
@@ -249,7 +256,10 @@ class FileEngine extends CacheEngine {
 		$this->_clearDirectory($this->_config['path'], $now, $threshold);
 
 		$directory = new \RecursiveDirectoryIterator($this->_config['path']);
-		$contents = new \RecursiveIteratorIterator($directory, \RecursiveIteratorIterator::SELF_FIRST);
+		$contents = new \RecursiveIteratorIterator(
+			$directory,
+			\RecursiveIteratorIterator::SELF_FIRST
+		);
 		$cleared = [];
 		foreach ($contents as $path) {
 			if ($path->isFile()) {
@@ -288,7 +298,7 @@ class FileEngine extends CacheEngine {
 
 			try {
 				$file = new \SplFileObject($path . $entry, 'r');
-			} catch (\Exception $e) {
+			} catch (Exception $e) {
 				continue;
 			}
 
@@ -321,10 +331,10 @@ class FileEngine extends CacheEngine {
  * @param string $key The key to decrement
  * @param int $offset The number to offset
  * @return void
- * @throws \Cake\Core\Exception\Exception
+ * @throws \LogicException
  */
 	public function decrement($key, $offset = 1) {
-		throw new Exception('Files cannot be atomically decremented.');
+		throw new LogicException('Files cannot be atomically decremented.');
 	}
 
 /**
@@ -333,10 +343,10 @@ class FileEngine extends CacheEngine {
  * @param string $key The key to decrement
  * @param int $offset The number to offset
  * @return void
- * @throws \Cake\Core\Exception\Exception
+ * @throws \LogicException
  */
 	public function increment($key, $offset = 1) {
-		throw new Exception('Files cannot be atomically incremented.');
+		throw new LogicException('Files cannot be atomically incremented.');
 	}
 
 /**
@@ -366,13 +376,15 @@ class FileEngine extends CacheEngine {
 			$exists = file_exists($path->getPathname());
 			try {
 				$this->_File = $path->openFile('c+');
-			} catch (\Exception $e) {
+			} catch (Exception $e) {
 				trigger_error($e->getMessage(), E_USER_WARNING);
 				return false;
 			}
 			unset($path);
 
-			if (!$exists && !chmod($this->_File->getPathname(), (int)$this->_config['mask'])) {
+			if (!$exists &&
+				!chmod($this->_File->getPathname(), (int)$this->_config['mask'])
+			) {
 				trigger_error(sprintf(
 					'Could not apply permission mask "%s" on cache file "%s"',
 					$this->_File->getPathname(), $this->_config['mask']
@@ -397,7 +409,9 @@ class FileEngine extends CacheEngine {
 		}
 		if ($this->_init && !($dir->isDir() && $dir->isWritable())) {
 			$this->_init = false;
-			trigger_error(sprintf('%s is not writable', $this->_config['path']), E_USER_WARNING);
+			trigger_error(sprintf(
+				'%s is not writable', $this->_config['path']
+			), E_USER_WARNING);
 			return false;
 		}
 		return true;
@@ -414,7 +428,11 @@ class FileEngine extends CacheEngine {
 			return false;
 		}
 
-		$key = Inflector::underscore(str_replace([DS, '/', '.', '<', '>', '?', ':', '|', '*', '"'], '_', strval($key)));
+		$key = Inflector::underscore(str_replace(
+			[DS, '/', '.', '<', '>', '?', ':', '|', '*', '"'],
+			'_',
+			strval($key)
+		));
 		return $key;
 	}
 
@@ -427,7 +445,10 @@ class FileEngine extends CacheEngine {
 	public function clearGroup($group) {
 		$this->_File = null;
 		$directoryIterator = new \RecursiveDirectoryIterator($this->_config['path']);
-		$contents = new \RecursiveIteratorIterator($directoryIterator, \RecursiveIteratorIterator::CHILD_FIRST);
+		$contents = new \RecursiveIteratorIterator(
+			$directoryIterator,
+			\RecursiveIteratorIterator::CHILD_FIRST
+		);
 		foreach ($contents as $object) {
 			$containsGroup = strpos($object->getPathName(), DS . $group . DS) !== false;
 			$hasPrefix = true;

+ 48 - 26
src/Cache/Engine/MemcachedEngine.php

@@ -15,9 +15,9 @@
 namespace Cake\Cache\Engine;
 
 use Cake\Cache\CacheEngine;
-use Cake\Core\Exception\Exception;
 use Cake\Utility\Inflector;
-use \Memcached;
+use InvalidArgumentException;
+use Memcached;
 
 /**
  * Memcached storage engine for cache. Memcached has some limitations in the amount of
@@ -94,7 +94,8 @@ class MemcachedEngine extends CacheEngine {
  *
  * @param array $config array of setting for the engine
  * @return bool True if the engine has been successfully initialized, false if not
- * @throws \Cake\Core\Exception\Exception when you try use authentication without Memcached compiled with SASL support
+ * @throws InvalidArgumentException When you try use authentication without
+ *   Memcached compiled with SASL support
  */
 	public function init(array $config = []) {
 		if (!class_exists('Memcached')) {
@@ -128,7 +129,8 @@ class MemcachedEngine extends CacheEngine {
 			return true;
 		}
 
-		$this->_Memcached = new Memcached($this->_config['persistent'] ? (string)$this->_config['persistent'] : null);
+		$this->_Memcached = new Memcached($this->_config['persistent'] ?
+			(string)$this->_config['persistent'] : null);
 		$this->_setOptions();
 
 		if (count($this->_Memcached->getServerList())) {
@@ -152,11 +154,14 @@ class MemcachedEngine extends CacheEngine {
 
 		if ($this->_config['login'] !== null && $this->_config['password'] !== null) {
 			if (!method_exists($this->_Memcached, 'setSaslAuthData')) {
-				throw new Exception(
+				throw new InvalidArgumentException(
 					'Memcached extension is not build with SASL support'
 				);
 			}
-			$this->_Memcached->setSaslAuthData($this->_config['login'], $this->_config['password']);
+			$this->_Memcached->setSaslAuthData(
+				$this->_config['login'],
+				$this->_config['password']
+			);
 		}
 
 		return true;
@@ -166,32 +171,46 @@ class MemcachedEngine extends CacheEngine {
  * Settings the memcached instance
  *
  * @return void
- * @throws \Cake\Core\Exception\Exception when the Memcached extension is not built with the desired serializer engine
+ * @throws InvalidArgumentException When the Memcached extension is not built
+ *   with the desired serializer engine.
  */
 	protected function _setOptions() {
 		$this->_Memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
 
 		$serializer = strtolower($this->_config['serialize']);
 		if (!isset($this->_serializers[$serializer])) {
-			throw new Exception(
+			throw new InvalidArgumentException(
 				sprintf('%s is not a valid serializer engine for Memcached', $serializer)
 			);
 		}
 
-		if ($serializer !== 'php' && !constant('Memcached::HAVE_' . strtoupper($serializer))) {
-			throw new Exception(
+		if ($serializer !== 'php' &&
+			!constant('Memcached::HAVE_' . strtoupper($serializer))
+		) {
+			throw new InvalidArgumentException(
 				sprintf('Memcached extension is not compiled with %s support', $serializer)
 			);
 		}
 
-		$this->_Memcached->setOption(Memcached::OPT_SERIALIZER, $this->_serializers[$serializer]);
+		$this->_Memcached->setOption(
+			Memcached::OPT_SERIALIZER,
+			$this->_serializers[$serializer]
+		);
 
 		// Check for Amazon ElastiCache instance
-		if (defined('Memcached::OPT_CLIENT_MODE') && defined('Memcached::DYNAMIC_CLIENT_MODE')) {
-			$this->_Memcached->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE);
+		if (defined('Memcached::OPT_CLIENT_MODE') &&
+			defined('Memcached::DYNAMIC_CLIENT_MODE')
+		) {
+			$this->_Memcached->setOption(
+				Memcached::OPT_CLIENT_MODE,
+				Memcached::DYNAMIC_CLIENT_MODE
+			);
 		}
 
-		$this->_Memcached->setOption(Memcached::OPT_COMPRESSION, (bool)$this->_config['compress']);
+		$this->_Memcached->setOption(
+			Memcached::OPT_COMPRESSION,
+			(bool)$this->_config['compress']
+		);
 	}
 
 /**
@@ -224,8 +243,9 @@ class MemcachedEngine extends CacheEngine {
 
 /**
  * Write data for key into cache. When using memcached as your cache engine
- * remember that the Memcached pecl extension does not support cache expiry times greater
- * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
+ * remember that the Memcached pecl extension does not support cache expiry
+ * times greater than 30 days in the future. Any duration greater than 30 days
+ * will be treated as never expiring.
  *
  * @param string $key Identifier for the data
  * @param mixed $value Data to be cached
@@ -247,7 +267,8 @@ class MemcachedEngine extends CacheEngine {
  * Write many cache entries to the cache at once
  *
  * @param array $data An array of data to be stored in the cache
- * @return array of bools for each key provided, true if the data was successfully cached, false on failure
+ * @return array of bools for each key provided, true if the data was
+ *   successfully cached, false on failure
  */
 	public function writeMany($data) {
 		$cacheData = array();
@@ -268,7 +289,8 @@ class MemcachedEngine extends CacheEngine {
  * Read a key from the cache
  *
  * @param string $key Identifier for the data
- * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
+ * @return mixed The cached data, or false if the data doesn't exist, has
+ * expired, or if there was an error fetching it.
  */
 	public function read($key) {
 		$key = $this->_key($key);
@@ -280,8 +302,8 @@ class MemcachedEngine extends CacheEngine {
  * Read many keys from the cache at once
  *
  * @param array $keys An array of identifiers for the data
- * @return An array containing, for each of the given $keys, the cached data or false if cached data could not be
- * retreived
+ * @return An array containing, for each of the given $keys, the cached data or
+ *   false if cached data could not be retreived.
  */
 	public function readMany($keys) {
 		$cacheKeys = array();
@@ -292,7 +314,8 @@ class MemcachedEngine extends CacheEngine {
 		$values = $this->_Memcached->getMulti($cacheKeys);
 		$return = array();
 		foreach ($keys as &$key) {
-			$return[$key] = array_key_exists($this->_key($key), $values) ? $values[$this->_key($key)] : false;
+			$return[$key] = array_key_exists($this->_key($key), $values) ?
+				$values[$this->_key($key)] : false;
 		}
 		return $return;
 	}
@@ -303,7 +326,6 @@ class MemcachedEngine extends CacheEngine {
  * @param string $key Identifier for the data
  * @param int $offset How much to increment
  * @return bool|int New incremented value, false otherwise
- * @throws \Cake\Core\Exception\Exception when you try to increment with compress = true
  */
 	public function increment($key, $offset = 1) {
 		$key = $this->_key($key);
@@ -317,7 +339,6 @@ class MemcachedEngine extends CacheEngine {
  * @param string $key Identifier for the data
  * @param int $offset How much to subtract
  * @return bool|int New decremented value, false otherwise
- * @throws \Cake\Core\Exception\Exception when you try to decrement with compress = true
  */
 	public function decrement($key, $offset = 1) {
 		$key = $this->_key($key);
@@ -329,7 +350,8 @@ class MemcachedEngine extends CacheEngine {
  * Delete a key from the cache
  *
  * @param string $key Identifier for the data
- * @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
+ * @return bool True if the value was successfully deleted, false if it didn't
+ *   exist or couldn't be removed.
  */
 	public function delete($key) {
 		$key = $this->_key($key);
@@ -341,8 +363,8 @@ class MemcachedEngine extends CacheEngine {
  * Delete many keys from the cache at once
  *
  * @param array $keys An array of identifiers for the data
- * @return array of boolean values that are true if the key was successfully deleted, false if it didn't exist or
- * couldn't be removed
+ * @return array of boolean values that are true if the key was successfully
+ *   deleted, false if it didn't exist or couldn't be removed.
  */
 	public function deleteMany($keys) {
 		$cacheKeys = array();

+ 3 - 2
src/Log/Engine/ConsoleLog.php

@@ -16,6 +16,7 @@ namespace Cake\Log\Engine;
 
 use Cake\Console\ConsoleOutput;
 use Cake\Core\Exception\Exception;
+use InvalidArgumentException;
 
 /**
  * Console logging. Writes logs to console output.
@@ -52,7 +53,7 @@ class ConsoleLog extends BaseLog {
  * - `outputAs` integer or ConsoleOutput::[RAW|PLAIN|COLOR]
  *
  * @param array $config Options for the FileLog, see above.
- * @throws \Cake\Core\Exception\Exception
+ * @throws \InvalidArgumentException
  */
 	public function __construct(array $config = array()) {
 		if (DS === '\\' && !(bool)env('ANSICON')) {
@@ -69,7 +70,7 @@ class ConsoleLog extends BaseLog {
 		} elseif (is_string($config['stream'])) {
 			$this->_output = new ConsoleOutput($config['stream']);
 		} else {
-			throw new Exception('`stream` not a ConsoleOutput nor string');
+			throw new InvalidArgumentException('`stream` not a ConsoleOutput nor string');
 		}
 		$this->_output->outputAs($config['outputAs']);
 	}

+ 4 - 4
src/Log/Log.php

@@ -14,8 +14,8 @@
 namespace Cake\Log;
 
 use Cake\Core\StaticConfigTrait;
-use Cake\Core\Exception\Exception;
 use Cake\Log\Engine\BaseLog;
+use InvalidArgumentException;
 
 /**
  * Logs messages to configured Log adapters.  One or more adapters
@@ -246,7 +246,7 @@ class Log {
  * @param string|array $key The name of the logger config, or an array of multiple configs.
  * @param array $config An array of name => config data for adapter.
  * @return mixed null when adding configuration and an array of configuration data when reading.
- * @throws \Cake\Core\Exception\Exception When trying to modify an existing config.
+ * @throws \BadMethodCallException When trying to modify an existing config.
  */
 	public static function config($key, $config = null) {
 		$return = static::_config($key, $config);
@@ -316,7 +316,7 @@ class Log {
  * @param string|array $scope The scope(s) a log message is being created in.
  *    See Cake\Log\Log::config() for more information on logging scopes.
  * @return bool Success
- * @throws \Cake\Core\Exception\Exception If invalid level is passed.
+ * @throws \InvalidArgumentException If invalid level is passed.
  */
 	public static function write($level, $message, $scope = array()) {
 		static::_init();
@@ -325,7 +325,7 @@ class Log {
 		}
 
 		if (!in_array($level, static::$_levels)) {
-			throw new Exception(sprintf('Invalid log level "%s"', $level));
+			throw new InvalidArgumentException(sprintf('Invalid log level "%s"', $level));
 		}
 
 		$logged = false;

+ 5 - 6
src/Log/LogEngineRegistry.php

@@ -15,9 +15,9 @@
 namespace Cake\Log;
 
 use Cake\Core\App;
-use Cake\Core\Exception\Exception;
 use Cake\Core\ObjectRegistry;
 use Cake\Log\LogInterface;
+use \RuntimeException;
 
 /**
  * Registry of loaded log engines
@@ -48,10 +48,10 @@ class LogEngineRegistry extends ObjectRegistry {
  * @param string $class The classname that is missing.
  * @param string $plugin The plugin the logger is missing in.
  * @return void
- * @throws \Cake\Core\Exception\Exception
+ * @throws \RuntimeException
  */
 	protected function _throwMissingClassError($class, $plugin) {
-		throw new Exception(sprintf('Could not load class %s', $class));
+		throw new RuntimeException(sprintf('Could not load class %s', $class));
 	}
 
 /**
@@ -63,8 +63,7 @@ class LogEngineRegistry extends ObjectRegistry {
  * @param string $alias The alias of the object.
  * @param array $settings An array of settings to use for the logger.
  * @return \Cake\Log\LogInterface The constructed logger class.
- * @throws \Cake\Core\Exception\Exception when an object doesn't implement
- *    the correct interface.
+ * @throws \RuntimeException when an object doesn't implement the correct interface.
  */
 	protected function _create($class, $alias, $settings) {
 		if (is_object($class)) {
@@ -79,7 +78,7 @@ class LogEngineRegistry extends ObjectRegistry {
 			return $instance;
 		}
 
-		throw new Exception(
+		throw new RuntimeException(
 			'Loggers must implement Cake\Log\LogInterface.'
 		);
 	}

+ 5 - 5
tests/TestCase/Cache/Engine/MemcachedEngineTest.php

@@ -177,7 +177,7 @@ class MemcachedEngineTest extends TestCase {
 		);
 
 		$this->setExpectedException(
-			'Cake\Core\Exception\Exception', 'invalid_serializer is not a valid serializer engine for Memcached'
+			'InvalidArgumentException', 'invalid_serializer is not a valid serializer engine for Memcached'
 		);
 		$Memcached->init($config);
 	}
@@ -289,7 +289,7 @@ class MemcachedEngineTest extends TestCase {
 		);
 
 		$this->setExpectedException(
-			'Cake\Core\Exception\Exception', 'Memcached extension is not compiled with json support'
+			'InvalidArgumentException', 'Memcached extension is not compiled with json support'
 		);
 		$Memcached->init($config);
 	}
@@ -314,7 +314,7 @@ class MemcachedEngineTest extends TestCase {
 		);
 
 		$this->setExpectedException(
-			'Cake\Core\Exception\Exception', 'msgpack is not a valid serializer engine for Memcached'
+			'InvalidArgumentException', 'msgpack is not a valid serializer engine for Memcached'
 		);
 		$Memcached->init($config);
 	}
@@ -339,7 +339,7 @@ class MemcachedEngineTest extends TestCase {
 		);
 
 		$this->setExpectedException(
-			'Cake\Core\Exception\Exception', 'Memcached extension is not compiled with igbinary support'
+			'InvalidArgumentException', 'Memcached extension is not compiled with igbinary support'
 		);
 		$Memcached->init($config);
 	}
@@ -366,7 +366,7 @@ class MemcachedEngineTest extends TestCase {
 		);
 
 		$this->setExpectedException(
-			'Cake\Core\Exception\Exception', 'Memcached extension is not build with SASL support'
+			'InvalidArgumentException', 'Memcached extension is not build with SASL support'
 		);
 		$Memcached->init($config);
 	}

+ 5 - 5
tests/TestCase/Log/LogTest.php

@@ -69,7 +69,7 @@ class LogTest extends TestCase {
 /**
  * test all the errors from failed logger imports
  *
- * @expectedException \Cake\Core\Exception\Exception
+ * @expectedException RuntimeException
  * @return void
  */
 	public function testImportingLoggerFailure() {
@@ -91,7 +91,7 @@ class LogTest extends TestCase {
 /**
  * test that loggers have to implement the correct interface.
  *
- * @expectedException \Cake\Core\Exception\Exception
+ * @expectedException \RuntimeException
  * @return void
  */
 	public function testNotImplementingInterface() {
@@ -122,7 +122,7 @@ class LogTest extends TestCase {
 /**
  * test config() with valid key name
  *
- * @expectedException \Cake\Core\Exception\Exception
+ * @expectedException \InvalidArgumentException
  * @return void
  */
 	public function testInvalidLevel() {
@@ -166,7 +166,7 @@ class LogTest extends TestCase {
  * Test that config() throws an exception when adding an
  * adapter with the wrong type.
  *
- * @expectedException \Cake\Core\Exception\Exception
+ * @expectedException \RuntimeException
  * @return void
  */
 	public function testConfigInjectErrorOnWrongType() {
@@ -195,7 +195,7 @@ class LogTest extends TestCase {
 /**
  * Ensure you cannot reconfigure a log adapter.
  *
- * @expectedException BadMethodCallException
+ * @expectedException \BadMethodCallException
  * @return void
  */
 	public function testConfigErrorOnReconfigure() {