Created
June 27, 2018 07:33
-
-
Save tamakiii/0f44db297a2c910ecbab422d599cbdef to your computer and use it in GitHub Desktop.
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 | |
/** | |
$ cat composer.json | |
{ | |
"require": { | |
"symfony/yaml": "^3.2" | |
} | |
} | |
$ php composer.phar install | |
*/ | |
include __DIR__ . '/vendor/autoload.php'; | |
use Symfony\Component\Yaml\Yaml; | |
function ignore($row) { | |
if (strlen($row) === 0) { | |
return true; | |
} | |
if (preg_match('/^mysql>/', $row)) { | |
return true; | |
} | |
if (preg_match('/\d+ rows in set/', $row)) { | |
return true; | |
} | |
return false; | |
} | |
function isNewRow($row, $matches = null) { | |
if (preg_match('/^\*+ (\d+)\. row \*+$/', $row, $matches)) { | |
if (!isset($matches[1])) { | |
throw new \UnexpectedValueException('Could not get row number'); | |
} | |
if (!is_numeric($matches[1])) { | |
throw new \UnexpectedValueException('Not numeric...'); | |
} | |
return (int)$matches[1]; | |
} | |
return false; | |
} | |
function parseKeyValue($row) { | |
$result = explode(':', $row, 2); | |
if (count($result) !== 2) { | |
throw new \UnexpectedValueException('Failed to parse key-value'); | |
} | |
return [ | |
trim($result[0]), | |
trim($result[1]), | |
]; | |
} | |
$input = file_get_contents('php://stdin'); | |
$results = []; | |
$current = null; | |
foreach (explode(PHP_EOL, $input) as $row) { | |
if (ignore($row)) { | |
continue; | |
} | |
if ($number = isNewRow($row)) { | |
if (isset($results[$number])) { | |
throw new \UnexpectedValueException("Number $number is already exists"); | |
} | |
$current = $number; | |
$results[$current] = []; | |
continue; | |
} | |
list($key, $value) = parseKeyValue($row); | |
$results[$current][$key] = $value; | |
} | |
echo Yaml::dump($results); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment