Last active
May 13, 2018 00:15
-
-
Save cmbuckley/cb15828f02965721a31be025db4d0d0b to your computer and use it in GitHub Desktop.
Emit WordPress comments as YML
This file contains 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 | |
$file = $argv[1]; | |
$header = null; | |
$spec = array( | |
'_id' => function ($data) { | |
return intval($data['comment_ID']); | |
}, | |
'name' => 'comment_author', | |
'email' => function ($data) { | |
return (empty($data['comment_author_email']) ? '' : md5($data['comment_author_email'])); | |
}, | |
'comment' => function ($data) { | |
return trim($data['comment_content']); | |
}, | |
'date' => function ($data) { | |
return strtotime($data['comment_date_gmt'] . ' UTC'); | |
}, | |
); | |
if ($fh = fopen($file, 'r')) { | |
while ($data = fgetcsv($fh)) { | |
if ($header) { | |
// convert data to YAML | |
$comment = array_combine($header, array_slice($data, 0, count($header))); | |
$yaml = substr(yaml_emit(map($comment, $spec), YAML_UTF8_ENCODING), 4, -4); | |
// create directory | |
$dir = $argv[3] . '/' . slug($comment['comment_post_ID'], $argv[2]); | |
echo "Creating directory $dir\n"; | |
if (!file_exists($dir)) { mkdir($dir); } | |
echo "Creating comment $dir/${comment['comment_ID']}.yml\n\n"; | |
file_put_contents("$dir/" . $comment['comment_ID'] . '.yml', $yaml); | |
} | |
else { | |
$header = $data; | |
} | |
} | |
} | |
function map($data, $spec) { | |
$return = array(); | |
foreach ($spec as $field => $value) { | |
$return[$field] = (is_callable($value) ? $value($data) : $data[$value]); | |
} | |
return array_filter($return); | |
} | |
function slug($id, $site, $pattern = '~^/blog/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[^/]+)/$~') { | |
echo "Getting URL for $site?p=$id\n"; | |
$ch = curl_init($site . "?p=$id"); | |
curl_exec($ch); | |
$url = curl_getinfo($ch, CURLINFO_REDIRECT_URL); | |
curl_close($ch); | |
echo "Got URL $url\n"; | |
if (preg_match($pattern, str_replace($site, '', $url), $matches)) { | |
return $matches['year'] . '-' . $matches['month'] . '-' . $matches['day'] . '-' . $matches['slug']; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Takes a CSV as created by WordPress Comments Import & Export and outputs into separate YAML files to match Pull Requests created by Staticman.