Last active
May 17, 2019 03:54
-
-
Save nojimage/508bf153d57f4bae9d39242207920ff3 to your computer and use it in GitHub Desktop.
CakePHP 3 TextFixture for many records
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\TestSuite\Fixture; | |
use Cake\Datasource\ConnectionInterface; | |
use Cake\TestSuite\Fixture\TestFixture; | |
/** | |
* ChunkInsertTestFixture | |
*/ | |
abstract class ChunkInsertTestFixture extends TestFixture | |
{ | |
/** | |
* Insert records per this chunk size | |
* | |
* @var int | |
*/ | |
protected static $insertChunkSize = 1000; | |
/** | |
* {@inheritDoc} | |
*/ | |
public function insert(ConnectionInterface $db) | |
{ | |
$generator = $this->recordGenerator(); | |
foreach ($this->chunkRecords($generator, static::$insertChunkSize) as $records) { | |
$this->records = $records; | |
if (!parent::insert($db)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
/** | |
* Divide the records per chunk size | |
* | |
* @param \Iterator $generator the insert records generator|iterator. | |
* @param int $size a chunk size. | |
* @return \Generator | |
*/ | |
private function chunkRecords(\Iterator $generator, $size) | |
{ | |
$records = []; | |
while ($generator->valid()) { | |
for ($c = 0; $c < $size && $generator->valid(); $c++, $generator->next()) { | |
$records[$generator->key()] = $generator->current(); | |
} | |
if (count($records) > 0) { | |
yield $records; | |
} | |
$records = []; | |
} | |
} | |
/** | |
* generate records | |
* | |
* @return \Generator|\Iterator | |
*/ | |
abstract protected function recordGenerator(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
継承したクラスでの recordGenerator の実装はこんな感じ