Skip to content

Instantly share code, notes, and snippets.

@gedex
Created December 7, 2020 13:46
Show Gist options
  • Save gedex/2875172955e14ad54010bb49ec72095a to your computer and use it in GitHub Desktop.
Save gedex/2875172955e14ad54010bb49ec72095a to your computer and use it in GitHub Desktop.
#!/usr/bin/env php
<?php
function err(string $message) {
print( $message );
exit(1);
}
function usage() {
global $argv;
err( sprintf( 'Usage: %s <log-file> <csv-output>', $argv[0] ) );
}
function main() {
global $argv;
if ( sizeof( $argv ) !== 3 ) {
usage();
}
$migrated_orders = parse_log( $argv[1] );
write_to_csv( $migrated_orders, $argv[2] );
}
function write_to_csv( array $migrated_orders, string $dst ) {
$handle = fopen( $dst, 'w' );
if ( ! $handle ) {
err( sprintf( 'Failed to open %s', $dst ) );
}
// Header.
fputcsv( $handle, [ 'Order ID', 'Edit', 'Result', 'Reason' ] );
foreach ( $migrated_orders as $order ) {
fputcsv( $handle, $order );
}
fclose( $handle );
}
function parse_log( string $filename ) {
$handle = @fopen( $filename, 'r' );
if ( ! $handle ) {
err( sprintf( 'Failed to open %s', $argv[1] ) );
}
$parsed = [];
$line = fgets( $handle );
while ( false !== $line ) {
$parsed_line = parse_line( $line );
if ( ! empty( $parsed_line ) && ( ! isset( $parsed[ $parsed_line[0] ] ) || 1 === $parsed_line[2] ) ) {
$parsed[ $parsed_line[0] ] = $parsed_line;
}
$line = fgets( $handle );
}
fclose( $handle );
return $parsed;
}
function parse_line( string $line ) {
$prefix = substr( $line, 0, 8 );
switch ( $prefix ) {
case 'Warning:':
return parse_warning_line( $line );
case 'Success:':
return parse_success_line( $line );
}
return [];
}
function parse_success_line( string $line ) {
if ( ! preg_match( '/^Success: order (?P<order_id>\d+) success/', $line, $matches ) ) {
return [];
}
return [
$matches['order_id'],
sprintf( 'https://woocommerce.com/wp-admin/post.php?post=%s&action=edit', $matches['order_id'] ),
1,
'',
];
}
function parse_warning_line( string $line ) {
if ( ! preg_match( '/^Warning: failed to migrate order #(?P<order_id>\d+): (?P<reason>.*)/', $line, $matches ) ) {
return [];
}
return [
$matches['order_id'],
sprintf( 'https://woocommerce.com/wp-admin/post.php?post=%s&action=edit', $matches['order_id'] ),
0,
$matches['reason'],
];
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment