Browse Source

Add isRequired() to Form\Schema

This new method will make implementing a FormHelper context simpler.
Mark Story 11 years ago
parent
commit
97fe033a76
2 changed files with 34 additions and 0 deletions
  1. 16 0
      src/Form/Schema.php
  2. 18 0
      tests/TestCase/Form/SchemaTest.php

+ 16 - 0
src/Form/Schema.php

@@ -100,4 +100,20 @@ class Schema {
 		return $this->_fields[$name];
 	}
 
+/**
+ * Check whether or not a field is required.
+ *
+ * Fields that are not defined in the schema are not required.
+ *
+ * @param string $name The name of the field.
+ * @return bool Whether or not a field is required.
+ */
+	public function isRequired($name) {
+		$field = $this->field($name);
+		if (!$field) {
+			return false;
+		}
+		return (bool) $field['required'];
+	}
+
 }

+ 18 - 0
tests/TestCase/Form/SchemaTest.php

@@ -93,4 +93,22 @@ class SchemaTest extends TestCase {
 		$this->assertNull($schema->field('name'));
 	}
 
+/**
+ * test isRequired
+ *
+ * @return void
+ */
+	public function testIsRequired() {
+		$schema = new Schema();
+
+		$schema->addField('name', ['type' => 'string'])
+			->addField('email', [
+				'type' => 'string',
+				'required' => true
+			]);
+		$this->assertFalse($schema->isRequired('name'));
+		$this->assertTrue($schema->isRequired('email'));
+		$this->assertFalse($schema->isRequired('nope'));
+	}
+
 }