summaryrefslogtreecommitdiffstats
path: root/src/Psecio/Gatekeeper/UserGroupCollection.php
blob: e6179596d3cccc71e13cb76e1192e36acfbc6c6f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php

namespace Psecio\Gatekeeper;

class UserGroupCollection extends \Psecio\Gatekeeper\Collection\Mysql
{
    /**
     * Find the groups that the given user belongs to
     *
     * @param integer $userId User ID
     */
    public function findByUserId($userId)
    {
        $prefix = $this->getPrefix();
        $data = array('userId' => $userId);
        $sql = 'select g.* from '.$prefix.'groups g, '.$prefix.'user_group ug'
            .' where ug.user_id = :userId'
            .' and ug.group_id = g.id';

        $results = $this->getDb()->fetch($sql, $data);

        foreach ($results as $result) {
            $group = new GroupModel($this->getDb(), $result);
            $this->add($group);
        }
    }

    /**
     * Create relational records linking the user and group
     *
     * @param \Gatekeeper\UserModel $model Model instance
     * @param array $data Data to use in create
     */
    public function create($model, array $data)
    {
        foreach ($data as $group) {
            // Determine if it's an integer (permissionId) or name
            if (is_int($group) === true) {
                $where = 'id = :id';
                $dbData = array('id' => $group);
            } else {
                $where = 'name = :name';
                $dbData = array('name' => $group);
            }

            $sql = 'select id, name from '.$this->getPrefix().'groups where '.$where;
            $results = $this->getDb()->fetch($sql, $dbData);
            if (!empty($results) && count($results) == 1) {
                // exists, make the relation
                $model = new UserGroupModel(
                    $this->getDb(),
                    array('groupId' => $results[0]['id'], 'userId' => $model->id)
                );
                if ($this->getDb()->save($model) === true) {
                    $this->add($model);
                }
            }
        }
    }
}