## File: README.md

> [!WARNING]
> There is no official Redis support planned for Yii3 DB. Use [predis](https://github.com/predis/predis) or [phpredis](https://github.com/phpredis/phpredis) instead.



[](https://packagist.org/packages/yiisoft/db-redis)
[](https://packagist.org/packages/yiisoft/db-redis)
[](https://scrutinizer-ci.com/g/yiisoft/db-redis/?branch=master)
[](https://scrutinizer-ci.com/g/yiisoft/db-redis/?branch=master)

This extension provides the [redis](https://redis.io/) connection support for the [Yii framework](https://www.yiiframework.com).

It includes a `Cache` and `Session` storage handler and implements the `ActiveRecord` pattern that allows
you to store active records in redis.

## Support version

| PHP | Redis Version | CI-Actions |
|-----|---------------|------------|
|**7.4 - 8.0**| **4 - 6**|[](https://github.com/yiisoft/db-redis/actions?query=workflow%3Abuild) [](https://dashboard.stryker-mutator.io/reports/github.com/yiisoft/db-redis/master) [](https://github.com/yiisoft/db-redis/actions?query=workflow%3A%22static+analysis%22) [](https://shepherd.dev/github/yiisoft/db-redis)

## Requirements

- Redis version 2.6.12 or higher.
- `Filter` PHP extension.

## Installation

The package could be installed with [Composer](https://getcomposer.org):

```shell
composer require yiisoft/db-redis
```

## General usage

Using `yiisoft/composer-config-plugin` automatically get the settings of `EventDispatcherInterface::class` and `LoggerInterface::class`.

Di-Container:

```php
use Yiisoft\Db\Redis\Connection as RedisConnection;

return [
    RedisConnection::class => [
        '__class' => RedisConnection::class,
        'host()' => [$params['yiisoft/db-redis']['dsn']['host']],
        'port()' => [$params['yiisoft/db-redis']['dsn']['port']],
        'database()' => [$params['yiisoft/db-redis']['dsn']['database']],
        'password()' => [$params['yiisoft/db-redis']['password']]
    ]
];
```

Params.php

```php
return [
    'yiisoft/db-redis' => [
        'dsn' => [
            'driver' => 'redis',
            'host' => '127.0.0.1',
            'database' => 0,
            'port' => 6379
        ],
        'password' => null,
    ]
];
```

## Configuring application

To use this extension, you have to configure the `Yiisoft\Db\Redis\Connection|Connection` class in your application configuration:

```php
return [
    //....
    'components' => [
        'redis' => [
            'class' => 'Yiisoft\Db\Redis\Connection',
            'hostname' => 'localhost',
            'port' => 6379,
            'database' => 0,
        ],
    ]
];
```

This provides the basic access to redis storage via the `redis` application component:

```php
Yii::$app->redis->set('mykey', 'some value');
echo Yii::$app->redis->get('mykey');
```

See [Yiisoft\Db\Redis\Connection] for a full list of available methods.

## Documentation

- Guide: [English](docs/guide/en/README.md), [日本語](docs/guide/ja/README.md), [Português - Brasil](docs/guide/pt-BR/README.md), [Русский](docs/guide/ru/README.md), [中国人](docs/guide/zh-CN/README.md)
- [Internals](docs/internals.md)

If you need help or have a question, the [Yii Forum](https://forum.yiiframework.com/c/yii-3-0/63) is a good place for that.
You may also check out other [Yii Community Resources](https://www.yiiframework.com/community).

## License

The Yii DBAL Redis connection is free software. It is released under the terms of the BSD License.
Please see [`LICENSE`](./LICENSE.md) for more information.

Maintained by [Yii Software](https://www.yiiframework.com/).

## Support the project

[](https://opencollective.com/yiisoft)

## Follow updates

[](https://www.yiiframework.com/)
[](https://twitter.com/yiiframework)
[](https://t.me/yii3en)
[](https://www.facebook.com/groups/yiitalk)
[](https://yiiframework.com/go/slack)

---

## File: CHANGELOG.md

# Yii DB Redis extension Change Log

## 2.0.9 under development

- no changes in this release.

## 2.0.8 March 20, 2018

- Bug #141: Calling ActiveQuery::indexBy() had no effect since Yii 2.0.14 (cebe)
- Bug: (CVE-2018-8073): Fix possible remote code execution when improperly filtered user input is passed to `ActiveRecord::findOne()` and `::findAll()` (cebe)
- Enh #66: Cache component can be configured to read / get from replicas (ryusoft)

## 2.0.7 December 11, 2017

- Bug #114: Fixed ActiveQuery `not between` and `not` conditions which where not working correctly (cebe, ak1987)
- Bug #123: Fixed ActiveQuery to work with negative limit values, which are used in ActiveDataProvider for the count query (cebe)
- Enh #9: Added orderBy support to redis ActiveQuery and LuaScriptBuilder (valinurovam)
- Enh #91: Added option to retry connection after failing to communicate with redis server on stale socket (cebe)
- Enh #106: Improved handling of connection errors and introduced `yii\redis\SocketException` for these (cebe)
- Chg #127: Added PHP 7.2 compatibility (brandonkelly)

## 2.0.6 April 05, 2017

- Bug #44: Remove quotes from numeric parts of composite key to avoid problem with different hashes for the same record (uniserpl)
- Bug #67: Fixed regression from 2.0.5, reconnecting a closed connection fails (cebe)
- Bug #82: Fixed session object destruction failure when key expires (juffin-halli, samdark)
- Bug #93: Fixed `yii\redis\ActiveRecord::deleteAll()` with condition (samdark)
- Bug #104: Fixed execution of two-word commands (cebe,branimir93)
- Enh #53: Added `Mutex` that implements a Redis based mutex (turboezh, sergeymakinen)
- Enh #81: Allow setting `Connection::$database` to `null` to avoid sending a `SELECT` command after connection (cebe)
- Enh #89: Added support for `\Yiisoft\Db\QueryInterface::emulateExecution()` (samdark)
- Enh #103: Added missing commands and `@method` documentation for redis commands (cebe)
- Enh: Optimized find by PK for relational queries and IN condition (cebe, andruha)

## 2.0.5 March 17, 2016

- Bug #22: Fixed string escaping issue in LuaScriptBuilder (vistart)
- Bug #37: Fixed detection of open socket (mirocow)
- Bug #46: Fixed bug to execute session_regenerate_id in PHP 7.0 (githubjeka)
- Enh #31: Added `Connection::$socketClientFlags` property for connection flags to be passed to `stream_socket_client()` (hugh-lee)
- Chg #14: Added missing `BLPOP` command to `$redisCommands` (samdark)
- Chg #61: Added missing `GEO*` commands to `$redisCommands` (leadermt)

## 2.0.4 May 10, 2015

- Enh #8: Auto increment value was not updated when a primary key was explicitly set (cebe, andruha)

## 2.0.3 March 01, 2015

- no changes in this release.

## 2.0.2 January 11, 2015

- Bug #6547: Fixed redis connection to deal with large data in combination with `mget()` (pyurin)

## 2.0.1 December 07, 2014

- Bug #4745: value of simple string returns was ignored by redis client and `true` is returned instead, now only `OK` will result in a `true` while all other values are returned as is (cebe)
- Enh #3714: Added support for connecting to redis server using a unix socket (savvot, robregonm)

## 2.0.0 October 12, 2014

- no changes in this release.

## 2.0.0-rc September 27, 2014

- Bug #1311: Fixed storage and finding of `null` and boolean values (samdark, cebe)
- Enh #3520: Added `unlinkAll()`-method to active record to remove all records of a model relation (NmDimas, samdark, cebe)
- Enh #4048: Added `init` event to `ActiveQuery` classes (qiangxue)
- Enh #4086: changedAttributes of afterSave Event now contain old values (dizews)

## 2.0.0-beta April 13, 2014

- Bug #1993: afterFind event in AR is now called after relations have been populated (cebe, creocoder)
- Enh #1773: keyPrefix property of Session and Cache is not restricted to alnum characters anymore (cebe)
- Enh #2002: Added filterWhere() method to yii\redis\ActiveQuery to allow easy addition of search filter conditions by ignoring empty search fields (samdark, cebe)
- Enh #2892: ActiveRecord dirty attributes are now reset after call to `afterSave()` so information about changed attributes is available in `afterSave`-event (cebe)
- Chg #2281: Renamed `ActiveRecord::create()` to `populateRecord()` and changed signature. This method will not call instantiate() anymore (cebe)
- Chg #2146: Removed `ActiveRelation` class and moved the functionality to `ActiveQuery`.
             All relational queries are now directly served by `ActiveQuery` allowing to use
             custom scopes in relations (cebe)

## 2.0.0-alpha, December 1, 2013

- Initial release.

---

## File: composer.json

{
    "name": "yiisoft/db-redis",
    "description": "Yii Framework Redis Cache, Session and ActiveRecord extension",
    "keywords": [
        "yii",
        "redis",
        "active-record",
        "cache",
        "session"
    ],
    "type": "library",
    "license": "BSD-3-Clause",
    "support": {
        "issues": "https://github.com/yiisoft/db-redis/issues?state=open",
        "source": "https://github.com/yiisoft/db-redis",
        "forum": "https://www.yiiframework.com/forum/",
        "wiki": "https://www.yiiframework.com/wiki/",
        "irc": "ircs://irc.libera.chat:6697/yii",
        "chat": "https://t.me/yii3en"
    },
    "funding": [
        {
            "type": "opencollective",
            "url": "https://opencollective.com/yiisoft"
        },
        {
            "type": "github",
            "url": "https://github.com/sponsors/yiisoft"
        }
    ],
    "minimum-stability": "dev",
    "prefer-stable": true,
    "require": {
        "php": "^8.0",
        "ext-mbstring": "*",
        "ext-json": "*",
        "yiisoft/arrays": "^2.0",
        "yiisoft/db": "^3.0@dev",
        "yiisoft/log": "^2.0",
        "yiisoft/strings": "^2.0",
        "yiisoft/yii-event": "^1.0"
    },
    "require-dev": {
        "phpunit/phpunit": "^9.4",
        "roave/infection-static-analysis-plugin": "^1.3",
        "vimeo/psalm": "^4.5",
        "yiisoft/aliases": "^1.0",
        "yiisoft/cache": "^1.0",
        "yiisoft/di": "^1.0"
    },
    "autoload": {
        "psr-4": {
            "Yiisoft\\Db\\Redis\\": "src"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Yiisoft\\Db\\Redis\\Tests\\": "tests/"
        }
    },
    "extra": {
        "branch-alias": {
            "dev-master": "1.0.x-dev"
        }
    },
    "config": {
        "allow-plugins": {
            "infection/extension-installer": true
        }
    }
}

---

## File: LICENSE.md

Copyright © 2008 by Yii Software (<https://www.yiiframework.com/>)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

 * Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in
   the documentation and/or other materials provided with the
   distribution.
 * Neither the name of Yii Software nor the names of its
   contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

---

## File: .scrutinizer.yml

checks:
    php: true

filter:
    paths:
        - "src/*"

tools:
    php_code_coverage:
        enabled: true

build:
    nodes:
        analysis:
            environment:
                php: 8.0.20

            tests:
                override:
                    - php-scrutinizer-run

---

## File: .styleci.yml

preset: psr12

finder:
  exclude:
    - docs
    - vendor

---

## File: docs/internals.md

# Internals

## Unit testing

The package is tested with [PHPUnit](https://phpunit.de/). To run tests:

```shell
./vendor/bin/phpunit
```

## Mutation testing

The package tests are checked with [Infection](https://infection.github.io/) mutation framework with
[Infection Static Analysis Plugin](https://github.com/Roave/infection-static-analysis-plugin). To run it:

```shell
./vendor/bin/roave-infection-static-analysis-plugin
```

## Static analysis

The code is statically analyzed with [Psalm](https://psalm.dev/). To run static analysis:

```shell
./vendor/bin/psalm
```

---

## File: docs/guide/en/README.md

# Yii Database Redis Cache, Session and ActiveRecord extension

## General usage

- [Using the ActiveRecord](usage-ar.md)
- [Using commands directly](usage-commands.md)

## Additional topics

- [Using the Cache component](topics-cache.md)
- [Using the Session component](topics-session.md)

---

## File: docs/guide/en/topics-cache.md

# Using the Cache component

To use the [Caching Library](https://github.com/yiisoft/cache-redis), in addition to configuring the connection as described in the [Configuring application](../../../README.md#Configuring-application) section,
you also have to configure the `cache` component to be `Yiisoft\Db\Redis\Cache`:

```php
return [
    //....
    'components' => [
        // ...
        'cache' => [
            'class' => 'Yiisoft\Db\Redis\Cache',
        ],
    ]
];
```

If you only use the redis cache (i.e., not using its [ActiveRecord](https://github.com/yiisoft/active-record) or [Session](https://github.com/yiisoft/session)), you can also configure the parameters of the connection within the
cache component (no connection application component needs to be configured in this case):

```php
return [
    //....
    'components' => [
        // ...
        'cache' => [
            'class' => 'Yiisoft\Db\Redis\Cache',
            'redis' => [
                'hostname' => 'localhost',
                'port' => 6379,
                'database' => 0,
            ],
        ],
    ]
];
```

The cache provides all methods of the `yii\caching\CacheInterface`. If you want to access redis specific methods that are not
included in the interface, you can use them via `Yiisoft\Db\Redis\Cache::$redis`, which is an instance of`Yiisoft\Db\Redis\Connection`:

```php
Yii::$app->cache->redis->hset('mykey', 'somefield', 'somevalue');
Yii::$app->cache->redis->hget('mykey', 'somefield');
...
```

See `Yiisoft\Db\Redis\Connection` for a full list of available methods.

---

## File: docs/guide/en/topics-session.md

# Using the Session component

To use the [Session](https://github.com/yiisoft/session) component, in addition to configuring the connection as described in the [Configuring application](../../../README.md#Configuring-application) section,
you also have to configure the `session` component to be `Yiisoft\Db\Redis\Session`:

```php
return [
    //....
    'components' => [
        // ...
        'session' => [
            'class' => 'Yiisoft\Db\Redis\Session',
        ],
    ]
];
```

If you only use redis session (i.e., not using its [ActiveRecord](https://github.com/yiisoft/active-record) or [Cache](https://github.com/yiisoft/cache-redis)), you can also configure the parameters of the connection within the
session component (no connection application component needs to be configured in this case):

```php
return [
    //....
    'components' => [
        // ...
        'session' => [
            'class' => 'Yiisoft\Db\Redis\Session',
            'redis' => [
                'hostname' => 'localhost',
                'port' => 6379,
                'database' => 0,
            ],
        ],
    ]
];
```

---

## File: docs/guide/en/usage-ar.md

# Using the ActiveRecord

For general information on how to use Yii ActiveRecord please refer to the [guide](https://www.yiiframework.com/doc/guide/2.0/en/db-active-record).

For defining a redis ActiveRecord class your record class needs to extend from `Yiisoft\Db\Redis\ActiveRecord` and
implement at least the `attributes()` method to define the attributes of the record.
A primary key can be defined via `Yiisoft\Db\Redis\ActiveRecord::primaryKey()` which defaults to `id` if not specified.
The primaryKey needs to be part of the attributes so make sure you have an `id` attribute defined if you do
not specify your own primary key.

The following is an example model called `Customer`:

```php
class Customer extends \Yiisoft\Db\Redis\ActiveRecord
{
    /**
     * @return array the list of attributes for this record
     */
    public function attributes()
    {
        return ['id', 'name', 'address', 'registration_date'];
    }

    /**
     * @return ActiveQuery defines a relation to the Order record (can be in other database, e.g. elasticsearch or sql)
     */
    public function getOrders()
    {
        return $this->hasMany(Order::className(), ['customer_id' => 'id']);
    }

    /**
     * Defines a scope that modifies the `$query` to return only active(status = 1) customers
     */
    public static function active($query)
    {
        $query->andWhere(['status' => 1]);
    }
}
```

The general usage of redis ActiveRecord is very similar to the database ActiveRecord as described in the
[guide](https://www.yiiframework.com/doc/guide/2.0/en/db-active-record).
It supports the same interface and features except the following limitations:

- As redis does not support SQL the query API is limited to the following methods:
  `where()`, `limit()`, `offset()`, `orderBy()` and `indexBy()`.
- `via`-relations can not be defined via a table as there are not tables in redis. You can only define relations via other records.

It is also possible to define relations from redis ActiveRecords to normal [ActiveRecord](https://github.com/yiisoft/active-record) classes and vice versa.

Usage example:

```php
$customer = new Customer();
$customer->attributes = ['name' => 'test'];
$customer->save();
echo $customer->id; // id will automatically be incremented if not set explicitly

$customer = Customer::find()->where(['name' => 'test'])->one(); // find by query
$customer = Customer::find()->active()->all(); // find all by query (using the `active` scope)
```

---

## File: docs/guide/en/usage-commands.md

# Using commands directly

Redis has lots of useful commands which could be used directly from connection. After configuring application as
shown in [Configuring application](../../../README.md#Configuring-application) section, connection could be obtained like the following:

```php
$redis = Yii::$app->redis;
```

After it's done one can execute commands. The most generic way to do it is using `executeCommand` method:

```php
$result = $redis->executeCommand('hmset', ['test_collection', 'key1', 'val1', 'key2', 'val2']);
```

There are shortcuts available for each command supported so insted of the above it can be used as follows:

```php
$result = $redis->hmset('test_collection', 'key1', 'val1', 'key2', 'val2');
```

For a list of available commands and their parameters see [redis Commands](https://redis.io/commands).

---

## File: docs/guide/ja/README.md

Yii 2 Redis キャッシュ、セッションおよびアクティブレコード
==========================================================

このエクステンションは Yii 2 フレームワークに [redis](https://redis.io/) の「キー・値」ストレージのサポートを提供します。
エクステンションは `Cache` と `Session` のストレージ・ハンドラを含み、アクティブレコードを redis に保存することを可能にする `ActiveRecord` パターンを実装しています。

始めよう
--------

* [インストール](installation.md)

使用方法
--------

* [アクティブレコードを使用する](usage-ar.md)
* [コマンドを直接に使用する](usage-commands.md)

追加のトピック
-----------------

* [キャッシュ・コンポーネントを使用する](topics-cache.md)
* [セッション・コンポーネントを使用する](topics-session.md)

---

## File: docs/guide/ja/installation.md

インストール
============

## 必要条件

全てのコンポーネントが正しく動作するためには、最低限、redis バージョン 2.6.12 が必要です。

## Composer パッケージを取得する

このエクステンションをインストールするのに推奨される方法は [Composer](https://getcomposer.org): によるものです。

下記のコマンドを実行してください。

```
composer require yiisoft/db-redis
```

または、あなたの `composer.json` ファイルの `require` セクションに、

```
"yiisoft/db-redis": "~1.0.0"
```

を追加してください。

## アプリケーションを構成する

このエクステンションを使用するためには、アプリケーション構成情報で [[Yiisoft\Db\Redis\Connection|Connection]] クラスを構成する必要があります。

```php
return [
    //....
    'components' => [
        'redis' => [
            'class' => 'Yiisoft\Db\Redis\Connection',
            'hostname' => 'localhost',
            'port' => 6379,
            'database' => 0,
        ],
    ]
];
```

これで、`redis` アプリケーション・コンポーネントによって、redis ストレージに対する基本的なアクセスが提供されるようになります。

```php
Yii::$app->redis->set('mykey', 'some value');
echo Yii::$app->redis->get('mykey');
```

利用可能なメソッドの一覧は [[Yiisoft\Db\Redis\Connection]] を参照して下さい。

---

## File: docs/guide/ja/topics-cache.md

キャッシュ・コンポーネントを使用する
====================================

`Cache` コンポーネントを使用するためには、[インストール](installation.md) の節で説明した接続の構成に加えて、
`cache` コンポーネントを [[Yiisoft\Db\Redis\Cache]] として構成する必要があります。

```php
return [
    //....
    'components' => [
        // ...
        'cache' => [
            'class' => 'Yiisoft\Db\Redis\Cache',
        ],
    ]
];
```

redis をキャッシュとしてのみ使用する場合、すなわち、redis のアクティブレコードやセッションを使用しない場合は、接続のパラメータをキャッシュ・コンポーネントの中で構成しても構いません
(この場合、接続のアプリケーション・コンポーネントを構成する必要はありません)。

```php
return [
    //....
    'components' => [
        // ...
        'cache' => [
            'class' => 'Yiisoft\Db\Redis\Cache',
            'redis' => [
                'hostname' => 'localhost',
                'port' => 6379,
                'database' => 0,
            ],
        ],
    ]
];
```

このキャッシュは [[yii\caching\CacheInterface]] の全てのメソッドを提供します。インタフェイスに含まれていない redis 固有のメソッドにアクセスしたい場合は、
[[Yiisoft\Db\Redis\Connection]] のインスタンスである [[Yiisoft\Db\Redis\Cache::$redis]] を通じてアクセスすることが出来ます。

```php
Yii::$app->cache->redis->hset('mykey', 'somefield', 'somevalue');
Yii::$app->cache->redis->hget('mykey', 'somefield');
...
```

利用可能なメソッドの一覧は [[Yiisoft\Db\Redis\Connection]] を参照して下さい。

---

## File: docs/guide/ja/topics-session.md

セッション・コンポーネントを使用する
====================================

`Session` コンポーネントを使用するためには、[インストール](installation.md) の節で説明した接続の構成に加えて、
`session` コンポーネントを [[Yiisoft\Db\Redis\Session]] として構成する必要があります。

```php
return [
    //....
    'components' => [
        // ...
        'session' => [
            'class' => 'Yiisoft\Db\Redis\Session',
        ],
    ]
];
```

redis をセッションとしてのみ使用する場合、すなわち、redis のアクティブレコードやキャッシュは使わない場合は、接続のパラメータをセッション・コンポーネントの中で構成しても構いません
(この場合、接続のアプリケーション・コンポーネントを構成する必要はありません)。

```php
return [
    //....
    'components' => [
        // ...
        'session' => [
            'class' => 'Yiisoft\Db\Redis\Session',
            'redis' => [
                'hostname' => 'localhost',
                'port' => 6379,
                'database' => 0,
            ],
        ],
    ]
];
```

---

## File: docs/guide/ja/usage-ar.md

[Binary file]

---

## File: docs/guide/ja/usage-commands.md

[Binary file]

---

## File: docs/guide/pt-BR/README.md

# Yii Database Redis Cache, Session and ActiveRecord extension

## Uso geral

- [Usando ActiveRecord](usage-ar.md)
- [Usando comandos diretamente](usage-commands.md)

## Tópicos adicionais

- [Usando o componente Cache](topics-cache.md)
- [Usando o componente Session](topics-session.md)

---

## File: docs/guide/pt-BR/topics-cache.md

# Usando o componente Cache

Para utilizar a [Caching Library](https://github.com/yiisoft/cache-redis), além de configurar a conexão conforme descrito na seção [Configurando o aplicativo](../../../README.md#Configuring-application),
você também deve configurar o componente `cache` como `Yiisoft\Db\Redis\Cache`:

```php
return [
    //....
    'components' => [
        // ...
        'cache' => [
            'class' => 'Yiisoft\Db\Redis\Cache',
        ],
    ]
];
```

Se você usar apenas o cache redis (ou seja, não usar seu [ActiveRecord](https://github.com/yiisoft/active-record) ou [Session](https://github.com/yiisoft/session)), você também pode configurar os parâmetros da conexão dentro do
componente de cache (nenhum componente de aplicativo de conexão precisa ser configurado neste caso):

```php
return [
    //....
    'components' => [
        // ...
        'cache' => [
            'class' => 'Yiisoft\Db\Redis\Cache',
            'redis' => [
                'hostname' => 'localhost',
                'port' => 6379,
                'database' => 0,
            ],
        ],
    ]
];
```

O cache fornece todos os métodos de `yii\caching\CacheInterface`. Se você deseja acessar métodos específicos do Redis que não estão
incluídos na interface, você pode usá-los via `Yiisoft\Db\Redis\Cache::$redis`, que é uma instância de`Yiisoft\Db\Redis\Connection`:

```php
Yii::$app->cache->redis->hset('mykey', 'somefield', 'somevalue');
Yii::$app->cache->redis->hget('mykey', 'somefield');
...
```

Veja `Yiisoft\Db\Redis\Connection` para uma lista completa dos métodos disponíveis.

---

## File: docs/guide/pt-BR/topics-session.md

# Usando o componente Session

Para utilizar o componente [Session](https://github.com/yiisoft/session), além de configurar a conexão conforme descrito na seção  [Configurando o aplicativo](../../../README.md#Configuring-application),
você também deve configurar o componente `session` como `Yiisoft\Db\Redis\Session`:

```php
return [
    //....
    'components' => [
        // ...
        'session' => [
            'class' => 'Yiisoft\Db\Redis\Session',
        ],
    ]
];
```

Se você usar apenas sessão redis (ou seja, não usar [ActiveRecord](https://github.com/yiisoft/active-record) ou [Cache](https://github.com/yiisoft/cache-redis)), você também pode configurar os parâmetros da conexão dentro do
componente de sessão (nenhum componente de aplicativo de conexão precisa ser configurado neste caso):

```php
return [
    //....
    'components' => [
        // ...
        'session' => [
            'class' => 'Yiisoft\Db\Redis\Session',
            'redis' => [
                'hostname' => 'localhost',
                'port' => 6379,
                'database' => 0,
            ],
        ],
    ]
];
```

---

## File: docs/guide/pt-BR/usage-ar.md

# Usando ActiveRecord

Para informações gerais sobre como usar o Yii ActiveRecord, consulte o [guia](https://www.yiiframework.com/doc/guide/2.0/en/db-active-record).

Para definir uma classe Redis ActiveRecord, sua classe de registro precisa se estender de `Yiisoft\Db\Redis\ActiveRecord` e
implemente pelo menos o método `attributes()` para definir os atributos do registro.
Uma chave primária pode ser definida via `Yiisoft\Db\Redis\ActiveRecord::primaryKey()` cujo padrão é `id` se não for especificado.
O PrimaryKey precisa fazer parte dos atributos, então certifique-se de ter um atributo `id` definido se você fizer isso
não especifique sua própria chave primária.

A seguir está um modelo de exemplo chamado `Customer`:

```php
class Customer extends \Yiisoft\Db\Redis\ActiveRecord
{
    /**
     * @return array the list of attributes for this record
     */
    public function attributes()
    {
        return ['id', 'name', 'address', 'registration_date'];
    }

    /**
     * @return ActiveQuery defines a relation to the Order record (can be in other database, e.g. elasticsearch or sql)
     */
    public function getOrders()
    {
        return $this->hasMany(Order::className(), ['customer_id' => 'id']);
    }

    /**
     * Defines a scope that modifies the `$query` to return only active(status = 1) customers
     */
    public static function active($query)
    {
        $query->andWhere(['status' => 1]);
    }
}
```

O uso geral do redis ActiveRecord é muito semelhante ao banco de dados ActiveRecord conforme descrito no
[guia](https://www.yiiframework.com/doc/guide/2.0/en/db-active-record).
Ele suporta a mesma interface e recursos, exceto as seguintes limitações:

- Como redis não suporta SQL, a API de consulta está limitada aos seguintes métodos:
   `where()`, `limit()`, `offset()`, `orderBy()` e `indexBy()`.
- As relações `via` não podem ser definidas através de uma tabela, pois não existem tabelas no redis. Você só pode definir relações através de outros registros.

Também é possível definir relações de ActiveRecords redis para classes [ActiveRecord](https://github.com/yiisoft/active-record) normais e vice-versa.

Exemplo de uso:

```php
$customer = new Customer();
$customer->attributes = ['name' => 'test'];
$customer->save();
echo $customer->id; // id will automatically be incremented if not set explicitly

$customer = Customer::find()->where(['name' => 'test'])->one(); // find by query
$customer = Customer::find()->active()->all(); // find all by query (using the `active` scope)
```

---

## File: docs/guide/pt-BR/usage-commands.md

# Usando comandos diretamente

Redis tem muitos comandos úteis que podem ser usados diretamente pela conexão. Depois de configurar o aplicativo como
mostrado na seção [Configurando o aplicativo](../../../README.md#Configuring-application), a conexão pode ser obtida da seguinte forma:

```php
$redis = Yii::$app->redis;
```

Depois de feito, pode-se executar comandos. A maneira mais genérica de fazer isso é usando o método `executeCommand`:

```php
$result = $redis->executeCommand('hmset', ['test_collection', 'key1', 'val1', 'key2', 'val2']);
```

Existem atalhos disponíveis para cada comando suportado, portanto, em vez do acima, ele pode ser usado da seguinte maneira:

```php
$result = $redis->hmset('test_collection', 'key1', 'val1', 'key2', 'val2');
```

Para obter uma lista de comandos disponíveis e seus parâmetros, consulte [Comandos redis](https://redis.io/commands).

---

## File: docs/guide/ru/README.md

Redis Cache, Session и ActiveRecord для Yii 2
===============================================

Это расширение обеспечивает поддержку хранилища ключ-значение [redis](https://redis.io/) для фреймворка Yii2.
Оно включает в себя обработчики хранилища `Cache` и `Session` и реализует шаблон `ActiveRecord`, который позволяет сохранять активные записи в Redis.

Как начать
---------------

* [Установка](installation.md)

Использование
-----

* [Использование ActiveRecord](usage-ar.md)
* [Использование команд напрямую](usage-commands.md)

Дополнительно
-----------------

* [Использование компонента Cache](topics-cache.md)
* [Использование компонента Session](topics-session.md)

---

## File: docs/guide/ru/installation.md

Установка
============

## Требования

Для того, чтобы все компоненты работали должным образом, требуется хотя бы версия Redis 2.6.12.

## Установка расширения

Предпочтительным способом установки этого расширения является [Composer](https://getcomposer.org):

Для этого запустите команду

```
composer require yiisoft/db-redis
```

или добавьте

```json
"yiisoft/db-redis": "~1.0.0"
```

в секцию `require` вашего composer.json.

## Конфигурирование приложения

Чтобы использовать это расширение, вам необходимо настроить класс [[Yiisoft\Db\Redis\Connection|Connection]] в конфигурации вашего приложения:

```php
return [
    //....
    'components' => [
        'redis' => [
            'class' => 'Yiisoft\Db\Redis\Connection',
            'hostname' => 'localhost',
            'port' => 6379,
            'database' => 0,
        ],
    ]
];
```

Это обеспечивает базовый доступ к redis-хранилищу через компонент приложения `redis`:

```php
Yii::$app->redis->set('mykey', 'some value');
echo Yii::$app->redis->get('mykey');
```

Смотри [[Yiisoft\Db\Redis\Connection]] для получения полного списка доступных методов.

---

## File: docs/guide/ru/topics-cache.md

Использование компонента Cache
==============================

Чтобы использовать компонент `Cache`, в дополнение к настройке соединения, как описано в разделе [Установка](installation.md), вам также нужно настроить компонент `cache` как [[Yiisoft\Db\Redis\Cache]]:

```php
return [
    //....
    'components' => [
        // ...
        'cache' => [
            'class' => 'Yiisoft\Db\Redis\Cache',
        ],
    ]
];
```

Если вы используете Redis только для кеширования (т.е. не используете его ActiveRecord или Session), то в этом случае вы можете настроить параметры соединения в пределах компонента `cache` следующим образом:

```php
return [
    //....
    'components' => [
        // ...
        'cache' => [
            'class' => 'Yiisoft\Db\Redis\Cache',
            'redis' => [
                'hostname' => 'localhost',
                'port' => 6379,
                'database' => 0,
            ],
        ],
    ]
];
```

Кэш предоставляет все методы [[yii\caching\CacheInterface]]. Если вы хотите получить доступ к определенным методам Redis, которые не присутствуют в интерфейсе, вы можете использовать их через [[Yiisoft\Db\Redis\Cache::$redis]], который является экземпляром [[Yiisoft\Db\Redis\Connection]]:

```php
Yii::$app->cache->redis->hset('mykey', 'somefield', 'somevalue');
Yii::$app->cache->redis->hget('mykey', 'somefield');
...
```

Смотри [[Yiisoft\Db\Redis\Connection]] для получения полного списка доступных методов.

---

## File: docs/guide/ru/topics-session.md

Использование компонента Session
================================

Чтобы использовать компонент `Session`, в дополнение к настройке соединения, как описано в разделе [Установка](installation.md), вам также нужно настроить компонент `session` как [[Yiisoft\Db\Redis\Session]]:

```php
return [
    //....
    'components' => [
        // ...
        'session' => [
            'class' => 'Yiisoft\Db\Redis\Session',
        ],
    ]
];
```

Если вы используете Redis только для хранения сессий (т.е. не используете его ActiveRecord или Cache), то в этом случае вы можете настроить параметры соединения в пределах компонента `session` следующим образом:

```php
return [
    //....
    'components' => [
        // ...
        'session' => [
            'class' => 'Yiisoft\Db\Redis\Session',
            'redis' => [
                'hostname' => 'localhost',
                'port' => 6379,
                'database' => 0,
            ],
        ],
    ]
];
```

---

## File: docs/guide/ru/usage-ar.md

Использование ActiveRecord
==========================

Для получения общей информации о том, как использовать Yii ActiveRecord, обратитесь к
[руководству](https://github.com/yiisoft/yii2/blob/master/docs/guide/db-active-record.md).
Для определения redis ActiveRecord класс записи должен расширяться от класса [[Yiisoft\Db\Redis\ActiveRecord]] и реализовывать хотя бы метод `attributes()` для определения атрибутов записи.
Первичный ключ может быть определен с помощью [[Yiisoft\Db\Redis\ActiveRecord::primaryKey()]], который по умолчанию имеет значение `id`.
Первичный ключ должен быть частью атрибутов, поэтому убедитесь, что атрибут `id` определен, если вы не указали свой собственный первичный ключ.

Ниже приведен пример модели `Customer`:

```php
class Customer extends \Yiisoft\Db\Redis\ActiveRecord
{
    /**
     * @return array the list of attributes for this record
     */
    public function attributes()
    {
        return ['id', 'name', 'address', 'registration_date'];
    }

    /**
     * @return ActiveQuery defines a relation to the Order record (can be in other database, e.g. elasticsearch or sql)
     */
    public function getOrders()
    {
        return $this->hasMany(Order::className(), ['customer_id' => 'id']);
    }

    /**
     * Defines a scope that modifies the `$query` to return only active(status = 1) customers
     */
    public static function active($query)
    {
        $query->andWhere(['status' => 1]);
    }
}
```

Общее использование redis ActiveRecord очень похоже на БД ActiveRecord как описано в [руководстве](https://github.com/yiisoft/yii2/blob/master/docs/guide/db-active-record.md).
Он поддерживает тот же интерфейс и функции, за исключением следующих ограничений:

- Поскольку redis не поддерживает SQL, API запросов ограничен следующими методами:
  `where()`, `limit()`, `offset()`, `orderBy()` и `indexBy()`.
  (orderBy() еще не реализовано: [#1305](https://github.com/yiisoft/yii2/issues/1305))
- `via`-отношения не могут быть определены через таблицу, поскольку в redis нет таблиц. Вы можете определять отношения только через другие записи.

Также можно определить отношения от redis ActiveRecords до обычных классов ActiveRecord и наоборот.

Например:

```php
$customer = new Customer();
$customer->attributes = ['name' => 'test'];
$customer->save();
echo $customer->id; // id will automatically be incremented if not set explicitly

$customer = Customer::find()->where(['name' => 'test'])->one(); // find by query
$customer = Customer::find()->active()->all(); // find all by query (using the `active` scope)
```

---

## File: docs/guide/ru/usage-commands.md

[Binary file]

---

## File: docs/guide/zh-CN/README.md

Yii 2 Redis 缓存，会话和活动记录
===============================================

此扩展为 Yii2 framework 提供了 [redis](https://redis.io/) 键-值存储的支持。
包含了一个 `Cache` 和 `Session` 存储句柄并且实现了 `ActiveRecord` 模式，允许
你存储活动记录到 redis 中。

入门指南
---------------

* [安装](installation.md)

用法
-----

* [活动记录的使用](usage-ar.md)
* [直接使用命令](usage-commands.md)

附加主题
-----------------

* [缓存组件的使用](topics-cache.md)
* [会话组件的使用](topics-session.md)

---

## File: docs/guide/zh-CN/installation.md

安装
============

## 需求

redis 2.6.12 版本是所有部件正常工作所必需的。

## 获取 Composer 安装包

安装此扩展的首选方式是通过 [Composer](https://getcomposer.org):。

可以运行

```
composer require yiisoft/db-redis
```

或者添加

```json
"yiisoft/db-redis": "~1.0.0"
```

在 `composer.json` 文件中的必要部分。

## 配置应用程序

使用此扩展时，需要在你的应用程序配置中配置 [[Yiisoft\Db\Redis\Connection|Connection]] 类：

```php
return [
    //....
    'components' => [
        'redis' => [
            'class' => 'Yiisoft\Db\Redis\Connection',
            'hostname' => 'localhost',
            'port' => 6379,
            'database' => 0,
        ],
    ]
];
```

---

## File: docs/guide/zh-CN/topics-cache.md

缓存组件的使用
=========================

为了使用 `Cache` 组件，如 [安装](installation.md) 章节中所描述的，除了配置连接，
你也需要配置 [[Yiisoft\Db\Redis\Cache]] 中的 `cache` 组件：

```php
return [
    //....
    'components' => [
        // ...
        'cache' => [
            'class' => 'Yiisoft\Db\Redis\Cache',
        ],
    ]
];
```

如果你只使用 redis 缓存（即，不使用它的活动记录或者会话），您还可以配置缓存组件内的
连接参数（在这种情况下，不需要配置连接应用程序的组件）：

```php
return [
    //....
    'components' => [
        // ...
        'cache' => [
            'class' => 'Yiisoft\Db\Redis\Cache',
            'redis' => [
                'hostname' => 'localhost',
                'port' => 6379,
                'database' => 0,
            ],
        ],
    ]
];
```

---

## File: docs/guide/zh-CN/topics-session.md

会话组件的使用
===========================

为了使用 `Session` 组件，如 [安装](installation.md) 章节中所描述的，除了配置连接，
你也需要配置 [[Yiisoft\Db\Redis\Session]] 中的 `session` 组件：

```php
return [
    //....
    'components' => [
        // ...
        'session' => [
            'class' => 'Yiisoft\Db\Redis\Session',
        ],
    ]
];
```

如果你只使用 redis 会话（即，不使用它的活动记录或者缓存），您还可以配置会话组件内的
连接参数（在这种情况下，不需要配置连接应用程序的组件）：

```php
return [
    //....
    'components' => [
        // ...
        'session' => [
            'class' => 'Yiisoft\Db\Redis\Session',
            'redis' => [
                'hostname' => 'localhost',
                'port' => 6379,
                'database' => 0,
            ],
        ],
    ]
];
```

---

## File: docs/guide/zh-CN/usage-ar.md

活动记录的使用
======================

对于如何使用 yii 的活动记录一般信息请参阅 [指南](https://github.com/yiisoft/yii2/blob/master/docs/guide/db-active-record.md)。

定义一个 redis 活动记录类，你的记录类需要继承自 [[Yiisoft\Db\Redis\ActiveRecord]] 并且
至少实现 `attributes()` 方法来定义记录的属性。
一个没有指定默认值，默认为 `id` 的主键可以通过 [[Yiisoft\Db\Redis\ActiveRecord::primaryKey()]] 定义。
主键是属性中必要的一部分，所以请确保你有一个 `id` 属性定义的，
如果你没有指定自己的主键。

以下是一个 `Customer` 的实例模型：

```php
class Customer extends \Yiisoft\Db\Redis\ActiveRecord
{
    /**
     * @return array 此记录的属性列表
     */
    public function attributes()
    {
        return ['id', 'name', 'address', 'registration_date'];
    }

    /**
     * @return ActiveQuery 定义一个关联到 Order 的记录（可以在其它数据库中，例如 elasticsearch 或者 sql）
     */
    public function getOrders()
    {
        return $this->hasMany(Order::className(), ['customer_id' => 'id']);
    }

    /**
     * 定义一个修改 `$query` 的范围返回有效（status = 1）的客户。
     */
    public static function active($query)
    {
        $query->andWhere(['status' => 1]);
    }
}
```

redis 活动记录的一般用法和数据库活动记录非常相似，正如
[指南](https://github.com/yiisoft/yii2/blob/master/docs/guide/db-active-record.md) 中所描述的。
它支持相同的界面和功能，除了以下限制：

- redis 不支持 SQL 查询的 API 仅限于以下方法：
  `where()`，`limit()`，`offset()`，`orderBy()` 和 `indexBy()`。
  (orderBy() 尚未实现：[#1305](https://github.com/yiisoft/yii2/issues/1305))
- `via`-关系不能通过在 redis 中没有的表定义。你只能通过其他记录来定义关系。

另外，也可以定义从 redis 的活动记录关系到正常的活动记录类，反之亦然。

使用实例：

```php
$customer = new Customer();
$customer->attributes = ['name' => 'test'];
$customer->save();
echo $customer->id; // 如果没有明确设置 id 会自动递增

$customer = Customer::find()->where(['name' => 'test'])->one(); // 通过 query 查找
$customer = Customer::find()->active()->all(); // 通过 query 查找全部（使用 `active` 范围）
```

---

## File: docs/guide/zh-CN/usage-commands.md

直接使用命令行
=======================

Redis 有很多可以直接从连接中使用的有用的命令。在配置应用程序后，
如 [安装](installation.md) 所示，连接可以像下面这样获取：

```php
$redis = Yii::$app->redis;
```

完成之后可以执行如下命令。最通用的方法是使用 `executeCommand` 方法：

```php
$result = $redis->executeCommand('hmset', ['test_collection', 'key1', 'val1', 'key2', 'val2']);
```

每个命令都有相应的快捷方式支持，所以可以像下面这样代替以上的命令：

```php
$result = $redis->hmset(['test_collection', 'key1', 'val1', 'key2', 'val2']);
```

可用命令列表和他们的参数可参阅 [https://redis.io/commands](https://redis.io/commands)。

---

## File: .github/CODE_OF_CONDUCT.md

# Yii Contributor Code of Conduct

## Our Pledge

As contributors and maintainers of this project, and in order to keep Yii community open and welcoming, we ask to respect all community members.

## Our Standards

Examples of behavior that contributes to creating a positive environment include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
  advances
* Personal attacks
* Trolling or insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing other's private information, such as physical or electronic
  addresses, without explicit permission
* Other conduct which could reasonably be considered inappropriate in
  a professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in response
to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments,
commits, code, wiki edits, issues, and other contributions that are not aligned to this
Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors
that they deem inappropriate, threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces when
an individual is representing the project or its community. Examples of representing
a project or community include posting via an official social media account,
within project GitHub, official forum or acting as an appointed representative at
an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported
by contacting core team members. All complaints will be reviewed and investigated
and will result in a response that is deemed necessary and appropriate to the circumstances.
The project team is obligated to maintain confidentiality with regard to the reporter of
an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith
may face temporary or permanent repercussions as determined by other members of
the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 1.4.0, available at
[https://contributor-covenant.org/version/1/4/][version]

[homepage]: https://contributor-covenant.org
[version]: https://contributor-covenant.org/version/1/4/

---

## File: .github/CONTRIBUTING.md

# Prerequisites

- [Yii goal and values](https://github.com/yiisoft/docs/blob/master/001-yii-values.md)
- [Namespaces](https://github.com/yiisoft/docs/blob/master/004-namespaces.md)
- [Git commit messages](https://github.com/yiisoft/docs/blob/master/006-git-commit-messages.md)
- [Exceptions](https://github.com/yiisoft/docs/blob/master/007-exceptions.md)
- [Interfaces](https://github.com/yiisoft/docs/blob/master/008-interfaces.md)

# Getting started

Since Yii 3 consists of many packages, we have a [special development tool](https://github.com/yiisoft/docs/blob/master/005-development-tool.md).

1. [Clone the repository](https://github.com/yiisoft/yii-dev-tool).

2. [Set up your own fork](https://github.com/yiisoft/yii-dev-tool#using-your-own-fork).

3. Now you are ready. Fork any package listed in `packages.php` and do `./yii-dev install username/package`.

If you don't have any particular package in mind to start with:

- [Check roadmap](https://github.com/yiisoft/docs/blob/master/003-roadmap.md).
- Check package issues at github. Usually there are some.
- Ask @samdark.

---

## File: .github/dependabot.yml

version: 2
updates:
- package-ecosystem: github-actions
  directory: "/"
  schedule:
    interval: daily
  open-pull-requests-limit: 10

---

## File: .github/FUNDING.yml

# These are supported funding model platforms

open_collective: yiisoft
github: [yiisoft]

---

## File: .github/ISSUE_TEMPLATE.md

### What steps will reproduce the problem?

### What is the expected result?

### What do you get instead?


### Additional info

| Q                | A
| ---------------- | ---
| Version          | 1.0.?
| PHP version      | 
| Operating system |

---

## File: .github/PULL_REQUEST_TEMPLATE.md

| Q             | A
| ------------- | ---
| Is bugfix?    | ✔️/❌
| New feature?  | ✔️/❌
| Breaks BC?    | ✔️/❌
| Fixed issues  | comma-separated list of tickets # fixed by the PR, if any

---

## File: .github/SECURITY.md

# Security Policy

Please use the [security issue form](https://www.yiiframework.com/security) to report to us any security issue you
find in Yii. DO NOT use the issue tracker or discuss it in the public forum as it will cause more damage than help.

Please note that as a non-commercial OpenSource project we are not able to pay bounties at the moment.

---

## File: .github/workflows/build.yml

on:
  - pull_request
  - push

name: build

jobs:
  tests:
    name: PHP ${{ matrix.php }}-redis-${{ matrix.redis }}

    env:
      key: cache-v1

    runs-on: ${{ matrix.os }}

    strategy:
      matrix:
        os:
          - ubuntu-latest

        php:
          - "8.0"

        redis:
          - "4"
          - "5"
          - "6"

    steps:
      - name: Checkout
        uses: actions/checkout@v2.4.0

      - name: Start Redis v${{ matrix.redis }}
        uses: superchargejs/redis-github-action@1.4.0
        with:
          redis-version: ${{ matrix.redis }}

      - name: Install PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: ${{ matrix.php }}
          ini-values: date.timezone='UTC'
          coverage: pcov
          tools: composer:v2

      - name: Determine composer cache directory on Linux
        if: matrix.os == 'ubuntu-latest'
        run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV

      - name: Determine composer cache directory on Windows
        if: matrix.os == 'windows-latest'
        run: echo "COMPOSER_CACHE_DIR=~\AppData\Local\Composer" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append

      - name: Cache dependencies installed with composer
        uses: actions/cache@v2
        with:
          path: ${{ env.COMPOSER_CACHE_DIR }}
          key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }}
          restore-keys: |
            php${{ matrix.php }}-composer-

      - name: Update composer
        run: composer self-update

      - name: Install dependencies with composer php 8.0
        if: matrix.php == '8.0'
        run: composer update --ignore-platform-reqs --prefer-dist --no-interaction --no-progress --optimize-autoloader --ansi

      - name: Run tests with phpunit without coverage
        run: vendor/bin/phpunit --colors=always

      - name: Code coverage
        if: matrix.php == '8.0'
        run: |
          wget https://scrutinizer-ci.com/ocular.phar
          php ocular.phar code-coverage:upload --format=php-clover coverage.clover

---

## File: .github/workflows/mutation.yml

on:
  pull_request:
  push:
    branches:
      - "master"

name: mutation test

jobs:
  mutation:
    name: PHP ${{ matrix.php }}-${{ matrix.os }}

    runs-on: ${{ matrix.os }}

    strategy:
      matrix:
        os:
          - ubuntu-latest

        php:
          - "8.0"

    steps:
      - name: Checkout
        uses: actions/checkout@v2.4.0

      - name: Start Redis v6
        uses: superchargejs/redis-github-action@1.4.0
        with:
          redis-version: 6

      - name: Install PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: "${{ matrix.php }}"
          ini-values: memory_limit=-1
          coverage: "pcov"
          tools: composer:v2

      - name: Determine composer cache directory
        run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV

      - name: Cache dependencies installed with composer
        uses: actions/cache@v2
        with:
          path: ${{ env.COMPOSER_CACHE_DIR }}
          key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }}
          restore-keys: |
            php${{ matrix.php }}-composer-

      - name: Update composer
        run: composer self-update

      - name: Install dependencies with composer
        run: composer update --prefer-dist --no-interaction --no-progress --optimize-autoloader --ansi

      - name: Run infection
        run: |
          git fetch --depth=1 origin $GITHUB_BASE_REF
          vendor/bin/roave-infection-static-analysis-plugin -j2 --git-diff-filter=A --git-diff-base=origin/$GITHUB_BASE_REF --logger-github --ignore-msi-with-no-mutations --only-covered
        env:
          STRYKER_DASHBOARD_API_KEY: ${{ secrets.STRYKER_DASHBOARD_API_KEY }}

---

## File: .github/workflows/static.yml

on:
  - pull_request
  - push

name: static analysis

jobs:
  mutation:
    name: PHP ${{ matrix.php }}-${{ matrix.os }}

    runs-on: ${{ matrix.os }}

    strategy:
      matrix:
        os:
          - ubuntu-latest

        php:
          - "8.0"

    steps:
      - name: Checkout
        uses: actions/checkout@v2.4.0

      - name: Install PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: "${{ matrix.php }}"
          tools: composer:v2, cs2pr
          coverage: none

      - name: Determine composer cache directory
        run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV

      - name: Cache dependencies installed with composer
        uses: actions/cache@v2
        with:
          path: ${{ env.COMPOSER_CACHE_DIR }}
          key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }}
          restore-keys: |
            php${{ matrix.php }}-composer-

      - name: Update composer
        run: composer self-update

      - name: Install dependencies with composer
        run: composer update --prefer-dist --no-interaction --no-progress --optimize-autoloader --ansi

      - name: Static analysis
        run: vendor/bin/psalm --shepherd --stats --output-format=checkstyle | cs2pr --graceful-warnings --colorize