TestFixture.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
  11. * @since 1.2.0
  12. * @license https://opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Cake\TestSuite\Fixture;
  15. use Cake\Core\Exception\Exception as CakeException;
  16. use Cake\Database\Schema\TableSchema;
  17. use Cake\Database\Schema\TableSchemaAwareInterface;
  18. use Cake\Database\Schema\TableSchemaInterface as DatabaseTableSchemaInterface;
  19. use Cake\Datasource\ConnectionInterface;
  20. use Cake\Datasource\ConnectionManager;
  21. use Cake\Datasource\FixtureInterface;
  22. use Cake\Datasource\TableSchemaInterface;
  23. use Cake\Log\Log;
  24. use Cake\ORM\TableRegistry;
  25. use Cake\Utility\Inflector;
  26. use Exception;
  27. /**
  28. * Cake TestFixture is responsible for building and destroying tables to be used
  29. * during testing.
  30. */
  31. class TestFixture implements FixtureInterface, TableSchemaInterface, TableSchemaAwareInterface
  32. {
  33. /**
  34. * Fixture Datasource
  35. *
  36. * @var string
  37. */
  38. public $connection = 'test';
  39. /**
  40. * Full Table Name
  41. *
  42. * @var string
  43. */
  44. public $table;
  45. /**
  46. * Fields / Schema for the fixture.
  47. *
  48. * This array should be compatible with Cake\Database\Schema\Schema.
  49. * The `_constraints`, `_options` and `_indexes` keys are reserved for defining
  50. * constraints, options and indexes respectively.
  51. *
  52. * @var array
  53. */
  54. public $fields = [];
  55. /**
  56. * Configuration for importing fixture schema
  57. *
  58. * Accepts a `connection` and `model` or `table` key, to define
  59. * which table and which connection contain the schema to be
  60. * imported.
  61. *
  62. * @var array|null
  63. */
  64. public $import;
  65. /**
  66. * Fixture records to be inserted.
  67. *
  68. * @var array
  69. */
  70. public $records = [];
  71. /**
  72. * The schema for this fixture.
  73. *
  74. * @var \Cake\Database\Schema\TableSchema
  75. */
  76. protected $_schema;
  77. /**
  78. * Fixture constraints to be created.
  79. *
  80. * @var array
  81. */
  82. protected $_constraints = [];
  83. /**
  84. * Instantiate the fixture.
  85. *
  86. * @throws \Cake\Core\Exception\Exception on invalid datasource usage.
  87. */
  88. public function __construct()
  89. {
  90. if (!empty($this->connection)) {
  91. $connection = $this->connection;
  92. if (strpos($connection, 'test') !== 0) {
  93. $message = sprintf(
  94. 'Invalid datasource name "%s" for "%s" fixture. Fixture datasource names must begin with "test".',
  95. $connection,
  96. $this->table
  97. );
  98. throw new CakeException($message);
  99. }
  100. }
  101. $this->init();
  102. }
  103. /**
  104. * {@inheritDoc}
  105. */
  106. public function connection()
  107. {
  108. return $this->connection;
  109. }
  110. /**
  111. * {@inheritDoc}
  112. */
  113. public function sourceName()
  114. {
  115. return $this->table;
  116. }
  117. /**
  118. * Initialize the fixture.
  119. *
  120. * @return void
  121. * @throws \Cake\ORM\Exception\MissingTableClassException When importing from a table that does not exist.
  122. */
  123. public function init()
  124. {
  125. if ($this->table === null) {
  126. $this->table = $this->_tableFromClass();
  127. }
  128. if (empty($this->import) && !empty($this->fields)) {
  129. $this->_schemaFromFields();
  130. }
  131. if (!empty($this->import)) {
  132. $this->_schemaFromImport();
  133. }
  134. if (empty($this->import) && empty($this->fields)) {
  135. $this->_schemaFromReflection();
  136. }
  137. }
  138. /**
  139. * Returns the table name using the fixture class
  140. *
  141. * @return string
  142. */
  143. protected function _tableFromClass()
  144. {
  145. list(, $class) = namespaceSplit(get_class($this));
  146. preg_match('/^(.*)Fixture$/', $class, $matches);
  147. $table = $class;
  148. if (isset($matches[1])) {
  149. $table = $matches[1];
  150. }
  151. return Inflector::tableize($table);
  152. }
  153. /**
  154. * Build the fixtures table schema from the fields property.
  155. *
  156. * @return void
  157. */
  158. protected function _schemaFromFields()
  159. {
  160. $connection = ConnectionManager::get($this->connection());
  161. $this->_schema = new TableSchema($this->table);
  162. foreach ($this->fields as $field => $data) {
  163. if ($field === '_constraints' || $field === '_indexes' || $field === '_options') {
  164. continue;
  165. }
  166. $this->_schema->addColumn($field, $data);
  167. }
  168. if (!empty($this->fields['_constraints'])) {
  169. foreach ($this->fields['_constraints'] as $name => $data) {
  170. if (!$connection->supportsDynamicConstraints() || $data['type'] !== TableSchema::CONSTRAINT_FOREIGN) {
  171. $this->_schema->addConstraint($name, $data);
  172. } else {
  173. $this->_constraints[$name] = $data;
  174. }
  175. }
  176. }
  177. if (!empty($this->fields['_indexes'])) {
  178. foreach ($this->fields['_indexes'] as $name => $data) {
  179. $this->_schema->addIndex($name, $data);
  180. }
  181. }
  182. if (!empty($this->fields['_options'])) {
  183. $this->_schema->setOptions($this->fields['_options']);
  184. }
  185. }
  186. /**
  187. * Build fixture schema from a table in another datasource.
  188. *
  189. * @return void
  190. * @throws \Cake\Core\Exception\Exception when trying to import from an empty table.
  191. */
  192. protected function _schemaFromImport()
  193. {
  194. if (!is_array($this->import)) {
  195. return;
  196. }
  197. $import = $this->import + ['connection' => 'default', 'table' => null, 'model' => null];
  198. if (!empty($import['model'])) {
  199. if (!empty($import['table'])) {
  200. throw new CakeException('You cannot define both table and model.');
  201. }
  202. $import['table'] = TableRegistry::get($import['model'])->getTable();
  203. }
  204. if (empty($import['table'])) {
  205. throw new CakeException('Cannot import from undefined table.');
  206. }
  207. $this->table = $import['table'];
  208. $db = ConnectionManager::get($import['connection'], false);
  209. $schemaCollection = $db->schemaCollection();
  210. $table = $schemaCollection->describe($import['table']);
  211. $this->_schema = $table;
  212. }
  213. /**
  214. * Build fixture schema directly from the datasource
  215. *
  216. * @return void
  217. * @throws \Cake\Core\Exception\Exception when trying to reflect a table that does not exist
  218. */
  219. protected function _schemaFromReflection()
  220. {
  221. $db = ConnectionManager::get($this->connection());
  222. $schemaCollection = $db->schemaCollection();
  223. $tables = $schemaCollection->listTables();
  224. if (!in_array($this->table, $tables)) {
  225. throw new CakeException(
  226. sprintf(
  227. 'Cannot describe schema for table `%s` for fixture `%s` : the table does not exist.',
  228. $this->table,
  229. get_class($this)
  230. )
  231. );
  232. }
  233. $this->_schema = $schemaCollection->describe($this->table);
  234. }
  235. /**
  236. * Gets/Sets the TableSchema instance used by this fixture.
  237. *
  238. * @param \Cake\Database\Schema\TableSchema|null $schema The table to set.
  239. * @return \Cake\Database\Schema\TableSchema|null
  240. * @deprecated 3.5.0 Use getTableSchema/setTableSchema instead.
  241. */
  242. public function schema(TableSchema $schema = null)
  243. {
  244. deprecationWarning(
  245. 'TestFixture::schema() is deprecated. ' .
  246. 'Use TestFixture::setTableSchema()/getTableSchema() instead.'
  247. );
  248. if ($schema) {
  249. $this->setTableSchema($schema);
  250. }
  251. return $this->getTableSchema();
  252. }
  253. /**
  254. * {@inheritDoc}
  255. */
  256. public function create(ConnectionInterface $db)
  257. {
  258. if (empty($this->_schema)) {
  259. return false;
  260. }
  261. if (empty($this->import) && empty($this->fields)) {
  262. return true;
  263. }
  264. try {
  265. $queries = $this->_schema->createSql($db);
  266. foreach ($queries as $query) {
  267. $stmt = $db->prepare($query);
  268. $stmt->execute();
  269. $stmt->closeCursor();
  270. }
  271. } catch (Exception $e) {
  272. $msg = sprintf(
  273. 'Fixture creation for "%s" failed "%s"',
  274. $this->table,
  275. $e->getMessage()
  276. );
  277. Log::error($msg);
  278. trigger_error($msg, E_USER_WARNING);
  279. return false;
  280. }
  281. return true;
  282. }
  283. /**
  284. * {@inheritDoc}
  285. */
  286. public function drop(ConnectionInterface $db)
  287. {
  288. if (empty($this->_schema)) {
  289. return false;
  290. }
  291. if (empty($this->import) && empty($this->fields)) {
  292. return true;
  293. }
  294. try {
  295. $sql = $this->_schema->dropSql($db);
  296. foreach ($sql as $stmt) {
  297. $db->execute($stmt)->closeCursor();
  298. }
  299. } catch (Exception $e) {
  300. return false;
  301. }
  302. return true;
  303. }
  304. /**
  305. * {@inheritDoc}
  306. */
  307. public function insert(ConnectionInterface $db)
  308. {
  309. if (isset($this->records) && !empty($this->records)) {
  310. list($fields, $values, $types) = $this->_getRecords();
  311. $query = $db->newQuery()
  312. ->insert($fields, $types)
  313. ->into($this->table);
  314. foreach ($values as $row) {
  315. $query->values($row);
  316. }
  317. $statement = $query->execute();
  318. $statement->closeCursor();
  319. return $statement;
  320. }
  321. return true;
  322. }
  323. /**
  324. * {@inheritDoc}
  325. */
  326. public function createConstraints(ConnectionInterface $db)
  327. {
  328. if (empty($this->_constraints)) {
  329. return true;
  330. }
  331. foreach ($this->_constraints as $name => $data) {
  332. $this->_schema->addConstraint($name, $data);
  333. }
  334. $sql = $this->_schema->addConstraintSql($db);
  335. if (empty($sql)) {
  336. return true;
  337. }
  338. foreach ($sql as $stmt) {
  339. $db->execute($stmt)->closeCursor();
  340. }
  341. return true;
  342. }
  343. /**
  344. * {@inheritDoc}
  345. */
  346. public function dropConstraints(ConnectionInterface $db)
  347. {
  348. if (empty($this->_constraints)) {
  349. return true;
  350. }
  351. $sql = $this->_schema->dropConstraintSql($db);
  352. if (empty($sql)) {
  353. return true;
  354. }
  355. foreach ($sql as $stmt) {
  356. $db->execute($stmt)->closeCursor();
  357. }
  358. foreach ($this->_constraints as $name => $data) {
  359. $this->_schema->dropConstraint($name);
  360. }
  361. return true;
  362. }
  363. /**
  364. * Converts the internal records into data used to generate a query.
  365. *
  366. * @return array
  367. */
  368. protected function _getRecords()
  369. {
  370. $fields = $values = $types = [];
  371. $columns = $this->_schema->columns();
  372. foreach ($this->records as $record) {
  373. $fields = array_merge($fields, array_intersect(array_keys($record), $columns));
  374. }
  375. $fields = array_values(array_unique($fields));
  376. foreach ($fields as $field) {
  377. $types[$field] = $this->_schema->getColumn($field)['type'];
  378. }
  379. $default = array_fill_keys($fields, null);
  380. foreach ($this->records as $record) {
  381. $values[] = array_merge($default, $record);
  382. }
  383. return [$fields, $values, $types];
  384. }
  385. /**
  386. * {@inheritDoc}
  387. */
  388. public function truncate(ConnectionInterface $db)
  389. {
  390. $sql = $this->_schema->truncateSql($db);
  391. foreach ($sql as $stmt) {
  392. $db->execute($stmt)->closeCursor();
  393. }
  394. return true;
  395. }
  396. /**
  397. * {@inheritDoc}
  398. */
  399. public function getTableSchema()
  400. {
  401. return $this->_schema;
  402. }
  403. /**
  404. * {@inheritDoc}
  405. */
  406. public function setTableSchema(DatabaseTableSchemaInterface $schema)
  407. {
  408. $this->_schema = $schema;
  409. return $this;
  410. }
  411. }