Skip to content

Commit

Permalink
MySQLImport: passes percent to onProgress
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed May 24, 2017
1 parent afd2788 commit 8970328
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
9 changes: 9 additions & 0 deletions examples/importFromFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@
$time = -microtime(TRUE);

$import = new MySQLImport(new mysqli('localhost', 'root', 'password', 'database'));

$import->onProgress = function ($count, $percent) {
if ($percent !== NULL) {
echo (int) $percent . " %\r";
} elseif ($count % 10 === 0) {
echo '.';
}
};

$import->load('dump.sql.gz');

$time += microtime(TRUE);
Expand Down
12 changes: 9 additions & 3 deletions src/MySQLImport.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
*/
class MySQLImport
{
/** @var callable */
/** @var callable function (int $count, ?float $percent): void */
public $onProgress;

/** @var mysqli */
Expand Down Expand Up @@ -60,12 +60,15 @@ public function read($handle)
throw new Exception('Argument must be stream resource.');
}

$stat = fstat($handle);

$sql = '';
$delimiter = ';';
$count = 0;
$count = $size = 0;

while (!feof($handle)) {
$s = fgets($handle);
$size += strlen($s);
if (strtoupper(substr($s, 0, 10)) === 'DELIMITER ') {
$delimiter = trim(substr($s, 10));

Expand All @@ -77,7 +80,7 @@ public function read($handle)
$sql = '';
$count++;
if ($this->onProgress) {
call_user_func($this->onProgress, $count);
call_user_func($this->onProgress, $count, isset($stat['size']) ? $size * 100 / $stat['size'] : NULL);
}

} else {
Expand All @@ -90,6 +93,9 @@ public function read($handle)
if (!$this->connection->query($sql)) {
throw new Exception($this->connection->error);
}
if ($this->onProgress) {
call_user_func($this->onProgress, $count, isset($stat['size']) ? 100 : NULL);
}
}

return $count;
Expand Down

0 comments on commit 8970328

Please sign in to comment.