link to my blog post
[auerswald-callnotifier.git] / src / callnotifier / CallMonitor / Detailler / CSV.php
1 <?php
2 namespace callnotifier;
3
4 /**
5  * Fetch caller names from a CSV file.
6  *
7  * The entries need to be separated by semicolons ";".
8  * The first line is interpreted as table head with column names.
9  *
10  * By default, column names "number" and "name" are used.
11  *
12  * Sets "toName" or "fromName", depending on call type.
13  */
14 class CallMonitor_Detailler_CSV implements CallMonitor_Detailler
15 {
16     protected $data = array();
17
18     /**
19      * Create new csv name resolver
20      *
21      * @param string $file    Path to CSV file
22      * @param array  $columns Names of the CSV columns that contain "number"
23      *                        and "name", e.g.
24      *                        array('number' => 'telephone', 'name' => 'name')
25      */
26     public function __construct($file, $columns = null)
27     {
28         if ($columns === null) {
29             $columns = array('number' => 'number', 'name' => 'name');
30         }
31         $columns = array_merge(
32             array('number' => 'number', 'name' => 'name'),
33             $columns
34         );
35         $this->loadFile($file, $columns);
36     }
37
38     protected function loadFile($file, $columns)
39     {
40         if (!is_readable($file)) {
41             throw new \Exception('CSV file not readable: ' . $file);
42         }
43         $handle = fopen($file, 'r');
44         if ($handle === false) {
45             throw new \Exception('Error opening CSV file: ' . $file);
46         }
47
48         $colPos = array();
49         $head   = fgetcsv($handle, 1000, ';');
50         foreach ($columns as $key => $colName) {
51             $pos = array_search($colName, $head);
52             if ($pos === false) {
53                 throw new \Exception(
54                     'CSV file does not have a colum with name: ' . $colName
55                 );
56             }
57             $colPos[$key] = $pos;
58         }
59
60         while (($lineData = fgetcsv($handle, 1000, ';')) !== false) {
61             $this->data[$lineData[$colPos['number']]]
62                 = $lineData[$colPos['name']];
63         }
64     }
65
66     public function loadCallDetails(CallMonitor_Call $call)
67     {
68         if ($call->type == CallMonitor_Call::INCOMING) {
69             if (!isset($call->fromName) || $call->fromName === null) {
70                 $call->fromName = $this->loadName($call->from);
71             }
72         } else {
73             if (!isset($call->toName) || $call->toName === null) {
74                 $call->toName = $this->loadName($call->to);
75             }
76         }
77     }
78
79     protected function loadName($number)
80     {
81         if (isset($this->data[$number])) {
82             return $this->data[$number];
83         }
84
85         return null;
86     }
87 }
88
89 ?>