1 <?php
defined('SYSPATH') OR die('No direct access allowed.');
6 * @todo since this works for csv files as well, rename the class to something
12 * Turns my_report.csv into my_report-2011-03-23.csv and, perhaps,
13 * my_report.pdf into my_report-2011-03-23-dsaf43.pdf
15 * @param $data The file to write
16 * @param $save_here string
17 * @throws Exception with reason of failure
18 * @return string filename of new file
20 static function save($data, $save_here) {
21 $save_here = (string) $save_here;
22 if(!is_writable(pathinfo($save_here, PATHINFO_DIRNAME
))) {
23 throw new Exception("Can't write output file '$save_here'");
25 $file_extension = 'pdf';
26 if('.csv' == substr($save_here, -4 , 4)) {
27 $file_extension = 'csv';
30 $local_persistent_filepath = pathinfo($save_here, PATHINFO_DIRNAME
);
31 $stripped_name = pathinfo($save_here, PATHINFO_BASENAME
);
32 $local_persistent_filepath .= '/'.preg_replace('/\.'.$file_extension.'$/', null, $stripped_name).'-'.date('Y-m-d').'.'.$file_extension;
35 while(file_exists($local_persistent_filepath)) {
36 $local_persistent_filepath = preg_replace(
37 '~(-[a-h0-9]{6})?\.'.$file_extension.'$~',
38 '-'.substr(md5(rand()), 0, 6).'.'.$file_extension,
39 $local_persistent_filepath
41 if(++
$current_try > $safety_limit) {
42 throw new Exception("Do not want to overwrite '$local_persistent_filepath', aborting. Please remove the already existing reports.");
45 $ok = file_put_contents($local_persistent_filepath, $data);
47 throw new Exception("Failed to write to '$local_persistent_filepath'");
49 return $local_persistent_filepath;