Completed
Push — develop ( c603db...77b219 )
by
unknown
16:24 queued 08:23
created

User::assertEntity()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 9
rs 8.8571
cc 5
eloc 4
nc 2
nop 2
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
7
 * @license   MIT
8
 */
9
10
namespace Auth\Repository;
11
12
use \Auth\Entity\Info;
13
use Auth\Entity\UserInterface;
14
use Core\Repository\AbstractRepository;
15
use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
16
use Doctrine\ODM\MongoDB\Events;
17
use Auth\Exception\UserDeactivatedException;
18
19
/**
20
 * class for accessing a user
21
 */
22
class User extends AbstractRepository
23
{
24
25
    /**
26
     * {@inheritDoc}
27
     */
28
    public function findBy(array $criteria, array $sort = null, $limit = null, $skip = null)
29
    {
30
        if (!array_key_exists('isDraft', $criteria)) {
31
            $criteria['isDraft'] = false;
32
        } elseif (null === $criteria['isDraft']) {
33
            unset($criteria['isDraft']);
34
        }
35
        
36
        if (!array_key_exists('status.name', $criteria)) {
37
            $criteria['status.name'] = \Jobs\Entity\StatusInterface::ACTIVE;
38
        } elseif (null === $criteria['status.name']) {
39
            unset($criteria['status.name']);
40
        }
41
        
42
        return parent::findBy($criteria, $sort, $limit, $skip);
43
    }
44
    
45
    /**
46
     * Finds a document by its identifier
47
     *
48
     * @param string|object $id The identifier
49
     * @param int $lockMode
50
     * @param int $lockVersion
0 ignored issues
show
Documentation introduced by
Should the type for parameter $lockVersion not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
51
     * @param array $options
52
     * @throws Mapping\MappingException
53
     * @throws LockException
54
     * @throws UserDeactivatedException
55
     * @return null | UserInterface
0 ignored issues
show
Documentation introduced by
Should the return type not be null|UserInterface?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
56
     */
57
    public function find($id, $lockMode = \Doctrine\ODM\MongoDB\LockMode::NONE, $lockVersion = null, array $options = [])
58
    {
59
        return $this->assertEntity(parent::find($id, $lockMode, $lockVersion), $options);
60
    }
61
62
    /**
63
     * @param array $criteria
64
     * @param array $options
65
     * @throws UserDeactivatedException
66
     * @return null | UserInterface
0 ignored issues
show
Documentation introduced by
Should the return type not be null|UserInterface?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
67
     */
68 View Code Duplication
    public function findOneBy(array $criteria, array $options = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
69
    {
70
        if (!array_key_exists('isDraft', $criteria)) {
71
            $criteria['isDraft'] = false;
72
        } elseif (null === $criteria['isDraft']) {
73
            unset($criteria['isDraft']);
74
        }
75
        return $this->assertEntity(parent::findOneBy($criteria), $options);
76
    }
77
    
78
79
    /**
80
     * {@inheritDoc}
81
     */
82 View Code Duplication
    public function createQueryBuilder($findDrafts = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
83
    {
84
        $qb = parent::createQueryBuilder();
85
        if (null !== $findDrafts) {
86
            $qb->field('isDraft')->equals($findDrafts);
87
        }
88
        return $qb;
89
    }
90
91
    /**
92
     * Creates a User
93
     *
94
     * @see \Core\Repository\AbstractRepository::create()
95
     * @return UserInterface
0 ignored issues
show
Documentation introduced by
Should the return type not be \Core\Entity\EntityInterface?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
96
     */
97
    public function create(array $data = null)
98
    {
99
        $entity = parent::create($data);
100
        
101
        $eventArgs = new LifecycleEventArgs($entity, $this->dm);
102
        $this->dm->getEventManager()->dispatchEvent(
103
            Events::postLoad,
104
            $eventArgs
105
        );
106
        return $entity;
107
    }
108
    
109
    /**
110
     * Finds user by profile identifier
111
     *
112
     * @param string $identifier
113
     * @param string $provider
114
     * @param array $options
115
     * @return UserInterface
0 ignored issues
show
Documentation introduced by
Should the return type not be UserInterface|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
116
     */
117
    public function findByProfileIdentifier($identifier, $provider, array $options = [])
118
    {
119
        return $this->findOneBy(array('profiles.' . $provider . '.auth.identifier' => $identifier), $options) ?: $this->findOneBy(array('profile.identifier' => $identifier), $options);
120
    }
121
    
122
    /**
123
     * Returns true if profile is already assigned to anotherUser
124
     *
125
     * @param int $curentUserId
126
     * @param string $identifier
127
     * @param string $provider
128
     * @return bool
129
     */
130
    public function isProfileAssignedToAnotherUser($curentUserId, $identifier, $provider)
131
    {
132
        $qb = $this->createQueryBuilder(null);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
133
        $qb->field('_id')->notEqual($curentUserId)
134
            ->addAnd(
135
                $qb->expr()
136
                    ->addOr($qb->expr()->field('profiles.' . $provider . '.auth.identifier' )->equals($identifier))
137
                    ->addOr($qb->expr()->field('profile.identifier')->equals($identifier))
138
            );
139
        
140
        return $qb->count()
141
            ->getQuery()
142
            ->execute() > 0;
143
    }
144
    
145
    /**
146
     * Finds user by login name
147
     *
148
     * @param string $login
149
     * @param array $options
150
     * @return UserInterface
0 ignored issues
show
Documentation introduced by
Should the return type not be UserInterface|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
151
     */
152
    public function findByLogin($login, array $options = [])
153
    {
154
        $entity = $this->findOneBy(array('login' => $login), $options);
155
        return $entity;
156
    }
157
158
    /**
159
     * @param      $email
160
     * @param bool $isDraft
161
     *
162
     * @return UserInterface|null
163
     */
164
    public function findByEmail($email, $isDraft = false)
165
    {
166
        $entity = $this->findOneBy(
167
            array(
168
            '$or' => array(
169
                array('email' => $email),
170
                array('info.email' => $email),
171
            ),
172
            'isDraft' => $isDraft,
173
            )
174
        );
175
176
        return $entity;
177
    }
178
179
    /**
180
     * Finds user by login name or email
181
     *
182
     * @param string $identity
183
     * @param string $suffix
184
     *
185
     * @return UserInterface|null
186
     */
187
    public function findByLoginOrEmail($identity, $suffix = '')
188
    {
189
        return $this->findOneBy(
190
            array(
191
            '$or' => array(
192
                array('login' => $identity . $suffix),
193
                array('info.email' => $identity)
194
            )
195
            )
196
        );
197
    }
198
199
    /**
200
     * Find an user by a token hash.
201
     *
202
     * @param string $tokenHash
203
     *
204
     * @return UserInterface|null
205
     */
206
    public function findByToken($tokenHash)
207
    {
208
        $criteria = array(
209
            'isDraft' => null,
210
            'tokens.hash' => $tokenHash
211
        );
212
213
        return $this->findOneBy($criteria);
214
    }
215
    
216
    /**
217
     * Finds user by internal id
218
     *
219
     * @param array $ids
220
     * @return \MongoCursor
0 ignored issues
show
Documentation introduced by
Should the return type not be array?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
221
     */
222
    public function findByIds(array $ids)
223
    {
224
        return $this->findBy(
225
            array(
226
            '_id' => array('$in' => $ids)
227
            )
228
        );
229
    }
230
    
231
    /**
232
     * Find user by query
233
     *
234
     * @param String $query
235
     * @deprecated since 0.19 not used anymore and probably broken.
236
     * @return object
237
     */
238
    public function findByQuery($query)
239
    {
240
        $qb = $this->createQueryBuilder();
241
        $parts  = explode(' ', trim($query));
242
        
243
        foreach ($parts as $q) {
244
            $regex = new \MongoRegex('/^' . $query . '/i');
245
            $qb->addOr($qb->expr()->field('info.firstName')->equals($regex));
246
            $qb->addOr($qb->expr()->field('info.lastName')->equals($regex));
247
            $qb->addOr($qb->expr()->field('info.email')->equals($regex));
248
        }
249
        $qb->sort(array('info.lastName' => 1))
250
           ->sort(array('info.email' => 1));
251
        
252
        return $qb->getQuery()->execute();
253
    }
254
    
255
    /**
256
     * Copy user info into the applications info Entity
257
     *
258
     * @param \Auth\Entity\Info $info
259
     */
260
    public function copyUserInfo(Info $info)
261
    {
262
        $contact = new Info();
263
        $contact->fromArray(Info::toArray($info));
0 ignored issues
show
Bug introduced by
The method toArray() does not seem to exist on object<Auth\Entity\Info>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method fromArray() does not seem to exist on object<Auth\Entity\Info>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
264
    }
265
    
266
    /**
267
     * @param UserInterface $user
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user not be null|UserInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
268
     * @param array $options
269
     * @throws UserDeactivatedException
270
     * @return null | UserInterface
0 ignored issues
show
Documentation introduced by
Should the return type not be null|UserInterface?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
271
     */
272
    protected function assertEntity(UserInterface $user = null, array $options)
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
273
    {
274
        if (isset($user) && (!isset($options['allowDeactivated']) || !$options['allowDeactivated']) && !$user->isActive())
275
        {
276
            throw new UserDeactivatedException(sprintf('User with ID %s is not active', $user->getId()));
277
        }
278
        
279
        return $user;
280
    }
281
}
282