From a833ef8465c738d117d2f72dab588f04bc0982ce Mon Sep 17 00:00:00 2001 From: Urban Müller Date: Wed, 15 Mar 2017 15:26:58 +0100 Subject: add add_dir(), add mkdir to file_put --- it.class | 12 ++++++++++++ tests/it.t | 4 ++++ 2 files changed, 16 insertions(+) diff --git a/it.class b/it.class index 55d57db..30dbf92 100644 --- a/it.class +++ b/it.class @@ -984,6 +984,14 @@ static function mail($p) return $mail->send($p); } +/** + * Add an extra md5 based directory name on bottom of path. foo/bar -> foo/07/bar + */ +static function add_dir($path) +{ + return dirname($path) . "/" . substr(md5(basename($path)), 0, 2) . "/" . basename($path); +} + /** * Reads a file and returns it as string or in one of several formats. Two params: filename and flags * @param $filename name of file to read or - for stdin @@ -1017,6 +1025,7 @@ static function file_get($filename, $p = array()) * @param $data data to write, string by default * @param $p['keyval'] $data must be an assoc array and is written as tab-separated lines * @param $p['lines'] write array of lines, appending newline + * @param $p['mkdir'] create parent directory (one level) */ static function file_put($filename, $data, $p = array()) { @@ -1025,6 +1034,9 @@ static function file_put($filename, $data, $p = array()) else if ($p['lines']) $data = count((array)$data) ? join("\n", (array)$data) ."\n" : ""; + if ($p['mkdir'] && $filename != "-") + @mkdir(dirname($filename)); + if (($result = file_put_contents($filename == "-" ? "php://stdout" : "$filename.tmp." . getmypid(), $data)) !== false && $filename != "-") $result = rename("$filename.tmp." . getmypid(), $filename); diff --git a/tests/it.t b/tests/it.t index e028f27..0c02106 100755 --- a/tests/it.t +++ b/tests/it.t @@ -438,3 +438,7 @@ is(it::map(42, array("aaa", "aa")), array(42, 42)); is(it::map('2*$v', [3, 4, 5], ['keys' => '0,1']), [6, 8, 5]); is(it::map('2*$v', [3, 4, 5], ['keys' => [0,1]]), [6, 8, 5]); is(it::map('2*$v', ['foo' => 1, 'bar' => 2], ['keys' => 'foo']), ['foo' => 2, 'bar' => 2]); + +is(it::add_dir("foo/bar"), "foo/37/bar"); +is(it::add_dir("baz/bar"), "baz/37/bar"); +is(it::add_dir("bar"), "./37/bar"); -- cgit v1.2.3