ソースを参照

Add Table::defaultValues()

This makes it easy to get the default values from a schema table. Having
this is really useful when you want to make an entity with the default
values from the database.

Refs #4398
mark_story 11 年 前
コミット
92627d1a46
2 ファイル変更40 行追加1 行削除
  1. 15 0
      src/Database/Schema/Table.php
  2. 25 1
      tests/TestCase/Database/Schema/TableTest.php

+ 15 - 0
src/Database/Schema/Table.php

@@ -335,6 +335,21 @@ class Table {
 	}
 
 /**
+ * Get a hash of columns and their default values.
+ *
+ * @return array
+ */
+	public function defaultValues() {
+		$defaults = [];
+		foreach ($this->_columns as $name => $data) {
+			if (isset($data['default'])) {
+				$defaults[$name] = $data['default'];
+			}
+		}
+		return $defaults;
+	}
+
+/**
  * Add an index.
  *
  * Used to add indexes, and full text indexes in platforms that support

+ 25 - 1
tests/TestCase/Database/Schema/TableTest.php

@@ -150,10 +150,34 @@ class TableTest extends TestCase {
 	}
 
 /**
- * Test adding an constraint.
+ * Test reading default values.
  *
  * @return void
  */
+	public function testDefaultValues() {
+		$table = new Table('articles');
+		$table->addColumn('id', [
+			'type' => 'integer',
+			'default' => 0
+		])->addColumn('title', [
+			'type' => 'string',
+			'default' => 'A title'
+		])->addColumn('body', [
+			'type' => 'text',
+		]);
+		$result = $table->defaultValues();
+		$expected = [
+			'id' => 0,
+			'title' => 'A title'
+		];
+		$this->assertEquals($expected, $result);
+	}
+
+/**
+ * Test adding an constraint.
+ *>
+ * @return void
+ */
 	public function testAddConstraint() {
 		$table = new Table('articles');
 		$table->addColumn('id', [