Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the ability to specify the field length to the bake command #140

Merged
merged 1 commit into from
Oct 14, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,12 +211,14 @@ name you are specifying.

Fields are verified via the following the following regular expression:

/^(\w*)(?::(\w*))?(?::(\w*))?(?::(\w*))?/
/^(\w*)(?::(\w*\[?\d*\]?))?(?::(\w*))?(?::(\w*))?/

They follow the format:

field:fieldType:indexType:indexName
field:fieldType[length]:indexType:indexName

The length parameter for the ``fieldType`` is optionnal and should always be
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extra n on optional here ;)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed with a432326

Thanks @josegonzalez

written between bracket.
For instance, the following are all valid ways of specifying the primary key `id`:

- `id:primary_key`
Expand All @@ -232,7 +234,11 @@ There are some heuristics to choosing fieldtypes when left unspecified or set to
- `created`, `modified`, `updated`: *datetime*
- Default *string*

Lengths for certain columns are also defaulted:
You can specify the wanted length for a field type by writing it between bracket:

username:string[128]

If no length is specified, lengths for certain columns are defaulted:

- *string*: `255`
- *integer*: `11`
Expand Down
57 changes: 46 additions & 11 deletions src/Util/ColumnParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,20 @@
class ColumnParser
{

/**
* Regex used to parse the column definition passed through the shell
*
* @var string
*/
protected $regexpParseColumn = '/^(\w*)(?::(\w*\[?\d*\]?))?(?::(\w*))?(?::(\w*))?/';

/**
* Regex used to parse the field type and length
*
* @var string
*/
protected $regexpParseField = '/(\w+)\[(\d+)\]/';

/**
* Parses a list of arguments into an array of fields
*
Expand All @@ -22,7 +36,7 @@ public function parseFields($arguments)
$fields = [];
$arguments = $this->validArguments($arguments);
foreach ($arguments as $field) {
preg_match('/^(\w*)(?::(\w*))?(?::(\w*))?(?::(\w*))?/', $field, $matches);
preg_match($this->regexpParseColumn, $field, $matches);
$field = $matches[1];
$type = Hash::get($matches, 2);
$indexType = Hash::get($matches, 3);
Expand All @@ -37,8 +51,7 @@ public function parseFields($arguments)
}
}

$type = $this->getType($field, $type);
$length = $this->getLength($type);
list($type, $length) = $this->getTypeAndLength($field, $type);
$fields[$field] = [
'columnType' => $type,
'options' => [
Expand Down Expand Up @@ -70,7 +83,7 @@ public function parseIndexes($arguments)
$indexes = [];
$arguments = $this->validArguments($arguments);
foreach ($arguments as $field) {
preg_match('/^(\w*)(?::(\w*))?(?::(\w*))?(?::(\w*))?/', $field, $matches);
preg_match($this->regexpParseColumn, $field, $matches);
$field = $matches[1];
$type = Hash::get($matches, 2);
$indexType = Hash::get($matches, 3);
Expand Down Expand Up @@ -117,7 +130,7 @@ public function parsePrimaryKey($arguments)
$primaryKey = [];
$arguments = $this->validArguments($arguments);
foreach ($arguments as $field) {
preg_match('/^(\w*)(?::(\w*))?(?::(\w*))?(?::(\w*))?/', $field, $matches);
preg_match($this->regexpParseColumn, $field, $matches);
$field = $matches[1];
$type = Hash::get($matches, 2);
$indexType = Hash::get($matches, 3);
Expand All @@ -141,10 +154,30 @@ public function validArguments($arguments)
$collection = new Collection($arguments);
return $collection->filter(function ($value, $field) {
$value;
return preg_match('/^(\w*)(?::(\w*))?(?::(\w*))?(?::(\w*))?/', $field);
return preg_match($this->regexpParseColumn, $field);
})->toArray();
}

/**
* Get the type and length of a field based on the field and the type passed
*
* @param string $field Name of field
* @param string $type User-specified type
* @return array First value is the field type, second value is the field length. If no length
* can be extracted, null is returned for the second value
*/
public function getTypeAndLength($field, $type)
{
if (preg_match($this->regexpParseField, $type, $matches)) {
return [$matches[1], $matches[2]];
}

$fieldType = $this->getType($field, $type);
$length = $this->getLength($fieldType);

return [$fieldType, $length];
}

/**
* Retrieves a type that should be used for a specific field
*
Expand All @@ -156,24 +189,26 @@ public function getType($field, $type)
{
$reflector = new ReflectionClass('Phinx\Db\Adapter\AdapterInterface');
$collection = new Collection($reflector->getConstants());

$validTypes = $collection->filter(function ($value, $constant) {
$value;
return substr($constant, 0, strlen('PHINX_TYPE_')) === 'PHINX_TYPE_';
})->toArray();

$fieldType = $type;
if ($type === null || !in_array($type, $validTypes)) {
if ($type == 'primary') {
$type = 'integer';
$fieldType = 'integer';
} elseif ($field == 'id') {
$type = 'integer';
$fieldType = 'integer';
} elseif (in_array($field, ['created', 'modified', 'updated'])) {
$type = 'datetime';
$fieldType = 'datetime';
} else {
$type = 'string';
$fieldType = 'string';
}
}

return $type;
return $fieldType;
}

/**
Expand Down
8 changes: 8 additions & 0 deletions tests/TestCase/Shell/Task/MigrationTaskTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,14 @@ public function testCreate()
];
$result = $this->Task->bake('CreateUsers');
$this->assertSameAsFile(__FUNCTION__ . 'PrimaryKeyUuid.php', $result);

$this->Task->args = [
'create_users',
'name:string[128]',
'counter:integer[8]'
];
$result = $this->Task->bake('CreateUsers');
$this->assertSameAsFile(__FUNCTION__ . 'FieldLength.php', $result);
}

/**
Expand Down
27 changes: 27 additions & 0 deletions tests/TestCase/Util/ColumnParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,18 @@ public function testValidArguments()
['field:fieldType:indexType:indexName'],
$this->columnParser->validArguments(['field:fieldType:indexType:indexName'])
);
$this->assertEquals(
['field:fieldType[128]:indexType:indexName'],
$this->columnParser->validArguments(['field:fieldType[128]:indexType:indexName'])
);
$this->assertEquals(
['field:integer[9]:indexType:indexName'],
$this->columnParser->validArguments(['field:integer[9]:indexType:indexName'])
);
$this->assertEquals(
['field:biginteger[18]:indexType:indexName'],
$this->columnParser->validArguments(['field:biginteger[18]:indexType:indexName'])
);
}

/**
Expand All @@ -208,6 +220,21 @@ public function testGetType()
$this->assertEquals('polygon', $this->columnParser->getType('field', 'polygon'));
}

/**
* @covers Migrations\Util\ColumnParser::getTypeAndLength
*/
public function testGetTypeAndLength()
{
$this->assertEquals(['string', 255], $this->columnParser->getTypeAndLength('name', 'string'));
$this->assertEquals(['integer', 11], $this->columnParser->getTypeAndLength('counter', 'integer'));
$this->assertEquals(['string', 128], $this->columnParser->getTypeAndLength('name', 'string[128]'));
$this->assertEquals(['integer', 9], $this->columnParser->getTypeAndLength('counter', 'integer[9]'));
$this->assertEquals(['biginteger', 18], $this->columnParser->getTypeAndLength('bigcounter', 'biginteger[18]'));
$this->assertEquals(['integer', 11], $this->columnParser->getTypeAndLength('id', null));
$this->assertEquals(['string', 255], $this->columnParser->getTypeAndLength('username', null));
$this->assertEquals(['datetime', null], $this->columnParser->getTypeAndLength('created', null));
}

/**
* @covers Migrations\Util\ColumnParser::getLength
*/
Expand Down
28 changes: 28 additions & 0 deletions tests/comparisons/Migration/testCreateFieldLength.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php
use Migrations\AbstractMigration;

class CreateUsers extends AbstractMigration
{
/**
* Change Method.
*
* More information on this method is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-change-method
* @return void
*/
public function change()
{
$table = $this->table('users');
$table->addColumn('name', 'string', [
'default' => null,
'limit' => 128,
'null' => false,
]);
$table->addColumn('counter', 'integer', [
'default' => null,
'limit' => 8,
'null' => false,
]);
$table->create();
}
}