1: <?php
2:
3: namespace Himedia\PDOTools;
4:
5: 6: 7: 8: 9: 10: 11: 12: 13: 14:
15: class Tools
16: {
17:
18: 19: 20: 21: 22: 23: 24:
25: public static function assocArrayToHstore(array $aData)
26: {
27: $aHstore = array();
28: foreach ($aData as $sKey => $sValue) {
29: if (is_null($sValue)) {
30: $aHstore[] = sprintf('"%s" => NULL', $sKey);
31: } else {
32: $aHstore[] = sprintf('"%s" => "%s"', $sKey, str_replace('"', "\\\"", $sValue));
33: }
34: }
35: return sprintf("'%s'::hstore", implode(', ', $aHstore));
36: }
37:
38: 39: 40: 41: 42: 43: 44: 45: 46:
47: public static function exportToCSV(array $aRows, $sCsvPath, $sDelimiter = ',', $sEnclosure = '"')
48: {
49: if (empty($sCsvPath)) {
50: $hFile = fopen('php://temp/maxmemory:' . (10*1024*1024), 'w');
51: } else {
52: $hFile = fopen($sCsvPath, 'w');
53: }
54:
55: $bIsHeaderPrinted = false;
56: foreach ($aRows as $aRow) {
57: if (! $bIsHeaderPrinted) {
58: $bIsHeaderPrinted = true;
59: fputcsv($hFile, array_keys($aRow), $sDelimiter, $sEnclosure);
60: }
61: fputcsv($hFile, $aRow, $sDelimiter, $sEnclosure);
62: }
63:
64: if (empty($sCsvPath)) {
65: rewind($hFile);
66: $sCSV = stream_get_contents($hFile);
67: } else {
68: $sCSV = '';
69: }
70: fclose($hFile);
71: return rtrim($sCSV, "\n");
72: }
73:
74: 75: 76: 77: 78: 79: 80:
81: public static function normalizeQuery($sRawQuery)
82: {
83: $sSqlComments = '@(([\'"]).*?[^\\\]\2)|((?:\#|--).*?$|/\*(?:[^/*]|/(?!\*)|\*(?!/)|(?R))*\*\/)\s*|(?<=;)\s+@ms';
84: $sNormalizedQuery = preg_replace('/\s+/', ' ', trim(preg_replace($sSqlComments, '$1', $sRawQuery)));
85: return $sNormalizedQuery;
86: }
87: }
88: