| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473 |
- <?php
- /**
- * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
- * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the LICENSE.txt
- * Redistributions of files must retain the above copyright notice
- *
- * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- * @since 1.2.0
- * @license https://opensource.org/licenses/mit-license.php MIT License
- */
- namespace Cake\TestSuite\Fixture;
- use Cake\Core\Exception\Exception as CakeException;
- use Cake\Database\Schema\TableSchema;
- use Cake\Database\Schema\TableSchemaAwareInterface;
- use Cake\Database\Schema\TableSchemaInterface as DatabaseTableSchemaInterface;
- use Cake\Datasource\ConnectionInterface;
- use Cake\Datasource\ConnectionManager;
- use Cake\Datasource\FixtureInterface;
- use Cake\Datasource\TableSchemaInterface;
- use Cake\Log\Log;
- use Cake\ORM\TableRegistry;
- use Cake\Utility\Inflector;
- use Exception;
- /**
- * Cake TestFixture is responsible for building and destroying tables to be used
- * during testing.
- */
- class TestFixture implements FixtureInterface, TableSchemaInterface, TableSchemaAwareInterface
- {
- /**
- * Fixture Datasource
- *
- * @var string
- */
- public $connection = 'test';
- /**
- * Full Table Name
- *
- * @var string
- */
- public $table;
- /**
- * Fields / Schema for the fixture.
- *
- * This array should be compatible with Cake\Database\Schema\Schema.
- * The `_constraints`, `_options` and `_indexes` keys are reserved for defining
- * constraints, options and indexes respectively.
- *
- * @var array
- */
- public $fields = [];
- /**
- * Configuration for importing fixture schema
- *
- * Accepts a `connection` and `model` or `table` key, to define
- * which table and which connection contain the schema to be
- * imported.
- *
- * @var array|null
- */
- public $import;
- /**
- * Fixture records to be inserted.
- *
- * @var array
- */
- public $records = [];
- /**
- * The schema for this fixture.
- *
- * @var \Cake\Database\Schema\TableSchema
- */
- protected $_schema;
- /**
- * Fixture constraints to be created.
- *
- * @var array
- */
- protected $_constraints = [];
- /**
- * Instantiate the fixture.
- *
- * @throws \Cake\Core\Exception\Exception on invalid datasource usage.
- */
- public function __construct()
- {
- if (!empty($this->connection)) {
- $connection = $this->connection;
- if (strpos($connection, 'test') !== 0) {
- $message = sprintf(
- 'Invalid datasource name "%s" for "%s" fixture. Fixture datasource names must begin with "test".',
- $connection,
- $this->table
- );
- throw new CakeException($message);
- }
- }
- $this->init();
- }
- /**
- * {@inheritDoc}
- */
- public function connection()
- {
- return $this->connection;
- }
- /**
- * {@inheritDoc}
- */
- public function sourceName()
- {
- return $this->table;
- }
- /**
- * Initialize the fixture.
- *
- * @return void
- * @throws \Cake\ORM\Exception\MissingTableClassException When importing from a table that does not exist.
- */
- public function init()
- {
- if ($this->table === null) {
- $this->table = $this->_tableFromClass();
- }
- if (empty($this->import) && !empty($this->fields)) {
- $this->_schemaFromFields();
- }
- if (!empty($this->import)) {
- $this->_schemaFromImport();
- }
- if (empty($this->import) && empty($this->fields)) {
- $this->_schemaFromReflection();
- }
- }
- /**
- * Returns the table name using the fixture class
- *
- * @return string
- */
- protected function _tableFromClass()
- {
- list(, $class) = namespaceSplit(get_class($this));
- preg_match('/^(.*)Fixture$/', $class, $matches);
- $table = $class;
- if (isset($matches[1])) {
- $table = $matches[1];
- }
- return Inflector::tableize($table);
- }
- /**
- * Build the fixtures table schema from the fields property.
- *
- * @return void
- */
- protected function _schemaFromFields()
- {
- $connection = ConnectionManager::get($this->connection());
- $this->_schema = new TableSchema($this->table);
- foreach ($this->fields as $field => $data) {
- if ($field === '_constraints' || $field === '_indexes' || $field === '_options') {
- continue;
- }
- $this->_schema->addColumn($field, $data);
- }
- if (!empty($this->fields['_constraints'])) {
- foreach ($this->fields['_constraints'] as $name => $data) {
- if (!$connection->supportsDynamicConstraints() || $data['type'] !== TableSchema::CONSTRAINT_FOREIGN) {
- $this->_schema->addConstraint($name, $data);
- } else {
- $this->_constraints[$name] = $data;
- }
- }
- }
- if (!empty($this->fields['_indexes'])) {
- foreach ($this->fields['_indexes'] as $name => $data) {
- $this->_schema->addIndex($name, $data);
- }
- }
- if (!empty($this->fields['_options'])) {
- $this->_schema->setOptions($this->fields['_options']);
- }
- }
- /**
- * Build fixture schema from a table in another datasource.
- *
- * @return void
- * @throws \Cake\Core\Exception\Exception when trying to import from an empty table.
- */
- protected function _schemaFromImport()
- {
- if (!is_array($this->import)) {
- return;
- }
- $import = $this->import + ['connection' => 'default', 'table' => null, 'model' => null];
- if (!empty($import['model'])) {
- if (!empty($import['table'])) {
- throw new CakeException('You cannot define both table and model.');
- }
- $import['table'] = TableRegistry::get($import['model'])->getTable();
- }
- if (empty($import['table'])) {
- throw new CakeException('Cannot import from undefined table.');
- }
- $this->table = $import['table'];
- $db = ConnectionManager::get($import['connection'], false);
- $schemaCollection = $db->schemaCollection();
- $table = $schemaCollection->describe($import['table']);
- $this->_schema = $table;
- }
- /**
- * Build fixture schema directly from the datasource
- *
- * @return void
- * @throws \Cake\Core\Exception\Exception when trying to reflect a table that does not exist
- */
- protected function _schemaFromReflection()
- {
- $db = ConnectionManager::get($this->connection());
- $schemaCollection = $db->schemaCollection();
- $tables = $schemaCollection->listTables();
- if (!in_array($this->table, $tables)) {
- throw new CakeException(
- sprintf(
- 'Cannot describe schema for table `%s` for fixture `%s` : the table does not exist.',
- $this->table,
- get_class($this)
- )
- );
- }
- $this->_schema = $schemaCollection->describe($this->table);
- }
- /**
- * Gets/Sets the TableSchema instance used by this fixture.
- *
- * @param \Cake\Database\Schema\TableSchema|null $schema The table to set.
- * @return \Cake\Database\Schema\TableSchema|null
- * @deprecated 3.5.0 Use getTableSchema/setTableSchema instead.
- */
- public function schema(TableSchema $schema = null)
- {
- deprecationWarning(
- 'TestFixture::schema() is deprecated. ' .
- 'Use TestFixture::setTableSchema()/getTableSchema() instead.'
- );
- if ($schema) {
- $this->setTableSchema($schema);
- }
- return $this->getTableSchema();
- }
- /**
- * {@inheritDoc}
- */
- public function create(ConnectionInterface $db)
- {
- if (empty($this->_schema)) {
- return false;
- }
- if (empty($this->import) && empty($this->fields)) {
- return true;
- }
- try {
- $queries = $this->_schema->createSql($db);
- foreach ($queries as $query) {
- $stmt = $db->prepare($query);
- $stmt->execute();
- $stmt->closeCursor();
- }
- } catch (Exception $e) {
- $msg = sprintf(
- 'Fixture creation for "%s" failed "%s"',
- $this->table,
- $e->getMessage()
- );
- Log::error($msg);
- trigger_error($msg, E_USER_WARNING);
- return false;
- }
- return true;
- }
- /**
- * {@inheritDoc}
- */
- public function drop(ConnectionInterface $db)
- {
- if (empty($this->_schema)) {
- return false;
- }
- if (empty($this->import) && empty($this->fields)) {
- return true;
- }
- try {
- $sql = $this->_schema->dropSql($db);
- foreach ($sql as $stmt) {
- $db->execute($stmt)->closeCursor();
- }
- } catch (Exception $e) {
- return false;
- }
- return true;
- }
- /**
- * {@inheritDoc}
- */
- public function insert(ConnectionInterface $db)
- {
- if (isset($this->records) && !empty($this->records)) {
- list($fields, $values, $types) = $this->_getRecords();
- $query = $db->newQuery()
- ->insert($fields, $types)
- ->into($this->table);
- foreach ($values as $row) {
- $query->values($row);
- }
- $statement = $query->execute();
- $statement->closeCursor();
- return $statement;
- }
- return true;
- }
- /**
- * {@inheritDoc}
- */
- public function createConstraints(ConnectionInterface $db)
- {
- if (empty($this->_constraints)) {
- return true;
- }
- foreach ($this->_constraints as $name => $data) {
- $this->_schema->addConstraint($name, $data);
- }
- $sql = $this->_schema->addConstraintSql($db);
- if (empty($sql)) {
- return true;
- }
- foreach ($sql as $stmt) {
- $db->execute($stmt)->closeCursor();
- }
- return true;
- }
- /**
- * {@inheritDoc}
- */
- public function dropConstraints(ConnectionInterface $db)
- {
- if (empty($this->_constraints)) {
- return true;
- }
- $sql = $this->_schema->dropConstraintSql($db);
- if (empty($sql)) {
- return true;
- }
- foreach ($sql as $stmt) {
- $db->execute($stmt)->closeCursor();
- }
- foreach ($this->_constraints as $name => $data) {
- $this->_schema->dropConstraint($name);
- }
- return true;
- }
- /**
- * Converts the internal records into data used to generate a query.
- *
- * @return array
- */
- protected function _getRecords()
- {
- $fields = $values = $types = [];
- $columns = $this->_schema->columns();
- foreach ($this->records as $record) {
- $fields = array_merge($fields, array_intersect(array_keys($record), $columns));
- }
- $fields = array_values(array_unique($fields));
- foreach ($fields as $field) {
- $types[$field] = $this->_schema->getColumn($field)['type'];
- }
- $default = array_fill_keys($fields, null);
- foreach ($this->records as $record) {
- $values[] = array_merge($default, $record);
- }
- return [$fields, $values, $types];
- }
- /**
- * {@inheritDoc}
- */
- public function truncate(ConnectionInterface $db)
- {
- $sql = $this->_schema->truncateSql($db);
- foreach ($sql as $stmt) {
- $db->execute($stmt)->closeCursor();
- }
- return true;
- }
- /**
- * {@inheritDoc}
- */
- public function getTableSchema()
- {
- return $this->_schema;
- }
- /**
- * {@inheritDoc}
- */
- public function setTableSchema(DatabaseTableSchemaInterface $schema)
- {
- $this->_schema = $schema;
- return $this;
- }
- }
|