Commit f4ebd91c authored by Carsten Brandt's avatar Carsten Brandt

Merge branch 'master' into redis

* master: (117 commits)
  More Model tests
  Better validation rules validity check
  Some tests for Model
  A bit more friendly behavior for unsetting a model attribute
  User WIP.
  Fixed Model::getFirstErrors()
  Finished AccessControl.
  Finished HttpCache.
  User WIP
  line ending fix.
  refactoring cache and db references.
  Fixed session bug.
  Finishes flash feature.
  refactored url creation shortcut method.
  HttpCache WIP.
  Finished AccessControl and HttpCache.
  Finished PageCache.
  finished fragment caching.
  fragment cache WIP
  bug fixes.
  ...
parents 0d2f5028 99238886
...@@ -300,7 +300,7 @@ foreach ($customers as $customer) { ...@@ -300,7 +300,7 @@ foreach ($customers as $customer) {
~~~ ~~~
How many SQL queries will be performed in the above code, assuming there are more than 100 customers in How many SQL queries will be performed in the above code, assuming there are more than 100 customers in
the database? 101! The first SQL query brings back 100 customers. Then for each customer, another SQL query the database? 101! The first SQL query brings back 100 customers. Then for each customer, a SQL query
is performed to bring back the customer's orders. is performed to bring back the customer's orders.
To solve the above performance problem, you can use the so-called *eager loading* by calling [[ActiveQuery::with()]]: To solve the above performance problem, you can use the so-called *eager loading* by calling [[ActiveQuery::with()]]:
...@@ -318,7 +318,7 @@ foreach ($customers as $customer) { ...@@ -318,7 +318,7 @@ foreach ($customers as $customer) {
} }
~~~ ~~~
As you can see, only two SQL queries were needed for the same task. As you can see, only two SQL queries are needed for the same task.
Sometimes, you may want to customize the relational queries on the fly. It can be Sometimes, you may want to customize the relational queries on the fly. It can be
......
Yii2 class loader
=================
Yii 2 class loader is PSR-0 compliant. That means it can handle most of the PHP
libraries and frameworks out there.
In order to autoload a library you need to set a root alias for it.
PEAR-style libraries
--------------------
```php
\Yii::setAlias('@Twig', '@app/vendors/Twig');
```
References
----------
- YiiBase::autoload
\ No newline at end of file
...@@ -204,7 +204,7 @@ doIt('a', array( ...@@ -204,7 +204,7 @@ doIt('a', array(
~~~ ~~~
if ($event === null) { if ($event === null) {
return new Event($this); return new Event();
} elseif ($event instanceof CoolEvent) { } elseif ($event instanceof CoolEvent) {
return $event->instance(); return $event->instance();
} else { } else {
...@@ -251,10 +251,8 @@ switch ($this->phpType) { ...@@ -251,10 +251,8 @@ switch ($this->phpType) {
~~~ ~~~
<?php <?php
/** /**
* Component class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
~~~ ~~~
......
<?php <?php
/** /**
* YiiBase class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
use yii\base\Exception; use yii\base\Exception;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
use yii\logging\Logger; use yii\logging\Logger;
/** /**
...@@ -63,9 +61,9 @@ class YiiBase ...@@ -63,9 +61,9 @@ class YiiBase
*/ */
public static $classPath = array(); public static $classPath = array();
/** /**
* @var yii\base\Application the application instance * @var yii\console\Application|yii\web\Application the application instance
*/ */
public static $application; public static $app;
/** /**
* @var array registered path aliases * @var array registered path aliases
* @see getAlias * @see getAlias
...@@ -96,7 +94,7 @@ class YiiBase ...@@ -96,7 +94,7 @@ class YiiBase
*/ */
public static $objectConfig = array(); public static $objectConfig = array();
private static $_imported = array(); // alias => class name or directory private static $_imported = array(); // alias => class name or directory
private static $_logger; private static $_logger;
/** /**
...@@ -125,8 +123,8 @@ class YiiBase ...@@ -125,8 +123,8 @@ class YiiBase
* *
* To import a class or a directory, one can use either path alias or class name (can be namespaced): * To import a class or a directory, one can use either path alias or class name (can be namespaced):
* *
* - `@application/components/GoogleMap`: importing the `GoogleMap` class with a path alias; * - `@app/components/GoogleMap`: importing the `GoogleMap` class with a path alias;
* - `@application/components/*`: importing the whole `components` directory with a path alias; * - `@app/components/*`: importing the whole `components` directory with a path alias;
* - `GoogleMap`: importing the `GoogleMap` class with a class name. [[autoload()]] will be used * - `GoogleMap`: importing the `GoogleMap` class with a class name. [[autoload()]] will be used
* when this class is used for the first time. * when this class is used for the first time.
* *
...@@ -161,9 +159,7 @@ class YiiBase ...@@ -161,9 +159,7 @@ class YiiBase
return self::$_imported[$alias] = $className; return self::$_imported[$alias] = $className;
} }
if (($path = static::getAlias(dirname($alias))) === false) { $path = static::getAlias(dirname($alias));
throw new Exception('Invalid path alias: ' . $alias);
}
if ($isClass) { if ($isClass) {
if ($forceInclude) { if ($forceInclude) {
...@@ -193,24 +189,30 @@ class YiiBase ...@@ -193,24 +189,30 @@ class YiiBase
* *
* Note, this method does not ensure the existence of the resulting path. * Note, this method does not ensure the existence of the resulting path.
* @param string $alias alias * @param string $alias alias
* @param boolean $throwException whether to throw an exception if the given alias is invalid.
* If this is false and an invalid alias is given, false will be returned by this method.
* @return string|boolean path corresponding to the alias, false if the root alias is not previously registered. * @return string|boolean path corresponding to the alias, false if the root alias is not previously registered.
* @see setAlias * @see setAlias
*/ */
public static function getAlias($alias) public static function getAlias($alias, $throwException = true)
{ {
if (!is_string($alias)) { if (is_string($alias)) {
return false; if (isset(self::$aliases[$alias])) {
} elseif (isset(self::$aliases[$alias])) { return self::$aliases[$alias];
return self::$aliases[$alias]; } elseif ($alias === '' || $alias[0] !== '@') { // not an alias
} elseif ($alias === '' || $alias[0] !== '@') { // not an alias return $alias;
return $alias; } elseif (($pos = strpos($alias, '/')) !== false || ($pos = strpos($alias, '\\')) !== false) {
} elseif (($pos = strpos($alias, '/')) !== false) { $rootAlias = substr($alias, 0, $pos);
$rootAlias = substr($alias, 0, $pos); if (isset(self::$aliases[$rootAlias])) {
if (isset(self::$aliases[$rootAlias])) { return self::$aliases[$alias] = self::$aliases[$rootAlias] . substr($alias, $pos);
return self::$aliases[$alias] = self::$aliases[$rootAlias] . substr($alias, $pos); }
} }
} }
return false; if ($throwException) {
throw new InvalidParamException("Invalid path alias: $alias");
} else {
return false;
}
} }
/** /**
...@@ -238,10 +240,8 @@ class YiiBase ...@@ -238,10 +240,8 @@ class YiiBase
unset(self::$aliases[$alias]); unset(self::$aliases[$alias]);
} elseif ($path[0] !== '@') { } elseif ($path[0] !== '@') {
self::$aliases[$alias] = rtrim($path, '\\/'); self::$aliases[$alias] = rtrim($path, '\\/');
} elseif (($p = static::getAlias($path)) !== false) {
self::$aliases[$alias] = $p;
} else { } else {
throw new Exception('Invalid path: ' . $path); self::$aliases[$alias] = static::getAlias($path);
} }
} }
...@@ -262,6 +262,7 @@ class YiiBase ...@@ -262,6 +262,7 @@ class YiiBase
* *
* @param string $className class name * @param string $className class name
* @return boolean whether the class has been loaded successfully * @return boolean whether the class has been loaded successfully
* @throws Exception if the class file does not exist
*/ */
public static function autoload($className) public static function autoload($className)
{ {
...@@ -274,14 +275,14 @@ class YiiBase ...@@ -274,14 +275,14 @@ class YiiBase
// namespaced class, e.g. yii\base\Component // namespaced class, e.g. yii\base\Component
// convert namespace to path alias, e.g. yii\base\Component to @yii/base/Component // convert namespace to path alias, e.g. yii\base\Component to @yii/base/Component
$alias = '@' . str_replace('\\', '/', ltrim($className, '\\')); $alias = '@' . str_replace('\\', '/', ltrim($className, '\\'));
if (($path = static::getAlias($alias)) !== false) { if (($path = static::getAlias($alias, false)) !== false) {
$classFile = $path . '.php'; $classFile = $path . '.php';
} }
} elseif (($pos = strpos($className, '_')) !== false) { } elseif (($pos = strpos($className, '_')) !== false) {
// PEAR-styled class, e.g. PHPUnit_Framework_TestCase // PEAR-styled class, e.g. PHPUnit_Framework_TestCase
// convert class name to path alias, e.g. PHPUnit_Framework_TestCase to @PHPUnit/Framework/TestCase // convert class name to path alias, e.g. PHPUnit_Framework_TestCase to @PHPUnit/Framework/TestCase
$alias = '@' . str_replace('_', '/', $className); $alias = '@' . str_replace('_', '/', $className);
if (($path = static::getAlias($alias)) !== false) { if (($path = static::getAlias($alias, false)) !== false) {
$classFile = $path . '.php'; $classFile = $path . '.php';
} }
} }
...@@ -297,7 +298,7 @@ class YiiBase ...@@ -297,7 +298,7 @@ class YiiBase
} }
} }
if (isset($classFile, $alias)) { if (isset($classFile, $alias) && is_file($classFile)) {
if (!YII_DEBUG || basename(realpath($classFile)) === basename($alias) . '.php') { if (!YII_DEBUG || basename(realpath($classFile)) === basename($alias) . '.php') {
include($classFile); include($classFile);
return true; return true;
...@@ -322,12 +323,12 @@ class YiiBase ...@@ -322,12 +323,12 @@ class YiiBase
* the class. For example, * the class. For example,
* *
* - `\app\components\GoogleMap`: fully-qualified namespaced class. * - `\app\components\GoogleMap`: fully-qualified namespaced class.
* - `@application/components/GoogleMap`: an alias * - `@app/components/GoogleMap`: an alias
* *
* Below are some usage examples: * Below are some usage examples:
* *
* ~~~ * ~~~
* $object = \Yii::createObject('@application/components/GoogleMap'); * $object = \Yii::createObject('@app/components/GoogleMap');
* $object = \Yii::createObject(array( * $object = \Yii::createObject(array(
* 'class' => '\app\components\GoogleMap', * 'class' => '\app\components\GoogleMap',
* 'apiKey' => 'xyz', * 'apiKey' => 'xyz',
...@@ -507,9 +508,6 @@ class YiiBase ...@@ -507,9 +508,6 @@ class YiiBase
* i.e., the message returned will be chosen from a few candidates according to the given * i.e., the message returned will be chosen from a few candidates according to the given
* number value. This feature is mainly used to solve plural format issue in case * number value. This feature is mainly used to solve plural format issue in case
* a message has different plural forms in some languages. * a message has different plural forms in some languages.
* @param string $category message category. Please use only word letters. Note, category 'yii' is
* reserved for Yii framework core code use. See {@link CPhpMessageSource} for
* more interpretation about message category.
* @param string $message the original message * @param string $message the original message
* @param array $params parameters to be applied to the message using <code>strtr</code>. * @param array $params parameters to be applied to the message using <code>strtr</code>.
* The first parameter can be a number without key. * The first parameter can be a number without key.
...@@ -517,62 +515,12 @@ class YiiBase ...@@ -517,62 +515,12 @@ class YiiBase
* an appropriate message translation. * an appropriate message translation.
* You can pass parameter for {@link CChoiceFormat::format} * You can pass parameter for {@link CChoiceFormat::format}
* or plural forms format without wrapping it with array. * or plural forms format without wrapping it with array.
* @param string $source which message source application component to use.
* Defaults to null, meaning using 'coreMessages' for messages belonging to
* the 'yii' category and using 'messages' for the rest messages.
* @param string $language the target language. If null (default), the {@link CApplication::getLanguage application language} will be used. * @param string $language the target language. If null (default), the {@link CApplication::getLanguage application language} will be used.
* @return string the translated message * @return string the translated message
* @see CMessageSource * @see CMessageSource
*/ */
public static function t($category, $message, $params = array(), $source = null, $language = null) public static function t($message, $params = array(), $language = null)
{ {
// todo; return Yii::$app->getI18N()->translate($message, $params, $language);
return $params !== array() ? strtr($message, $params) : $message;
if (self::$application !== null)
{
if ($source === null)
{
$source = $category === 'yii' ? 'coreMessages' : 'messages';
}
if (($source = self::$application->getComponent($source)) !== null)
{
$message = $source->translate($category, $message, $language);
}
}
if ($params === array())
{
return $message;
}
if (!is_array($params))
{
$params = array($params);
}
if (isset($params[0])) // number choice
{
if (strpos($message, '|') !== false)
{
if (strpos($message, '#') === false)
{
$chunks = explode('|', $message);
$expressions = self::$application->getLocale($language)->getPluralRules();
if ($n = min(count($chunks), count($expressions)))
{
for ($i = 0; $i < $n; $i++)
{
$chunks[$i] = $expressions[$i] . '#' . $chunks[$i];
}
$message = implode('|', $chunks);
}
}
$message = CChoiceFormat::format($message, $params[0]);
}
if (!isset($params['{n}']))
{
$params['{n}'] = $params[0];
}
unset($params[0]);
}
return $params !== array() ? strtr($message, $params) : $message;
} }
} }
<?php <?php
/** /**
* Action class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -55,6 +53,15 @@ class Action extends Component ...@@ -55,6 +53,15 @@ class Action extends Component
parent::__construct($config); parent::__construct($config);
} }
/**
* Returns the unique ID of this action among the whole application.
* @return string the unique ID of this action among the whole application.
*/
public function getUniqueId()
{
return $this->controller->getUniqueId() . '/' . $this->id;
}
/** /**
* Runs this action with the specified parameters. * Runs this action with the specified parameters.
* This method is mainly invoked by the controller. * This method is mainly invoked by the controller.
...@@ -67,36 +74,7 @@ class Action extends Component ...@@ -67,36 +74,7 @@ class Action extends Component
if (!method_exists($this, 'run')) { if (!method_exists($this, 'run')) {
throw new InvalidConfigException(get_class($this) . ' must define a "run()" method.'); throw new InvalidConfigException(get_class($this) . ' must define a "run()" method.');
} }
$method = new \ReflectionMethod($this, 'run'); $args = $this->controller->bindActionParams($this, $params);
$args = $this->bindActionParams($method, $params); return (int)call_user_func_array(array($this, 'run'), $args);
return (int)$method->invokeArgs($this, $args);
}
/**
* Binds the given parameters to the action method.
* The returned array contains the parameters that need to be passed to the action method.
* This method calls [[Controller::validateActionParams()]] to check if any exception
* should be raised if there are missing or unknown parameters.
* @param \ReflectionMethod $method the action method reflection object
* @param array $params the supplied parameters
* @return array the parameters that can be passed to the action method
*/
protected function bindActionParams($method, $params)
{
$args = array();
$missing = array();
foreach ($method->getParameters() as $param) {
$name = $param->getName();
if (array_key_exists($name, $params)) {
$args[] = $params[$name];
unset($params[$name]);
} elseif ($param->isDefaultValueAvailable()) {
$args[] = $param->getDefaultValue();
} else {
$missing[] = $name;
}
}
$this->controller->validateActionParams($this, $missing, $params);
return $args;
} }
} }
<?php <?php
/** /**
* ActionEvent class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class ActionFilter extends Behavior
{
/**
* @var array list of action IDs that this filter should apply to. If this property is not set,
* then the filter applies to all actions, unless they are listed in [[except]].
*/
public $only;
/**
* @var array list of action IDs that this filter should not apply to.
*/
public $except = array();
/**
* Declares event handlers for the [[owner]]'s events.
* @return array events (array keys) and the corresponding event handler methods (array values).
*/
public function events()
{
return array(
'beforeAction' => 'beforeFilter',
'afterAction' => 'afterFilter',
);
}
/**
* @param ActionEvent $event
* @return boolean
*/
public function beforeFilter($event)
{
if ($this->isActive($event->action)) {
$event->isValid = $this->beforeAction($event->action);
}
return $event->isValid;
}
/**
* @param ActionEvent $event
* @return boolean
*/
public function afterFilter($event)
{
if ($this->isActive($event->action)) {
$this->afterAction($event->action);
}
}
/**
* This method is invoked right before an action is to be executed (after all possible filters.)
* You may override this method to do last-minute preparation for the action.
* @param Action $action the action to be executed.
* @return boolean whether the action should continue to be executed.
*/
public function beforeAction($action)
{
return true;
}
/**
* This method is invoked right after an action is executed.
* You may override this method to do some postprocessing for the action.
* @param Action $action the action just executed.
*/
public function afterAction($action)
{
}
/**
* Returns a value indicating whether the filer is active for the given action.
* @param Action $action the action being filtered
* @return boolean whether the filer is active for the given action.
*/
protected function isActive($action)
{
return !in_array($action->id, $this->except, true) && (empty($this->only) || in_array($action->id, $this->only, true));
}
}
\ No newline at end of file
This diff is collapsed.
<?php <?php
/** /**
* Behavior class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
......
<?php <?php
/** /**
* Component class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -60,7 +58,7 @@ class Component extends \yii\base\Object ...@@ -60,7 +58,7 @@ class Component extends \yii\base\Object
} }
} }
} }
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '.' . $name); throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
} }
/** /**
...@@ -107,9 +105,9 @@ class Component extends \yii\base\Object ...@@ -107,9 +105,9 @@ class Component extends \yii\base\Object
} }
} }
if (method_exists($this, 'get' . $name)) { if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '.' . $name); throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
} else { } else {
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '.' . $name); throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
} }
} }
...@@ -424,7 +422,10 @@ class Component extends \yii\base\Object ...@@ -424,7 +422,10 @@ class Component extends \yii\base\Object
$this->ensureBehaviors(); $this->ensureBehaviors();
if (isset($this->_e[$name]) && $this->_e[$name]->getCount()) { if (isset($this->_e[$name]) && $this->_e[$name]->getCount()) {
if ($event === null) { if ($event === null) {
$event = new Event($this); $event = new Event;
}
if ($event->sender === null) {
$event->sender = $this;
} }
$event->handled = false; $event->handled = false;
$event->name = $name; $event->name = $name;
......
<?php <?php
/** /**
* Controller class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
namespace yii\base; namespace yii\base;
use Yii; use Yii;
use yii\util\StringHelper; use yii\helpers\FileHelper;
use yii\helpers\StringHelper;
/** /**
* Controller is the base class for classes containing controller logic. * Controller is the base class for classes containing controller logic.
* *
* @property string $route the route (module ID, controller ID and action ID) of the current request.
* @property string $uniqueId the controller ID that is prefixed with the module ID (if any).
*
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
...@@ -72,9 +68,9 @@ class Controller extends Component ...@@ -72,9 +68,9 @@ class Controller extends Component
* *
* ~~~ * ~~~
* return array( * return array(
* 'action1' => '@application/components/Action1', * 'action1' => '@app/components/Action1',
* 'action2' => array( * 'action2' => array(
* 'class' => '@application/components/Action2', * 'class' => '@app/components/Action2',
* 'property1' => 'value1', * 'property1' => 'value1',
* 'property2' => 'value2', * 'property2' => 'value2',
* ), * ),
...@@ -139,8 +135,50 @@ class Controller extends Component ...@@ -139,8 +135,50 @@ class Controller extends Component
} elseif ($pos > 0) { } elseif ($pos > 0) {
return $this->module->runAction($route, $params); return $this->module->runAction($route, $params);
} else { } else {
return \Yii::$application->runAction(ltrim($route, '/'), $params); return \Yii::$app->runAction(ltrim($route, '/'), $params);
}
}
/**
* Binds the parameters to the action.
* This method is invoked by [[Action]] when it begins to run with the given parameters.
* This method will check the parameter names that the action requires and return
* the provided parameters according to the requirement. If there is any missing parameter,
* an exception will be thrown.
* @param Action $action the action to be bound with parameters
* @param array $params the parameters to be bound to the action
* @return array the valid parameters that the action can run with.
* @throws InvalidRequestException if there are missing parameters.
*/
public function bindActionParams($action, $params)
{
if ($action instanceof InlineAction) {
$method = new \ReflectionMethod($this, $action->actionMethod);
} else {
$method = new \ReflectionMethod($action, 'run');
}
$args = array();
$missing = array();
foreach ($method->getParameters() as $param) {
$name = $param->getName();
if (array_key_exists($name, $params)) {
$args[] = $params[$name];
unset($params[$name]);
} elseif ($param->isDefaultValueAvailable()) {
$args[] = $param->getDefaultValue();
} else {
$missing[] = $name;
}
}
if ($missing !== array()) {
throw new InvalidRequestException(Yii::t('yii|Missing required parameters: {params}', array(
'{params}' => implode(', ', $missing),
)));
} }
return $args;
} }
/** /**
...@@ -250,34 +288,51 @@ class Controller extends Component ...@@ -250,34 +288,51 @@ class Controller extends Component
*/ */
public function getRoute() public function getRoute()
{ {
return $this->action !== null ? $this->getUniqueId() . '/' . $this->action->id : $this->getUniqueId(); return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
} }
/** /**
* Renders a view and applies layout if available. * Renders a view and applies layout if available.
* * @param string $view the view name. Please refer to [[findViewFile()]] on how to specify a view name.
* @param $view * @param array $params the parameters (name-value pairs) that should be made available in the view.
* @param array $params * These parameters will not be available in the layout.
* @return string * @return string the rendering result.
* @throws InvalidParamException if the view file or the layout file does not exist.
*/ */
public function render($view, $params = array()) public function render($view, $params = array())
{ {
return $this->createView()->render($view, $params); $output = Yii::$app->getView()->render($view, $params, $this);
} $layoutFile = $this->findLayoutFile();
if ($layoutFile !== false) {
public function renderContent($content) return Yii::$app->getView()->renderFile($layoutFile, array('content' => $output), $this);
{ } else {
return $this->createView()->renderContent($content); return $output;
}
} }
/**
* Renders a view.
* This method differs from [[render()]] in that it does not apply any layout.
* @param string $view the view name. Please refer to [[findViewFile()]] on how to specify a view name.
* @param array $params the parameters (name-value pairs) that should be made available in the view.
* @return string the rendering result.
* @throws InvalidParamException if the view file does not exist.
*/
public function renderPartial($view, $params = array()) public function renderPartial($view, $params = array())
{ {
return $this->createView()->renderPartial($view, $params); return Yii::$app->getView()->render($view, $params, $this);
} }
public function createView() /**
* Renders a view file.
* @param string $file the view file to be rendered. This can be either a file path or a path alias.
* @param array $params the parameters (name-value pairs) that should be made available in the view.
* @return string the rendering result.
* @throws InvalidParamException if the view file does not exist.
*/
public function renderFile($file, $params = array())
{ {
return new View($this); return Yii::$app->getView()->renderFile($file, $params, $this);
} }
/** /**
...@@ -290,4 +345,63 @@ class Controller extends Component ...@@ -290,4 +345,63 @@ class Controller extends Component
{ {
return $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id; return $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id;
} }
/**
* Finds the applicable layout file.
*
* This method locates an applicable layout file via two steps.
*
* In the first step, it determines the layout name and the context module:
*
* - If [[layout]] is specified as a string, use it as the layout name and [[module]] as the context module;
* - If [[layout]] is null, search through all ancestor modules of this controller and find the first
* module whose [[Module::layout|layout]] is not null. The layout and the corresponding module
* are used as the layout name and the context module, respectively. If such a module is not found
* or the corresponding layout is not a string, it will return false, meaning no applicable layout.
*
* In the second step, it determines the actual layout file according to the previously found layout name
* and context module. The layout name can be
*
* - a path alias (e.g. "@app/views/layouts/main");
* - an absolute path (e.g. "/main"): the layout name starts with a slash. The actual layout file will be
* looked for under the [[Application::layoutPath|layout path]] of the application;
* - a relative path (e.g. "main"): the actual layout layout file will be looked for under the
* [[Module::viewPath|view path]] of the context module.
*
* If the layout name does not contain a file extension, it will use the default one `.php`.
*
* @return string|boolean the layout file path, or false if layout is not needed.
* @throws InvalidParamException if an invalid path alias is used to specify the layout
*/
protected function findLayoutFile()
{
$module = $this->module;
if (is_string($this->layout)) {
$view = $this->layout;
} elseif ($this->layout === null) {
while ($module !== null && $module->layout === null) {
$module = $module->module;
}
if ($module !== null && is_string($module->layout)) {
$view = $module->layout;
}
}
if (!isset($view)) {
return false;
}
if (strncmp($view, '@', 1) === 0) {
$file = Yii::getAlias($view);
} elseif (strncmp($view, '/', 1) === 0) {
$file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . $view;
} else {
$file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $view;
}
if (FileHelper::getExtension($file) === '') {
$file .= '.php';
}
return $file;
}
} }
<?php <?php
/** /**
* Dictionary class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
namespace yii\base; namespace yii\base;
use yii\util\ArrayHelper; use yii\helpers\ArrayHelper;
/** /**
* Dictionary implements a collection that stores key-value pairs. * Dictionary implements a collection that stores key-value pairs.
...@@ -150,7 +148,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co ...@@ -150,7 +148,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
* Defaults to false, meaning all items in the dictionary will be cleared directly * Defaults to false, meaning all items in the dictionary will be cleared directly
* without calling [[remove]]. * without calling [[remove]].
*/ */
public function clear($safeClear = false) public function removeAll($safeClear = false)
{ {
if ($safeClear) { if ($safeClear) {
foreach (array_keys($this->_d) as $key) { foreach (array_keys($this->_d) as $key) {
...@@ -166,7 +164,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co ...@@ -166,7 +164,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
* @param mixed $key the key * @param mixed $key the key
* @return boolean whether the dictionary contains an item with the specified key * @return boolean whether the dictionary contains an item with the specified key
*/ */
public function contains($key) public function has($key)
{ {
return isset($this->_d[$key]) || array_key_exists($key, $this->_d); return isset($this->_d[$key]) || array_key_exists($key, $this->_d);
} }
...@@ -184,13 +182,13 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co ...@@ -184,13 +182,13 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
* Copies iterable data into the dictionary. * Copies iterable data into the dictionary.
* Note, existing data in the dictionary will be cleared first. * Note, existing data in the dictionary will be cleared first.
* @param mixed $data the data to be copied from, must be an array or an object implementing `Traversable` * @param mixed $data the data to be copied from, must be an array or an object implementing `Traversable`
* @throws InvalidCallException if data is neither an array nor an iterator. * @throws InvalidParamException if data is neither an array nor an iterator.
*/ */
public function copyFrom($data) public function copyFrom($data)
{ {
if (is_array($data) || $data instanceof \Traversable) { if (is_array($data) || $data instanceof \Traversable) {
if ($this->_d !== array()) { if ($this->_d !== array()) {
$this->clear(); $this->removeAll();
} }
if ($data instanceof self) { if ($data instanceof self) {
$data = $data->_d; $data = $data->_d;
...@@ -199,7 +197,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co ...@@ -199,7 +197,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
$this->add($key, $value); $this->add($key, $value);
} }
} else { } else {
throw new InvalidCallException('Data must be either an array or an object implementing Traversable.'); throw new InvalidParamException('Data must be either an array or an object implementing Traversable.');
} }
} }
...@@ -216,7 +214,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co ...@@ -216,7 +214,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
* *
* @param array|\Traversable $data the data to be merged with. It must be an array or object implementing Traversable * @param array|\Traversable $data the data to be merged with. It must be an array or object implementing Traversable
* @param boolean $recursive whether the merging should be recursive. * @param boolean $recursive whether the merging should be recursive.
* @throws InvalidCallException if data is neither an array nor an object implementing `Traversable`. * @throws InvalidParamException if data is neither an array nor an object implementing `Traversable`.
*/ */
public function mergeWith($data, $recursive = true) public function mergeWith($data, $recursive = true)
{ {
...@@ -240,7 +238,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co ...@@ -240,7 +238,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
} }
} }
} else { } else {
throw new InvalidCallException('The data to be merged with must be an array or an object implementing Traversable.'); throw new InvalidParamException('The data to be merged with must be an array or an object implementing Traversable.');
} }
} }
...@@ -254,7 +252,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co ...@@ -254,7 +252,7 @@ class Dictionary extends Object implements \IteratorAggregate, \ArrayAccess, \Co
*/ */
public function offsetExists($offset) public function offsetExists($offset)
{ {
return $this->contains($offset); return $this->has($offset);
} }
/** /**
......
<?php <?php
/** /**
* DictionaryIterator class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* ErrorException represents a PHP error.
*
* @author Alexander Makarov <sam@rmcreative.ru>
* @since 2.0
*/
class ErrorException extends Exception
{
protected $severity;
/**
* Constructs the exception
* @link http://php.net/manual/en/errorexception.construct.php
* @param $message [optional]
* @param $code [optional]
* @param $severity [optional]
* @param $filename [optional]
* @param $lineno [optional]
* @param $previous [optional]
*/
public function __construct($message = '', $code = 0, $severity = 1, $filename = __FILE__, $lineno = __LINE__, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);
$this->severity = $severity;
$this->file = $filename;
$this->line = $lineno;
}
/**
* Gets the exception severity
* @link http://php.net/manual/en/errorexception.getseverity.php
* @return int the severity level of the exception.
*/
final public function getSeverity()
{
return $this->severity;
}
/**
* Returns if error is one of fatal type
*
* @param array $error error got from error_get_last()
* @return bool if error is one of fatal type
*/
public static function isFatalErorr($error)
{
return isset($error['type']) && in_array($error['type'], array(E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING));
}
/**
* @return string the user-friendly name of this exception
*/
public function getName()
{
$names = array(
E_ERROR => \Yii::t('yii|Fatal Error'),
E_PARSE => \Yii::t('yii|Parse Error'),
E_CORE_ERROR => \Yii::t('yii|Core Error'),
E_COMPILE_ERROR => \Yii::t('yii|Compile Error'),
E_USER_ERROR => \Yii::t('yii|User Error'),
E_WARNING => \Yii::t('yii|Warning'),
E_CORE_WARNING => \Yii::t('yii|Core Warning'),
E_COMPILE_WARNING => \Yii::t('yii|Compile Warning'),
E_USER_WARNING => \Yii::t('yii|User Warning'),
E_STRICT => \Yii::t('yii|Strict'),
E_NOTICE => \Yii::t('yii|Notice'),
E_RECOVERABLE_ERROR => \Yii::t('yii|Recoverable Error'),
E_DEPRECATED => \Yii::t('yii|Deprecated'),
);
return isset($names[$this->getCode()]) ? $names[$this->getCode()] : \Yii::t('yii|Error');
}
}
<?php <?php
/** /**
* ErrorHandler class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -18,7 +16,7 @@ namespace yii\base; ...@@ -18,7 +16,7 @@ namespace yii\base;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
use yii\util\VarDumper; use yii\helpers\VarDumper;
class ErrorHandler extends Component class ErrorHandler extends Component
{ {
...@@ -36,7 +34,7 @@ class ErrorHandler extends Component ...@@ -36,7 +34,7 @@ class ErrorHandler extends Component
public $discardExistingOutput = true; public $discardExistingOutput = true;
/** /**
* @var string the route (eg 'site/error') to the controller action that will be used to display external errors. * @var string the route (eg 'site/error') to the controller action that will be used to display external errors.
* Inside the action, it can retrieve the error information by \Yii::$application->errorHandler->error. * Inside the action, it can retrieve the error information by \Yii::$app->errorHandler->error.
* This property defaults to null, meaning ErrorHandler will handle the error display. * This property defaults to null, meaning ErrorHandler will handle the error display.
*/ */
public $errorAction; public $errorAction;
...@@ -71,27 +69,27 @@ class ErrorHandler extends Component ...@@ -71,27 +69,27 @@ class ErrorHandler extends Component
protected function render($exception) protected function render($exception)
{ {
if ($this->errorAction !== null) { if ($this->errorAction !== null) {
\Yii::$application->runAction($this->errorAction); \Yii::$app->runAction($this->errorAction);
} elseif (\Yii::$application instanceof \yii\web\Application) { } elseif (\Yii::$app instanceof \yii\web\Application) {
if (!headers_sent()) { if (!headers_sent()) {
$errorCode = $exception instanceof HttpException ? $exception->statusCode : 500; $errorCode = $exception instanceof HttpException ? $exception->statusCode : 500;
header("HTTP/1.0 $errorCode " . get_class($exception)); header("HTTP/1.0 $errorCode " . get_class($exception));
} }
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') { if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
\Yii::$application->renderException($exception); \Yii::$app->renderException($exception);
} else { } else {
$view = new View($this); $view = new View;
if (!YII_DEBUG || $exception instanceof Exception && $exception->causedByUser) { if (!YII_DEBUG || $exception instanceof UserException) {
$viewName = $this->errorView; $viewName = $this->errorView;
} else { } else {
$viewName = $this->exceptionView; $viewName = $this->exceptionView;
} }
echo $view->render($viewName, array( echo $view->render($viewName, array(
'exception' => $exception, 'exception' => $exception,
)); ), $this);
} }
} else { } else {
\Yii::$application->renderException($exception); \Yii::$app->renderException($exception);
} }
} }
...@@ -239,7 +237,7 @@ class ErrorHandler extends Component ...@@ -239,7 +237,7 @@ class ErrorHandler extends Component
public function htmlEncode($text) public function htmlEncode($text)
{ {
return htmlspecialchars($text, ENT_QUOTES, \Yii::$application->charset); return htmlspecialchars($text, ENT_QUOTES, \Yii::$app->charset);
} }
public function clearOutput() public function clearOutput()
...@@ -255,15 +253,10 @@ class ErrorHandler extends Component ...@@ -255,15 +253,10 @@ class ErrorHandler extends Component
*/ */
public function renderAsHtml($exception) public function renderAsHtml($exception)
{ {
$view = new View($this); $view = new View;
if (!YII_DEBUG || $exception instanceof Exception && $exception->causedByUser) {
$viewName = $this->errorView;
} else {
$viewName = $this->exceptionView;
}
$name = !YII_DEBUG || $exception instanceof HttpException ? $this->errorView : $this->exceptionView; $name = !YII_DEBUG || $exception instanceof HttpException ? $this->errorView : $this->exceptionView;
echo $view->render($name, array( echo $view->render($name, array(
'exception' => $exception, 'exception' => $exception,
)); ), $this);
} }
} }
<?php <?php
/** /**
* Event class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -30,7 +28,8 @@ class Event extends \yii\base\Object ...@@ -30,7 +28,8 @@ class Event extends \yii\base\Object
*/ */
public $name; public $name;
/** /**
* @var object the sender of this event * @var object the sender of this event. If not set, this property will be
* set as the object whose "trigger()" method is called.
*/ */
public $sender; public $sender;
/** /**
...@@ -40,21 +39,7 @@ class Event extends \yii\base\Object ...@@ -40,21 +39,7 @@ class Event extends \yii\base\Object
*/ */
public $handled = false; public $handled = false;
/** /**
* @var mixed extra data associated with the event. * @var mixed extra custom data associated with the event.
*/ */
public $data; public $data;
/**
* Constructor.
*
* @param mixed $sender sender of the event
* @param mixed $data extra data associated with the event
* @param array $config name-value pairs that will be used to initialize the object properties
*/
public function __construct($sender = null, $data = null, $config = array())
{
$this->sender = $sender;
$this->data = $data;
parent::__construct($config);
}
} }
<?php <?php
/** /**
* Exception class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -17,17 +15,11 @@ namespace yii\base; ...@@ -17,17 +15,11 @@ namespace yii\base;
*/ */
class Exception extends \Exception class Exception extends \Exception
{ {
/**
* @var boolean whether this exception is caused by end user's mistake (e.g. wrong URL)
*/
public $causedByUser = false;
/** /**
* @return string the user-friendly name of this exception * @return string the user-friendly name of this exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii', 'Exception'); return \Yii::t('yii|Exception');
} }
} }
\ No newline at end of file
<?php <?php
/** /**
* HttpException class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -19,16 +17,12 @@ namespace yii\base; ...@@ -19,16 +17,12 @@ namespace yii\base;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class HttpException extends Exception class HttpException extends UserException
{ {
/** /**
* @var integer HTTP status code, such as 403, 404, 500, etc. * @var integer HTTP status code, such as 403, 404, 500, etc.
*/ */
public $statusCode; public $statusCode;
/**
* @var boolean whether this exception is caused by end user's mistake (e.g. wrong URL)
*/
public $causedByUser = true;
/** /**
* Constructor. * Constructor.
...@@ -41,4 +35,73 @@ class HttpException extends Exception ...@@ -41,4 +35,73 @@ class HttpException extends Exception
$this->statusCode = $status; $this->statusCode = $status;
parent::__construct($message, $code); parent::__construct($message, $code);
} }
/**
* @return string the user-friendly name of this exception
*/
public function getName()
{
static $httpCodes = array(
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
118 => 'Connection timed out',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
210 => 'Content Different',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
310 => 'Too many Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested range unsatisfiable',
417 => 'Expectation failed',
418 => 'I’m a teapot',
422 => 'Unprocessable entity',
423 => 'Locked',
424 => 'Method failure',
425 => 'Unordered Collection',
426 => 'Upgrade Required',
449 => 'Retry With',
450 => 'Blocked by Windows Parental Controls',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway ou Proxy Error',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported',
507 => 'Insufficient storage',
509 => 'Bandwidth Limit Exceeded',
);
if(isset($httpCodes[$this->statusCode]))
return $httpCodes[$this->statusCode];
else
return \Yii::t('yii|Error');
}
} }
<?php <?php
/** /**
* InlineAction class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -45,8 +43,7 @@ class InlineAction extends Action ...@@ -45,8 +43,7 @@ class InlineAction extends Action
*/ */
public function runWithParams($params) public function runWithParams($params)
{ {
$method = new \ReflectionMethod($this->controller, $this->actionMethod); $args = $this->controller->bindActionParams($this, $params);
$args = $this->bindActionParams($method, $params); return (int)call_user_func_array(array($this->controller, $this->actionMethod), $args);
return (int)$method->invokeArgs($this->controller, $args);
} }
} }
<?php <?php
/** /**
* InvalidCallException class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -15,14 +13,14 @@ namespace yii\base; ...@@ -15,14 +13,14 @@ namespace yii\base;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class InvalidCallException extends \Exception class InvalidCallException extends Exception
{ {
/** /**
* @return string the user-friendly name of this exception * @return string the user-friendly name of this exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii', 'Invalid Call'); return \Yii::t('yii|Invalid Call');
} }
} }
<?php <?php
/** /**
* InvalidConfigException class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -15,14 +13,14 @@ namespace yii\base; ...@@ -15,14 +13,14 @@ namespace yii\base;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class InvalidConfigException extends \Exception class InvalidConfigException extends Exception
{ {
/** /**
* @return string the user-friendly name of this exception * @return string the user-friendly name of this exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii', 'Invalid Configuration'); return \Yii::t('yii|Invalid Configuration');
} }
} }
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* InvalidParamException represents an exception caused by invalid parameters passed to a method.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class InvalidParamException extends Exception
{
/**
* @return string the user-friendly name of this exception
*/
public function getName()
{
return \Yii::t('yii|Invalid Parameter');
}
}
<?php <?php
/** /**
* InvalidRequestException class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -15,19 +13,14 @@ namespace yii\base; ...@@ -15,19 +13,14 @@ namespace yii\base;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class InvalidRequestException extends \Exception class InvalidRequestException extends UserException
{ {
/**
* @var boolean whether this exception is caused by end user's mistake (e.g. wrong URL)
*/
public $causedByUser = true;
/** /**
* @return string the user-friendly name of this exception * @return string the user-friendly name of this exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii', 'Invalid Request'); return \Yii::t('yii|Invalid Request');
} }
} }
<?php <?php
/** /**
* InvalidRouteException class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -15,19 +13,14 @@ namespace yii\base; ...@@ -15,19 +13,14 @@ namespace yii\base;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class InvalidRouteException extends \Exception class InvalidRouteException extends UserException
{ {
/**
* @var boolean whether this exception is caused by end user's mistake (e.g. wrong URL)
*/
public $causedByUser = true;
/** /**
* @return string the user-friendly name of this exception * @return string the user-friendly name of this exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii', 'Invalid Route'); return \Yii::t('yii|Invalid Route');
} }
} }
<?php <?php
/** /**
* Model class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
namespace yii\base; namespace yii\base;
use yii\util\StringHelper; use yii\helpers\StringHelper;
use yii\validators\Validator; use yii\validators\Validator;
use yii\validators\RequiredValidator; use yii\validators\RequiredValidator;
...@@ -260,7 +258,7 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess ...@@ -260,7 +258,7 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess
*/ */
public function beforeValidate() public function beforeValidate()
{ {
$event = new ModelEvent($this); $event = new ModelEvent;
$this->trigger(self::EVENT_BEFORE_VALIDATE, $event); $this->trigger(self::EVENT_BEFORE_VALIDATE, $event);
return $event->isValid; return $event->isValid;
} }
...@@ -331,7 +329,7 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess ...@@ -331,7 +329,7 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess
foreach ($this->rules() as $rule) { foreach ($this->rules() as $rule) {
if ($rule instanceof Validator) { if ($rule instanceof Validator) {
$validators->add($rule); $validators->add($rule);
} elseif (isset($rule[0], $rule[1])) { // attributes, validator type } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type
$validator = Validator::createValidator($rule[1], $this, $rule[0], array_slice($rule, 2)); $validator = Validator::createValidator($rule[1], $this, $rule[0], array_slice($rule, 2));
$validators->add($validator); $validators->add($validator);
} else { } else {
...@@ -421,13 +419,32 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess ...@@ -421,13 +419,32 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess
} }
} }
/**
* Returns the first error of every attribute in the model.
* @return array the first errors. An empty array will be returned if there is no error.
*/
public function getFirstErrors()
{
if (empty($this->_errors)) {
return array();
} else {
$errors = array();
foreach ($this->_errors as $attributeErrors) {
if (isset($attributeErrors[0])) {
$errors[] = $attributeErrors[0];
}
}
}
return $errors;
}
/** /**
* Returns the first error of the specified attribute. * Returns the first error of the specified attribute.
* @param string $attribute attribute name. * @param string $attribute attribute name.
* @return string the error message. Null is returned if no error. * @return string the error message. Null is returned if no error.
* @see getErrors * @see getErrors
*/ */
public function getError($attribute) public function getFirstError($attribute)
{ {
return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null; return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
} }
...@@ -442,25 +459,6 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess ...@@ -442,25 +459,6 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess
$this->_errors[$attribute][] = $error; $this->_errors[$attribute][] = $error;
} }
/**
* Adds a list of errors.
* @param array $errors a list of errors. The array keys must be attribute names.
* The array values should be error messages. If an attribute has multiple errors,
* these errors must be given in terms of an array.
*/
public function addErrors($errors)
{
foreach ($errors as $attribute => $error) {
if (is_array($error)) {
foreach ($error as $e) {
$this->_errors[$attribute][] = $e;
}
} else {
$this->_errors[$attribute][] = $error;
}
}
}
/** /**
* Removes errors for all attributes or a single attribute. * Removes errors for all attributes or a single attribute.
* @param string $attribute attribute name. Use null to remove errors for all attribute. * @param string $attribute attribute name. Use null to remove errors for all attribute.
...@@ -543,7 +541,7 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess ...@@ -543,7 +541,7 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess
public function onUnsafeAttribute($name, $value) public function onUnsafeAttribute($name, $value)
{ {
if (YII_DEBUG) { if (YII_DEBUG) {
\Yii::warning("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'."); \Yii::info("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.", __CLASS__);
} }
} }
...@@ -658,13 +656,13 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess ...@@ -658,13 +656,13 @@ class Model extends Component implements \IteratorAggregate, \ArrayAccess
} }
/** /**
* Unsets the element at the specified offset. * Sets the element value at the specified offset to null.
* This method is required by the SPL interface `ArrayAccess`. * This method is required by the SPL interface `ArrayAccess`.
* It is implicitly called when you use something like `unset($model[$offset])`. * It is implicitly called when you use something like `unset($model[$offset])`.
* @param mixed $offset the offset to unset element * @param mixed $offset the offset to unset element
*/ */
public function offsetUnset($offset) public function offsetUnset($offset)
{ {
unset($this->$offset); $this->$offset = null;
} }
} }
<?php <?php
/** /**
* ModelEvent class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
......
This diff is collapsed.
<?php <?php
/** /**
* NotSupportedException class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -15,14 +13,14 @@ namespace yii\base; ...@@ -15,14 +13,14 @@ namespace yii\base;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class NotSupportedException extends \Exception class NotSupportedException extends Exception
{ {
/** /**
* @return string the user-friendly name of this exception * @return string the user-friendly name of this exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii', 'Not Supported'); return \Yii::t('yii|Not Supported');
} }
} }
<?php <?php
/** /**
* Object class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -67,7 +65,7 @@ class Object ...@@ -67,7 +65,7 @@ class Object
if (method_exists($this, $getter)) { if (method_exists($this, $getter)) {
return $this->$getter(); return $this->$getter();
} else { } else {
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '.' . $name); throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
} }
} }
...@@ -88,9 +86,9 @@ class Object ...@@ -88,9 +86,9 @@ class Object
if (method_exists($this, $setter)) { if (method_exists($this, $setter)) {
$this->$setter($value); $this->$setter($value);
} elseif (method_exists($this, 'get' . $name)) { } elseif (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '.' . $name); throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
} else { } else {
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '.' . $name); throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
} }
} }
...@@ -131,7 +129,7 @@ class Object ...@@ -131,7 +129,7 @@ class Object
if (method_exists($this, $setter)) { if (method_exists($this, $setter)) {
$this->$setter(null); $this->$setter(null);
} elseif (method_exists($this, 'get' . $name)) { } elseif (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '.' . $name); throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
} }
} }
......
<?php <?php
/** /**
* Request class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -13,11 +11,17 @@ namespace yii\base; ...@@ -13,11 +11,17 @@ namespace yii\base;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class Request extends Component abstract class Request extends Component
{ {
private $_scriptFile; private $_scriptFile;
private $_isConsoleRequest; private $_isConsoleRequest;
/**
* Resolves the current request into a route and the associated parameters.
* @return array the first element is the route, and the second is the associated parameters.
*/
abstract public function resolve();
/** /**
* Returns a value indicating whether the current request is made via command line * Returns a value indicating whether the current request is made via command line
* @return boolean the value indicating whether the current request is made via console * @return boolean the value indicating whether the current request is made via console
...@@ -39,24 +43,35 @@ class Request extends Component ...@@ -39,24 +43,35 @@ class Request extends Component
/** /**
* Returns entry script file path. * Returns entry script file path.
* @return string entry script file path (processed w/ realpath()) * @return string entry script file path (processed w/ realpath())
* @throws InvalidConfigException if the entry script file path cannot be determined automatically.
*/ */
public function getScriptFile() public function getScriptFile()
{ {
if ($this->_scriptFile === null) { if ($this->_scriptFile === null) {
$this->_scriptFile = realpath($_SERVER['SCRIPT_FILENAME']); if (isset($_SERVER['SCRIPT_FILENAME'])) {
$this->setScriptFile($_SERVER['SCRIPT_FILENAME']);
} else {
throw new InvalidConfigException('Unable to determine the entry script file path.');
}
} }
return $this->_scriptFile; return $this->_scriptFile;
} }
/** /**
* Sets the entry script file path. * Sets the entry script file path.
* This can be an absolute or relative file path, or a path alias. * The entry script file path can normally be determined based on the `SCRIPT_FILENAME` SERVER variable.
* Note that you normally do not have to set the script file path * However, for some server configurations, this may not be correct or feasible.
* as [[getScriptFile()]] can determine it based on `$_SERVER['SCRIPT_FILENAME']`. * This setter is provided so that the entry script file path can be manually specified.
* @param string $value the entry script file * @param string $value the entry script file path. This can be either a file path or a path alias.
* @throws InvalidConfigException if the provided entry script file path is invalid.
*/ */
public function setScriptFile($value) public function setScriptFile($value)
{ {
$this->_scriptFile = realpath(\Yii::getAlias($value)); $scriptFile = realpath(\Yii::getAlias($value));
if ($scriptFile !== false && is_file($scriptFile)) {
$this->_scriptFile = $scriptFile;
} else {
throw new InvalidConfigException('Unable to determine the entry script file path.');
}
} }
} }
<?php <?php
/** /**
* Response class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
......
<?php
/**
* SecurityManager class file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* SecurityManager provides private keys, hashing and encryption functions.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class SecurityManager extends Component
{
const STATE_VALIDATION_KEY = 'Yii.SecurityManager.validationkey';
const STATE_ENCRYPTION_KEY = 'Yii.SecurityManager.encryptionkey';
/**
* @var string the name of the hashing algorithm to be used by {@link computeHMAC}.
* See {@link http://php.net/manual/en/function.hash-algos.php hash-algos} for the list of possible
* hash algorithms. Note that if you are using PHP 5.1.1 or below, you can only use 'sha1' or 'md5'.
*
* Defaults to 'sha1', meaning using SHA1 hash algorithm.
*/
public $hashAlgorithm = 'sha1';
/**
* @var mixed the name of the crypt algorithm to be used by {@link encrypt} and {@link decrypt}.
* This will be passed as the first parameter to {@link http://php.net/manual/en/function.mcrypt-module-open.php mcrypt_module_open}.
*
* This property can also be configured as an array. In this case, the array elements will be passed in order
* as parameters to mcrypt_module_open. For example, <code>array('rijndael-256', '', 'ofb', '')</code>.
*
* Defaults to 'des', meaning using DES crypt algorithm.
*/
public $cryptAlgorithm = 'des';
private $_validationKey;
private $_encryptionKey;
/**
* @return string a randomly generated private key
*/
protected function generateRandomKey()
{
return sprintf('%08x%08x%08x%08x', mt_rand(), mt_rand(), mt_rand(), mt_rand());
}
/**
* @return string the private key used to generate HMAC.
* If the key is not explicitly set, a random one is generated and returned.
*/
public function getValidationKey()
{
if ($this->_validationKey !== null) {
return $this->_validationKey;
} else {
if (($key = \Yii::$application->getGlobalState(self::STATE_VALIDATION_KEY)) !== null) {
$this->setValidationKey($key);
} else {
$key = $this->generateRandomKey();
$this->setValidationKey($key);
\Yii::$application->setGlobalState(self::STATE_VALIDATION_KEY, $key);
}
return $this->_validationKey;
}
}
/**
* @param string $value the key used to generate HMAC
* @throws CException if the key is empty
*/
public function setValidationKey($value)
{
if (!empty($value)) {
$this->_validationKey = $value;
} else {
throw new CException(Yii::t('yii', 'SecurityManager.validationKey cannot be empty.'));
}
}
/**
* @return string the private key used to encrypt/decrypt data.
* If the key is not explicitly set, a random one is generated and returned.
*/
public function getEncryptionKey()
{
if ($this->_encryptionKey !== null) {
return $this->_encryptionKey;
} else {
if (($key = \Yii::$application->getGlobalState(self::STATE_ENCRYPTION_KEY)) !== null) {
$this->setEncryptionKey($key);
} else {
$key = $this->generateRandomKey();
$this->setEncryptionKey($key);
\Yii::$application->setGlobalState(self::STATE_ENCRYPTION_KEY, $key);
}
return $this->_encryptionKey;
}
}
/**
* @param string $value the key used to encrypt/decrypt data.
* @throws CException if the key is empty
*/
public function setEncryptionKey($value)
{
if (!empty($value)) {
$this->_encryptionKey = $value;
} else {
throw new CException(Yii::t('yii', 'SecurityManager.encryptionKey cannot be empty.'));
}
}
/**
* This method has been deprecated since version 1.1.3.
* Please use {@link hashAlgorithm} instead.
* @return string
*/
public function getValidation()
{
return $this->hashAlgorithm;
}
/**
* This method has been deprecated since version 1.1.3.
* Please use {@link hashAlgorithm} instead.
* @param string $value -
*/
public function setValidation($value)
{
$this->hashAlgorithm = $value;
}
/**
* Encrypts data.
* @param string $data data to be encrypted.
* @param string $key the decryption key. This defaults to null, meaning using {@link getEncryptionKey EncryptionKey}.
* @return string the encrypted data
* @throws CException if PHP Mcrypt extension is not loaded
*/
public function encrypt($data, $key = null)
{
$module = $this->openCryptModule();
$key = $this->substr($key === null ? md5($this->getEncryptionKey()) : $key, 0, mcrypt_enc_get_key_size($module));
srand();
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($module), MCRYPT_RAND);
mcrypt_generic_init($module, $key, $iv);
$encrypted = $iv . mcrypt_generic($module, $data);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
return $encrypted;
}
/**
* Decrypts data
* @param string $data data to be decrypted.
* @param string $key the decryption key. This defaults to null, meaning using {@link getEncryptionKey EncryptionKey}.
* @return string the decrypted data
* @throws CException if PHP Mcrypt extension is not loaded
*/
public function decrypt($data, $key = null)
{
$module = $this->openCryptModule();
$key = $this->substr($key === null ? md5($this->getEncryptionKey()) : $key, 0, mcrypt_enc_get_key_size($module));
$ivSize = mcrypt_enc_get_iv_size($module);
$iv = $this->substr($data, 0, $ivSize);
mcrypt_generic_init($module, $key, $iv);
$decrypted = mdecrypt_generic($module, $this->substr($data, $ivSize, $this->strlen($data)));
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
return rtrim($decrypted, "\0");
}
/**
* Opens the mcrypt module with the configuration specified in {@link cryptAlgorithm}.
* @return resource the mycrypt module handle.
* @since 1.1.3
*/
protected function openCryptModule()
{
if (extension_loaded('mcrypt')) {
if (is_array($this->cryptAlgorithm)) {
$module = @call_user_func_array('mcrypt_module_open', $this->cryptAlgorithm);
} else {
$module = @mcrypt_module_open($this->cryptAlgorithm, '', MCRYPT_MODE_CBC, '');
}
if ($module === false) {
throw new CException(Yii::t('yii', 'Failed to initialize the mcrypt module.'));
}
return $module;
} else {
throw new CException(Yii::t('yii', 'SecurityManager requires PHP mcrypt extension to be loaded in order to use data encryption feature.'));
}
}
/**
* Prefixes data with an HMAC.
* @param string $data data to be hashed.
* @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
* @return string data prefixed with HMAC
*/
public function hashData($data, $key = null)
{
return $this->computeHMAC($data, $key) . $data;
}
/**
* Validates if data is tampered.
* @param string $data data to be validated. The data must be previously
* generated using {@link hashData()}.
* @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
* @return string the real data with HMAC stripped off. False if the data
* is tampered.
*/
public function validateData($data, $key = null)
{
$len = $this->strlen($this->computeHMAC('test'));
if ($this->strlen($data) >= $len) {
$hmac = $this->substr($data, 0, $len);
$data2 = $this->substr($data, $len, $this->strlen($data));
return $hmac === $this->computeHMAC($data2, $key) ? $data2 : false;
} else {
return false;
}
}
/**
* Computes the HMAC for the data with {@link getValidationKey ValidationKey}.
* @param string $data data to be generated HMAC
* @param string $key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
* @return string the HMAC for the data
*/
protected function computeHMAC($data, $key = null)
{
if ($key === null) {
$key = $this->getValidationKey();
}
if (function_exists('hash_hmac')) {
return hash_hmac($this->hashAlgorithm, $data, $key);
}
if (!strcasecmp($this->hashAlgorithm, 'sha1')) {
$pack = 'H40';
$func = 'sha1';
} else {
$pack = 'H32';
$func = 'md5';
}
if ($this->strlen($key) > 64) {
$key = pack($pack, $func($key));
}
if ($this->strlen($key) < 64) {
$key = str_pad($key, 64, chr(0));
}
$key = $this->substr($key, 0, 64);
return $func((str_repeat(chr(0x5C), 64) ^ $key) . pack($pack, $func((str_repeat(chr(0x36), 64) ^ $key) . $data)));
}
/**
* Returns the length of the given string.
* If available uses the multibyte string function mb_strlen.
* @param string $string the string being measured for length
* @return int the length of the string
*/
private function strlen($string)
{
return function_exists('mb_strlen') ? mb_strlen($string, '8bit') : strlen($string);
}
/**
* Returns the portion of string specified by the start and length parameters.
* If available uses the multibyte string function mb_substr
* @param string $string the input string. Must be one character or longer.
* @param int $start the starting position
* @param int $length the desired portion length
* @return string the extracted part of string, or FALSE on failure or an empty string.
*/
private function substr($string, $start, $length)
{
return function_exists('mb_substr') ? mb_substr($string, $start, $length, '8bit') : substr($string, $start, $length);
}
}
<?php <?php
/** /**
* Theme class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -11,7 +9,7 @@ namespace yii\base; ...@@ -11,7 +9,7 @@ namespace yii\base;
use Yii; use Yii;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
use yii\util\FileHelper; use yii\helpers\FileHelper;
/** /**
* Theme represents an application theme. * Theme represents an application theme.
...@@ -42,7 +40,8 @@ class Theme extends Component ...@@ -42,7 +40,8 @@ class Theme extends Component
/** /**
* @var array the mapping between view directories and their corresponding themed versions. * @var array the mapping between view directories and their corresponding themed versions.
* If not set, it will be initialized as a mapping from [[Application::basePath]] to [[basePath]]. * If not set, it will be initialized as a mapping from [[Application::basePath]] to [[basePath]].
* This property is used by [[apply()]] when a view is trying to apply the theme. * This property is used by [[applyTo()]] when a view is trying to apply the theme.
* Path aliases can be used when specifying directories.
*/ */
public $pathMap; public $pathMap;
...@@ -58,14 +57,16 @@ class Theme extends Component ...@@ -58,14 +57,16 @@ class Theme extends Component
if (empty($this->pathMap)) { if (empty($this->pathMap)) {
if ($this->basePath !== null) { if ($this->basePath !== null) {
$this->basePath = FileHelper::ensureDirectory($this->basePath); $this->basePath = FileHelper::ensureDirectory($this->basePath);
$this->pathMap = array(Yii::$application->getBasePath() => $this->basePath); $this->pathMap = array(Yii::$app->getBasePath() => $this->basePath);
} else { } else {
throw new InvalidConfigException("Theme::basePath must be set."); throw new InvalidConfigException("Theme::basePath must be set.");
} }
} }
$paths = array(); $paths = array();
foreach ($this->pathMap as $from => $to) { foreach ($this->pathMap as $from => $to) {
$paths[FileHelper::normalizePath($from) . DIRECTORY_SEPARATOR] = FileHelper::normalizePath($to) . DIRECTORY_SEPARATOR; $from = FileHelper::normalizePath(Yii::getAlias($from));
$to = FileHelper::normalizePath(Yii::getAlias($to));
$paths[$from . DIRECTORY_SEPARATOR] = $to . DIRECTORY_SEPARATOR;
} }
$this->pathMap = $paths; $this->pathMap = $paths;
} }
...@@ -95,7 +96,7 @@ class Theme extends Component ...@@ -95,7 +96,7 @@ class Theme extends Component
* @param string $path the file to be themed * @param string $path the file to be themed
* @return string the themed file, or the original file if the themed version is not available. * @return string the themed file, or the original file if the themed version is not available.
*/ */
public function apply($path) public function applyTo($path)
{ {
$path = FileHelper::normalizePath($path); $path = FileHelper::normalizePath($path);
foreach ($this->pathMap as $from => $to) { foreach ($this->pathMap as $from => $to) {
......
<?php <?php
/** /**
* UnknownMethodException class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -15,14 +13,14 @@ namespace yii\base; ...@@ -15,14 +13,14 @@ namespace yii\base;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class UnknownMethodException extends \Exception class UnknownMethodException extends Exception
{ {
/** /**
* @return string the user-friendly name of this exception * @return string the user-friendly name of this exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii', 'Unknown Method'); return \Yii::t('yii|Unknown Method');
} }
} }
<?php <?php
/** /**
* UnknownPropertyException class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -15,14 +13,14 @@ namespace yii\base; ...@@ -15,14 +13,14 @@ namespace yii\base;
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class UnknownPropertyException extends \Exception class UnknownPropertyException extends Exception
{ {
/** /**
* @return string the user-friendly name of this exception * @return string the user-friendly name of this exception
*/ */
public function getName() public function getName()
{ {
return \Yii::t('yii', 'Unknown Property'); return \Yii::t('yii|Unknown Property');
} }
} }
This diff is collapsed.
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* UserException is the base class for exceptions that are meant to be shown to end users.
* Such exceptions are often caused by mistakes of end users.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class UserException extends Exception
{
}
<?php <?php
/** /**
* Vector class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
...@@ -101,7 +99,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta ...@@ -101,7 +99,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
* Returns the item at the specified index. * Returns the item at the specified index.
* @param integer $index the index of the item * @param integer $index the index of the item
* @return mixed the item at the index * @return mixed the item at the index
* @throws InvalidCallException if the index is out of range * @throws InvalidParamException if the index is out of range
*/ */
public function itemAt($index) public function itemAt($index)
{ {
...@@ -110,7 +108,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta ...@@ -110,7 +108,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
} elseif ($index >= 0 && $index < $this->_c) { // in case the value is null } elseif ($index >= 0 && $index < $this->_c) { // in case the value is null
return $this->_d[$index]; return $this->_d[$index];
} else { } else {
throw new InvalidCallException('Index out of range: ' . $index); throw new InvalidParamException('Index out of range: ' . $index);
} }
} }
...@@ -132,7 +130,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta ...@@ -132,7 +130,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
* one step towards the end. * one step towards the end.
* @param integer $index the specified position. * @param integer $index the specified position.
* @param mixed $item new item to be inserted into the vector * @param mixed $item new item to be inserted into the vector
* @throws InvalidCallException if the index specified is out of range, or the vector is read-only. * @throws InvalidParamException if the index specified is out of range, or the vector is read-only.
*/ */
public function insertAt($index, $item) public function insertAt($index, $item)
{ {
...@@ -142,7 +140,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta ...@@ -142,7 +140,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
array_splice($this->_d, $index, 0, array($item)); array_splice($this->_d, $index, 0, array($item));
$this->_c++; $this->_c++;
} else { } else {
throw new InvalidCallException('Index out of range: ' . $index); throw new InvalidParamException('Index out of range: ' . $index);
} }
} }
...@@ -169,7 +167,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta ...@@ -169,7 +167,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
* Removes an item at the specified position. * Removes an item at the specified position.
* @param integer $index the index of the item to be removed. * @param integer $index the index of the item to be removed.
* @return mixed the removed item. * @return mixed the removed item.
* @throws InvalidCallException if the index is out of range, or the vector is read only. * @throws InvalidParamException if the index is out of range, or the vector is read only.
*/ */
public function removeAt($index) public function removeAt($index)
{ {
...@@ -183,7 +181,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta ...@@ -183,7 +181,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
return $item; return $item;
} }
} else { } else {
throw new InvalidCallException('Index out of range: ' . $index); throw new InvalidParamException('Index out of range: ' . $index);
} }
} }
...@@ -193,7 +191,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta ...@@ -193,7 +191,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
* Defaults to false, meaning all items in the vector will be cleared directly * Defaults to false, meaning all items in the vector will be cleared directly
* without calling [[removeAt]]. * without calling [[removeAt]].
*/ */
public function clear($safeClear = false) public function removeAll($safeClear = false)
{ {
if ($safeClear) { if ($safeClear) {
for ($i = $this->_c - 1; $i >= 0; --$i) { for ($i = $this->_c - 1; $i >= 0; --$i) {
...@@ -211,7 +209,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta ...@@ -211,7 +209,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
* @param mixed $item the item * @param mixed $item the item
* @return boolean whether the vector contains the item * @return boolean whether the vector contains the item
*/ */
public function contains($item) public function has($item)
{ {
return $this->indexOf($item) >= 0; return $this->indexOf($item) >= 0;
} }
...@@ -242,13 +240,13 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta ...@@ -242,13 +240,13 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
* Copies iterable data into the vector. * Copies iterable data into the vector.
* Note, existing data in the vector will be cleared first. * Note, existing data in the vector will be cleared first.
* @param mixed $data the data to be copied from, must be an array or an object implementing `Traversable` * @param mixed $data the data to be copied from, must be an array or an object implementing `Traversable`
* @throws InvalidCallException if data is neither an array nor an object implementing `Traversable`. * @throws InvalidParamException if data is neither an array nor an object implementing `Traversable`.
*/ */
public function copyFrom($data) public function copyFrom($data)
{ {
if (is_array($data) || $data instanceof \Traversable) { if (is_array($data) || $data instanceof \Traversable) {
if ($this->_c > 0) { if ($this->_c > 0) {
$this->clear(); $this->removeAll();
} }
if ($data instanceof self) { if ($data instanceof self) {
$data = $data->_d; $data = $data->_d;
...@@ -257,7 +255,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta ...@@ -257,7 +255,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
$this->add($item); $this->add($item);
} }
} else { } else {
throw new InvalidCallException('Data must be either an array or an object implementing Traversable.'); throw new InvalidParamException('Data must be either an array or an object implementing Traversable.');
} }
} }
...@@ -265,7 +263,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta ...@@ -265,7 +263,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
* Merges iterable data into the vector. * Merges iterable data into the vector.
* New items will be appended to the end of the existing items. * New items will be appended to the end of the existing items.
* @param array|\Traversable $data the data to be merged with. It must be an array or object implementing Traversable * @param array|\Traversable $data the data to be merged with. It must be an array or object implementing Traversable
* @throws InvalidCallException if data is neither an array nor an object implementing `Traversable`. * @throws InvalidParamException if data is neither an array nor an object implementing `Traversable`.
*/ */
public function mergeWith($data) public function mergeWith($data)
{ {
...@@ -277,7 +275,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta ...@@ -277,7 +275,7 @@ class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Counta
$this->add($item); $this->add($item);
} }
} else { } else {
throw new InvalidCallException('The data to be merged with must be an array or an object implementing Traversable.'); throw new InvalidParamException('The data to be merged with must be an array or an object implementing Traversable.');
} }
} }
......
<?php <?php
/** /**
* VectorIterator class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
......
This diff is collapsed.
<?php <?php
/** /**
* ViewRenderer class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
......
<?php <?php
/** /**
* Widget class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
namespace yii\base; namespace yii\base;
use Yii;
use yii\helpers\FileHelper;
/** /**
* Widget is the base class for widgets. * Widget is the base class for widgets.
* *
...@@ -72,35 +73,26 @@ class Widget extends Component ...@@ -72,35 +73,26 @@ class Widget extends Component
/** /**
* Renders a view. * Renders a view.
* * @param string $view the view name. Please refer to [[findViewFile()]] on how to specify a view name.
* The method first finds the actual view file corresponding to the specified view. * @param array $params the parameters (name-value pairs) that should be made available in the view.
* It then calls [[renderFile()]] to render the view file. The rendering result is returned * @return string the rendering result.
* as a string. If the view file does not exist, an exception will be thrown. * @throws InvalidParamException if the view file does not exist.
*
* To determine which view file should be rendered, the method calls [[findViewFile()]] which
* will search in the directories as specified by [[basePath]].
*
* View name can be a path alias representing an absolute file path (e.g. `@application/views/layout/index`),
* or a path relative to [[basePath]]. The file suffix is optional and defaults to `.php` if not given
* in the view name.
*
* @param string $view the view to be rendered. This can be either a path alias or a path relative to [[basePath]].
* @param array $params the parameters that should be made available in the view. The PHP function `extract()`
* will be called on this variable to extract the variables from this parameter.
* @return string the rendering result
* @throws Exception if the view file cannot be found
*/ */
public function render($view, $params = array()) public function render($view, $params = array())
{ {
return $this->createView()->renderPartial($view, $params); return Yii::$app->getView()->render($view, $params, $this);
} }
/** /**
* @return View * Renders a view file.
* @param string $file the view file to be rendered. This can be either a file path or a path alias.
* @param array $params the parameters (name-value pairs) that should be made available in the view.
* @return string the rendering result.
* @throws InvalidParamException if the view file does not exist.
*/ */
public function createView() public function renderFile($file, $params = array())
{ {
return new View($this); return Yii::$app->getView()->renderFile($file, $params, $this);
} }
/** /**
......
<?php <?php
/** /**
* ApcCache class file
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
......
<?php <?php
/** /**
* Cache class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
namespace yii\caching; namespace yii\caching;
use yii\base\Component; use yii\base\Component;
use yii\helpers\StringHelper;
/** /**
* Cache is the base class for cache classes supporting different cache storage implementation. * Cache is the base class for cache classes supporting different cache storage implementation.
...@@ -72,13 +71,13 @@ abstract class Cache extends Component implements \ArrayAccess ...@@ -72,13 +71,13 @@ abstract class Cache extends Component implements \ArrayAccess
/** /**
* Builds a normalized cache key from one or multiple parameters. * Builds a normalized cache key from a given key.
* *
* The generated key contains letters and digits only, and its length is no more than 32. * The generated key contains letters and digits only, and its length is no more than 32.
* *
* If only one parameter is given and it is already a normalized key, then * If the given key is a string containing alphanumeric characters only and no more than 32 characters,
* it will be returned back without change. Otherwise, a normalized key * then the key will be returned back without change. Otherwise, a normalized key
* is generated by serializing all given parameters and applying MD5 hashing. * is generated by serializing the given key and applying MD5 hashing.
* *
* The following example builds a cache key using three parameters: * The following example builds a cache key using three parameters:
* *
...@@ -86,16 +85,15 @@ abstract class Cache extends Component implements \ArrayAccess ...@@ -86,16 +85,15 @@ abstract class Cache extends Component implements \ArrayAccess
* $key = $cache->buildKey($className, $method, $id); * $key = $cache->buildKey($className, $method, $id);
* ~~~ * ~~~
* *
* @param string $key the first parameter * @param array|string $key the key to be normalized
* @return string the generated cache key * @return string the generated cache key
*/ */
public function buildKey($key) public function buildKey($key)
{ {
if (func_num_args() === 1 && ctype_alnum($key) && strlen($key) <= 32) { if (is_string($key)) {
return (string)$key; return ctype_alnum($key) && StringHelper::strlen($key) <= 32 ? $key : md5($key);
} else { } else {
$params = func_get_args(); return md5(json_encode($key));
return md5(serialize($params));
} }
} }
......
<?php <?php
/** /**
* ChainedDependency class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
......
<?php <?php
/** /**
* DbCache class file
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
namespace yii\caching; namespace yii\caching;
use Yii;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
use yii\db\Connection; use yii\db\Connection;
use yii\db\Query; use yii\db\Query;
...@@ -16,30 +15,20 @@ use yii\db\Query; ...@@ -16,30 +15,20 @@ use yii\db\Query;
/** /**
* DbCache implements a cache application component by storing cached data in a database. * DbCache implements a cache application component by storing cached data in a database.
* *
* DbCache stores cache data in a DB table whose name is specified via [[cacheTableName]]. * By default, DbCache stores session data in a DB table named 'tbl_cache'. This table
* For MySQL database, the table should be created beforehand as follows : * must be pre-created. The table name can be changed by setting [[cacheTable]].
*
* ~~~
* CREATE TABLE tbl_cache (
* id char(128) NOT NULL,
* expire int(11) DEFAULT NULL,
* data LONGBLOB,
* PRIMARY KEY (id),
* KEY expire (expire)
* );
* ~~~
*
* You should replace `LONGBLOB` as follows if you are using a different DBMS:
*
* - PostgreSQL: `BYTEA`
* - SQLite, SQL server, Oracle: `BLOB`
*
* DbCache connects to the database via the DB connection specified in [[connectionID]]
* which must refer to a valid DB application component.
* *
* Please refer to [[Cache]] for common cache operations that are supported by DbCache. * Please refer to [[Cache]] for common cache operations that are supported by DbCache.
* *
* @property Connection $db The DB connection instance. * The following example shows how you can configure the application to use DbCache:
*
* ~~~
* 'cache' => array(
* 'class' => 'yii\caching\DbCache',
* // 'db' => 'mydb',
* // 'cacheTable' => 'my_cache',
* )
* ~~~
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
...@@ -47,50 +36,56 @@ use yii\db\Query; ...@@ -47,50 +36,56 @@ use yii\db\Query;
class DbCache extends Cache class DbCache extends Cache
{ {
/** /**
* @var string the ID of the [[Connection|DB connection]] application component. Defaults to 'db'. * @var Connection|string the DB connection object or the application component ID of the DB connection.
* After the DbCache object is created, if you want to change this property, you should only assign it
* with a DB connection object.
*/ */
public $connectionID = 'db'; public $db = 'db';
/** /**
* @var string name of the DB table to store cache content. Defaults to 'tbl_cache'. * @var string name of the DB table to store cache content.
* The table must be created before using this cache component. * The table should be pre-created as follows:
*
* ~~~
* CREATE TABLE tbl_cache (
* id char(128) NOT NULL PRIMARY KEY,
* expire int(11),
* data BLOB
* );
* ~~~
*
* where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB type
* that can be used for some popular DBMS:
*
* - MySQL: LONGBLOB
* - PostgreSQL: BYTEA
* - MSSQL: BLOB
*
* When using DbCache in a production server, we recommend you create a DB index for the 'expire'
* column in the cache table to improve the performance.
*/ */
public $cacheTableName = 'tbl_cache'; public $cacheTable = 'tbl_cache';
/** /**
* @var integer the probability (parts per million) that garbage collection (GC) should be performed * @var integer the probability (parts per million) that garbage collection (GC) should be performed
* when storing a piece of data in the cache. Defaults to 10, meaning 0.001% chance. * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
* This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all. * This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all.
**/ **/
public $gcProbability = 100; public $gcProbability = 100;
/**
* @var Connection the DB connection instance
*/
private $_db;
/**
* Returns the DB connection instance used for caching purpose.
* @return Connection the DB connection instance
* @throws InvalidConfigException if [[connectionID]] does not point to a valid application component.
*/
public function getDb()
{
if ($this->_db === null) {
$db = \Yii::$application->getComponent($this->connectionID);
if ($db instanceof Connection) {
$this->_db = $db;
} else {
throw new InvalidConfigException("DbCache::connectionID must refer to the ID of a DB application component.");
}
}
return $this->_db;
}
/** /**
* Sets the DB connection used by the cache component. * Initializes the DbCache component.
* @param Connection $value the DB connection instance * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
* @throws InvalidConfigException if [[db]] is invalid.
*/ */
public function setDb($value) public function init()
{ {
$this->_db = $value; parent::init();
if (is_string($this->db)) {
$this->db = Yii::$app->getComponent($this->db);
}
if (!$this->db instanceof Connection) {
throw new InvalidConfigException("DbCache::db must be either a DB connection instance or the application component ID of a DB connection.");
}
} }
/** /**
...@@ -103,17 +98,16 @@ class DbCache extends Cache ...@@ -103,17 +98,16 @@ class DbCache extends Cache
{ {
$query = new Query; $query = new Query;
$query->select(array('data')) $query->select(array('data'))
->from($this->cacheTableName) ->from($this->cacheTable)
->where('id = :id AND (expire = 0 OR expire > :time)', array(':id' => $key, ':time' => time())); ->where('id = :id AND (expire = 0 OR expire >' . time() . ')', array(':id' => $key));
$db = $this->getDb(); if ($this->db->enableQueryCache) {
if ($db->enableQueryCache) {
// temporarily disable and re-enable query caching // temporarily disable and re-enable query caching
$db->enableQueryCache = false; $this->db->enableQueryCache = false;
$result = $query->createCommand($db)->queryScalar(); $result = $query->createCommand($this->db)->queryScalar();
$db->enableQueryCache = true; $this->db->enableQueryCache = true;
return $result; return $result;
} else { } else {
return $query->createCommand($db)->queryScalar(); return $query->createCommand($this->db)->queryScalar();
} }
} }
...@@ -129,17 +123,16 @@ class DbCache extends Cache ...@@ -129,17 +123,16 @@ class DbCache extends Cache
} }
$query = new Query; $query = new Query;
$query->select(array('id', 'data')) $query->select(array('id', 'data'))
->from($this->cacheTableName) ->from($this->cacheTable)
->where(array('id' => $keys)) ->where(array('id' => $keys))
->andWhere("expire = 0 OR expire > " . time() . ")"); ->andWhere('(expire = 0 OR expire > ' . time() . ')');
$db = $this->getDb(); if ($this->db->enableQueryCache) {
if ($db->enableQueryCache) { $this->db->enableQueryCache = false;
$db->enableQueryCache = false; $rows = $query->createCommand($this->db)->queryAll();
$rows = $query->createCommand($db)->queryAll(); $this->db->enableQueryCache = true;
$db->enableQueryCache = true;
} else { } else {
$rows = $query->createCommand($db)->queryAll(); $rows = $query->createCommand($this->db)->queryAll();
} }
$results = array(); $results = array();
...@@ -163,13 +156,13 @@ class DbCache extends Cache ...@@ -163,13 +156,13 @@ class DbCache extends Cache
*/ */
protected function setValue($key, $value, $expire) protected function setValue($key, $value, $expire)
{ {
$command = $this->getDb()->createCommand(); $command = $this->db->createCommand()
$command->update($this->cacheTableName, array( ->update($this->cacheTable, array(
'expire' => $expire > 0 ? $expire + time() : 0, 'expire' => $expire > 0 ? $expire + time() : 0,
'data' => array($value, \PDO::PARAM_LOB), 'data' => array($value, \PDO::PARAM_LOB),
), array( ), array(
'id' => $key, 'id' => $key,
));; ));
if ($command->execute()) { if ($command->execute()) {
$this->gc(); $this->gc();
...@@ -198,14 +191,13 @@ class DbCache extends Cache ...@@ -198,14 +191,13 @@ class DbCache extends Cache
$expire = 0; $expire = 0;
} }
$command = $this->getDb()->createCommand();
$command->insert($this->cacheTableName, array(
'id' => $key,
'expire' => $expire,
'data' => array($value, \PDO::PARAM_LOB),
));
try { try {
$command->execute(); $this->db->createCommand()
->insert($this->cacheTable, array(
'id' => $key,
'expire' => $expire,
'data' => array($value, \PDO::PARAM_LOB),
))->execute();
return true; return true;
} catch (\Exception $e) { } catch (\Exception $e) {
return false; return false;
...@@ -220,8 +212,9 @@ class DbCache extends Cache ...@@ -220,8 +212,9 @@ class DbCache extends Cache
*/ */
protected function deleteValue($key) protected function deleteValue($key)
{ {
$command = $this->getDb()->createCommand(); $this->db->createCommand()
$command->delete($this->cacheTableName, array('id' => $key))->execute(); ->delete($this->cacheTable, array('id' => $key))
->execute();
return true; return true;
} }
...@@ -233,8 +226,9 @@ class DbCache extends Cache ...@@ -233,8 +226,9 @@ class DbCache extends Cache
public function gc($force = false) public function gc($force = false)
{ {
if ($force || mt_rand(0, 1000000) < $this->gcProbability) { if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
$command = $this->getDb()->createCommand(); $this->db->createCommand()
$command->delete($this->cacheTableName, 'expire > 0 AND expire < ' . time())->execute(); ->delete($this->cacheTable, 'expire > 0 AND expire < ' . time())
->execute();
} }
} }
...@@ -245,8 +239,9 @@ class DbCache extends Cache ...@@ -245,8 +239,9 @@ class DbCache extends Cache
*/ */
protected function flushValues() protected function flushValues()
{ {
$command = $this->getDb()->createCommand(); $this->db->createCommand()
$command->delete($this->cacheTableName)->execute(); ->delete($this->cacheTable)
->execute();
return true; return true;
} }
} }
This diff is collapsed.
<?php <?php
/** /**
* Dependency class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
......
This diff is collapsed.
<?php <?php
/** /**
* ExpressionDependency class file.
*
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC * @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/ * @license http://www.yiiframework.com/license/
*/ */
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
<?php <?php
/** @var $controller \yii\console\controllers\CreateController */ /** @var $controller \yii\console\controllers\AppController */
$controller = $this; $controller = $this;
return array( return array(
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment