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