diff options
author | Phil Burton <philbeansburton@gmail.com> | 2015-12-09 14:01:49 +0000 |
---|---|---|
committer | Phil Burton <philbeansburton@gmail.com> | 2015-12-09 14:01:49 +0000 |
commit | a787e9fdd23def5a0b0502f90c04027e2bdb6f39 (patch) | |
tree | 83985744832f1fa8a5d6a02d924c0a840c3102ff /search.php | |
parent | a1a294d5ac75f74e615134faa76841e660cf823f (diff) | |
parent | 83102b75ce9876cf247814f857ee44483b5a19e6 (diff) |
Merge branch 'refactor' into 'master'
Refactor
Refactor everything into functions so we can easily test/maintain/improve individual components of this program.
Add lots of doc-blocking to the functions for extra information.
Unless there are any complaints I will merge this fairly quickly.
See merge request !3
Diffstat (limited to 'search.php')
-rw-r--r-- | search.php | 317 |
1 files changed, 226 insertions, 91 deletions
@@ -1,9 +1,21 @@ <?php - $version = 1.2; - +/** + * Load and parse the config file, setting any defaults here if non-required + * fields are not set + * + * @return string[] + * @author Phil Burton <phil@pgburton.com> + * @throws Exception when file is not readable + * @throws Exception when ini file fails to parse + * @throws Exception when url not found in ini file + * @throws Exception when command not found in ini file + * @throws Exception when pagesize is set incorrectly + */ +function getConfig() +{ $config = false; -try { + if (!is_readable("config.ini")) { throw new Exception('File config.ini does not exist'); } @@ -16,119 +28,242 @@ try { if (!isset($config["command"])) { throw new Exception('`command` not found in ini file'); } + + // Set default page size if it's not in the config + if (!isset($config["pagesize"])) { + $config["pagesize"] = 3; + } elseif (!is_int((int)$config["pagesize"]) || $config["pagesize"] < 1) { + throw new Exception('Page size ' . $config["pagesize"] . ' not valid in config'); + } // hash the password if (isset($config['password'])) { - $hash = hash("sha256", $config['password']); + $config['hash'] = hash("sha256", $config['password']); } - $curl = curl_init($config["url"]. "?format=json"); - if (isset($hash)) { - curl_setopt($curl, CURLOPT_HTTPHEADER, array("Cookie: password=$hash")); + return $config; +} + +/** + * Use curl to find get the json file for a url + * Using the sha256 hashed password if it's been set in the config + * + * @param string[] $config + * @return StdClass[] + * @author Phil Burton <phil@pgburton.com> + */ +function getJsonFromUrl($config) +{ + $curl = curl_init($config["url"] . "?format=json"); + if (isset($config["hash"])) { + curl_setopt($curl, CURLOPT_HTTPHEADER, array("Cookie: password=" . $config["hash"])); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $output = json_decode(curl_exec($curl)); curl_close($curl); - $search = read_stdin(); - - if (empty($search)) { - throw new Exception("Please enter a search term"); + if (!isset($output)) { + throw new Exception( + "Could not retrive JSON from http server `" + . $config["url"] + . "?format=json` using password=" + . (isset($config["hash"]) ? "true" : "false") + ); } + return $output; +} - $args = explode(" ", $search); - $page = 1; - $out = []; - if ($args[0] == "-v" || $args[0] == "--version") { - $out[] = "blaupload-search v" . $version; - } elseif ($args[0] == "-h" || $args[0] == "--help") { - $help = "Usage: !" . $config["command"] . " [query] #[page] | "; - $help .= "e.g: !" . $config["command"] . " intense | "; - $help .= "!" . $config["command"] . " intense marcus | "; - $help .= "!" . $config["command"] . " intense marcus #2 (returns the second page of results)"; - $out[] = $help; +/** + * Return the help text + * + * @param StdClass[] $config + * @return string + * @author Phil Burton <phil@pgburton.com> + */ +function getHelp($config) +{ + return "Usage: !" . $config["command"] . " [query] #[page] | " + . "e.g: !" . $config["command"] . " intense | " + . "!" . $config["command"] . " intense marcus | " + . "!" . $config["command"] . " intense marcus #2 (returns the second page of results)"; +} + +/** + * Get the version string + * + * @param stdClass[] $config + * @return string + * @author Phil Burton <phil@pgburton.com> + */ +function getVersion($config) +{ + return $config["command"] . " v" . "2.0"; +} + +/** + * Output the given string, adding a new line at the end + * If pieces is an array, use the glue to implode and output a single string + * + * EXIT + * + * @param string|string[] $pieces + * @param string $glue + * @author Phil Burton <phil@pgburton.com> + */ +function output($pieces, $glue = " - ") +{ + if (!is_array($pieces)) { + echo $pieces . "\n"; } else { + echo implode($glue, $pieces) . "\n"; + } - // Check to see if user specified pagination - $pages = array_filter($args, function($elem) { - if (strpos($elem, "#") === 0) { - return true; - } - return false; - }); - // reset the indexes after the array filter - $pages = array_merge($pages); + exit; +} - if (count($pages) > 1) { - throw new Exception("Too many page choices. Enter only one `#<page>`"); - } +/** + * Read stdin and return as a string + * + * @return string + * @author Phil Burton <phil@pgburton.com> + */ +function read_stdin() +{ + $fr = fopen("php://stdin", "r"); + $input = fgets($fr, 128); + $input = rtrim($input); + fclose($fr); + return $input; +} + +/** + * Get the start and end index positions for the required page and + * page size + * + * @param int $page + * @param int $pagesize + * @return int[] + * @author Phil Burton <phil@pgburton.com> + */ +function getPaginationBounds($page, $pagesize) +{ + return [ + "start" => ($page - 1) * $pagesize, + "end" => (($page - 1) * $pagesize) + ($pagesize - 1) + ]; +} + +/** + * Loop through the stdin and parse the arguments given + * If we hit a "special" argument then run the specific code and exit + * Otherwise we set the page and search terms and return them as an array + * + * @param $config + * @return mixed[] + * @author Phil Burton <phil@pgburton.com> + */ +function getFormattedArguments($config) +{ + $args = explode(" ", read_stdin()); - if (!empty($pages)) { - // Set the page - $page = substr($pages[0], 1); + if (!isset($args) || empty($args)) { + throw new Exception("No arguments found"); + } + // Loop the raw arguments and create our formated argument array + $formatArgs = []; + $formatArgs["search"] = []; + foreach ($args as $arg) { + // Switch to check for special arguments + // output should exit but incase it errors we double break + switch ($arg) { + case "--version": + case "-v": // Flow through + output(getVersion($config)); + break 2; + case "--help": + case "-h": // Flow through + output(getHelp($config)); + break 2; } - if (!is_int((int)$page) || $page <= 0) { - throw new Exception("Page `" . $page . "` is not valid"); + + // Check to see if we have a page specified + if (strpos($arg, "#") === 0) { + $formatArgs["page"] = substr($arg, 1); + continue; } + // If we reach here, then the argument is a search term + $formatArgs["search"][] = $arg; + } - // remove the pagination from the search args - $pos = array_search("#" . $page, $args); - if ($pos) { - $args[$pos] = null; - } + // If we reach this point we must have at least one search term + if (empty($formatArgs["search"])) { + throw new Exception("Please Enter a search term"); + } - // Really slow search - $results = []; - foreach ($output as $upload) { - $match = false; - foreach ($args as $arg) { - if (!is_null($arg) && stripos($upload->filename, $arg) === false) { - $match = false; - break; - } - $match = true; - } - if ($match) { - $results[] = $config["url"] . "/" . rawurlencode($upload->filename); + if (!isset($formatArgs["page"])) { + $formatArgs["page"] = 1; + } elseif (!is_int((int)$formatArgs["page"]) || $formatArgs["page"] < 1) { + throw new Exception("Page number `" . $formatArgs["page"] . "` is not valid"); + } + + return $formatArgs; +} + +/********************************* + * ENTRY POINT FOR FUNCTION HERE * + *********************************/ +try { + $config = getConfig(); + $content = getJsonFromUrl($config); + $arguments = getFormattedArguments($config); + + // parse the arguments + $page = $arguments["page"]; + + $out = []; + + // Really slow search + $results = []; + foreach ($content as $upload) { + $match = false; + foreach ($arguments["search"] as $arg) { + if (!is_null($arg) && stripos($upload->filename, $arg) === false) { + $match = false; + break; } + $match = true; + } + if ($match) { + $results[] = $config["url"] . "/" . rawurlencode($upload->filename); } + } - // Return results - if (empty($results)) { - echo "No results found\n"; - } else { - $count = count($results); - $i = 0; - - $start = ($page-1)*3; - $end = $start+2; - if ($start > ($count-1)) { - throw new Exception("No results for this page"); - } - foreach($results as $result) { - if ($i < $start || $i > $end) { - $i++; - continue; - } - $out[] = $i+1 . ": " . $result; - $i++; - } - if ($count > 3) { - $out[] = "results (" . $count . ")"; - } + if (empty($results)) { + output("No results found"); + } + + $count = count($results); + $i = 0; + $bounds = getPaginationBounds($page, $config["pagesize"]); + + if ($bounds["start"] > ($count - 1)) { + throw new Exception("No results for this page"); + } + + foreach ($results as $result) { + if ($i < $bounds["start"] || $i > $bounds["end"]) { + $i++; + continue; } + $out[] = $i + 1 . ": " . $result; + $i++; } - echo implode(" - ", $out) . "\n"; + if ($count > 3) { + $out[] = "results (" . $count . ")"; + } -} catch (Exception $e) { - echo $e->getMessage() . "\n";die(); -} + output($out, " - "); -function read_stdin() -{ - $fr=fopen("php://stdin","r"); // open our file pointer to read from stdin - $input = fgets($fr,128); // read a maximum of 128 characters - $input = rtrim($input); // trim any trailing spaces. - fclose ($fr); // close the file handle - return $input; // return the text entered +} catch (Exception $e) { + output($e->getMessage()); } |