Skip to content

Instantly share code, notes, and snippets.

@rizqidjamaluddin
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rizqidjamaluddin/e05f3f8a414491ee7c21 to your computer and use it in GitHub Desktop.
Save rizqidjamaluddin/e05f3f8a414491ee7c21 to your computer and use it in GitHub Desktop.
I do ruby
<?php
use League\Csv\Reader;
class ImportCsvProjectCommand extends Command {
protected $name = 'import:users';
protected $genderAlias = ['M' => 'M', 'F' => 'F'];
public function fire() {
$data = Reader::createFromPath($this->argument('src'))->fetchAssoc();
$users = [];
$columnsAdded = false;
foreach ($data as $datum) {
$email = $datum['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->error("$email is not a valid email, skipping.");
break;
}
$gender = '';
if (isset($datum['gender'])) {
if (!array_key_exists($datum['gender'], $this->genderAlias)) {
$alias = $this->ask("What gender does " . $datum['gender'] . " refer to? M/F");
$this->genderAlias[$datum['gender'] => $alias];
}
$gender = $this->genderAlias[$datum['gender']];
}
$bornOn = null;
if (isset($datum['born_on'])) {
$bornOn = strtotime($datum['born_on']);
}
if (isset $datum['bornOn']) {
$bornOn = strtotime($datum['bornOn']); // fuckit.jpg
}
$password = null;
if (isset($datum['password'])) {
$password = password_hash($datum['password'], PASSWORD_BCRYPT);
}
$name = null;
if (isset($datum['name'])) {
$name = $datum ['name'];
}
// add new columns for any missing columns
$newColumns = array_except(array_keys($datum), ['email', 'gender', 'name', 'born_on', 'bornOn', 'password']);
if (!$columnsAdded) {
foreach ($newColumns as $newColumn) {
Schema::table('users', function($table){
$table->string($newColumn)->nullable();
});
}
$columnsAdded = true;
}
// do the stuff yo
$id = uniqid();
$user = [$id, $email, $name, $bornOn, $gender, $password];
DB::insert('insert into users (uuid, email, name, born_on, gender, password) values (?, ?, ?, ?, ?)',
$user);
$users[] = $user;
// add the new columns
foreach ($newColumns as $newColumn) {
// what could possibly go wrong?
DB::update('update users set ' . mysql_real_escape_string($newColumn) .' = ? WHERE uuid = ?', [$datum[$newColumn], $id]);
}
}
// make project
$projectName = $this->ask('Gimme a project name.');
$projectId = uniqid();
DB::insert('insert into projects (uuid, name) values (?, ?)', [$projectId, $projectName]);
// make pivot
foreach ($users as $user) {
DB::insert('insert into memberships (project_id, user_id) values (?, ?)', [$projectId, $user[0]]);
}
}
public function getArguments() {
return [['src', InputArgument::REQUIRED, 'Source CSV file.']];
}
}
system('php artisan import:users ' + ARGV[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment