Skip to content

Instantly share code, notes, and snippets.

@brianally
Last active April 22, 2017 02:09
Show Gist options
  • Save brianally/67fda7e0ed40f71e5c4a003c7686acf9 to your computer and use it in GitHub Desktop.
Save brianally/67fda7e0ed40f71e5c4a003c7686acf9 to your computer and use it in GitHub Desktop.
#!/usr/bin/php
<?php
/*
Example shell script for using the ReRanger class.
https://github.com/brianally/ReRanger
*/
use \InvalidArgumentException as InvalidArgumentException;
// or load however you want
require(__DIR__ . "/ReRanger.php");
// set up
define("DELIMLINE", "|"); // character(s) separating index entry from page number(s)
define("DELIMSERIES", ", "); // character(s) separating page numbers
define("DELIMRANGE", "--"); // character(s) separating page numbers in range
define("INCREMENT", -2); // number of pages to increment (negative for decrement)
define("MINPAGE", 158); // page number ABOVE which all other pages should be decremented
define("REFSTR", "(r)"); // reference/notes append eg. 505(n), 432(r), etc.
if ( $argc != 3 ) {
die("usage: {$argv[0]} readfile writefile" . PHP_EOL);
}
$sourceFile = $argv[1]; // plaintext file with index entries, one per line
$targetFile = $argv[2]; // modified index
$readPointer = fopen($sourceFile, "r");
$writePointer = fopen($targetFile, "a");
if ( !$writePointer ) {
die("could not open target" . PHP_EOL);
}
if ( !$readPointer ) {
die("could not open source" . PHP_EOL);
}
$reRanger = new ReRanger\ReRanger(DELIMSERIES, DELIMRANGE, INCREMENT, MINPAGE, REFSTR);
$hasErrors = 0;
// process lines of input file
// if an exception occurs everything aborts
try {
while( ($line = fgets($readPointer)) !== false ) {
// split each line between index entry and page numbers
$line = str_replace(PHP_EOL, "", $line);
$split = explode(DELIMLINE, $line);
// allow lines without numbers to pass through
if ( sizeof($split) == 2) {
try {
$numbers = $reRanger->processSeries( trim($split[1]) );
// join to first part of line
$line = trim($split[0]) . DELIMLINE . $numbers;
}
catch( InvalidArgumentException $e ) {
$msg = [
"** ERROR **",
$line,
$e->getMessage()
];
$previous = $e->getPrevious();
if ( !is_null($previous) ) {
$msg[] = $previous->getMessage();
}
$msg[] = "*******" . PHP_EOL;
$out = implode( PHP_EOL, $msg );
// writing error to file for later editing
fwrite($writePointer, $out);
echo $out;
// continuing with next line
++$hasErrors;
continue;
}
}
$line = $line . PHP_EOL;
fwrite($writePointer, $line);
echo $line;
}
}
catch(Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
finally {
fclose($readPointer);
fclose($writePointer);
unset($reRanger);
echo "done" . PHP_EOL;
if ( $hasErrors ) {
echo "${hasErrors} errors written to file";
}
}
/*
* Local variables:
* tab-width: 2
* c-basic-offset: 2
* c-hanging-comment-ender-p: nil
* End:
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment