Completed
Push — master ( 275c1f...cb75c2 )
by Emmanuel
05:43
created

AbstractAnonymizer::processEntity()

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 0
cp 0
c 0
b 0
f 0
nc 1
1
<?php
2
/**
3
 * neuralyzer : Data Anonymization Library and CLI Tool
4
 *
5
 * PHP Version 7.1
6
 *
7
 * @author Emmanuel Dyan
8
 * @author Rémi Sauvat
9
 * @copyright 2018 Emmanuel Dyan
10
 *
11
 * @package edyan/neuralyzer
12
 *
13
 * @license GNU General Public License v2.0
14
 *
15
 * @link https://github.com/edyan/neuralyzer
16
 */
17
18
namespace Edyan\Neuralyzer\Anonymizer;
19
20
use Edyan\Neuralyzer\Configuration\Reader;
21
use Edyan\Neuralyzer\Exception\NeuralizerConfigurationException;
22
23
/**
24
 * Abstract Anonymizer, that can be implemented as DB Anonymizer for example
25
 * Its goal is only to anonymize any data, from a simple array
26
 * not to write or read it from anywhere
27
 *
28
 */
29
abstract class AbstractAnonymizer
30
{
31
    /**
32
     * Truncate table
33
     */
34
    const TRUNCATE_TABLE = 1;
35
36
    /**
37
     * Update data into table
38
     */
39
    const UPDATE_TABLE = 2;
40
41
    /**
42
     * Insert data into table
43
     */
44
    const INSERT_TABLE = 4;
45
46
47
    /**
48
     * Contains the configuration object
49
     *
50
     * @var Reader
51
     */
52
    protected $configuration;
53
54
    /**
55
     * Configuration of entities
56
     *
57
     * @var array
58
     */
59
    protected $configEntites = [];
60
61
    /**
62
     * Current table (entity) to process
63
     *
64
     * @var string
65
     */
66
    protected $entity;
67
68
    /**
69
     * Current table (entity) Columns
70
     *
71
     * @var array
72
     */
73
    protected $entityCols;
74
75
76
    /**
77
     * Process the entity according to the anonymizer type
78
     *
79
     * @param string        $entity         Entity's name
80
     * @param callable|null $callback       Callback function with current row num as parameter
81
     * @param bool          $pretend        Simulate update
82
     * @param bool          $returnRes      Return queries
83
     */
84
    abstract public function processEntity(
85
        string $entity,
86
        callable $callback = null,
87
        bool $pretend = true,
88
        bool $returnRes = false
89
    ): array;
90
91
92
    /**
93
     * Set the configuration
94
     *
95
     * @param Reader $configuration
96
     */
97 20
    public function setConfiguration(Reader $configuration): void
98
    {
99 20
        $this->configuration = $configuration;
100 20
        $this->configEntites = $configuration->getConfigValues()['entities'];
101 20
    }
102
103
104
    /**
105
     * Evaluate, from the configuration if I have to update or Truncate the table
106
     *
107
     * @return int
108
     */
109 16
    protected function whatToDoWithEntity(): int
110
    {
111 16
        $this->checkEntityIsInConfig();
112
113 14
        $entityConfig = $this->configEntites[$this->entity];
114
115 14
        $actions = 0;
116 14
        if (array_key_exists('delete', $entityConfig) && $entityConfig['delete'] === true) {
117 4
            $actions |= self::TRUNCATE_TABLE;
118
        }
119
120 14
        if (array_key_exists('cols', $entityConfig)) {
121 14
            switch ($entityConfig['action']) {
122 14
                case 'update':
123 11
                    $actions |= self::UPDATE_TABLE;
124 11
                    break;
125 3
                case 'insert':
126 3
                    $actions |= self::INSERT_TABLE;
127 3
                    break;
128
            }
129
        }
130
131 14
        return $actions;
132
    }
133
134
135
    /**
136
     * Returns the 'delete_where' parameter for an entity in config (or empty)
137
     *
138
     * @return string
139
     */
140 4
    public function getWhereConditionInConfig(): string
141
    {
142 4
        $this->checkEntityIsInConfig();
143
144 4
        if (!array_key_exists('delete_where', $this->configEntites[$this->entity])) {
145 1
            return '';
146
        }
147
148 3
        return $this->configEntites[$this->entity]['delete_where'];
149
    }
150
151
152
    /**
153
     * Generate fake data for an entity and return it as an Array
154
     *
155
     * @return array
156
     */
157 12
    protected function generateFakeData(): array
158
    {
159 12
        $this->checkEntityIsInConfig();
160
161 12
        $faker = \Faker\Factory::create($this->configuration->getConfigValues()['language']);
162
163 12
        $colsInConfig = $this->configEntites[$this->entity]['cols'];
164 12
        $row = [];
165 12
        foreach ($colsInConfig as $colName => $colProps) {
166 12
            $this->checkColIsInEntity($colName);
167 11
            $data = call_user_func_array(
168 11
                [$faker, $colProps['method']],
169 11
                $colProps['params']
170
            );
171
172 11
            if (!is_scalar($data)) {
173 1
                $msg = "You must use faker methods that generate strings: '{$colProps['method']}' forbidden";
174 1
                throw new NeuralizerConfigurationException($msg);
175
            }
176
177 11
            $row[$colName] = $data;
178
179 11
            $colLength = $this->entityCols[$colName]['length'];
180
            // Cut the value if too long ...
181 11
            if (!empty($colLength) && strlen($data) > $colLength) {
182 11
                $row[$colName] = substr($data, 0, $this->entityCols[$colName]['length']);
183
            }
184
        }
185
186 10
        return $row;
187
    }
188
189
190
    /**
191
     * Make sure that entity is defined in the configuration
192
     *
193
     * @throws NeuralizerConfigurationException
194
     */
195 16
    private function checkEntityIsInConfig(): void
196
    {
197 16
        if (empty($this->configEntites)) {
198 1
            throw new NeuralizerConfigurationException(
199 1
                'No entities found. Have you loaded a configuration file ?'
200
            );
201
        }
202 15
        if (!array_key_exists($this->entity, $this->configEntites)) {
203 1
            throw new NeuralizerConfigurationException(
204 1
                "No configuration for that entity ({$this->entity})"
205
            );
206
        }
207 14
    }
208
209
    /**
210
     * Verify a column is defined in the real entityCols
211
     *
212
     * @throws NeuralizerConfigurationException
213
     * @param  string $colName [description]
214
     */
215 12
    private function checkColIsInEntity(string $colName): void
216
    {
217 12
        if (!array_key_exists($colName, $this->entityCols)) {
218 1
            throw new NeuralizerConfigurationException("Col $colName does not exist");
219
        }
220 11
    }
221
}
222