Skip to content

Instantly share code, notes, and snippets.

@nojimage
Last active May 17, 2019 03:54
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 nojimage/508bf153d57f4bae9d39242207920ff3 to your computer and use it in GitHub Desktop.
Save nojimage/508bf153d57f4bae9d39242207920ff3 to your computer and use it in GitHub Desktop.
CakePHP 3 TextFixture for many records
<?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();
}
@nojimage
Copy link
Author

継承したクラスでの recordGenerator の実装はこんな感じ

    /**
     * @return \Generator
     */
    protected function recordGenerator()
    {
       for ($i = 0; $i < static::$numOfRecords; $i++) {
            $id = $i + 1;
            $record = [
                'id' => $id,
                'title' => sprintf('title_%06d', $id),
                'content' => sprintf('content_%06d', $id),
            ];

            yield $i => $record;
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment