Completed
Push — master ( 024767...e7bc73 )
by Henry Stivens
02:04
created

User::uploadPhoto()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Clase para manejar los datos del usuario, tabla 'user'
5
 */
6
class User extends ActiveRecord {
7
8
    /**
9
     * Guarda un usuario y sube la foto de un usuario.
10
     * 
11
     * @param array $data Arreglo con los datos de usuario
12
     * @return boolean
13
     * @throws Exception
14
     */
15
    public function saveWithPhoto($data) {
16
        //Inicia la transacción
17
        $this->begin();
18
        if ($this->create($data)) {
19
            //Intenta actualizar la foto
20
            if($this->updatePhoto()){
21
                //Se confirma la transacción
22
                $this->commit();
23
                return true;
24
            }           
25
        } 
26
        
27
        //Si alga falla se regresa la transacción
28
        $this->rollback();
29
        return false;        
30
    }
31
32
    /**
33
     * Sube y actualiza la foto del usuario.
34
     * 
35
     * @return boolean|null
36
     */
37
    public function updatePhoto() {
38
        if ($photo = $this->uploadPhoto('photo')) {
39
            //Actualiza el campo photo
40
            $this->photo = $photo;
41
            return $this->update();
42
        }
43
    }
44
45
    /**
46
     * Sube la foto y retorna el nombre del archivo generado.
47
     * 
48
     * @param string $imageField
49
     * @return string|false
50
     */
51
    public function uploadPhoto($imageField) {
52
        //Usamos el adapter 'image'
53
        $file = Upload::factory($imageField, 'image');
54
        $fileName = false;
55
        //le asignamos las extensiones a permitir
56
        $file->setExtensions(array('jpg', 'png', 'gif'));
57
        //Intenta subir el arhivo
58
        if ($file->isUploaded()) {
59
            //Lo guarda usando un nombre de archivo aleatorio
60
            $fileName = $file->saveRandom();
61
        }
62
        
63
        return $fileName;
64
    }
65
66
}
67