Skip to content

Commit

Permalink
added Schema::infer
Browse files Browse the repository at this point in the history
  • Loading branch information
OriHoch committed Nov 30, 2017
1 parent 917e4fc commit 3748750
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,13 @@ validate the row to get a list of errors
$schema->validateRow(["id" => "foobar"]); // ["id is not numeric", "name is required" .. ]
```

Infer schema based on source data:

```php
$schema = Schema::infer("tests/fixtures/data.csv");
$table->schema()->fields(); // ["first_name" => StringField, "last_name" => StringField, "order" => IntegerField]
```

You can also create a new empty schema for editing

```php
Expand Down
7 changes: 7 additions & 0 deletions src/Schema.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@ public static function validate($descriptor)
}
}

public static function infer($dataSource, $csvDialect = null, $limit = null)
{
$table = new Table($dataSource, null, $csvDialect);

return $table->schema($limit ? $limit : 100);
}

/**
* @return object
*/
Expand Down
29 changes: 29 additions & 0 deletions tests/SchemaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,35 @@ public function testSpecsUriFormat()
]], $validator->getErrors());
}

public function testSchemaInfer()
{
$schema = Schema::infer('tests/fixtures/data.csv');
$this->assertEquals((object) [
'fields' => [
(object) ['name' => 'first_name', 'type' => 'string'],
(object) ['name' => 'last_name', 'type' => 'string'],
(object) ['name' => 'order', 'type' => 'integer'],
],
], $schema->descriptor());
}

public function testSchemaInferCsvDialect()
{
$schema = Schema::infer('tests/fixtures/data.lolsv', [
'delimiter' => 'o',
'quoteChar' => 'L',
'header' => true,
'caseSensitiveHeader' => false,
]);
$this->assertEquals((object) [
'fields' => [
(object) ['name' => 'first_name', 'type' => 'string'],
(object) ['name' => 'last_name', 'type' => 'string'],
(object) ['name' => 'order', 'type' => 'integer'],
],
], $schema->descriptor());
}

public function tearDown()
{
foreach ($this->tempFiles as $tempFile) {
Expand Down

0 comments on commit 3748750

Please sign in to comment.