This commit is contained in:
2020-02-01 16:47:12 +07:00
commit 4c619ad6e6
16739 changed files with 3329179 additions and 0 deletions

View File

@@ -0,0 +1,149 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\behaviors;
use Closure;
use yii\base\Behavior;
use yii\base\Event;
use yii\db\ActiveRecord;
/**
* AttributeBehavior automatically assigns a specified value to one or multiple attributes of an ActiveRecord
* object when certain events happen.
*
* To use AttributeBehavior, configure the [[attributes]] property which should specify the list of attributes
* that need to be updated and the corresponding events that should trigger the update. Then configure the
* [[value]] property with a PHP callable whose return value will be used to assign to the current attribute(s).
* For example,
*
* ```php
* use yii\behaviors\AttributeBehavior;
*
* public function behaviors()
* {
* return [
* [
* 'class' => AttributeBehavior::className(),
* 'attributes' => [
* ActiveRecord::EVENT_BEFORE_INSERT => 'attribute1',
* ActiveRecord::EVENT_BEFORE_UPDATE => 'attribute2',
* ],
* 'value' => function ($event) {
* return 'some value';
* },
* ],
* ];
* }
* ```
*
* Because attribute values will be set automatically by this behavior, they are usually not user input and should therefore
* not be validated, i.e. they should not appear in the [[\yii\base\Model::rules()|rules()]] method of the model.
*
* @author Luciano Baraglia <luciano.baraglia@gmail.com>
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class AttributeBehavior extends Behavior
{
/**
* @var array list of attributes that are to be automatically filled with the value specified via [[value]].
* The array keys are the ActiveRecord events upon which the attributes are to be updated,
* and the array values are the corresponding attribute(s) to be updated. You can use a string to represent
* a single attribute, or an array to represent a list of attributes. For example,
*
* ```php
* [
* ActiveRecord::EVENT_BEFORE_INSERT => ['attribute1', 'attribute2'],
* ActiveRecord::EVENT_BEFORE_UPDATE => 'attribute2',
* ]
* ```
*/
public $attributes = [];
/**
* @var mixed the value that will be assigned to the current attributes. This can be an anonymous function,
* callable in array format (e.g. `[$this, 'methodName']`), an [[\yii\db\Expression|Expression]] object representing a DB expression
* (e.g. `new Expression('NOW()')`), scalar, string or an arbitrary value. If the former, the return value of the
* function will be assigned to the attributes.
* The signature of the function should be as follows,
*
* ```php
* function ($event)
* {
* // return value will be assigned to the attribute
* }
* ```
*/
public $value;
/**
* @var bool whether to skip this behavior when the `$owner` has not been
* modified
* @since 2.0.8
*/
public $skipUpdateOnClean = true;
/**
* @var bool whether to preserve non-empty attribute values.
* @since 2.0.13
*/
public $preserveNonEmptyValues = false;
/**
* {@inheritdoc}
*/
public function events()
{
return array_fill_keys(
array_keys($this->attributes),
'evaluateAttributes'
);
}
/**
* Evaluates the attribute value and assigns it to the current attributes.
* @param Event $event
*/
public function evaluateAttributes($event)
{
if ($this->skipUpdateOnClean
&& $event->name == ActiveRecord::EVENT_BEFORE_UPDATE
&& empty($this->owner->dirtyAttributes)
) {
return;
}
if (!empty($this->attributes[$event->name])) {
$attributes = (array) $this->attributes[$event->name];
$value = $this->getValue($event);
foreach ($attributes as $attribute) {
// ignore attribute names which are not string (e.g. when set by TimestampBehavior::updatedAtAttribute)
if (is_string($attribute)) {
if ($this->preserveNonEmptyValues && !empty($this->owner->$attribute)) {
continue;
}
$this->owner->$attribute = $value;
}
}
}
}
/**
* Returns the value for the current attributes.
* This method is called by [[evaluateAttributes()]]. Its return value will be assigned
* to the attributes corresponding to the triggering event.
* @param Event $event the event that triggers the current attribute updating.
* @return mixed the attribute value
*/
protected function getValue($event)
{
if ($this->value instanceof Closure || (is_array($this->value) && is_callable($this->value))) {
return call_user_func($this->value, $event);
}
return $this->value;
}
}

View File

@@ -0,0 +1,368 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\behaviors;
use yii\base\Behavior;
use yii\base\InvalidArgumentException;
use yii\base\Model;
use yii\db\BaseActiveRecord;
use yii\helpers\StringHelper;
use yii\validators\BooleanValidator;
use yii\validators\NumberValidator;
use yii\validators\StringValidator;
/**
* AttributeTypecastBehavior provides an ability of automatic model attribute typecasting.
* This behavior is very useful in case of usage of ActiveRecord for the schema-less databases like MongoDB or Redis.
* It may also come in handy for regular [[\yii\db\ActiveRecord]] or even [[\yii\base\Model]], allowing to maintain
* strict attribute types after model validation.
*
* This behavior should be attached to [[\yii\base\Model]] or [[\yii\db\BaseActiveRecord]] descendant.
*
* You should specify exact attribute types via [[attributeTypes]].
*
* For example:
*
* ```php
* use yii\behaviors\AttributeTypecastBehavior;
*
* class Item extends \yii\db\ActiveRecord
* {
* public function behaviors()
* {
* return [
* 'typecast' => [
* 'class' => AttributeTypecastBehavior::className(),
* 'attributeTypes' => [
* 'amount' => AttributeTypecastBehavior::TYPE_INTEGER,
* 'price' => AttributeTypecastBehavior::TYPE_FLOAT,
* 'is_active' => AttributeTypecastBehavior::TYPE_BOOLEAN,
* ],
* 'typecastAfterValidate' => true,
* 'typecastBeforeSave' => false,
* 'typecastAfterFind' => false,
* ],
* ];
* }
*
* // ...
* }
* ```
*
* Tip: you may left [[attributeTypes]] blank - in this case its value will be detected
* automatically based on owner validation rules.
* Following example will automatically create same [[attributeTypes]] value as it was configured at the above one:
*
* ```php
* use yii\behaviors\AttributeTypecastBehavior;
*
* class Item extends \yii\db\ActiveRecord
* {
*
* public function rules()
* {
* return [
* ['amount', 'integer'],
* ['price', 'number'],
* ['is_active', 'boolean'],
* ];
* }
*
* public function behaviors()
* {
* return [
* 'typecast' => [
* 'class' => AttributeTypecastBehavior::className(),
* // 'attributeTypes' will be composed automatically according to `rules()`
* ],
* ];
* }
*
* // ...
* }
* ```
*
* This behavior allows automatic attribute typecasting at following cases:
*
* - after successful model validation
* - before model save (insert or update)
* - after model find (found by query or refreshed)
*
* You may control automatic typecasting for particular case using fields [[typecastAfterValidate]],
* [[typecastBeforeSave]] and [[typecastAfterFind]].
* By default typecasting will be performed only after model validation.
*
* Note: you can manually trigger attribute typecasting anytime invoking [[typecastAttributes()]] method:
*
* ```php
* $model = new Item();
* $model->price = '38.5';
* $model->is_active = 1;
* $model->typecastAttributes();
* ```
*
* @author Paul Klimov <klimov.paul@gmail.com>
* @since 2.0.10
*/
class AttributeTypecastBehavior extends Behavior
{
const TYPE_INTEGER = 'integer';
const TYPE_FLOAT = 'float';
const TYPE_BOOLEAN = 'boolean';
const TYPE_STRING = 'string';
/**
* @var Model|BaseActiveRecord the owner of this behavior.
*/
public $owner;
/**
* @var array attribute typecast map in format: attributeName => type.
* Type can be set via PHP callable, which accept raw value as an argument and should return
* typecast result.
* For example:
*
* ```php
* [
* 'amount' => 'integer',
* 'price' => 'float',
* 'is_active' => 'boolean',
* 'date' => function ($value) {
* return ($value instanceof \DateTime) ? $value->getTimestamp(): (int)$value;
* },
* ]
* ```
*
* If not set, attribute type map will be composed automatically from the owner validation rules.
*/
public $attributeTypes;
/**
* @var bool whether to skip typecasting of `null` values.
* If enabled attribute value which equals to `null` will not be type-casted (e.g. `null` remains `null`),
* otherwise it will be converted according to the type configured at [[attributeTypes]].
*/
public $skipOnNull = true;
/**
* @var bool whether to perform typecasting after owner model validation.
* Note that typecasting will be performed only if validation was successful, e.g.
* owner model has no errors.
* Note that changing this option value will have no effect after this behavior has been attached to the model.
*/
public $typecastAfterValidate = true;
/**
* @var bool whether to perform typecasting before saving owner model (insert or update).
* This option may be disabled in order to achieve better performance.
* For example, in case of [[\yii\db\ActiveRecord]] usage, typecasting before save
* will grant no benefit an thus can be disabled.
* Note that changing this option value will have no effect after this behavior has been attached to the model.
*/
public $typecastBeforeSave = false;
/**
* @var bool whether to perform typecasting after saving owner model (insert or update).
* This option may be disabled in order to achieve better performance.
* For example, in case of [[\yii\db\ActiveRecord]] usage, typecasting after save
* will grant no benefit an thus can be disabled.
* Note that changing this option value will have no effect after this behavior has been attached to the model.
* @since 2.0.14
*/
public $typecastAfterSave = false;
/**
* @var bool whether to perform typecasting after retrieving owner model data from
* the database (after find or refresh).
* This option may be disabled in order to achieve better performance.
* For example, in case of [[\yii\db\ActiveRecord]] usage, typecasting after find
* will grant no benefit in most cases an thus can be disabled.
* Note that changing this option value will have no effect after this behavior has been attached to the model.
*/
public $typecastAfterFind = false;
/**
* @var array internal static cache for auto detected [[attributeTypes]] values
* in format: ownerClassName => attributeTypes
*/
private static $autoDetectedAttributeTypes = [];
/**
* Clears internal static cache of auto detected [[attributeTypes]] values
* over all affected owner classes.
*/
public static function clearAutoDetectedAttributeTypes()
{
self::$autoDetectedAttributeTypes = [];
}
/**
* {@inheritdoc}
*/
public function attach($owner)
{
parent::attach($owner);
if ($this->attributeTypes === null) {
$ownerClass = get_class($this->owner);
if (!isset(self::$autoDetectedAttributeTypes[$ownerClass])) {
self::$autoDetectedAttributeTypes[$ownerClass] = $this->detectAttributeTypes();
}
$this->attributeTypes = self::$autoDetectedAttributeTypes[$ownerClass];
}
}
/**
* Typecast owner attributes according to [[attributeTypes]].
* @param array $attributeNames list of attribute names that should be type-casted.
* If this parameter is empty, it means any attribute listed in the [[attributeTypes]]
* should be type-casted.
*/
public function typecastAttributes($attributeNames = null)
{
$attributeTypes = [];
if ($attributeNames === null) {
$attributeTypes = $this->attributeTypes;
} else {
foreach ($attributeNames as $attribute) {
if (!isset($this->attributeTypes[$attribute])) {
throw new InvalidArgumentException("There is no type mapping for '{$attribute}'.");
}
$attributeTypes[$attribute] = $this->attributeTypes[$attribute];
}
}
foreach ($attributeTypes as $attribute => $type) {
$value = $this->owner->{$attribute};
if ($this->skipOnNull && $value === null) {
continue;
}
$this->owner->{$attribute} = $this->typecastValue($value, $type);
}
}
/**
* Casts the given value to the specified type.
* @param mixed $value value to be type-casted.
* @param string|callable $type type name or typecast callable.
* @return mixed typecast result.
*/
protected function typecastValue($value, $type)
{
if (is_scalar($type)) {
if (is_object($value) && method_exists($value, '__toString')) {
$value = $value->__toString();
}
switch ($type) {
case self::TYPE_INTEGER:
return (int) $value;
case self::TYPE_FLOAT:
return (float) $value;
case self::TYPE_BOOLEAN:
return (bool) $value;
case self::TYPE_STRING:
if (is_float($value)) {
return StringHelper::floatToString($value);
}
return (string) $value;
default:
throw new InvalidArgumentException("Unsupported type '{$type}'");
}
}
return call_user_func($type, $value);
}
/**
* Composes default value for [[attributeTypes]] from the owner validation rules.
* @return array attribute type map.
*/
protected function detectAttributeTypes()
{
$attributeTypes = [];
foreach ($this->owner->getValidators() as $validator) {
$type = null;
if ($validator instanceof BooleanValidator) {
$type = self::TYPE_BOOLEAN;
} elseif ($validator instanceof NumberValidator) {
$type = $validator->integerOnly ? self::TYPE_INTEGER : self::TYPE_FLOAT;
} elseif ($validator instanceof StringValidator) {
$type = self::TYPE_STRING;
}
if ($type !== null) {
foreach ((array) $validator->attributes as $attribute) {
$attributeTypes[ltrim($attribute, '!')] = $type;
}
}
}
return $attributeTypes;
}
/**
* {@inheritdoc}
*/
public function events()
{
$events = [];
if ($this->typecastAfterValidate) {
$events[Model::EVENT_AFTER_VALIDATE] = 'afterValidate';
}
if ($this->typecastBeforeSave) {
$events[BaseActiveRecord::EVENT_BEFORE_INSERT] = 'beforeSave';
$events[BaseActiveRecord::EVENT_BEFORE_UPDATE] = 'beforeSave';
}
if ($this->typecastAfterSave) {
$events[BaseActiveRecord::EVENT_AFTER_INSERT] = 'afterSave';
$events[BaseActiveRecord::EVENT_AFTER_UPDATE] = 'afterSave';
}
if ($this->typecastAfterFind) {
$events[BaseActiveRecord::EVENT_AFTER_FIND] = 'afterFind';
}
return $events;
}
/**
* Handles owner 'afterValidate' event, ensuring attribute typecasting.
* @param \yii\base\Event $event event instance.
*/
public function afterValidate($event)
{
if (!$this->owner->hasErrors()) {
$this->typecastAttributes();
}
}
/**
* Handles owner 'beforeInsert' and 'beforeUpdate' events, ensuring attribute typecasting.
* @param \yii\base\Event $event event instance.
*/
public function beforeSave($event)
{
$this->typecastAttributes();
}
/**
* Handles owner 'afterInsert' and 'afterUpdate' events, ensuring attribute typecasting.
* @param \yii\base\Event $event event instance.
* @since 2.0.14
*/
public function afterSave($event)
{
$this->typecastAttributes();
}
/**
* Handles owner 'afterFind' event, ensuring attribute typecasting.
* @param \yii\base\Event $event event instance.
*/
public function afterFind($event)
{
$this->typecastAttributes();
}
}

View File

@@ -0,0 +1,185 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\behaviors;
use Closure;
use yii\base\Behavior;
use yii\base\Event;
use yii\db\ActiveRecord;
/**
* AttributesBehavior automatically assigns values specified to one or multiple attributes of an ActiveRecord
* object when certain events happen.
*
* To use AttributesBehavior, configure the [[attributes]] property which should specify the list of attributes
* that need to be updated and the corresponding events that should trigger the update. Then configure the
* value of enclosed arrays with a PHP callable whose return value will be used to assign to the current attribute.
* For example,
*
* ```php
* use yii\behaviors\AttributesBehavior;
*
* public function behaviors()
* {
* return [
* [
* 'class' => AttributesBehavior::className(),
* 'attributes' => [
* 'attribute1' => [
* ActiveRecord::EVENT_BEFORE_INSERT => new Expression('NOW()'),
* ActiveRecord::EVENT_BEFORE_UPDATE => \Yii::$app->formatter->asDatetime('2017-07-13'),
* ],
* 'attribute2' => [
* ActiveRecord::EVENT_BEFORE_VALIDATE => [$this, 'storeAttributes'],
* ActiveRecord::EVENT_AFTER_VALIDATE => [$this, 'restoreAttributes'],
* ],
* 'attribute3' => [
* ActiveRecord::EVENT_BEFORE_VALIDATE => $fn2 = [$this, 'getAttribute2'],
* ActiveRecord::EVENT_AFTER_VALIDATE => $fn2,
* ],
* 'attribute4' => [
* ActiveRecord::EVENT_BEFORE_DELETE => function ($event, $attribute) {
* static::disabled() || $event->isValid = false;
* },
* ],
* ],
* ],
* ];
* }
* ```
*
* Because attribute values will be set automatically by this behavior, they are usually not user input and should therefore
* not be validated, i.e. they should not appear in the [[\yii\base\Model::rules()|rules()]] method of the model.
*
* @author Luciano Baraglia <luciano.baraglia@gmail.com>
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Bogdan Stepanenko <bscheshirwork@gmail.com>
* @since 2.0.13
*/
class AttributesBehavior extends Behavior
{
/**
* @var array list of attributes that are to be automatically filled with the values specified via enclosed arrays.
* The array keys are the ActiveRecord attributes upon which the events are to be updated,
* and the array values are the array of corresponding events(s). For this enclosed array:
* the array keys are the ActiveRecord events upon which the attributes are to be updated,
* and the array values are the value that will be assigned to the current attributes. This can be an anonymous function,
* callable in array format (e.g. `[$this, 'methodName']`), an [[\yii\db\Expression|Expression]] object representing a DB expression
* (e.g. `new Expression('NOW()')`), scalar, string or an arbitrary value. If the former, the return value of the
* function will be assigned to the attributes.
*
* ```php
* [
* 'attribute1' => [
* ActiveRecord::EVENT_BEFORE_INSERT => new Expression('NOW()'),
* ActiveRecord::EVENT_BEFORE_UPDATE => \Yii::$app->formatter->asDatetime('2017-07-13'),
* ],
* 'attribute2' => [
* ActiveRecord::EVENT_BEFORE_VALIDATE => [$this, 'storeAttributes'],
* ActiveRecord::EVENT_AFTER_VALIDATE => [$this, 'restoreAttributes'],
* ],
* 'attribute3' => [
* ActiveRecord::EVENT_BEFORE_VALIDATE => $fn2 = [$this, 'getAttribute2'],
* ActiveRecord::EVENT_AFTER_VALIDATE => $fn2,
* ],
* 'attribute4' => [
* ActiveRecord::EVENT_BEFORE_DELETE => function ($event, $attribute) {
* static::disabled() || $event->isValid = false;
* },
* ],
* ]
* ```
*/
public $attributes = [];
/**
* @var array list of order of attributes that are to be automatically filled with the event.
* The array keys are the ActiveRecord events upon which the attributes are to be updated,
* and the array values are represent the order corresponding attributes.
* The rest of the attributes are processed at the end.
* If the [[attributes]] for this attribute do not specify this event, it is ignored
*
* ```php
* [
* ActiveRecord::EVENT_BEFORE_VALIDATE => ['attribute1', 'attribute2'],
* ActiveRecord::EVENT_AFTER_VALIDATE => ['attribute2', 'attribute1'],
* ]
* ```
*/
public $order = [];
/**
* @var bool whether to skip this behavior when the `$owner` has not been modified
*/
public $skipUpdateOnClean = true;
/**
* @var bool whether to preserve non-empty attribute values.
*/
public $preserveNonEmptyValues = false;
/**
* {@inheritdoc}
*/
public function events()
{
return array_fill_keys(
array_reduce($this->attributes, function ($carry, $item) {
return array_merge($carry, array_keys($item));
}, []),
'evaluateAttributes'
);
}
/**
* Evaluates the attributes values and assigns it to the current attributes.
* @param Event $event
*/
public function evaluateAttributes($event)
{
if ($this->skipUpdateOnClean
&& $event->name === ActiveRecord::EVENT_BEFORE_UPDATE
&& empty($this->owner->dirtyAttributes)
) {
return;
}
$attributes = array_keys(array_filter($this->attributes, function ($carry) use ($event) {
return array_key_exists($event->name, $carry);
}));
if (!empty($this->order[$event->name])) {
$attributes = array_merge(
array_intersect((array) $this->order[$event->name], $attributes),
array_diff($attributes, (array) $this->order[$event->name]));
}
foreach ($attributes as $attribute) {
if ($this->preserveNonEmptyValues && !empty($this->owner->$attribute)) {
continue;
}
$this->owner->$attribute = $this->getValue($attribute, $event);
}
}
/**
* Returns the value for the current attributes.
* This method is called by [[evaluateAttributes()]]. Its return value will be assigned
* to the target attribute corresponding to the triggering event.
* @param string $attribute target attribute name
* @param Event $event the event that triggers the current attribute updating.
* @return mixed the attribute value
*/
protected function getValue($attribute, $event)
{
if (!isset($this->attributes[$attribute][$event->name])) {
return null;
}
$value = $this->attributes[$attribute][$event->name];
if ($value instanceof Closure || (is_array($value) && is_callable($value))) {
return $value($event, $attribute);
}
return $value;
}
}

View File

@@ -0,0 +1,130 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\behaviors;
use Yii;
use yii\db\BaseActiveRecord;
/**
* BlameableBehavior automatically fills the specified attributes with the current user ID.
*
* To use BlameableBehavior, insert the following code to your ActiveRecord class:
*
* ```php
* use yii\behaviors\BlameableBehavior;
*
* public function behaviors()
* {
* return [
* BlameableBehavior::className(),
* ];
* }
* ```
*
* By default, BlameableBehavior will fill the `created_by` and `updated_by` attributes with the current user ID
* when the associated AR object is being inserted; it will fill the `updated_by` attribute
* with the current user ID when the AR object is being updated.
*
* Because attribute values will be set automatically by this behavior, they are usually not user input and should therefore
* not be validated, i.e. `created_by` and `updated_by` should not appear in the [[\yii\base\Model::rules()|rules()]] method of the model.
*
* If your attribute names are different, you may configure the [[createdByAttribute]] and [[updatedByAttribute]]
* properties like the following:
*
* ```php
* public function behaviors()
* {
* return [
* [
* 'class' => BlameableBehavior::className(),
* 'createdByAttribute' => 'author_id',
* 'updatedByAttribute' => 'updater_id',
* ],
* ];
* }
* ```
*
* @author Luciano Baraglia <luciano.baraglia@gmail.com>
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @since 2.0
*/
class BlameableBehavior extends AttributeBehavior
{
/**
* @var string the attribute that will receive current user ID value
* Set this property to false if you do not want to record the creator ID.
*/
public $createdByAttribute = 'created_by';
/**
* @var string the attribute that will receive current user ID value
* Set this property to false if you do not want to record the updater ID.
*/
public $updatedByAttribute = 'updated_by';
/**
* {@inheritdoc}
*
* In case, when the property is `null`, the value of `Yii::$app->user->id` will be used as the value.
*/
public $value;
/**
* @var mixed Default value for cases when the user is guest
* @since 2.0.14
*/
public $defaultValue;
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
if (empty($this->attributes)) {
$this->attributes = [
BaseActiveRecord::EVENT_BEFORE_INSERT => [$this->createdByAttribute, $this->updatedByAttribute],
BaseActiveRecord::EVENT_BEFORE_UPDATE => $this->updatedByAttribute,
];
}
}
/**
* {@inheritdoc}
*
* In case, when the [[value]] property is `null`, the value of [[defaultValue]] will be used as the value.
*/
protected function getValue($event)
{
if ($this->value === null && Yii::$app->has('user')) {
$userId = Yii::$app->get('user')->id;
if ($userId === null) {
return $this->getDefaultValue($event);
}
return $userId;
}
return parent::getValue($event);
}
/**
* Get default value
* @param \yii\base\Event $event
* @return array|mixed
* @since 2.0.14
*/
protected function getDefaultValue($event)
{
if ($this->defaultValue instanceof \Closure || (is_array($this->defaultValue) && is_callable($this->defaultValue))) {
return call_user_func($this->defaultValue, $event);
}
return $this->defaultValue;
}
}

View File

@@ -0,0 +1,197 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\behaviors;
use yii\base\Behavior;
use yii\base\InvalidConfigException;
use yii\base\Widget;
use yii\base\WidgetEvent;
use yii\caching\CacheInterface;
use yii\caching\Dependency;
use yii\di\Instance;
/**
* Cacheable widget behavior automatically caches widget contents according to duration and dependencies specified.
*
* The behavior may be used without any configuration if an application has `cache` component configured.
* By default the widget will be cached for one minute.
*
* The following example will cache the posts widget for an indefinite duration until any post is modified.
*
* ```php
* use yii\behaviors\CacheableWidgetBehavior;
*
* public function behaviors()
* {
* return [
* [
* 'class' => CacheableWidgetBehavior::className(),
* 'cacheDuration' => 0,
* 'cacheDependency' => [
* 'class' => 'yii\caching\DbDependency',
* 'sql' => 'SELECT MAX(updated_at) FROM posts',
* ],
* ],
* ];
* }
* ```
*
* @author Nikolay Oleynikov <oleynikovny@mail.ru>
* @since 2.0.14
*/
class CacheableWidgetBehavior extends Behavior
{
/**
* @var CacheInterface|string|array a cache object or a cache component ID
* or a configuration array for creating a cache object.
* Defaults to the `cache` application component.
*/
public $cache = 'cache';
/**
* @var int cache duration in seconds.
* Set to `0` to indicate that the cached data will never expire.
* Defaults to 60 seconds or 1 minute.
*/
public $cacheDuration = 60;
/**
* @var Dependency|array|null a cache dependency or a configuration array
* for creating a cache dependency or `null` meaning no cache dependency.
*
* For example,
*
* ```php
* [
* 'class' => 'yii\caching\DbDependency',
* 'sql' => 'SELECT MAX(updated_at) FROM posts',
* ]
* ```
*
* would make the widget cache depend on the last modified time of all posts.
* If any post has its modification time changed, the cached content would be invalidated.
*/
public $cacheDependency;
/**
* @var string[]|string an array of strings or a single string which would cause
* the variation of the content being cached (e.g. an application language, a GET parameter).
*
* The following variation setting will cause the content to be cached in different versions
* according to the current application language:
*
* ```php
* [
* Yii::$app->language,
* ]
* ```
*/
public $cacheKeyVariations = [];
/**
* @var bool whether to enable caching or not. Allows to turn the widget caching
* on and off according to specific conditions.
* The following configuration will disable caching when a special GET parameter is passed:
*
* ```php
* empty(Yii::$app->request->get('disable-caching'))
* ```
*/
public $cacheEnabled = true;
/**
* {@inheritdoc}
*/
public function attach($owner)
{
parent::attach($owner);
$this->initializeEventHandlers();
}
/**
* Begins fragment caching. Prevents owner widget from execution
* if its contents can be retrieved from the cache.
*
* @param WidgetEvent $event `Widget::EVENT_BEFORE_RUN` event.
*/
public function beforeRun($event)
{
$cacheKey = $this->getCacheKey();
$fragmentCacheConfiguration = $this->getFragmentCacheConfiguration();
if (!$this->owner->view->beginCache($cacheKey, $fragmentCacheConfiguration)) {
$event->isValid = false;
}
}
/**
* Outputs widget contents and ends fragment caching.
*
* @param WidgetEvent $event `Widget::EVENT_AFTER_RUN` event.
*/
public function afterRun($event)
{
echo $event->result;
$event->result = null;
$this->owner->view->endCache();
}
/**
* Initializes widget event handlers.
*/
private function initializeEventHandlers()
{
$this->owner->on(Widget::EVENT_BEFORE_RUN, [$this, 'beforeRun']);
$this->owner->on(Widget::EVENT_AFTER_RUN, [$this, 'afterRun']);
}
/**
* Returns the cache instance.
*
* @return CacheInterface cache instance.
* @throws InvalidConfigException if cache instance instantiation fails.
*/
private function getCacheInstance()
{
$cacheInterface = 'yii\caching\CacheInterface';
return Instance::ensure($this->cache, $cacheInterface);
}
/**
* Returns the widget cache key.
*
* @return string[] an array of strings representing the cache key.
*/
private function getCacheKey()
{
// `$cacheKeyVariations` may be a `string` and needs to be cast to an `array`.
$cacheKey = array_merge(
(array)get_class($this->owner),
(array)$this->cacheKeyVariations
);
return $cacheKey;
}
/**
* Returns a fragment cache widget configuration array.
*
* @return array a fragment cache widget configuration array.
*/
private function getFragmentCacheConfiguration()
{
$cache = $this->getCacheInstance();
$fragmentCacheConfiguration = [
'cache' => $cache,
'duration' => $this->cacheDuration,
'dependency' => $this->cacheDependency,
'enabled' => $this->cacheEnabled,
];
return $fragmentCacheConfiguration;
}
}

View File

@@ -0,0 +1,283 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\behaviors;
use Yii;
use yii\base\InvalidConfigException;
use yii\db\BaseActiveRecord;
use yii\helpers\ArrayHelper;
use yii\helpers\Inflector;
use yii\validators\UniqueValidator;
/**
* SluggableBehavior automatically fills the specified attribute with a value that can be used a slug in a URL.
*
* To use SluggableBehavior, insert the following code to your ActiveRecord class:
*
* ```php
* use yii\behaviors\SluggableBehavior;
*
* public function behaviors()
* {
* return [
* [
* 'class' => SluggableBehavior::className(),
* 'attribute' => 'title',
* // 'slugAttribute' => 'slug',
* ],
* ];
* }
* ```
*
* By default, SluggableBehavior will fill the `slug` attribute with a value that can be used a slug in a URL
* when the associated AR object is being validated.
*
* Because attribute values will be set automatically by this behavior, they are usually not user input and should therefore
* not be validated, i.e. the `slug` attribute should not appear in the [[\yii\base\Model::rules()|rules()]] method of the model.
*
* If your attribute name is different, you may configure the [[slugAttribute]] property like the following:
*
* ```php
* public function behaviors()
* {
* return [
* [
* 'class' => SluggableBehavior::className(),
* 'slugAttribute' => 'alias',
* ],
* ];
* }
* ```
*
* @author Alexander Kochetov <creocoder@gmail.com>
* @author Paul Klimov <klimov.paul@gmail.com>
* @since 2.0
*/
class SluggableBehavior extends AttributeBehavior
{
/**
* @var string the attribute that will receive the slug value
*/
public $slugAttribute = 'slug';
/**
* @var string|array|null the attribute or list of attributes whose value will be converted into a slug
* or `null` meaning that the `$value` property will be used to generate a slug.
*/
public $attribute;
/**
* @var callable|string|null the value that will be used as a slug. This can be an anonymous function
* or an arbitrary value or null. If the former, the return value of the function will be used as a slug.
* If `null` then the `$attribute` property will be used to generate a slug.
* The signature of the function should be as follows,
*
* ```php
* function ($event)
* {
* // return slug
* }
* ```
*/
public $value;
/**
* @var bool whether to generate a new slug if it has already been generated before.
* If true, the behavior will not generate a new slug even if [[attribute]] is changed.
* @since 2.0.2
*/
public $immutable = false;
/**
* @var bool whether to ensure generated slug value to be unique among owner class records.
* If enabled behavior will validate slug uniqueness automatically. If validation fails it will attempt
* generating unique slug value from based one until success.
*/
public $ensureUnique = false;
/**
* @var bool whether to skip slug generation if [[attribute]] is null or an empty string.
* If true, the behaviour will not generate a new slug if [[attribute]] is null or an empty string.
* @since 2.0.13
*/
public $skipOnEmpty = false;
/**
* @var array configuration for slug uniqueness validator. Parameter 'class' may be omitted - by default
* [[UniqueValidator]] will be used.
* @see UniqueValidator
*/
public $uniqueValidator = [];
/**
* @var callable slug unique value generator. It is used in case [[ensureUnique]] enabled and generated
* slug is not unique. This should be a PHP callable with following signature:
*
* ```php
* function ($baseSlug, $iteration, $model)
* {
* // return uniqueSlug
* }
* ```
*
* If not set unique slug will be generated adding incrementing suffix to the base slug.
*/
public $uniqueSlugGenerator;
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
if (empty($this->attributes)) {
$this->attributes = [BaseActiveRecord::EVENT_BEFORE_VALIDATE => $this->slugAttribute];
}
if ($this->attribute === null && $this->value === null) {
throw new InvalidConfigException('Either "attribute" or "value" property must be specified.');
}
}
/**
* {@inheritdoc}
*/
protected function getValue($event)
{
if (!$this->isNewSlugNeeded()) {
return $this->owner->{$this->slugAttribute};
}
if ($this->attribute !== null) {
$slugParts = [];
foreach ((array) $this->attribute as $attribute) {
$part = ArrayHelper::getValue($this->owner, $attribute);
if ($this->skipOnEmpty && $this->isEmpty($part)) {
return $this->owner->{$this->slugAttribute};
}
$slugParts[] = $part;
}
$slug = $this->generateSlug($slugParts);
} else {
$slug = parent::getValue($event);
}
return $this->ensureUnique ? $this->makeUnique($slug) : $slug;
}
/**
* Checks whether the new slug generation is needed
* This method is called by [[getValue]] to check whether the new slug generation is needed.
* You may override it to customize checking.
* @return bool
* @since 2.0.7
*/
protected function isNewSlugNeeded()
{
if (empty($this->owner->{$this->slugAttribute})) {
return true;
}
if ($this->immutable) {
return false;
}
if ($this->attribute === null) {
return true;
}
foreach ((array) $this->attribute as $attribute) {
if ($this->owner->isAttributeChanged($attribute)) {
return true;
}
}
return false;
}
/**
* This method is called by [[getValue]] to generate the slug.
* You may override it to customize slug generation.
* The default implementation calls [[\yii\helpers\Inflector::slug()]] on the input strings
* concatenated by dashes (`-`).
* @param array $slugParts an array of strings that should be concatenated and converted to generate the slug value.
* @return string the conversion result.
*/
protected function generateSlug($slugParts)
{
return Inflector::slug(implode('-', $slugParts));
}
/**
* This method is called by [[getValue]] when [[ensureUnique]] is true to generate the unique slug.
* Calls [[generateUniqueSlug]] until generated slug is unique and returns it.
* @param string $slug basic slug value
* @return string unique slug
* @see getValue
* @see generateUniqueSlug
* @since 2.0.7
*/
protected function makeUnique($slug)
{
$uniqueSlug = $slug;
$iteration = 0;
while (!$this->validateSlug($uniqueSlug)) {
$iteration++;
$uniqueSlug = $this->generateUniqueSlug($slug, $iteration);
}
return $uniqueSlug;
}
/**
* Checks if given slug value is unique.
* @param string $slug slug value
* @return bool whether slug is unique.
*/
protected function validateSlug($slug)
{
/* @var $validator UniqueValidator */
/* @var $model BaseActiveRecord */
$validator = Yii::createObject(array_merge(
[
'class' => UniqueValidator::className(),
],
$this->uniqueValidator
));
$model = clone $this->owner;
$model->clearErrors();
$model->{$this->slugAttribute} = $slug;
$validator->validateAttribute($model, $this->slugAttribute);
return !$model->hasErrors();
}
/**
* Generates slug using configured callback or increment of iteration.
* @param string $baseSlug base slug value
* @param int $iteration iteration number
* @return string new slug value
* @throws \yii\base\InvalidConfigException
*/
protected function generateUniqueSlug($baseSlug, $iteration)
{
if (is_callable($this->uniqueSlugGenerator)) {
return call_user_func($this->uniqueSlugGenerator, $baseSlug, $iteration, $this->owner);
}
return $baseSlug . '-' . ($iteration + 1);
}
/**
* Checks if $slugPart is empty string or null.
*
* @param string $slugPart One of attributes that is used for slug generation.
* @return bool whether $slugPart empty or not.
* @since 2.0.13
*/
protected function isEmpty($slugPart)
{
return $slugPart === null || $slugPart === '';
}
}

View File

@@ -0,0 +1,141 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\behaviors;
use yii\base\InvalidCallException;
use yii\db\BaseActiveRecord;
/**
* TimestampBehavior automatically fills the specified attributes with the current timestamp.
*
* To use TimestampBehavior, insert the following code to your ActiveRecord class:
*
* ```php
* use yii\behaviors\TimestampBehavior;
*
* public function behaviors()
* {
* return [
* TimestampBehavior::className(),
* ];
* }
* ```
*
* By default, TimestampBehavior will fill the `created_at` and `updated_at` attributes with the current timestamp
* when the associated AR object is being inserted; it will fill the `updated_at` attribute
* with the timestamp when the AR object is being updated. The timestamp value is obtained by `time()`.
*
* Because attribute values will be set automatically by this behavior, they are usually not user input and should therefore
* not be validated, i.e. `created_at` and `updated_at` should not appear in the [[\yii\base\Model::rules()|rules()]] method of the model.
*
* For the above implementation to work with MySQL database, please declare the columns(`created_at`, `updated_at`) as int(11) for being UNIX timestamp.
*
* If your attribute names are different or you want to use a different way of calculating the timestamp,
* you may configure the [[createdAtAttribute]], [[updatedAtAttribute]] and [[value]] properties like the following:
*
* ```php
* use yii\db\Expression;
*
* public function behaviors()
* {
* return [
* [
* 'class' => TimestampBehavior::className(),
* 'createdAtAttribute' => 'create_time',
* 'updatedAtAttribute' => 'update_time',
* 'value' => new Expression('NOW()'),
* ],
* ];
* }
* ```
*
* In case you use an [[\yii\db\Expression]] object as in the example above, the attribute will not hold the timestamp value, but
* the Expression object itself after the record has been saved. If you need the value from DB afterwards you should call
* the [[\yii\db\ActiveRecord::refresh()|refresh()]] method of the record.
*
* TimestampBehavior also provides a method named [[touch()]] that allows you to assign the current
* timestamp to the specified attribute(s) and save them to the database. For example,
*
* ```php
* $model->touch('creation_time');
* ```
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @since 2.0
*/
class TimestampBehavior extends AttributeBehavior
{
/**
* @var string the attribute that will receive timestamp value
* Set this property to false if you do not want to record the creation time.
*/
public $createdAtAttribute = 'created_at';
/**
* @var string the attribute that will receive timestamp value.
* Set this property to false if you do not want to record the update time.
*/
public $updatedAtAttribute = 'updated_at';
/**
* {@inheritdoc}
*
* In case, when the value is `null`, the result of the PHP function [time()](http://php.net/manual/en/function.time.php)
* will be used as value.
*/
public $value;
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
if (empty($this->attributes)) {
$this->attributes = [
BaseActiveRecord::EVENT_BEFORE_INSERT => [$this->createdAtAttribute, $this->updatedAtAttribute],
BaseActiveRecord::EVENT_BEFORE_UPDATE => $this->updatedAtAttribute,
];
}
}
/**
* {@inheritdoc}
*
* In case, when the [[value]] is `null`, the result of the PHP function [time()](http://php.net/manual/en/function.time.php)
* will be used as value.
*/
protected function getValue($event)
{
if ($this->value === null) {
return time();
}
return parent::getValue($event);
}
/**
* Updates a timestamp attribute to the current timestamp.
*
* ```php
* $model->touch('lastVisit');
* ```
* @param string $attribute the name of the attribute to update.
* @throws InvalidCallException if owner is a new record (since version 2.0.6).
*/
public function touch($attribute)
{
/* @var $owner BaseActiveRecord */
$owner = $this->owner;
if ($owner->getIsNewRecord()) {
throw new InvalidCallException('Updating the timestamp is not possible on a new record.');
}
$owner->updateAttributes(array_fill_keys((array) $attribute, $this->getValue(null)));
}
}