yii2

Форк
1
/
FixtureTrait.php 
219 строк · 7.8 Кб
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7

8
namespace yii\test;
9

10
use Yii;
11
use yii\base\InvalidConfigException;
12

13
/**
14
 * FixtureTrait provides functionalities for loading, unloading and accessing fixtures for a test case.
15
 *
16
 * By using FixtureTrait, a test class will be able to specify which fixtures to load by overriding
17
 * the [[fixtures()]] method. It can then load and unload the fixtures using [[loadFixtures()]] and [[unloadFixtures()]].
18
 * Once a fixture is loaded, it can be accessed like an object property, thanks to the PHP `__get()` magic method.
19
 * Also, if the fixture is an instance of [[ActiveFixture]], you will be able to access AR models
20
 * through the syntax `$this->fixtureName('model name')`.
21
 *
22
 * For more details and usage information on FixtureTrait, see the [guide article on fixtures](guide:test-fixtures).
23
 *
24
 * @author Qiang Xue <qiang.xue@gmail.com>
25
 * @since 2.0
26
 */
27
trait FixtureTrait
28
{
29
    /**
30
     * @var array the list of fixture objects available for the current test.
31
     * The array keys are the corresponding fixture class names.
32
     * The fixtures are listed in their dependency order. That is, fixture A is listed before B
33
     * if B depends on A.
34
     */
35
    private $_fixtures;
36

37

38
    /**
39
     * Declares the fixtures that are needed by the current test case.
40
     *
41
     * The return value of this method must be an array of fixture configurations. For example,
42
     *
43
     * ```php
44
     * [
45
     *     // anonymous fixture
46
     *     PostFixture::class,
47
     *     // "users" fixture
48
     *     'users' => UserFixture::class,
49
     *     // "cache" fixture with configuration
50
     *     'cache' => [
51
     *          'class' => CacheFixture::class,
52
     *          'host' => 'xxx',
53
     *     ],
54
     * ]
55
     * ```
56
     *
57
     * Note that the actual fixtures used for a test case will include both [[globalFixtures()]]
58
     * and [[fixtures()]].
59
     *
60
     * @return array the fixtures needed by the current test case
61
     */
62
    public function fixtures()
63
    {
64
        return [];
65
    }
66

67
    /**
68
     * Declares the fixtures shared required by different test cases.
69
     * The return value should be similar to that of [[fixtures()]].
70
     * You should usually override this method in a base class.
71
     * @return array the fixtures shared and required by different test cases.
72
     * @see fixtures()
73
     */
74
    public function globalFixtures()
75
    {
76
        return [];
77
    }
78

79
    /**
80
     * Loads the specified fixtures.
81
     * This method will call [[Fixture::load()]] for every fixture object.
82
     * @param Fixture[]|null $fixtures the fixtures to be loaded. If this parameter is not specified,
83
     * the return value of [[getFixtures()]] will be used.
84
     */
85
    public function loadFixtures($fixtures = null)
86
    {
87
        if ($fixtures === null) {
88
            $fixtures = $this->getFixtures();
89
        }
90

91
        /* @var $fixture Fixture */
92
        foreach ($fixtures as $fixture) {
93
            $fixture->beforeLoad();
94
        }
95
        foreach ($fixtures as $fixture) {
96
            $fixture->load();
97
        }
98
        foreach (array_reverse($fixtures) as $fixture) {
99
            $fixture->afterLoad();
100
        }
101
    }
102

103
    /**
104
     * Unloads the specified fixtures.
105
     * This method will call [[Fixture::unload()]] for every fixture object.
106
     * @param Fixture[]|null $fixtures the fixtures to be loaded. If this parameter is not specified,
107
     * the return value of [[getFixtures()]] will be used.
108
     */
109
    public function unloadFixtures($fixtures = null)
110
    {
111
        if ($fixtures === null) {
112
            $fixtures = $this->getFixtures();
113
        }
114

115
        /* @var $fixture Fixture */
116
        foreach ($fixtures as $fixture) {
117
            $fixture->beforeUnload();
118
        }
119
        $fixtures = array_reverse($fixtures);
120
        foreach ($fixtures as $fixture) {
121
            $fixture->unload();
122
        }
123
        foreach ($fixtures as $fixture) {
124
            $fixture->afterUnload();
125
        }
126
    }
127

128
    /**
129
     * Initialize the fixtures.
130
     * @since 2.0.12
131
     */
132
    public function initFixtures()
133
    {
134
        $this->unloadFixtures();
135
        $this->loadFixtures();
136
    }
137

138
    /**
139
     * Returns the fixture objects as specified in [[globalFixtures()]] and [[fixtures()]].
140
     * @return Fixture[] the loaded fixtures for the current test case
141
     */
142
    public function getFixtures()
143
    {
144
        if ($this->_fixtures === null) {
145
            $this->_fixtures = $this->createFixtures(array_merge($this->globalFixtures(), $this->fixtures()));
146
        }
147

148
        return $this->_fixtures;
149
    }
150

151
    /**
152
     * Returns the named fixture.
153
     * @param string $name the fixture name. This can be either the fixture alias name, or the class name if the alias is not used.
154
     * @return Fixture|null the fixture object, or null if the named fixture does not exist.
155
     */
156
    public function getFixture($name)
157
    {
158
        if ($this->_fixtures === null) {
159
            $this->_fixtures = $this->createFixtures(array_merge($this->globalFixtures(), $this->fixtures()));
160
        }
161
        $name = ltrim($name, '\\');
162

163
        return isset($this->_fixtures[$name]) ? $this->_fixtures[$name] : null;
164
    }
165

166
    /**
167
     * Creates the specified fixture instances.
168
     * All dependent fixtures will also be created. Duplicate fixtures and circular dependencies will only be created once.
169
     * @param array $fixtures the fixtures to be created. You may provide fixture names or fixture configurations.
170
     * If this parameter is not provided, the fixtures specified in [[globalFixtures()]] and [[fixtures()]] will be created.
171
     * @return Fixture[] the created fixture instances
172
     * @throws InvalidConfigException if fixtures are not properly configured
173
     */
174
    protected function createFixtures(array $fixtures)
175
    {
176
        // normalize fixture configurations
177
        $config = [];  // configuration provided in test case
178
        $aliases = [];  // class name => alias or class name
179
        foreach ($fixtures as $name => $fixture) {
180
            if (!is_array($fixture)) {
181
                $class = ltrim($fixture, '\\');
182
                $fixtures[$name] = ['class' => $class];
183
                $aliases[$class] = is_int($name) ? $class : $name;
184
            } elseif (isset($fixture['class'])) {
185
                $class = ltrim($fixture['class'], '\\');
186
                $config[$class] = $fixture;
187
                $aliases[$class] = $name;
188
            } else {
189
                throw new InvalidConfigException("You must specify 'class' for the fixture '$name'.");
190
            }
191
        }
192

193
        // create fixture instances
194
        $instances = [];
195
        $stack = array_reverse($fixtures);
196
        while (($fixture = array_pop($stack)) !== null) {
197
            if ($fixture instanceof Fixture) {
198
                $class = get_class($fixture);
199
                $name = isset($aliases[$class]) ? $aliases[$class] : $class;
200
                unset($instances[$name]);  // unset so that the fixture is added to the last in the next line
201
                $instances[$name] = $fixture;
202
            } else {
203
                $class = ltrim($fixture['class'], '\\');
204
                $name = isset($aliases[$class]) ? $aliases[$class] : $class;
205
                if (!isset($instances[$name])) {
206
                    $instances[$name] = false;
207
                    $stack[] = $fixture = Yii::createObject($fixture);
208
                    foreach ($fixture->depends as $dep) {
209
                        // need to use the configuration provided in test case
210
                        $stack[] = isset($config[$dep]) ? $config[$dep] : ['class' => $dep];
211
                    }
212
                }
213
                // if the fixture is already loaded (ie. a circular dependency or if two fixtures depend on the same fixture) just skip it.
214
            }
215
        }
216

217
        return $instances;
218
    }
219
}
220

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

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.