summaryrefslogtreecommitdiffstats
path: root/inc/fileutil.inc.php
blob: e986b2de1f0a6f9d4d4350f2f71995606e8e817c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php

declare(strict_types=1);

class FileUtil
{
	
	/**
	 * Return contents of given file as string, but only read up to maxBytes bytes.
	 *
	 * @param string $file file to read
	 * @param int $maxBytes maximum length to read
	 * @return false|string data, false on error
	 */
	public static function readFile(string $file, int $maxBytes = 1000)
	{
		$fh = @fopen($file, 'rb');
		if ($fh === false)
			return false;
		$data = fread($fh, $maxBytes);
		fclose($fh);
		return $data;
	}

	/**
	 * Read a file of key=value lines to assoc array.
	 *
	 * @param string $file Filename
	 * @return ?array assoc array, null on error
	 */
	public static function fileToArray(string $file): ?array
	{
		$data = self::readFile($file, 2000);
		if ($data === false)
			return null;
		$data = explode("\n", str_replace("\r", "\n", $data));
		$ret = array();
		foreach ($data as $line) {
			if (preg_match('/^(\w+)\s*=\s*(.*?)\s*$/', $line, $out)) {
				$ret[$out[1]] = $out[2];
			}
		}
		return $ret;
	}

	/**
	 * Write given associative array to file as key=value pairs.
	 * 
	 * @param string $file Filename
	 * @param array $array Associative array to write
	 * @return boolean success of operation
	 */
	public static function arrayToFile(string $file, array $array): bool
	{
		$fh = fopen($file, 'wb');
		if ($fh === false)
			return false;
		foreach ($array as $key => $value) {
			if (false === fwrite($fh, $key . ' = ' . preg_replace('/[\x00-\x1F]/s', '', (string)$value) . "\n")) {
				fclose($fh);
				return false;
			}
		}
		fclose($fh);
		return true;
	}

}