FixtureTrait.php 6.56 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9 10 11
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\test;

use Yii;
use yii\base\InvalidConfigException;
12 13
use yii\base\UnknownMethodException;
use yii\base\UnknownPropertyException;
Qiang Xue committed
14 15 16 17

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

Carsten Brandt committed
41

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
	/**
	 * Returns the value of an object property.
	 *
	 * Do not call this method directly as it is a PHP magic method that
	 * will be implicitly called when executing `$value = $object->property;`.
	 * @param string $name the property name
	 * @return mixed the property value
	 * @throws UnknownPropertyException if the property is not defined
	 */
	public function __get($name)
	{
		$fixture = $this->getFixture($name);
		if ($fixture !== null) {
			return $fixture;
		} else {
			throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
		}
	}

	/**
	 * Calls the named method which is not a class method.
	 *
	 * Do not call this method directly as it is a PHP magic method that
	 * will be implicitly called when an unknown method is being invoked.
	 * @param string $name the method name
	 * @param array $params method parameters
	 * @throws UnknownMethodException when calling unknown method
	 * @return mixed the method return value
	 */
	public function __call($name, $params)
	{
		$fixture = $this->getFixture($name);
		if ($fixture instanceof ActiveFixture) {
			return $fixture->getModel(reset($params));
		} else {
			throw new UnknownMethodException('Unknown method: ' . get_class($this) . "::$name()");
		}
	}

Qiang Xue committed
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
	/**
	 * Declares the fixtures that are needed by the current test case.
	 * The return value of this method must be an array of fixture configurations. For example,
	 *
	 * ```php
	 * [
	 *     // anonymous fixture
	 *     PostFixture::className(),
	 *     // "users" fixture
	 *     'users' => UserFixture::className(),
	 *     // "cache" fixture with configuration
	 *     'cache' => [
	 *          'class' => CacheFixture::className(),
	 *          'host' => 'xxx',
	 *     ],
	 * ]
	 * ```
	 *
Qiang Xue committed
99 100 101
	 * Note that the actual fixtures used for a test case will include both [[globalFixtures()]]
	 * and [[fixtures()]].
	 *
Qiang Xue committed
102 103
	 * @return array the fixtures needed by the current test case
	 */
104
	protected function fixtures()
Qiang Xue committed
105 106 107 108
	{
		return [];
	}

Qiang Xue committed
109 110 111 112 113 114 115 116 117 118 119 120
	/**
	 * Declares the fixtures shared required by different test cases.
	 * The return value should be similar to that of [[fixtures()]].
	 * You should usually override this method in a base class.
	 * @return array the fixtures shared and required by different test cases.
	 * @see fixtures()
	 */
	protected function globalFixtures()
	{
		return [];
	}

Qiang Xue committed
121 122
	/**
	 * Loads the fixtures.
Qiang Xue committed
123
	 * This method will load the fixtures specified by `$fixtures` or [[globalFixtures()]] and [[fixtures()]].
Qiang Xue committed
124 125 126 127
	 * @param array $fixtures the fixtures to loaded. If not set, [[fixtures()]] will be loaded instead.
	 * @throws InvalidConfigException if fixtures are not properly configured or if a circular dependency among
	 * the fixtures is detected.
	 */
128
	protected function loadFixtures($fixtures = null)
Qiang Xue committed
129 130
	{
		if ($fixtures === null) {
Qiang Xue committed
131
			$fixtures = array_merge($this->globalFixtures(), $this->fixtures());
Qiang Xue committed
132 133 134 135 136 137 138
		}

		// normalize fixture configurations
		$config = [];  // configuration provided in test case
		$this->_fixtureAliases = [];
		foreach ($fixtures as $name => $fixture) {
			if (!is_array($fixture)) {
139
				$fixtures[$name] = $fixture = ['class' => $fixture];
Qiang Xue committed
140 141 142 143 144 145 146 147 148
			} elseif (!isset($fixture['class'])) {
				throw new InvalidConfigException("You must specify 'class' for the fixture '$name'.");
			}
			$config[$fixture['class']] = $fixture;
			$this->_fixtureAliases[$name] = $fixture['class'];
		}

		// create fixture instances
		$this->_fixtures = [];
Qiang Xue committed
149
		$stack = array_reverse($fixtures);
Qiang Xue committed
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
		while (($fixture = array_pop($stack)) !== null) {
			if ($fixture instanceof Fixture) {
				$class = get_class($fixture);
				unset($this->_fixtures[$class]);  // unset so that the fixture is added to the last in the next line
				$this->_fixtures[$class] = $fixture;
			} else {
				$class = $fixture['class'];
				if (!isset($this->_fixtures[$class])) {
					$this->_fixtures[$class] = false;
					$stack[] = $fixture = Yii::createObject($fixture);
					foreach ($fixture->depends as $dep) {
						// need to use the configuration provided in test case
						$stack[] = isset($config[$dep]) ? $config[$dep] : ['class' => $dep];
	 				}
				} elseif ($this->_fixtures[$class] === false) {
					throw new InvalidConfigException("A circular dependency is detected for fixture '$class'.");
				}
			}
		}

		// load fixtures
		/** @var Fixture $fixture */
		foreach ($this->_fixtures as $fixture) {
			$fixture->beforeLoad();
		}
		foreach ($this->_fixtures as $fixture) {
			$fixture->load();
		}
		foreach ($this->_fixtures as $fixture) {
			$fixture->afterLoad();
		}
	}

	/**
	 * Unloads all existing fixtures.
	 */
186
	protected function unloadFixtures()
Qiang Xue committed
187 188 189 190 191 192 193 194 195 196
	{
		/** @var Fixture $fixture */
		foreach (array_reverse($this->_fixtures) as $fixture) {
			$fixture->unload();
		}
	}

	/**
	 * @return array the loaded fixtures for the current test case
	 */
197
	protected function getFixtures()
Qiang Xue committed
198 199 200 201 202 203 204 205 206
	{
		return $this->_fixtures;
	}

	/**
	 * Returns the named fixture.
	 * @param string $name the fixture alias or class name
	 * @return Fixture the fixture object, or null if the named fixture does not exist.
	 */
207
	protected function getFixture($name)
Qiang Xue committed
208 209 210 211 212
	{
		$class = isset($this->_fixtureAliases[$name]) ? $this->_fixtureAliases[$name] : $name;
		return isset($this->_fixtures[$class]) ? $this->_fixtures[$class] : null;
	}
}