Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
13532 anikendra 1
<?php
2
/**
3
 * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
4
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice
9
 *
10
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
11
 * @link          http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
12
 * @package       Cake.TestSuite.Fixture
13
 * @since         CakePHP(tm) v 1.2.0.4667
14
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
15
 */
16
 
17
App::uses('CakeSchema', 'Model');
18
 
19
/**
20
 * CakeTestFixture is responsible for building and destroying tables to be used
21
 * during testing.
22
 *
23
 * @package       Cake.TestSuite.Fixture
24
 */
25
class CakeTestFixture {
26
 
27
/**
28
 * Name of the object
29
 *
30
 * @var string
31
 */
32
	public $name = null;
33
 
34
/**
35
 * CakePHP's DBO driver (e.g: DboMysql).
36
 *
37
 * @var object
38
 */
39
	public $db = null;
40
 
41
/**
42
 * Fixture Datasource
43
 *
44
 * @var string
45
 */
46
	public $useDbConfig = 'test';
47
 
48
/**
49
 * Full Table Name
50
 *
51
 * @var string
52
 */
53
	public $table = null;
54
 
55
/**
56
 * List of datasources where this fixture has been created
57
 *
58
 * @var array
59
 */
60
	public $created = array();
61
 
62
/**
63
 * Fields / Schema for the fixture.
64
 * This array should match the output of Model::schema()
65
 *
66
 * @var array
67
 */
68
	public $fields = array();
69
 
70
/**
71
 * Fixture records to be inserted.
72
 *
73
 * @var array
74
 */
75
	public $records = array();
76
 
77
/**
78
 * The primary key for the table this fixture represents.
79
 *
80
 * @var string
81
 */
82
	public $primaryKey = null;
83
 
84
/**
85
 * Instantiate the fixture.
86
 *
87
 * @throws CakeException on invalid datasource usage.
88
 */
89
	public function __construct() {
90
		if ($this->name === null) {
91
			if (preg_match('/^(.*)Fixture$/', get_class($this), $matches)) {
92
				$this->name = $matches[1];
93
			} else {
94
				$this->name = get_class($this);
95
			}
96
		}
97
		$connection = 'test';
98
		if (!empty($this->useDbConfig)) {
99
			$connection = $this->useDbConfig;
100
			if (strpos($connection, 'test') !== 0) {
101
				$message = __d(
102
					'cake_dev',
103
					'Invalid datasource name "%s" for "%s" fixture. Fixture datasource names must begin with "test".',
104
					$connection,
105
					$this->name
106
				);
107
				throw new CakeException($message);
108
			}
109
		}
110
		$this->Schema = new CakeSchema(array('name' => 'TestSuite', 'connection' => $connection));
111
		$this->init();
112
	}
113
 
114
/**
115
 * Initialize the fixture.
116
 *
117
 * @return void
118
 * @throws MissingModelException Whe importing from a model that does not exist.
119
 */
120
	public function init() {
121
		if (isset($this->import) && (is_string($this->import) || is_array($this->import))) {
122
			$import = array_merge(
123
				array('connection' => 'default', 'records' => false),
124
				is_array($this->import) ? $this->import : array('model' => $this->import)
125
			);
126
 
127
			$this->Schema->connection = $import['connection'];
128
			if (isset($import['model'])) {
129
				list($plugin, $modelClass) = pluginSplit($import['model'], true);
130
				App::uses($modelClass, $plugin . 'Model');
131
				if (!class_exists($modelClass)) {
132
					throw new MissingModelException(array('class' => $modelClass));
133
				}
134
				$model = new $modelClass(null, null, $import['connection']);
135
				$db = $model->getDataSource();
136
				if (empty($model->tablePrefix)) {
137
					$model->tablePrefix = $db->config['prefix'];
138
				}
139
				$this->fields = $model->schema(true);
140
				$this->fields[$model->primaryKey]['key'] = 'primary';
141
				$this->table = $db->fullTableName($model, false, false);
142
				$this->primaryKey = $model->primaryKey;
143
				ClassRegistry::config(array('ds' => 'test'));
144
				ClassRegistry::flush();
145
			} elseif (isset($import['table'])) {
146
				$model = new Model(null, $import['table'], $import['connection']);
147
				$db = ConnectionManager::getDataSource($import['connection']);
148
				$db->cacheSources = false;
149
				$model->useDbConfig = $import['connection'];
150
				$model->name = Inflector::camelize(Inflector::singularize($import['table']));
151
				$model->table = $import['table'];
152
				$model->tablePrefix = $db->config['prefix'];
153
				$this->fields = $model->schema(true);
154
				$this->primaryKey = $model->primaryKey;
155
				ClassRegistry::flush();
156
			}
157
 
158
			if (!empty($db->config['prefix']) && strpos($this->table, $db->config['prefix']) === 0) {
159
				$this->table = str_replace($db->config['prefix'], '', $this->table);
160
			}
161
 
162
			if (isset($import['records']) && $import['records'] !== false && isset($model) && isset($db)) {
163
				$this->records = array();
164
				$query = array(
165
					'fields' => $db->fields($model, null, array_keys($this->fields)),
166
					'table' => $db->fullTableName($model),
167
					'alias' => $model->alias,
168
					'conditions' => array(),
169
					'order' => null,
170
					'limit' => null,
171
					'group' => null
172
				);
173
				$records = $db->fetchAll($db->buildStatement($query, $model), false, $model->alias);
174
 
175
				if ($records !== false && !empty($records)) {
176
					$this->records = Hash::extract($records, '{n}.' . $model->alias);
177
				}
178
			}
179
		}
180
 
181
		if (!isset($this->table)) {
182
			$this->table = Inflector::underscore(Inflector::pluralize($this->name));
183
		}
184
 
185
		if (!isset($this->primaryKey) && isset($this->fields['id'])) {
186
			$this->primaryKey = 'id';
187
		}
188
	}
189
 
190
/**
191
 * Run before all tests execute, should return SQL statement to create table for this fixture could be executed successfully.
192
 *
193
 * @param DboSource $db An instance of the database object used to create the fixture table
194
 * @return boolean True on success, false on failure
195
 */
196
	public function create($db) {
197
		if (!isset($this->fields) || empty($this->fields)) {
198
			return false;
199
		}
200
 
201
		if (empty($this->fields['tableParameters']['engine'])) {
202
			$canUseMemory = true;
203
			foreach ($this->fields as $args) {
204
 
205
				if (is_string($args)) {
206
					$type = $args;
207
				} elseif (!empty($args['type'])) {
208
					$type = $args['type'];
209
				} else {
210
					continue;
211
				}
212
 
213
				if (in_array($type, array('blob', 'text', 'binary'))) {
214
					$canUseMemory = false;
215
					break;
216
				}
217
			}
218
 
219
			if ($canUseMemory) {
220
				$this->fields['tableParameters']['engine'] = 'MEMORY';
221
			}
222
		}
223
		$this->Schema->build(array($this->table => $this->fields));
224
		try {
225
			$db->execute($db->createSchema($this->Schema), array('log' => false));
226
			$this->created[] = $db->configKeyName;
227
		} catch (Exception $e) {
228
			$msg = __d(
229
				'cake_dev',
230
				'Fixture creation for "%s" failed "%s"',
231
				$this->table,
232
				$e->getMessage()
233
			);
234
			CakeLog::error($msg);
235
			trigger_error($msg, E_USER_WARNING);
236
			return false;
237
		}
238
		return true;
239
	}
240
 
241
/**
242
 * Run after all tests executed, should return SQL statement to drop table for this fixture.
243
 *
244
 * @param DboSource $db An instance of the database object used to create the fixture table
245
 * @return boolean True on success, false on failure
246
 */
247
	public function drop($db) {
248
		if (empty($this->fields)) {
249
			return false;
250
		}
251
		$this->Schema->build(array($this->table => $this->fields));
252
		try {
253
 
254
			$db->execute($db->dropSchema($this->Schema), array('log' => false));
255
			$this->created = array_diff($this->created, array($db->configKeyName));
256
		} catch (Exception $e) {
257
			return false;
258
		}
259
		return true;
260
	}
261
 
262
/**
263
 * Run before each tests is executed, should return a set of SQL statements to insert records for the table
264
 * of this fixture could be executed successfully.
265
 *
266
 * @param DboSource $db An instance of the database into which the records will be inserted
267
 * @return boolean on success or if there are no records to insert, or false on failure
268
 */
269
	public function insert($db) {
270
		if (!isset($this->_insert)) {
271
			$values = array();
272
			if (isset($this->records) && !empty($this->records)) {
273
				$fields = array();
274
				foreach ($this->records as $record) {
275
					$fields = array_merge($fields, array_keys(array_intersect_key($record, $this->fields)));
276
				}
277
				$fields = array_unique($fields);
278
				$default = array_fill_keys($fields, null);
279
				foreach ($this->records as $record) {
280
					$values[] = array_values(array_merge($default, $record));
281
				}
282
				$nested = $db->useNestedTransactions;
283
				$db->useNestedTransactions = false;
284
				$result = $db->insertMulti($this->table, $fields, $values);
285
				if (
286
					$this->primaryKey &&
287
					isset($this->fields[$this->primaryKey]['type']) &&
288
					in_array($this->fields[$this->primaryKey]['type'], array('integer', 'biginteger'))
289
				) {
290
					$db->resetSequence($this->table, $this->primaryKey);
291
				}
292
				$db->useNestedTransactions = $nested;
293
				return $result;
294
			}
295
			return true;
296
		}
297
	}
298
 
299
/**
300
 * Truncates the current fixture. Can be overwritten by classes extending
301
 * CakeFixture to trigger other events before / after truncate.
302
 *
303
 * @param DboSource $db A reference to a db instance
304
 * @return boolean
305
 */
306
	public function truncate($db) {
307
		$fullDebug = $db->fullDebug;
308
		$db->fullDebug = false;
309
		$return = $db->truncate($this->table);
310
		$db->fullDebug = $fullDebug;
311
		return $return;
312
	}
313
 
314
}