Completed
Push — 2.0 ( f2e1fb...45d12b )
by Christopher
03:56
created

WhoDidItBehavior::_getUserId()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 14
rs 9.4285
cc 3
eloc 9
nc 3
nop 0
1
<?php
2
/**
3
 * Licensed under The GPL-3.0 License
4
 * For full copyright and license information, please see the LICENSE.txt
5
 * Redistributions of files must retain the above copyright notice.
6
 *
7
 * @since    2.0.0
8
 * @author   Christopher Castro <[email protected]>
9
 * @link     http://www.quickappscms.org
10
 * @license  http://opensource.org/licenses/gpl-3.0.html GPL-3.0 License
11
 */
12
namespace User\Model\Behavior;
13
14
use Cake\Event\Event;
15
use Cake\Network\Session;
16
use Cake\ORM\Behavior;
17
use Cake\ORM\Table;
18
19
/**
20
 * WhoDidIt Behavior.
21
 *
22
 * Handles "created_by", "modified_by" fields for a given table. It's similar to
23
 * the "created", "modified" automagic, but it stores the logged User's ID.
24
 *
25
 * This is useful to track who created records, and the last user that has
26
 * changed them.
27
 */
28
class WhoDidItBehavior extends Behavior
29
{
30
31
    /**
32
     * Table which this behavior is attached to.
33
     *
34
     * @var \Cake\ORM\Table
35
     */
36
    protected $_table;
37
38
    /**
39
     * Default configuration.
40
     *
41
     * - idCallable: It can be either a *callable* method that should return logged
42
     *   User's ID or a *string* representing a `session key` from where to read
43
     *   the ID. By Defaults it's set yo `Auth.id` for reading from Auth's session.
44
     *
45
     * - createdByField: The name of the "created_by" field in DB. Defaults to
46
     *   `created_by`.
47
     *
48
     * - modifiedByField: The name of the "modified_by" field in DB. Default to
49
     *   `modified_by`.
50
     *
51
     * - userModel: The name of the Users class table, used to bind user's
52
     *   information to the table being managed by this behavior. Defaults to
53
     *   `User.Users`
54
     *
55
     * - autoBind: Automatically bind the table to the User table. (default true)
56
     *
57
     * @var array
58
     */
59
    protected $_defaultConfig = [
60
        'idCallable' => 'Auth.id',
61
        'createdByField' => 'created_by',
62
        'modifiedByField' => 'modified_by',
63
        'userModel' => 'User.Users',
64
        'autoBind' => true,
65
    ];
66
67
    /**
68
     * Constructor.
69
     *
70
     * @param \Cake\ORM\Table $table The table this behavior is attached to
71
     * @param array $config Configuration array for this behavior
72
     */
73
    public function __construct(Table $table, array $config = [])
74
    {
75
        $this->_table = $table;
76
        parent::__construct($this->_table, $config);
77
78
        if ($this->config('autoBind')) {
79 View Code Duplication
            if ($this->_table->hasField($this->config('createdByField'))) {
80
                $this->_table->belongsTo('CreatedBy', [
81
                    'className' => $this->config('userModel'),
82
                    'foreignKey' => $this->config('createdByField'),
83
                    'propertyName' => 'created_by',
84
                ]);
85
            }
86
87 View Code Duplication
            if ($this->_table->hasField($this->config('modifiedByField'))) {
88
                $this->_table->belongsTo('ModifiedBy', [
89
                    'className' => $this->config('userModel'),
90
                    'foreignKey' => $this->config('modifiedByField'),
91
                    'propertyName' => 'modified_by',
92
                ]);
93
            }
94
        }
95
    }
96
97
    /**
98
     * Run before a model is saved.
99
     *
100
     * @param \Cake\Event\Event $event The event that was triggered
101
     * @param \Cake\ORM\Entity $entity The entity being saved
102
     * @param array $options Array of options for the save operation
103
     * @return bool True if save should proceed, false otherwise
104
     */
105
    public function beforeSave(Event $event, $entity, $options = [])
106
    {
107
        if ($this->_table->hasField($this->config('createdByField')) ||
108
            $this->_table->hasField($this->config('modifiedByField'))
109
        ) {
110
            $userId = $this->_getUserId();
111
            if ($userId > 0) {
112
                $entity->set($this->config('modifiedByField'), $userId);
113
                if ($entity->isNew()) {
114
                    $entity->set($this->config('createdByField'), $userId);
115
                }
116
            }
117
        }
118
119
        return true;
120
    }
121
122
    /**
123
     * Gets current User's ID.
124
     *
125
     * @return int User ID, zero if not found
126
     */
127
    protected function _getUserId()
128
    {
129
        $callable = $this->config('idCallable');
130
        $id = 0;
131
132
        if (is_string($callable)) {
133
            $session = Session::create();
134
            $id = $session->read($callable);
135
        } elseif (is_callable($callable)) {
136
            $id = $callable();
137
        }
138
139
        return (int)$id;
140
    }
141
}
142