Automattic / newspack-custom-content-migrator

Custom migration tasks for launching and migrating Newspack sites on Atomic
5 stars 5 forks source link

Add a CSV file iterator that uses the BatchLogic #388

Closed naxoc closed 9 months ago

naxoc commented 10 months ago

This adds a CSV iterator a lot like the JsonIterator we already have. It uses BatchLogic args so it should be easy to use without having to do math.

How to test

Test that all lines are read correctly passing in nothing, --start=x and/or --end=x. Use a .csv file something like this:

        $csv_file_path = $assoc_args[ $this->csv_input_file['name'] ];
        $batch_args = $this->csv_iterator->validate_and_get_batch_args_for_file( $csv_file_path, $assoc_args, ',' );
        $counter    = 0;
        foreach ( $this->csv_iterator->batched_items( $csv_file_path, ',', $batch_args['start'], $batch_args['end'] ) as $row ) {
}

To use the BatchLogic, register a command something like this:

    private array $csv_input_file = [
        'type'        => 'assoc',
        'name'        => 'csv-input-file',
        'description' => 'Path to CSV input file.',
        'optional'    => false,
    ];

    public function register_commands(): void {
        WP_CLI::add_command(
            'newspack-content-migrator my-test-thing',
            [ $this, 'cmd_test-thing' ],
            [
                'shortdesc' => 'Test the thing!.',
                'synopsis'  => [
                    $this->csv_input_file,
                    ...BatchLogic::get_batch_args(),
                ],
            ]
        );
    }