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

Use an abstract method instead of a bunch of ifs #3

Closed
Closed
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
16 changes: 1 addition & 15 deletions src/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,21 +35,7 @@ public function parse(string $filename, Schema $schema, bool $ignoreFirstLine =
$line = str_getcsv($line);

foreach ($schema->columnDefinitions() as $column => $definition) {
$value = $line[$column - 1];

if ($definition->type()->isBoolean()) {
$value = (bool) $value;
}

if ($definition->type()->isInteger()) {
$value = (int) $value;
}

if ($definition->type()->isFloat()) {
$value = (float) $value;
}

$data[$definition->name()] = $value;
$data[$definition->name()] = $definition->type()->cast($line[$column - 1] ?? '');
}

yield $data;
Expand Down
5 changes: 5 additions & 0 deletions src/schema/type/BooleanType.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,9 @@ public function isBoolean(): bool
{
return true;
}

public function cast(string $value): bool
{
return (bool) $value;
}
}
5 changes: 5 additions & 0 deletions src/schema/type/FloatType.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,9 @@ public function isFloat(): bool
{
return true;
}

public function cast(string $value): float
{
return (float) $value;
}
}
5 changes: 5 additions & 0 deletions src/schema/type/IntegerType.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,9 @@ public function isInteger(): bool
{
return true;
}

public function cast(string $value): int
{
return (int) $value;
}
}
5 changes: 5 additions & 0 deletions src/schema/type/StringType.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,9 @@ public function isString(): bool
{
return true;
}

public function cast(string $value): string
{
return $value;
}
}
2 changes: 2 additions & 0 deletions src/schema/type/Type.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,6 @@ public function isString(): bool
{
return false;
}

abstract public function cast(string $value): mixed;
}