Completed
Push — master ( 10e479...8ee696 )
by Reginaldo
32:57
created

ApiController::postConsulta()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 13

Duplication

Lines 19
Ratio 100 %
Metric Value
dl 19
loc 19
rs 9.4286
cc 2
eloc 13
nc 2
nop 1
1
<?php
2
3
class ApiController extends AppController {
4
5
	public function beforeFilter()
6
	{
7
		return true;
8
   	}
9
10
	public function wishlist($dados)
0 ignored issues
show
Unused Code introduced by
The parameter $dados is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
11
	{
12
		return true;
13
	}
14
15
	public function client($id_cliente = null)
16
	{
17
		$api = 'cliente';
18
	    $this->loadModel('Cliente');
19
		$this->autoRender = false;
20
		$this->response->type('json');
21
		
22
		$type = $this->request;
23
24
	    if (!$this->validate_use_api($type, $api)) {
25
	    	echo '{message: Você não tem permissão para usar nosso modulo}';
26
	    	return;
27
	    }
28
29
	    if ($type->is('get')) {
30
	    	$conditions = array(
31
				'ativo' => 1,
32
				'id_usuario' => $this->getIdUser(),
33
			);
34
35
			if (isset($id_cliente))
36
			 	$conditions['id'] = $id_cliente;
37
38
39
		    $cliente = $this->Cliente->find('all', 
40
				array('conditions' => 
41
					$conditions
42
				)
43
			);
44
45
			$this->response->body(json_encode($cliente));
46
	    } else if ($type->is('post')) {
47
	    	$dados = $this->request->data;
48
	    	
49
	    	if (empty($dados)) {
50
				$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
51
				return;
52
	    	}
53
54
	    	if (!empty($dados['nome1']) && !empty($dados['nome2']) && !empty($dados['email']) && !empty($dados['senha'])) {
55
	    		$this->postClient($dados);
56
	    	} 
57
58
	    	$this->loginClient($dados);
59 View Code Duplication
	    } else if ($type->is('put')) {
60
61
	    	$dados = $this->request->data;
62
	    	
63
			if (empty($dados)) {
64
				$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
65
				return;
66
	    	}
67
68
	    	if ($id_cliente == null) {
69
	    		$this->response->body(json_encode(array('message' => 'Você não passou o id do usuario')));
70
	    		return;
71
	    	}
72
73
	    	$this->putClient($dados, $id_cliente);
74
	    } else if ($type->is('delete')) {
75
	    	
76
	    	if ($id_cliente == null) {
77
	    		$this->response->body(json_encode(array('message' => 'Você não passou o id do usuario')));
78
	    		return;
79
	    	}
80
81
	    	$this->inactiveClient($id_cliente);
82
	    }
83
	}
84
85
	public function parent($id_cliente = null, $id_parente = null)
86
	{
87
		$api = 'parente';
88
89
	    $this->loadModel('Parente');
90
91
		$this->autoRender = false;
92
		$this->response->type('json');
93
		
94
		$type = $this->request;
95
96
	    if (!$this->validate_use_api($type, $api)) {
97
	    	echo '{message: Você não tem permissão para usar nosso modulo}';
98
	    	return;
99
	    }
100
101
	    if ($type->is('get')) {
102
	    	$conditions = array(
103
				'ativo' => 1,
104
				'usuario_id' => $this->getIdUser(),
105
			);
106
107
			$conditions['cliente_id'] = $id_cliente;
108
109
			if (isset($id_parente)) {
110
				$conditions['id'] = $id_parente;
111
			}
112
113
		    $parentes = $this->Parente->find('all', 
114
				array('conditions' => 
115
					$conditions
116
				)
117
			);
118
119
			$this->response->body(json_encode($parentes));
120
	    } else if ($type->is('post')) {
121
	    	$dados = $this->request->data;
122
	    	
123
	    	if (empty($dados)) {
124
				$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
125
				return;
126
	    	}
127
128
	    	if (!empty($dados['cliente_id'])) {
129
	    		$this->postParent($dados);
130
	    	} 
131
132
	    	$this->loginParent($dados);
133 View Code Duplication
	    } else if ($type->is('put')) {
134
135
	    	$dados = $this->request->data;
136
	    	
137
			if (empty($dados)) {
138
				$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
139
				return;
140
	    	}
141
142
	    	if ($id_parente == null) {
143
	    		$this->response->body(json_encode(array('message' => 'Você não passou o id do usuario')));
144
	    		return;
145
	    	}
146
147
	    	$this->putParent($dados, $id_parente);
148
	    } else if ($type->is('delete')) {
149
	    	
150
	    	if ($id_parente == null) {
151
	    		$this->response->body(json_encode(array('message' => 'Você não passou o id do usuario')));
152
	    		return;
153
	    	}
154
155
	    	$this->inactiveClient($id_parente);
156
	    }
157
	}
158
159
	public function occurrences($id_cliente = null) 
160
	{
161
		$api = 'parente';	
162
163
		$this->autoRender = false;
164
		$this->response->type('json');
165
		$this->loadModel('Ocorrencias');
166
167
		$type = $this->request;
168
169
	    if ($type->is('get'))
170
	    {
171
	    	$conditions = array(
172
				'ativo' => 1,
173
				'cliente_id' => $id_cliente,
174
			);
175
176
			$conditions['cliente_id'] = $id_cliente;
177
178
		    $ocorrencias = $this->Ocorrencias->find('all', 
179
				array('conditions' => 
180
					$conditions
181
				)
182
			);
183
184
			$this->response->body(json_encode($ocorrencias));	    	
185
	    }
186
	}
187
188
	public function newsletter()
189
	{
190
		$api = 'newsletter';
191
192
		$this->loadModel('Newsletter');
193
194
		$this->autoRender = false;
195
		$this->response->type('json');
196
		
197
		$type = $this->request;
198
199
	    if (!$this->validate_use_api($type, $api)) {
200
	    	echo '{message: Você não tem permissão para usar nosso modulo}';
201
	    	return;
202
	    }
203
204
    	$request = $this->request->data;
205
    	
206
    	if (empty($request)) {
207
			$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
208
			return;
209
    	}
210
211
		$dados = array(
212
			'email'  => $request['email'],
213
			'origem' => $request['origem'],
214
			'ativo'  => 1,
215
			'usuario_id' => $this->getIdUser()
216
		);
217
218
		$this->Newsletter->save($dados);
219
220
		$this->response->body('{"message": "success", "result":'.json_encode($dados).'}');
221
		return;		
222
	}
223
224
	public function banner()
225
	{
226
		$api = 'banner';
227
228
		$this->loadModel('Banner');
229
230
		$this->autoRender = false;
231
		$this->response->type('json');
232
233
		$type = $this->request;
234
235
		if (!$this->validate_use_api($type, $api)) {
236
	    	echo '{message: Você não tem permissão para usar nosso modulo}';
237
	    	return;
238
	    }
239
240
    	$conditions = array(
241
			'ativo' => 1,
242
			'usuario_id' => $this->getIdUser()
243
		);
244
245
	    $banner = $this->Banner->find('all', 
246
			array('conditions' => 
247
				$conditions
248
			)
249
		);
250
251
	    if (!empty($banner)) {
252
			$this->response->body('{"message": "success", "result":'.json_encode($banner).'}');
253
			return;
254
	    }
255
		
256
		$this->response->body('{"message": "error"}');
257
		return;	
258
	}
259
260
	public function consulta()
261
	{
262
		$api = 'consulta';
263
264
		$this->loadModel('Consulta');
265
266
		$this->autoRender = false;
267
		$this->response->type('json');
268
269
		$type = $this->request;
270
271
		if (!$this->validate_use_api($type, $api)) {
272
	    	echo '{message: Você não tem permissão para usar nosso modulo}';
273
	    	return;
274
	    }
275
276
277
	    if ($type->is('get')) {
278
	    	$conditions = array(
279
				'ativo' => 1,
280
				'id_usuario' => $this->getIdUser()
281
			);
282
283
		    $consulta = $this->Consulta->find('all', 
284
				array('conditions' => 
285
					$conditions
286
				)
287
			);
288
289
		    if (!empty($consulta)) {
290
				$this->response->body('{"message": "success", "result":'.json_encode($consulta).'}');
291
				return;
292
		    }
293
		}
294
295
		if ($type->is('post'))
296
		{
297
	    	$dados = $this->request->data;
298
	    	
299
	    	if (empty($dados)) {
300
				$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
301
				return;
302
	    	}
303
304
	    	return $this->postConsulta($dados);			
305
		}
306
307
		$this->response->body('{"message": "error"}');
308
		return;	
309
	}
310
311 View Code Duplication
	public function loginClient($dados)
312
	{
313
314
    	$conditions = array(
315
			'ativo' => 1,
316
			'id_usuario' => $this->getIdUser(),
317
			'email' => $dados['email'],
318
			'senha' => sha1($dados['senha'])
319
		);
320
321
	    $cliente = $this->Cliente->find('all', 
322
			array('conditions' => 
323
				$conditions
324
			)
325
		);
326
327
	    if (!empty($cliente)) {
328
			$this->response->body('{"message": "success", "result":'.json_encode($cliente).'}');
329
			return;
330
	    }
331
		
332
		$this->response->body('{"message": "error"}');
333
		return;	    
334
	}
335
336
	public function postClient($dados)
337
	{
338
		$this->loadModel('Cliente');
339
340
    	$dados['senha'] = sha1($dados['senha']);
341
		$dados['ativo'] = 1;
342
		$dados['id_usuario'] = $this->instancia;
343
		
344
		if ($this->Cliente->save($dados)) {
345
			$this->response->body('{"message": "success", "result":'.json_encode($dados).'}');
346
			return;
347
		}
348
349
		$this->response->body('{"message": "error"}');
350
		return true;
351
	}
352
353 View Code Duplication
	public function putClient($dados, $id_cliente)
354
	{
355
		if ($dados['senha'] != '') {
356
			$dados['senha'] = sha1($dados['senha']);
357
		}
358
359
		$this->Cliente->id = $id_cliente;
360
		$this->Cliente->id_usuario = $this->getIdUser();
361
362
		if ($this->Cliente->save($dados)) {
363
			$this->response->body('{"message": "success", "result": '. json_encode($dados) .'}');
364
			return;
365
		}
366
367
		$this->response->body('{"message": "error"}');
368
		return;
369
	}
370
371 View Code Duplication
	public function inactiveClient($id_cliente) 
372
	{
373
		$dados['ativo'] = 0;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$dados was never initialized. Although not strictly required by PHP, it is generally a good practice to add $dados = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
374
		
375
		$this->Cliente->id = $id_cliente;
376
377
		if ($this->Cliente->save($dados)) {
378
			$this->response->body('{"message": "success", "result":'.json_encode($dados).'}');
379
			return;
380
		} else {
381
			$this->response->body('{"message": "error"}');
382
			return;
383
		}	
384
	}
385
386
387 View Code Duplication
	public function postParent($dados)
388
	{
389
    	$dados = array(
390
			'senha'      => sha1($dados['senha']),
391
			'usuario_id' => $this->getIdUser(),
392
			'cliente_id' => $dados['cliente_id'],
393
			'login'      => $dados['login'],
394
			'ativo'      => 1,
395
		);
396
		
397
		if ($this->Parente->save($dados)) {
398
			$this->response->body('{"message": "success", "result":'.json_encode($dados).'}');
399
			return;
400
		}
401
402
		$this->response->body('{"message": "error"}');
403
		return;
404
	}
405
406 View Code Duplication
	public function loginParent($dados) 
407
	{
408
    	$conditions = array(
409
			'ativo' => 1,
410
			'usuario_id' => $this->getIdUser(),
411
			'login' => $dados['login'],
412
			'senha' => sha1($dados['senha'])
413
		);
414
415
	    $parente = $this->Parente->find('all', 
416
			array('conditions' => 
417
				$conditions
418
			)
419
		);
420
421
	    if (!empty($parente)) {
422
			$this->response->body('{"message": "success", "result":'.json_encode($parente).'}');
423
			return;
424
	    }
425
		
426
		$this->response->body('{"message": "error"}');
427
		return;	
428
	}
429
430 View Code Duplication
	public function putParent($dados, $id_parente) 
431
	{
432
		if ($dados['senha'] != '') {
433
			$dados['senha'] = sha1($dados['senha']);
434
		}
435
436
		$this->Parente->id = $id_parente;
437
		$this->Parente->id_usuario = $this->getIdUser();
438
439
		if ($this->Parente->save($dados)) {
440
			$this->response->body('{"message": "success", "result": '. json_encode($dados) .'}');
441
			return;
442
		}
443
444
		$this->response->body('{"message": "error"}');
445
		return;
446
	}
447
448 View Code Duplication
	public function inactiveParent($id_parente) 
449
	{
450
		$dados['ativo'] = 0;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$dados was never initialized. Although not strictly required by PHP, it is generally a good practice to add $dados = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
451
		
452
		$this->Parente->id = $id_parente;
453
454
		if ($this->Parente->save($dados)) {
455
			$this->response->body('{"message": "success", "result":'.json_encode($dados).'}');
456
			return;
457
		} else {
458
			$this->response->body('{"message": "error"}');
459
			return;
460
		}	
461
	}
462
463 View Code Duplication
	public function postConsulta($dados)
464
	{
465
    	$dados = array(
466
			'nome'       => $dados['nome'],
467
			'email'      => $dados['email'],
468
			'data'       => $dados['date'],
469
			'hora'       => $dados['hora'],
470
			'id_usuario' => $this->getIdUser(),
471
			'ativo'      => 1,
472
		);
473
		
474
		if ($this->Consulta->save($dados)) {
475
			$this->response->body('{"message": "success", "result":' . json_encode($dados) . '}');
476
			return;
477
		}
478
479
		$this->response->body('{"message": "error"}');
480
		return;
481
	}
482
483
	/**
484
	* Valida o usuario que está tentando usar a api
485
	*/
486
	public function validate_use_api($req, $api)
487
	{
488
		$this->loadModel('Usuario');
489
		
490
		$data['auth'] = $req->query;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
491
		
492
		$resposta = $this->Usuario->find('all',
493
			array('conditions' => 
494
				array('Usuario.email' => $data['auth']['email'], 
495
					  'Usuario.senha' => sha1($data['auth']['senha'])
496
				)
497
			)
498
		)[0];
499
500
		if (empty($resposta))
501
		{
502
			return false;
503
		}
504
505
		$this->setIdUser($resposta['Usuario']['id']);
506
507
		if (!$this->verifyUseApi($api)) 
508
		{
509
			return false;
510
		}
511
512
		return true;
513
	}
514
515
	public function verifyUseApi($api)
516
	{
517
		$this->loadModel('ModuloRelacionaUsuario');
518
519
		$modulos = $this->ModuloRelacionaUsuario->find('all',
520
		array('conditions' => 
521
			array('ModuloRelacionaUsuario.id_usuario' => $this->getIdUser(), 
522
				  'ModuloRelacionaUsuario.ativo' => 1,
523
				  'Modulo.ativo' => 1
524
				)
525
			)
526
		);
527
528
		foreach ($modulos as $i => $modulo) {
529
			if ($modulo['Modulo']['modulo'] == $api) {
530
				return true;
531
			}
532
		}
533
534
		return false;
535
	}
536
537
	public function setIdUser($id)
538
	{
539
		$this->instancia = $id;
540
	}
541
542
	public function getIdUser()
543
	{
544
		if (!is_numeric($this->instancia))
545
		{
546
			return false;
547
		}
548
549
		return $this->instancia;
550
	}
551
}
552