From 92627d1a46c7f6c6cb1fb92f92217d35de55cb78 Mon Sep 17 00:00:00 2001 From: mark_story Date: Sun, 31 Aug 2014 08:04:18 -0400 Subject: [PATCH] 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 --- src/Database/Schema/Table.php | 15 +++++++++++ tests/TestCase/Database/Schema/TableTest.php | 26 +++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/Database/Schema/Table.php b/src/Database/Schema/Table.php index ff13abf23b0..6ead9af11ed 100644 --- a/src/Database/Schema/Table.php +++ b/src/Database/Schema/Table.php @@ -334,6 +334,21 @@ public function columnType($name, $type = null) { return $this->_columns[$name]['type']; } +/** + * 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. * diff --git a/tests/TestCase/Database/Schema/TableTest.php b/tests/TestCase/Database/Schema/TableTest.php index 3faafcd59a4..7f69bc03e52 100644 --- a/tests/TestCase/Database/Schema/TableTest.php +++ b/tests/TestCase/Database/Schema/TableTest.php @@ -150,9 +150,33 @@ public function testAddColumnFiltersAttributes() { } /** - * 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');