Merge pull request #15313 from yashodha/report_cleanup
[civicrm-core.git] / CRM / Core / CodeGen / Util / File.php
1 <?php
2
3 /**
4 * Class CRM_Core_CodeGen_Util_File
5 */
6 class CRM_Core_CodeGen_Util_File {
7
8 /**
9 * @param $dir
10 * @param int $perm
11 */
12 public static function createDir($dir, $perm = 0755) {
13 if (!is_dir($dir)) {
14 mkdir($dir, $perm, TRUE);
15 }
16 }
17
18 /**
19 * @param $dir
20 */
21 public static function cleanTempDir($dir) {
22 foreach (glob("$dir/*") as $tempFile) {
23 unlink($tempFile);
24 }
25 rmdir($dir);
26 if (preg_match(':^(.*)\.d$:', $dir, $matches)) {
27 if (file_exists($matches[1])) {
28 unlink($matches[1]);
29 }
30 }
31 }
32
33 /**
34 * @param $prefix
35 *
36 * @return string
37 */
38 public static function createTempDir($prefix) {
39 $newTempDir = tempnam(sys_get_temp_dir(), $prefix) . '.d';
40 if (file_exists($newTempDir)) {
41 self::removeDir($newTempDir);
42 }
43 self::createDir($newTempDir);
44
45 return $newTempDir;
46 }
47
48 /**
49 * Calculate a cumulative digest based on a collection of files.
50 *
51 * @param array $files
52 * List of file names (strings).
53 * @param callable|string $digest a one-way hash function (string => string)
54 *
55 * @return string
56 */
57 public static function digestAll($files, $digest = 'md5') {
58 $buffer = '';
59 foreach ($files as $file) {
60 $buffer .= $digest(file_get_contents($file));
61 }
62 return $digest($buffer);
63 }
64
65 /**
66 * Find the path to the main Civi source tree.
67 *
68 * @return string
69 * @throws RuntimeException
70 */
71 public static function findCoreSourceDir() {
72 $path = str_replace(DIRECTORY_SEPARATOR, '/', __DIR__);
73 if (!preg_match(':(.*)/CRM/Core/CodeGen/Util:', $path, $matches)) {
74 throw new RuntimeException("Failed to determine path of code-gen");
75 }
76
77 return $matches[1];
78 }
79
80 /**
81 * Find files in several directories using several filename patterns.
82 *
83 * @param array $pairs
84 * Each item is an array(0 => $searchBaseDir, 1 => $filePattern).
85 * @return array
86 * Array of file paths
87 */
88 public static function findManyFiles($pairs) {
89 $files = [];
90 foreach ($pairs as $pair) {
91 list ($dir, $pattern) = $pair;
92 $files = array_merge($files, CRM_Utils_File::findFiles($dir, $pattern));
93 }
94 sort($files);
95 return $files;
96 }
97
98 }