Issues (3627)

app/bundles/CoreBundle/Helper/CsvHelper.php (1 issue)

1
<?php
2
3
/*
4
 * @copyright   2014 Mautic Contributors. All rights reserved
5
 * @author      Mautic
6
 *
7
 * @link        http://mautic.org
8
 *
9
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
10
 */
11
12
namespace Mautic\CoreBundle\Helper;
13
14
/**
15
 * Class CsvHelper.
16
 */
17
class CsvHelper
18
{
19
    /**
20
     * @param string $filename
21
     * @param string $delimiter
22
     *
23
     * @return array
24
     */
25
    public static function csv_to_array($filename = '', $delimiter = ',')
26
    {
27
        if (!file_exists($filename) || !is_readable($filename)) {
28
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type array.
Loading history...
29
        }
30
31
        $header = null;
32
        $data   = [];
33
        if (false !== ($handle = fopen($filename, 'r'))) {
34
            while (false !== ($row = fgetcsv($handle, 1000, $delimiter))) {
35
                if (!$header) {
36
                    $header = $row;
37
                } else {
38
                    $data[] = array_combine($header, $row);
39
                }
40
            }
41
            fclose($handle);
42
        }
43
44
        return $data;
45
    }
46
47
    /**
48
     * @return array
49
     */
50
    public static function sanitizeHeaders(array $headers)
51
    {
52
        return array_map('trim', $headers);
53
    }
54
55
    /**
56
     * @return array
57
     */
58
    public static function convertHeadersIntoFields(array $headers)
59
    {
60
        sort($headers);
61
62
        $importedFields = [];
63
64
        foreach ($headers as $header) {
65
            $fieldName = strtolower(InputHelper::alphanum($header, false, '_'));
66
67
            // Skip columns with empty names as they cannot be mapped.
68
            if (!empty($fieldName)) {
69
                $importedFields[$fieldName] = $header;
70
            }
71
        }
72
73
        return $importedFields;
74
    }
75
}
76