Browse Source

Implement EntityContext::type()

mark_story 12 years ago
parent
commit
9f5555ad12
2 changed files with 76 additions and 0 deletions
  1. 15 0
      src/View/Form/EntityContext.php
  2. 61 0
      tests/TestCase/View/Form/EntityContextTest.php

+ 15 - 0
src/View/Form/EntityContext.php

@@ -250,7 +250,22 @@ class EntityContext {
 		return $target;
 	}
 
+/**
+ * Get the abstract field type for a given field name.
+ *
+ * @param string $field A dot separated path to get a schema type for.
+ * @return null|string An abstract data type or null.
+ * @see Cake\Database\Type
+ */
 	public function type($field) {
+		$parts = explode('.', $field);
+		list($entity, $prop) = $this->_getEntity($parts);
+		if (!$entity) {
+			return null;
+		}
+		$table = $this->_getTable($prop);
+		$column = array_pop($parts);
+		return $table->schema()->columnType($column);
 	}
 
 	public function attributes($field) {

+ 61 - 0
tests/TestCase/View/Form/EntityContextTest.php

@@ -281,4 +281,65 @@ class EntityContextTest extends TestCase {
 		$this->assertFalse($context->isRequired('user.first_name'));
 	}
 
+/**
+ * Test type() basic
+ *
+ * @return void
+ */
+	public function testType() {
+		$articles = TableRegistry::get('Articles');
+		$articles->schema([
+			'title' => ['type' => 'string'],
+			'body' => ['type' => 'text'],
+			'user_id' => ['type' => 'integer']
+		]);
+
+		$row = new Entity([
+			'title' => 'My title',
+			'body' => 'Some content',
+		]);
+		$context = new EntityContext($this->request, [
+			'entity' => $row,
+			'table' => 'Articles',
+		]);
+
+		$this->assertEquals('string', $context->type('title'));
+		$this->assertEquals('text', $context->type('body'));
+		$this->assertEquals('integer', $context->type('user_id'));
+		$this->assertNull($context->type('nope'));
+	}
+
+/**
+ * Test getting types for associated records.
+ *
+ * @return void
+ */
+	public function testTypeAssociated() {
+		$articles = TableRegistry::get('Articles');
+		$articles->belongsTo('Users');
+		$users = TableRegistry::get('Users');
+
+		$articles->schema([
+			'title' => ['type' => 'string'],
+			'body' => ['type' => 'text']
+		]);
+		$users->schema([
+			'username' => ['type' => 'string'],
+			'bio' => ['type' => 'text']
+		]);
+
+		$row = new Entity([
+			'title' => 'My title',
+			'user' => new Entity(['username' => 'Mark']),
+		]);
+		$context = new EntityContext($this->request, [
+			'entity' => $row,
+			'table' => 'Articles',
+		]);
+
+		$this->assertEquals('string', $context->type('user.username'));
+		$this->assertEquals('text', $context->type('user.bio'));
+		$this->assertNull($context->type('user.nope'));
+	}
+
 }