Skip to content

Commit

Permalink
Add documentation for Schema.
Browse files Browse the repository at this point in the history
Also add the ability to provide only the field type as a string.
  • Loading branch information
markstory committed Dec 14, 2014
1 parent db1681f commit 8132247
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/Form/Schema.php
Expand Up @@ -19,33 +19,72 @@
*/
class Schema {

/**
* The fields in this schema.
*
* @var array
*/
protected $_fields = [];

/**
* The default values for fields.
*
* @var array
*/
protected $_fieldDefaults = [
'type' => null,
'length' => null,
'required' => false,
];

/**
* Adds a field to the schema.
*
* @param string $name The field name.
* @param string|array $attrs The attributes for the field, or the type
* as a string.
* @return $this
*/
public function addField($name, $attrs) {
if (is_string($attrs)) {
$attrs = ['type' => $attrs];
}
$attrs = array_intersect_key($attrs, $this->_fieldDefaults);
$this->_fields[$name] = $attrs + $this->_fieldDefaults;
return $this;
}

/**
* Removes a field to the schema.
*
* @param string $name The field to remove.
* @return $this
*/
public function removeField($name) {
unset($this->_fields[$name]);
return $this;
}

/**
* Get the list of fields in the schema.
*
* @return array The list of field names.
*/
public function fields() {
return array_keys($this->_fields);
}

/**
* Get the attributes for a given field.
*
* @param string $name The field name.
* @return null|array The attributes for a field, or null.
*/
public function field($name) {
if (!isset($this->_fields[$name])) {
return null;
}
return $this->_fields[$name];
}

}
8 changes: 8 additions & 0 deletions tests/TestCase/Form/SchemaTest.php
Expand Up @@ -37,6 +37,14 @@ public function testAddingFields() {
$res = $schema->field('name');
$expected = ['type' => 'string', 'length' => null, 'required' => false];
$this->assertEquals($expected, $res);

$res = $schema->addField('email', 'string');
$this->assertSame($schema, $res, 'Should be chainable');

$this->assertEquals(['name', 'email'], $schema->fields());
$res = $schema->field('email');
$expected = ['type' => 'string', 'length' => null, 'required' => false];
$this->assertEquals($expected, $res);
}

/**
Expand Down

0 comments on commit 8132247

Please sign in to comment.