## File: README.md

> [!WARNING]
> There is no official ElasticSearch support planned for Yii3 DB. [Use official PHP client](https://www.elastic.co/docs/reference/elasticsearch/clients/php) or [SEAL](https://github.com/PHP-CMSIG/search) instead.




[](https://packagist.org/packages/yiisoft/db-elasticsearch)
[](https://packagist.org/packages/yiisoft/db-elasticsearch)
[](https://github.com/yiisoft/db-elasticsearch/actions?query=workflow%3Abuild)
[](https://codecov.io/gh/yiisoft/db-elasticsearch)
[](https://dashboard.stryker-mutator.io/reports/github.com/yiisoft/db-elasticsearch/master)
[](https://github.com/yiisoft/db-elasticsearch/actions?query=workflow%3A%22static+analysis%22)
[](https://shepherd.dev/github/yiisoft/db-elasticsearch)
[](https://shepherd.dev/github/yiisoft/db-elasticsearch)

This extension provides the [elasticsearch](https://www.elastic.co/products/elasticsearch) integration for the [Yii framework](https://www.yiiframework.com).
It includes basic querying/search support and also implements the `ActiveRecord` pattern that allows you to store active
records in elasticsearch.

## Requirements

- Elasticsearch version 5.0 or higher.

## Installation

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

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

## General usage

To use this extension, you have to configure the Connection class in your application configuration:

```php
return [
    //....
    'components' => [
        'elasticsearch' => [
            'class' => 'Yiisoft\Db\ElasticSearch\Connection',
            'nodes' => [
                ['http_address' => '127.0.0.1:9200'],
                // configure more hosts if you have a cluster
            ],
        ],
    ]
];
```

## Documentation

- Guide: [English](docs/guide/en/README.md), [Français](docs/guide/fr/README.md), [日本語](docs/guide/ja/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 Database Elasticsearch Query and ActiveRecord 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

# Elasticsearch Change Log

## 1.0.0 under development

- Initial release.

---

## File: composer.json

{
    "name": "yiisoft/db-elasticsearch",
    "description": "Yii Framework Elasticsearch Query and ActiveRecord",
    "keywords": [
        "yii",
        "elasticsearch",
        "active-record",
        "search",
        "fulltext"
    ],
    "homepage": "https://www.yiiframework.com/",
    "license": "BSD-3-Clause",
    "type": "library",
    "support": {
        "issues": "https://github.com/yiisoft/db-elasticsearch/issues?state=open",
        "source": "https://github.com/yiisoft/db-elasticsearch",
        "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"
        }
    ],
    "authors": [
        {
            "name": "Carsten Brandt",
            "email": "mail@cebe.cc"
        }
    ],
    "minimum-stability": "dev",
    "prefer-stable": true,
    "require": {
        "yiisoft/arrays": "^3.0@dev",
        "yiisoft/di": "^3.0@dev",
        "yiisoft/strings": "^3.0@dev",
        "yiisoft/yii-core": "^3.0@dev",
        "ext-curl": "*"
    },
    "require-dev": {
        "yiisoft/log": "^3.0@dev",
        "yiisoft/cache": "^3.0@dev",
        "yiisoft/active-record": "^3.0@dev",
        "phpunit/phpunit": "^9.0",
        "hiqdev/composer-config-plugin": "^1.0@dev"
    },
    "autoload": {
        "psr-4": {
            "Yiisoft\\Db\\ElasticSearch\\": "src"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Yiisoft\\Db\\ElasticSearch\\Tests\\": "tests"
        }
    },
    "extra": {
        "branch-alias": {
            "dev-master": "1.0.x-dev"
        }
    }
}

---

## 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: .styleci.yml

preset: psr12
risky: true

version: 8.1

finder:
  exclude:
    - docs
    - vendor

enabled:
  - alpha_ordered_traits
  - array_indentation
  - array_push
  - combine_consecutive_issets
  - combine_consecutive_unsets
  - combine_nested_dirname
  - declare_strict_types
  - dir_constant
  - fully_qualified_strict_types
  - function_to_constant
  - hash_to_slash_comment
  - is_null
  - logical_operators
  - magic_constant_casing
  - magic_method_casing
  - method_separation
  - modernize_types_casting
  - native_function_casing
  - native_function_type_declaration_casing
  - no_alias_functions
  - no_empty_comment
  - no_empty_phpdoc
  - no_empty_statement
  - no_extra_block_blank_lines
  - no_short_bool_cast
  - no_superfluous_elseif
  - no_unneeded_control_parentheses
  - no_unneeded_curly_braces
  - no_unneeded_final_method
  - no_unset_cast
  - no_unused_imports
  - no_unused_lambda_imports
  - no_useless_else
  - no_useless_return
  - normalize_index_brace
  - php_unit_dedicate_assert
  - php_unit_dedicate_assert_internal_type
  - php_unit_expectation
  - php_unit_mock
  - php_unit_mock_short_will_return
  - php_unit_namespaced
  - php_unit_no_expectation_annotation
  - phpdoc_no_empty_return
  - phpdoc_no_useless_inheritdoc
  - phpdoc_order
  - phpdoc_property
  - phpdoc_scalar
  - phpdoc_singular_inheritdoc
  - phpdoc_trim
  - phpdoc_trim_consecutive_blank_line_separation
  - phpdoc_type_to_var
  - phpdoc_types
  - phpdoc_types_order
  - print_to_echo
  - regular_callable_call
  - return_assignment
  - self_accessor
  - self_static_accessor
  - set_type_to_cast
  - short_array_syntax
  - short_list_syntax
  - simplified_if_return
  - single_quote
  - standardize_not_equals
  - ternary_to_null_coalescing
  - trailing_comma_in_multiline_array
  - unalign_double_arrow
  - unalign_equals
  - empty_loop_body_braces
  - integer_literal_case
  - union_type_without_spaces

disabled:
  - function_declaration

---

## File: docs/internals.md

# Internals

## Unit testing

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

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

---

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

# Yii Framework Elasticsearch Query and ActiveRecord

This extension provides the [elasticsearch](https://www.elastic.co/products/elasticsearch) integration for the [Yii framework](https://www.yiiframework.com).
It includes basic querying/search support and also implements the `ActiveRecord` pattern that allows you to store active
records in elasticsearch.

## Usage

- [Data Mapping & Indexing](mapping-indexing.md)
- [Using the Query](usage-query.md)
- [Using the ActiveRecord](usage-ar.md)
- [Working with data providers](usage-data-providers.md)

## Additional topics

- [Using the elasticsearch DebugPanel](topics-debug.md)
- Relation definitions with records whose primary keys are not part of attributes
- Fetching records from different indexes/types

---

## File: docs/guide/en/mapping-indexing.md

Mapping & Indexing
==================

## Creating index and mapping

Since it is not always possible to update ElasticSearch mappings incrementally, it is a good idea to create several static methods in your model that deal with index creation and updates. Here is one example of how this can be done.

```php
Class Book extends Yiisoft\Db\ElasticSearch\ActiveRecord
{
    // Other class attributes and methods go here
    // ...

    /**
     * @return array This model's mapping
     */
    public static function mapping()
    {
        return [
            static::type() => [
                'properties' => [
                    'name'           => ['type' => 'string'],
                    'author_name'    => ['type' => 'string'],
                    'publisher_name' => ['type' => 'string'],
                    'created_at'     => ['type' => 'long'],
                    'updated_at'     => ['type' => 'long'],
                    'status'         => ['type' => 'long'],
                ]
            ],
        ];
    }

    /**
     * Set (update) mappings for this model
     */
    public static function updateMapping()
    {
        $db = static::getDb();
        $command = $db->createCommand();
        $command->setMapping(static::index(), static::type(), static::mapping());
    }

    /**
     * Create this model's index
     */
    public static function createIndex()
    {
        $db = static::getDb();
        $command = $db->createCommand();
        $command->createIndex(static::index(), [
            'settings' => [ /* ... */ ],
            'mappings' => static::mapping(),
            //'warmers' => [ /* ... */ ],
            //'aliases' => [ /* ... */ ],
            //'creation_date' => '...'
        ]);
    }

    /**
     * Delete this model's index
     */
    public static function deleteIndex()
    {
        $db = static::getDb();
        $command = $db->createCommand();
        $command->deleteIndex(static::index(), static::type());
    }
}
```

To create the index with proper mappings, call `Book::createIndex()`. If you have changed the mapping in a way that allows mapping update (e.g. created a new property), call `Book::updateMapping()`.

However, if you have changed a property (e.g. went from `string` to `date`), ElasticSearch will not be able to update the mapping. In this case you need to delete your index (by calling `Book::deleteIndex()`), create it anew with updated mapping (by calling `Book::createIndex()`), and then repopulate it with data.  

## Indexing
TBD

---

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

Using the Elasticsearch DebugPanel
----------------------------------

The yii2 elasticsearch extensions provides a `DebugPanel` that can be integrated with the yii debug module
and shows the executed elasticsearch queries. It also allows to run these queries
and view the results.

Add the following to you application config to enable it (if you already have the debug module
enabled, it is sufficient to just add the panels configuration):

```php
    // ...
    'bootstrap' => ['debug'],
    'modules' => [
        'debug' => [
            'class' => 'yii\\debug\\Module',
            'panels' => [
                'elasticsearch' => [
                    'class' => 'Yiisoft\\Db\\ElasticSearch\\DebugPanel',
                ],
            ],
        ],
    ],
    // ...
```

---

## 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://github.com/yiisoft/yii2/blob/master/docs/guide/db-active-record.md).

For defining an elasticsearch ActiveRecord class your record class needs to extend from `Yiisoft\Db\ElasticSearch\ActiveRecord` and
implement at least the `Yiisoft\Db\ElasticSearch\ActiveRecord::attributes()|attributes()` method to define the attributes of the record.
The handling of primary keys is different in elasticsearch as the primary key (the `_id` field in elasticsearch terms)
is not part of the attributes by default. However it is possible to define a [path mapping](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-id-field.html)
for the `_id` field to be part of the attributes.
See [elasticsearch docs](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-id-field.html) on how to define it.
The `_id` field of a document/record can be accessed using `Yiisoft\Db\ElasticSearch\ActiveRecord::getPrimaryKey()|getPrimaryKey()` and
`Yiisoft\Db\ElasticSearch\ActiveRecord::setPrimaryKey()|setPrimaryKey()`.
When path mapping is defined, the attribute name can be defined using the `Yiisoft\Db\ElasticSearch\ActiveRecord::primaryKey()|primaryKey()` method.

The following is an example model called `Customer`:

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

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

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

You may override `Yiisoft\Db\ElasticSearch\ActiveRecord::index()|index()` and `Yiisoft\Db\ElasticSearch\ActiveRecord::type()|type()`
to define the index and type this record represents.

The general usage of elasticsearch ActiveRecord is very similar to the database ActiveRecord as described in the
[guide](https://github.com/yiisoft/yii2/blob/master/docs/guide/db-active-record.md).
It supports the same interface and features except the following limitations and additions(*!*):

- As elasticsearch does not support SQL, the query API does not support `join()`, `groupBy()`, `having()` and `union()`.
  Sorting, limit, offset and conditional where are all supported.
- `Yiisoft\Db\ElasticSearch\ActiveQuery::from()|from()` does not select the tables, but the
  [index](https://www.elastic.co/guide/en/elasticsearch/reference/current/glossary.html#glossary-index)
  and [type](https://www.elastic.co/guide/en/elasticsearch/reference/current/glossary.html#glossary-type) to query against.
- `select()` has been replaced with `Yiisoft\Db\ElasticSearch\ActiveQuery::fields()|fields()` which basically does the same but
  `fields` is more elasticsearch terminology.
  It defines the fields to retrieve from a document.
- `Yiisoft\Db\ElasticSearch\ActiveQuery::via()|via`-relations can not be defined via a table as there are no tables in elasticsearch. You can only define relations via other records.
- As elasticsearch is not only a data storage but also a search engine there is of course support added for searching your records.
  There are
  `Yiisoft\Db\ElasticSearch\ActiveQuery::query()|query()`,
  `Yiisoft\Db\ElasticSearch\ActiveQuery::filter()|filter()` and
  `Yiisoft\Db\ElasticSearch\ActiveQuery::addFacet()|addFacet()` methods that allows to compose an elasticsearch query.
  See the usage example below on how they work and check out the [Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html)
  on how to compose `query` and `filter` parts.
- It is also possible to define relations from elasticsearch ActiveRecords to normal ActiveRecord classes and vice versa.

> **NOTE:** elasticsearch limits the number of records returned by any query to 10 records by default.
> If you expect to get more records you should specify limit explicitly in query **and also** relation definition.
> This is also important for relations that use via() so that if via records are limited to 10
> the relations records can also not be more than 10.


Usage example:

```php
$customer = new Customer();
$customer->primaryKey = 1; // in this case equivalent to $customer->id = 1;
$customer->attributes = ['name' => 'test'];
$customer->save();

$customer = Customer::get(1); // get a record by pk
$customers = Customer::mget([1,2,3]); // get multiple records by pk
$customer = Customer::find()->where(['name' => 'test'])->one(); // find by query, note that you need to configure mapping for this field in order to find records properly
$customers = Customer::find()->active()->all(); // find all by query (using the `active` scope)

// https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html
$result = Article::find()->query(["match" => ["title" => "yii"]])->all(); // articles whose title contains "yii"

// https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-flt-query.html
$query = Article::find()->query([
    "fuzzy_like_this" => [
        "fields" => ["title", "description"],
        "like_text" => "This query will return articles that are similar to this text :-)",
        "max_query_terms" => 12
    ]
]);

$query->all(); // gives you all the documents
// you can add facets to your search:
$query->addStatisticalFacet('click_stats', ['field' => 'visit_count']);
$query->search(); // gives you all the records + stats about the visit_count field. e.g. mean, sum, min, max etc...
```

## Complex queries

Any query can be composed using ElasticSearch's query DSL and passed to the `ActiveRecord::query()` method. However, ES query DSL is notorious for its verbosity, and these oversized queries soon become unmanageable.
Here is a method to make queries more maintainable. Start by defining a query class just as it is done for SQL-based `ActiveRecord`.

```php
class CustomerQuery extends ActiveQuery
{
    public static function name($name)
    {
        return ['match' => ['name' => $name]];
    }

    public static function address($address)
    {
        return ['match' => ['address' => $address]];
    }

    public static function registrationDateRange($dateFrom, $dateTo)
    {
        return ['range' => ['registration_date' => [
            'gte' => $dateFrom,
            'lte' => $dateTo,
        ]]];
    }
}

```

Now you can use these query components to assemble the resulting query and/or filter.

```php
$customers = Customer::find()->filter([
    CustomerQuery::registrationDateRange('2016-01-01', '2016-01-20'),
])->query([
    'bool' => [
        'should' => [
            CustomerQuery::name('John'),
            CustomerQuery::address('London'),
        ],
        'must_not' => [
            CustomerQuery::name('Jack'),
        ],
    ],
])->all();
```

## Aggregation

[The aggregations framework](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html) helps provide aggregated data based on a search query. It is based on simple building blocks called aggregations, that can be composed in order to build complex summaries of the data.  

Using the previously defined `Customer` class, let's find out how many customers have registered each day. To do that we use the `terms` aggregation.


```php
$aggData = Customer::find()->addAggregation('customers_by_date', 'terms', [
    'field' => 'registration_date',
    'order' => ['_count' => 'desc'],
    'size' => 10, //top 10 registration dates
])->search(null, ['search_type' => 'count']);

```                    

In this example we are specifically requesting aggregation results only. The following code further process the data.

```php
$customersByDate = ArrayHelper::map($aggData['aggregations']['customers_by_date']['buckets'], 'key', 'doc_count');
```

Now `$customersByDate` contains 10 dates that correspond to the the highest number of users registered.

---

## File: docs/guide/en/usage-data-providers.md

Working with data providers
===========================

You can use `\yii\data\ActiveDataProvider` with the `\Yiisoft\Db\ElasticSearch\Query` and `\Yiisoft\Db\ElasticSearch\ActiveQuery`:

```php
use yii\data\ActiveDataProvider;
use Yiisoft\Db\ElasticSearch\Query;

$query = new Query();
$query->from('yiitest', 'user');
$provider = new ActiveDataProvider([
    'query' => $query,
    'pagination' => [
        'pageSize' => 10,
    ]
]);
$models = $provider->getModels();
```

```php
use yii\data\ActiveDataProvider;
use app\models\User;

$provider = new ActiveDataProvider([
    'query' => User::find(),
    'pagination' => [
        'pageSize' => 10,
    ]
]);
$models = $provider->getModels();
```

However, usage of `\yii\data\ActiveDataProvider` with enabled pagination is not efficient, since it require
performing unnecessary extra query for the total item count fetching. Also it will be unable to give you access
for the query aggregations results. You can use `Yiisoft\Db\ElasticSearch\ActiveDataProvider` instead. It allows preparing
total item count using query 'meta' information and fetching of the aggregations results:

```php
use Yiisoft\Db\ElasticSearch\ActiveDataProvider;
use Yiisoft\Db\ElasticSearch\Query;

$query = new Query();
$query->from('yiitest', 'user')
    ->addAggregation('foo', 'terms', []);
$provider = new ActiveDataProvider([
    'query' => $query,
    'pagination' => [
        'pageSize' => 10,
    ]
]);
$models = $provider->getModels();
$aggregations = $provider->getAggregations();
$fooAggregation = $provider->getAggregation('foo');
```

---

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

Using the Query
===============

TBD

> **NOTE:** elasticsearch limits the number of records returned by any query to 10 records by default.
> If you expect to get more records you should specify limit explicitly in relation definition.

---

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

Extension Elasticsearch pour Yii 2
==================================

Cette extension fournit l'intégration d'[elasticsearch](https://www.elastic.co/products/elasticsearch) pour le [Yii framework](https://www.yiiframework.com).
Elle inclut un support basique des requêtes/recherches et implémente également la pattern `ActiveRecord` qui vous permet de stocker vos active records dans elasticsearch.

Utilisation
-----------

- [Utilisation des Query](usage-query.md)
- [Utilisation des ActiveRecord](usage-ar.md)

Sujets additionnels
-------------------

- [Utilisation du DebugPanel d'elasticsearch ](topics-debug.md)
- Définition de relations avec des enregistrements dont les clefs primaires ne font pas partie des attributs
- Récupération d'enregistrement depuis différents index/types

---

## File: docs/guide/fr/topics-debug.md

Utilisation du DebugPanel d'Elasticsearch
-----------------------------------------

L'extension yii2 elasticsearch extensions fournit un `DebugPanel` qui peut être intégré avec le module de débogage de yii, et qui affiche les requêtes elasticsearch exécutées. Il vous permet aussi d'exécuter ces requêtes et d'en voir les résultats.

Ajoutez ce qui suit à la configuration de votre application pour l'activer (si vous avez déjà activé le module de débogage, il vous suffit d'ajouter juste la partie `panels`) :

```php
    // ...
    'bootstrap' => ['debug'],
    'modules' => [
        'debug' => [
            'class' => 'yii\\debug\\Module',
            'panels' => [
                'elasticsearch' => [
                    'class' => 'Yiisoft\\Db\\ElasticSearch\\DebugPanel',
                ],
            ],
        ],
    ],
    // ...
```

---

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

Utilisation des ActiveRecord
============================

Pour des informations générales sur l'utilisation d'ActiveRecord avec yii, référez-vous à cette section du [guide](https://github.com/yiisoft/yii2/blob/master/docs/guide/db-active-record.md).

Afin de définir une classe ActiveRecord elasticsearch, votre classe doit étendre [[Yiisoft\Db\ElasticSearch\ActiveRecord]] et implémenter au moins la méthode [[Yiisoft\Db\ElasticSearch\ActiveRecord::attributes()|attributes()]] pour définir les attributes de votre enregistrement.
La gestion des clefs primaires est différente dans elasticsearch, étant donné que la clef primaire (le champ `_id` dans elasticsearch) ne fait pas partie des attributs par défaut. Il est cependant possible de définir un [mapping de path](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-id-field.html)
pour que le champ `_id` fasse partie des attributs.
Référez-vous à la [documentation elasticsearch](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-id-field.html) pour voir comment le définir.
Le champ `_id` d'un document/enregistrement peut être accédé en utilisant [[Yiisoft\Db\ElasticSearch\ActiveRecord::getPrimaryKey()|getPrimaryKey()]] et
[[Yiisoft\Db\ElasticSearch\ActiveRecord::setPrimaryKey()|setPrimaryKey()]].
Lorsque le mapping de path est défini, le nom de l'attribut peut être défini en utilisant la méthode [[Yiisoft\Db\ElasticSearch\ActiveRecord::primaryKey()|primaryKey()]].

Voici un modèle d'exemple nommé `Customer`:

```php
class Customer extends \Yiisoft\Db\ElasticSearch\ActiveRecord
{
    /**
     * @return array the list of attributes for this record
     */
    public function attributes()
    {
        // le mapping de '_id' est configuré pour le champ 'id'
        return ['id', 'name', 'address', 'registration_date'];
    }

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

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

Vous pouvez surcharger [[Yiisoft\Db\ElasticSearch\ActiveRecord::index()|index()]] et [[Yiisoft\Db\ElasticSearch\ActiveRecord::type()|type()]] pour définir l'index et type que cet enregistrement représente.

L'utilisation des ActiveRecord elasticsearch est très similaire à celle d'ActiveRecord pour les bases de données, et qui est décrite dans le 
[guide](https://github.com/yiisoft/yii2/blob/master/docs/guide/db-active-record.md).
Elle supporte la même interface et les mêmes fonctionnalités, exceptions faite des limitations et additions suivantes (*!*) :

- Etant donné que elasticsearch ne supporte pas SQL, l'API de requêtes ne supporte pas `join()`, `groupBy()`, `having()` and `union()`.
  Les tris, limites, décallages et conditions sont tous supportés.
- [[Yiisoft\Db\ElasticSearch\ActiveQuery::from()|from()]] ne sélectionne pas les tables, mais les
  [index](https://www.elastic.co/guide/en/elasticsearch/reference/current/glossary.html#glossary-index)
  et [type](https://www.elastic.co/guide/en/elasticsearch/reference/current/glossary.html#glossary-type) sur lesquels la requête sera exécutée.
- `select()` a été remplacée par [[Yiisoft\Db\ElasticSearch\ActiveQuery::fields()|fields()]] qui fait globalement la même chose, le terme `fields` étant plus orienté vers la terminologie elasticsearch.
  Cette méthode définit les champs à récupérer dans le document.
- Les relations [[Yiisoft\Db\ElasticSearch\ActiveQuery::via()|via]] ne peuvent être définies via une table étant donné qu'il n'y a pas de tables dans elasticsearch. Vous pouvez uniquement définir des relations avec les autres enregistrements.
- Etant donné qu'elasticsearch n'est pas uniquement fait pour le stockage des données, mais également pour les rechercher, le support de la recherche a été implémenté.
  Les méthodes
  [[Yiisoft\Db\ElasticSearch\ActiveQuery::query()|query()]],
  [[Yiisoft\Db\ElasticSearch\ActiveQuery::filter()|filter()]] et
  [[Yiisoft\Db\ElasticSearch\ActiveQuery::addFacet()|addFacet()]] permettent de définir une requête elasticsearch.
  Regardez l'exemple suivant pour comprendre leur fonctionnement et voir l'utilisation des [Query DSL](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html)
  pour composer les parties `query` et `filter`.
- Il est aussi possible de définir des relations entre des ActiveRecord elasticsearch et des ActiveRecord normaux, et vice versa.

> **NOTE:** elasticsearch limite le nombre d'enregistrements retournés par n'importe quelle requête à 10 enregistrements par défaut.
> Si vous vous attendez à obtenir plus de résultats, vous devez explicitement définir leur nombre dans la requête **et également** dans la définition de la relation.
> Ceci est également important pour les relations qui utilisent via(), étant donné que si les enregistrements "via" sont limités à 10, les enregistrements liés ne pourront également pas dépasser la limite de 10.

Exemple d'utilisation :

```php
$customer = new Customer();
$customer->primaryKey = 1; // ici, équivalent à $customer->id = 1;
$customer->attributes = ['name' => 'test'];
$customer->save();

$customer = Customer::get(1); // récupère un document par pk
$customers = Customer::mget([1,2,3]); // récupère plusieurs documents par pk
$customer = Customer::find()->where(['name' => 'test'])->one(); // récupère par requête, vous devez configurer le mapping de ce champ afin que la recherche fonctionne correctement
$customers = Customer::find()->active()->all(); // récupère l'ensemble des documents en utilisant une requête (et le scope `active`)

// https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html
$result = Article::find()->query(["match" => ["title" => "yii"]])->all(); // articles dont le titre contient "yii"

// https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-flt-query.html
$query = Article::find()->query([
    "fuzzy_like_this" => [
        "fields" => ["title", "description"],
        "like_text" => "Cette requête retournera les articles similaires à ce texte :-)",
        "max_query_terms" => 12
    ]
]);

$query->all(); // retourne l'ensemble des documents
// vous pouvez ajouter des facets à votre recherche :
$query->addStatisticalFacet('click_stats', ['field' => 'visit_count']);
$query->search(); // retourne l'ensemble des documents + des statistiques à propos du champ visit_count (minimum, maximum, somme, ..)
```

Et beaucoup plus. "Ce que vous pouvez bâtir est infini"[?](https://www.elastic.co/)

---

## File: docs/guide/fr/usage-query.md

Utilisation des Query
=====================

TBD

> **NOTE:** elasticsearch limite le nombre d'enregistrements retournés par n'importe quelle requête à 10 enregistrements par défaut.
> Si vous vous attendez à obtenir plus de résultats, vous devez explicitement définir leur nombre dans la définition de la relation.

---

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

Yii 2.0 elasticsearch エクステンション
======================================

このエクステンションは、Yii 2 フレームワークに対する [elasticsearch](https://www.elastic.co/products/elasticsearch) の統合を提供します。
基本的なクエリや検索をサポートするとともに、`ActiveRecord` パターンを実装して、アクティブレコードを elasticsearch に保存することを可能にしています。

使用方法
--------
- [データのマッピングとインデクシング](mapping-indexing.md)
- [クエリを使う](usage-query.md)
- [アクティブレコードを使う](usage-ar.md)
- [データプロバイダと連携する](usage-data-providers.md)

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

- [Elasticsearch DebugPanel を使う](topics-debug.md)
- プライマリキーが属性に含まれていないレコードとのリレーションの定義
- さまざまな index/type からレコードを取得する

---

## File: docs/guide/ja/mapping-indexing.md

マッピングとインデクシング
==========================

## インデックスとマッピングを生成する

ElasticSearch のマッピングを漸進的に更新することは常に可能であるとは限りません。
ですから、あなたのモデルの中に、インデックスの生成と更新を扱ういくつかの静的なメソッドを作っておくというのは、良いアイデアです。
どのようにすればそれが出来るかの一例を次に示します。

```php
Class Book extends Yiisoft\Db\ElasticSearch\ActiveRecord
{
    // クラスのその他の属性とメソッド
    // ...

    /**
     * @return array このモデルのマッピングを返す
     */
    public static function mapping()
    {
        return [
            static::type() => [
                'properties' => [
                    'name'           => ['type' => 'string'],
                    'author_name'    => ['type' => 'string'],
                    'publisher_name' => ['type' => 'string'],
                    'created_at'     => ['type' => 'long'],
                    'updated_at'     => ['type' => 'long'],
                    'status'         => ['type' => 'long'],
                ]
            ],
        ];
    }

    /**
     * このモデルのマッピングを設定(更新)する
     */
    public static function updateMapping()
    {
        $db = static::getDb();
        $command = $db->createCommand();
        $command->setMapping(static::index(), static::type(), static::mapping());
    }

    /**
     * このモデルのインデックスを生成する
     */
    public static function createIndex()
    {
        $db = static::getDb();
        $command = $db->createCommand();
        $command->createIndex(static::index(), [
            'settings' => [ /* ... */ ],
            'mappings' => static::mapping(),
            //'warmers' => [ /* ... */ ],
            //'aliases' => [ /* ... */ ],
            //'creation_date' => '...'
        ]);
    }

    /**
     * このモデルのインデックスを削除する
     */
    public static function deleteIndex()
    {
        $db = static::getDb();
        $command = $db->createCommand();
        $command->deleteIndex(static::index(), static::type());
    }
}
```

適切なマッピングでインデックスを生成するためには、`Book::createIndex()` を呼びます。
マッピングの更新を許すような仕方でマッピングを変更した場合 (例えば、新しいプロパティを作成した場合など) は、`Book::updateMapping()` を呼びます。

しかし、プロパティを変更した場合 (例えば、`string` から `date` に変えた場合など) は、ElasticSearch はマッピングを更新することが出来ません。
この場合は、インデックスを削除し (`Book::deleteIndex()` を呼びます)、更新されたマッピングでインデックスを新規に作成し (`Book::createIndex()` を呼びます)、そして、データを投入しなければなりません。

## インデクシング
TBD

---

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

Elasticsearch DebugPanel を使う
-------------------------------

Yii 2 elasticsearch エクステンションは、yii のデバッグモジュールと統合可能な `DebugPanel` を提供しています。
これは、実行された elasticsearch のクエリを表示するだけでなく、クエリを実行して結果を表示することも出来ます。

`DebugPanel` を有効にするためには、下記の構成をアプリケーションの構成情報に追加してください
(デバッグモジュールを既に有効にしている場合は、パネルの構成情報を追加するだけで十分です)。

```php
    // ...
    'bootstrap' => ['debug'],
    'modules' => [
        'debug' => [
            'class' => 'yii\\debug\\Module',
            'panels' => [
                'elasticsearch' => [
                    'class' => 'Yiisoft\\Db\\ElasticSearch\\DebugPanel',
                ],
            ],
        ],
    ],
    // ...
```

---

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

アクティブレコードを使う
========================

Yii のアクティブレコードの使用方法に関する一般的な情報については、[ガイド](https://github.com/yiisoft/yii2/blob/master/docs/guide-ja/db-active-record.md) を参照してください。

Elasticsearch のアクティブレコードを定義するためには、あなたのレコードクラスを [[Yiisoft\Db\ElasticSearch\ActiveRecord]] から拡張して、最低限、レコードの属性を定義するための [[Yiisoft\Db\ElasticSearch\ActiveRecord::attributes()|attributes()]] メソッドを実装する必要があります。
Elasticsearch ではプライマリキーの扱いが通常と異なります。
というのは、プライマリキー (elasticsearch の用語では `_id` フィールド) が、デフォルトでは属性のうちに入らないからです。
ただし、`_id` フィールドを属性に含めるための [パスマッピング](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-id-field.html) を定義することは出来ます。
パスマッピングの定義の仕方については、[elasticsearch のドキュメント](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-id-field.html) を参照してください。
document または record の `_id` フィールドは、[[Yiisoft\Db\ElasticSearch\ActiveRecord::getPrimaryKey()|getPrimaryKey()]] および [[Yiisoft\Db\ElasticSearch\ActiveRecord::setPrimaryKey()|setPrimaryKey()]] を使ってアクセスすることが出来ます。
パスマッピングが定義されている場合は、[[Yiisoft\Db\ElasticSearch\ActiveRecord::primaryKey()|primaryKey()]] メソッドを使って属性の名前を定義することが出来ます。

以下は `Customer` と呼ばれるモデルの例です。

```php
class Customer extends \Yiisoft\Db\ElasticSearch\ActiveRecord
{
    /**
     * @return array このレコードの属性のリスト
     */
    public function attributes()
    {
        // '_id' に対するパスマッピングis setup to field 'id'
        return ['id', 'name', 'address', 'registration_date'];
    }

    /**
     * @return ActiveQuery Order レコード へのリレーションを定義
     * (Order は他のデータベース、例えば、redis や通常の SQLDB にあっても良い)
     */
    public function getOrders()
    {
        return $this->hasMany(Order::className(), ['customer_id' => 'id'])->orderBy('id');
    }

    /**
     * `$query` を修正してアクティブ (status = 1) な顧客だけを返すスコープを定義
     */
    public static function active($query)
    {
        $query->andWhere(['status' => 1]);
    }
}
```

[[Yiisoft\Db\ElasticSearch\ActiveRecord::index()|index()]] と [[Yiisoft\Db\ElasticSearch\ActiveRecord::type()|type()]] をオーバーライドして、このレコードが表すインデックスとタイプを定義することが出来ます。

elasticsearch のアクティブレコードの一般的な使用方法は、[ガイド](https://github.com/yiisoft/yii2/blob/master/docs/guide-ja/active-record.md) で説明されたデータベースのアクティブレコードの場合と非常によく似ています。
以下の制限と拡張 (*!*) があることを除けば、同じインターフェイスと機能をサポートしています。

- elasticsearch は SQL をサポートしていないため、クエリの API は `join()`、`groupBy()`、`having()` および `union()` をサポートしません。
  並べ替え、リミット、オフセット、条件付き WHERE は、すべてサポートされています。
- [[Yiisoft\Db\ElasticSearch\ActiveQuery::from()|from()]] はテーブルを選択しません。
  そうではなく、クエリ対象の [インデックス](https://www.elastic.co/guide/en/elasticsearch/reference/current/glossary.html#glossary-index) と [タイプ](https://www.elastic.co/guide/en/elasticsearch/reference/current/glossary.html#glossary-type) を選択します。
- `select()` は [[Yiisoft\Db\ElasticSearch\ActiveQuery::fields()|fields()]] に置き換えられています。
  基本的には同じことをするものですが、`fields` の方が elasticsearch の用語として相応しいでしょう。
  ドキュメントから取得するフィールドを定義します。
- Elasticsearch にはテーブルがありませんので、テーブルを通じての [[Yiisoft\Db\ElasticSearch\ActiveQuery::via()|via]] リレーションは定義することが出来ません。
- Elasticsearch はデータストレージであると同時に検索エンジンでもありますので、当然ながら、レコードの検索に対するサポートが追加されています。
  Elasticsearch のクエリを構成するための [[Yiisoft\Db\ElasticSearch\ActiveQuery::query()|query()]]、[[Yiisoft\Db\ElasticSearch\ActiveQuery::filter()|filter()]] そして [[Yiisoft\Db\ElasticSearch\ActiveQuery::addFacet()|addFacet()]] というメソッドがあります。
  これらがどのように働くかについて、下の使用例を見てください。
  また、`query` と `filter` の部分を構成する方法については、[クエリ DSL](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html) を参照してください。
- Elasticsearch のアクティブレコードから通常のアクティブレコードクラスへのリレーションを定義することも可能です。また、その逆も可能です。

> Note: デフォルトでは、elasticsearch は、どんなクエリでも、返されるレコードの数を 10 に限定しています。
> もっと多くのレコードを取得することを期待する場合は、リレーションの定義で上限を明示的に指定しなければなりません。
> このことは、via() を使うリレーションにとっても重要です。
> なぜなら、via のレコードが 10 までに制限されている場合は、リレーションのレコードも 10 を超えることは出来ないからです。


使用例:

```php
$customer = new Customer();
$customer->primaryKey = 1; // この場合は、$customer->id = 1 と等価
$customer->attributes = ['name' => 'test'];
$customer->save();

$customer = Customer::get(1); // PK によってレコードを取得
$customers = Customer::mget([1,2,3]); // PK によって複数のレコードを取得
$customer = Customer::find()->where(['name' => 'test'])->one(); // クエリによる取得。レコードを正しく取得するためにはこのフィールドにマッピングを構成する必要があることに注意。
$customers = Customer::find()->active()->all(); // クエリによって全てを取得 (`active` スコープを使って)

// https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html
$result = Article::find()->query(["match" => ["title" => "yii"]])->all(); // articles whose title contains "yii"

// https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-flt-query.html
$query = Article::find()->query([
    "fuzzy_like_this" => [
        "fields" => ["title", "description"],
        "like_text" => "このクエリは、このテキストに似た記事を返します :-)",
        "max_query_terms" => 12
    ]
]);

$query->all(); // 全てのドキュメントを取得
// 検索に facets を追加できる
$query->addStatisticalFacet('click_stats', ['field' => 'visit_count']);
$query->search(); // 全てのレコード、および、visit_count フィールドに関する統計 (例えば、平均、合計、最小、最大など) を取得
```

## 複雑なクエリ

どのようなクエリでも、ElasticSearch のクエリ DSL を使って作成して `ActiveRecord::query()` メソッドに渡すことが出来ます。
しかし、ES のクエリ DSL は冗長さで悪名高いものです。
長すぎるクエリは、すぐに管理できないものになってしまいます。
クエリをもっと保守しやすくする方法があります。
SQL ベースの `ActiveRecord` のために定義されているようなクエリクラスを定義することから始めましょう。

```php
class CustomerQuery extends ActiveQuery
{
    public static function name($name)
    {
        return ['match' => ['name' => $name]];
    }

    public static function address($address)
    {
        return ['match' => ['address' => $address]];
    }

    public static function registrationDateRange($dateFrom, $dateTo)
    {
        return ['range' => ['registration_date' => [
            'gte' => $dateFrom,
            'lte' => $dateTo,
        ]]];
    }
}

```

こうすれば、これらのクエリコンポーネントを、結果となるクエリやフィルタを組み上げるために使用することが出来ます。

```php
$customers = Customer::find()->filter([
    CustomerQuery::registrationDateRange('2016-01-01', '2016-01-20'),
])->query([
    'bool' => [
        'should' => [
            CustomerQuery::name('John'),
            CustomerQuery::address('London'),
        ],
        'must_not' => [
            CustomerQuery::name('Jack'),
        ],
    ],
])->all();
```

## 集合 (Aggregations)

[集合フレームワーク](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html) が、検索クエリに基づいた集合データを提供するのを助けてくれます。
これは集合 (aggregation) と呼ばれる単純な構成要素に基づくもので、複雑なデータの要約を構築するために作成することが出来るものです。

以前に定義された `Customer` クラスを使って、毎日何人の顧客が登録されているかを検索しましょう。
そうするために `terms` 集合を使います。


```php
$aggData = Customer::find()->addAggregation('customers_by_date', 'terms', [
    'field' => 'registration_date',
    'order' => ['_count' => 'desc'],
    'size' => 10, // 登録日の上位 10
])->search(null, ['search_type' => 'count']);

```                    

この例では、集合の結果だけを特にリクエストしています。
データを更に処理するために次のコードを使います。

```php
$customersByDate = ArrayHelper::map($aggData['aggregations']['customers_by_date']['buckets'], 'key', 'doc_count');
```

これで `$customersByDate` に、ユーザー登録数の最も多い日付け上位 10 個が入ります。

---

## File: docs/guide/ja/usage-data-providers.md

[Binary file]

---

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

クエリを使う
============

(内容未定)

> Note: デフォルトでは、elasticsearch は、どんなクエリでも、返されるレコードの数を 10 に限定しています。
> もっと多くのレコードを取得することを期待する場合は、リレーションの定義で上限を明示的に指定しなければなりません。

---

## 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 a positive environment for our community include:

* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting

## Enforcement Responsibilities

Core team members are responsible for clarifying and enforcing our standards of acceptable behavior and will take 
appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.

Core team members 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, and will communicate reasons for 
moderation decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing
the community in public spaces. Examples of representing a project or community include using an official e-mail
address, 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 promptly and fairly.

All core team members are obligated to respect the privacy and security of the reporter of any incident.

## Enforcement Guidelines

Core team members will follow these Community Impact Guidelines in determining the consequences for any action they
deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in 
the community.

**Consequence**: A private, written warning from core team members, providing clarity around the nature of the violation
and an explanation of why the behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series of actions.

**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including
unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding
interactions in community spaces as well as external channels like social media. Violating these terms may lead to 
a temporary or permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified
period of time. No public or private interaction with the people involved, including unsolicited interaction with those
enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate
behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].

Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].

For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
[https://www.contributor-covenant.org/translations][translations].

[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations

---

## 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:
  # Maintain dependencies for GitHub Actions.
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule:
      interval: "daily"
    # Too noisy. See https://github.community/t/increase-if-necessary-for-github-actions-in-dependabot/179581
    open-pull-requests-limit: 0

  # Maintain dependencies for Composer
  - package-ecosystem: "composer"
    directory: "/"
    schedule:
      interval: "daily"
    versioning-strategy: increase-if-necessary

---

## 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  |

---

## 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:
    paths-ignore:
      - 'docs/**'
      - 'README.md'
      - 'CHANGELOG.md'
      - '.gitignore'
      - '.gitattributes'
      - 'infection.json.dist'
      - 'psalm.xml'

  push:
    paths-ignore:
      - 'docs/**'
      - 'README.md'
      - 'CHANGELOG.md'
      - '.gitignore'
      - '.gitattributes'
      - 'infection.json.dist'
      - 'psalm.xml'

name: build

jobs:
  tests:
    name: PHP ${{ matrix.php }} / ES ${{ matrix.es }}
    env:
      extensions: curl, mbstring, dom, intl
      key: cache-v1

    runs-on: ubuntu-latest

    strategy:
      matrix:
        php:
          - 8.0
          - 8.1
          - 8.2
        es:
          - 8.1.3
          - 7.14.0

    services:
      elasticsearch:
        image: elasticsearch:${{ matrix.es }}
        ports:
          - 9200:9200
        env:
          http.publish_host: 127.0.0.1
          transport.host: 127.0.0.1
          xpack.security.enabled: false
          indices.id_field_data.enabled: true
        options: >-
          --health-cmd "curl http://localhost:9200/_cluster/health"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 10

    steps:
      - name: Checkout.
        uses: actions/checkout@v3

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

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

      - name: Run tests with phpunit.
        run: vendor/bin/phpunit

---

## File: .github/workflows/composer-require-checker.yml

on:
  pull_request:
    paths-ignore:
      - 'docs/**'
      - 'README.md'
      - 'CHANGELOG.md'
      - '.gitignore'
      - '.gitattributes'
      - 'infection.json.dist'
      - 'phpunit.xml.dist'
      - 'psalm.xml'

  push:
    paths-ignore:
      - 'docs/**'
      - 'README.md'
      - 'CHANGELOG.md'
      - '.gitignore'
      - '.gitattributes'
      - 'infection.json.dist'
      - 'phpunit.xml.dist'
      - 'psalm.xml'

name: Composer require checker

jobs:
  composer-require-checker:
    uses: yiisoft/actions/.github/workflows/composer-require-checker.yml@master
    with:
      os: >-
        ['ubuntu-latest']
      php: >-
        ['8.0', '8.1']

---

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

on:
  pull_request:
    paths-ignore:
      - 'docs/**'
      - 'README.md'
      - 'CHANGELOG.md'
      - '.gitignore'
      - '.gitattributes'
      - 'infection.json.dist'
      - 'phpunit.xml.dist'

  push:
    paths-ignore:
      - 'docs/**'
      - 'README.md'
      - 'CHANGELOG.md'
      - '.gitignore'
      - '.gitattributes'
      - 'infection.json.dist'
      - 'phpunit.xml.dist'

name: static analysis

jobs:
  psalm:
    uses: yiisoft/actions/.github/workflows/psalm.yml@master
    with:
      os: >-
        ['ubuntu-latest']
      php: >-
        ['8.0', '8.1', '8.2']