Completed
Pull Request — develop (#274)
by
unknown
42:37
created

Organization::findbyRef()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 9
Ratio 100 %

Importance

Changes 0
Metric Value
dl 9
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 2
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
6
 * @license   GPLv3
7
 */
8
9
namespace Organizations\Repository;
10
11
use Auth\Entity\UserInterface;
12
use Core\Repository\AbstractRepository;
13
use Organizations\Entity\EmployeeInterface;
14
use Organizations\Entity\OrganizationInterface;
15
16
/**
17
 * This is the repository for Organizations entities.
18
 *
19
 * @author Mathias Gelhausen <[email protected]>
20
 * @author Miroslav Fedeleš <[email protected]>
21
 * @todo   write test
22
 */
23
class Organization extends AbstractRepository
24
{
25
    /**
26
     * Gets a cursor to a set of organizations
27
     *
28
     * @param array $params
29
     */
30
    public function getPaginatorCursor($params)
31
    {
32
        return $this->getPaginationQueryBuilder($params)
33
                    ->getQuery()
34
                    ->execute();
35
    }
36
37
    /**
38
     * Gets a query builder to search for organizations
39
     *
40
     * @param array $params
41
     * @return mixed
42
     */
43 View Code Duplication
    protected function getPaginationQueryBuilder($params)
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...
44
    {
45
        $filter = $this->getService('filterManager')->get('Organizations/PaginationQuery');
46
        $qb = $filter->filter($params, $this->createQueryBuilder());
47
        
48
        return $qb;
49
    }
50
51
    /**
52
     * Gets a cursor for all hiring organizations.
53
     *
54
     * @param OrganizationInterface $organization parent organization
55
     *
56
     * @return \Doctrine\ODM\MongoDB\Cursor
57
     * @usedBy \Organizations\Entity\Organization::getHiringOrganizations()
58
     * @since 0.18
59
     */
60
    public function getHiringOrganizationsCursor(OrganizationInterface $organization)
61
    {
62
        $qb = $this->createQueryBuilder();
63
        $qb->field('parent')->equals($organization->getId());
64
        $qb->field('isDraft')->equals(false);
65
        $q  = $qb->getQuery();
66
        $cursor = $q->execute();
67
68
        return $cursor;
69
    }
70
71
    /**
72
     * Find a organizations by an name
73
     *
74
     * @param String $name
75
     * @param boolean $create
76
     * @return array
77
     */
78
    public function findByName($name, $create = true)
79
    {
80
        $query = $this->dm->createQueryBuilder('Organizations\Entity\OrganizationName')->hydrate(false)->field('name')->equals($name)->select("_id");
81
        $result = $query->getQuery()->execute()->toArray(false);
82
        if (empty($result) && $create) {
83
            $repositoryNames = $this->dm->getRepository('Organizations\Entity\OrganizationName');
84
            $entityName = $repositoryNames->create();
0 ignored issues
show
Bug introduced by
The method create() does not exist on Doctrine\ODM\MongoDB\DocumentRepository. Did you maybe mean createQueryBuilder()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
85
            $entityName->setName($name);
86
            $entity = $this->create();
87
            $entity->setOrganizationName($entityName);
88
            $this->store($entity);
89
            $organizations = array($entity);
90
        } else {
91
            $idName = $result[0]['_id'];
92
            $organizations = $this->findBy(array('organizationName' => $idName));
93
        }
94
        return $organizations;
95
    }
96
    
97 View Code Duplication
    public function findbyRef($ref, $create = true)
0 ignored issues
show
Unused Code introduced by
The parameter $create 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...
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...
98
    {
99
        $entity = $this->findOneBy(array('externalId' => $ref));
100
        if (empty($entity)) {
101
            $entity = $this->create();
102
            $entity->setExternalId($ref);
103
        }
104
        return $entity;
105
    }
106
107
    /**
108
     * Finds the main organization of an user.
109
     *
110
     * @param string|UserInterface $userOrId
111
     *
112
     * @return null|OrganizationInterface
0 ignored issues
show
Documentation introduced by
Should the return type not be array|object|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...
113
     */
114
    public function findByUser($userOrId)
115
    {
116
        $userId = $userOrId instanceof \Auth\Entity\UserInterface ? $userOrId->getId() : $userOrId;
117
        $qb     = $this->createQueryBuilder();
118
119
        /*
120
         * HiringOrganizations also could be associated to the user, but we
121
         * do not want them to be queried here, so the query needs to check the
122
         * "parent" field, too.
123
         */
124
//        $qb->addAnd(
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
125
//           $qb->expr()->field('user')->equals($userId)
126
//                      ->addOr(
127
//                            $qb->expr()->addOr($qb->expr()->field('parent')->exists(false))
128
//                                       ->addOr($qb->expr()->field('parent')->equals(null))
129
//           )
130
//        );
131
        $qb->addAnd($qb->expr()->field('user')->equals($userId))
132
           ->addAnd(
133
               $qb->expr()->addOr($qb->expr()->field('parent')->exists(false))
134
                               ->addOr($qb->expr()->field('parent')->equals(null))
135
           );
136
137
        $q      = $qb->getQuery();
138
        $entity = $q->getSingleResult();
139
140
        return $entity;
141
    }
142
143
    /**
144
     * Finds the organization, an user is employed by.
145
     *
146
     * @param string|UserInterface $userOrId
147
     *
148
     * @return null|OrganizationInterface
0 ignored issues
show
Documentation introduced by
Should the return type not be object|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...
149
     */
150 View Code Duplication
    public function findByEmployee($userOrId)
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...
151
    {
152
        $userId = $userOrId instanceof \Auth\Entity\UserInterface ? $userOrId->getId() : $userOrId;
153
154
        /*
155
         * Employees collection is only set on main organization,
156
         * so here, we do not have to query the "parent" field.
157
         *
158
         * Only search for "assigned" employees.
159
         */
160
        $entity = $this->findOneBy(
161
            array(
162
            'employees.user' => new \MongoId($userId),
163
            'employees.status' => EmployeeInterface::STATUS_ASSIGNED
164
            )
165
        );
166
167
        return $entity;
168
    }
169
170 View Code Duplication
    public function findPendingOrganizationsByEmployee($userOrId)
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...
171
    {
172
        $userId = $userOrId instanceof \Auth\Entity\UserInterface ? $userOrId->getId() : $userOrId;
173
174
        $collection = $this->findBy(
175
            array(
176
            'employees.user' => new \MongoId($userId),
177
            'employees.status' => EmployeeInterface::STATUS_PENDING
178
            )
179
        );
180
181
        return $collection;
182
    }
183
184 View Code Duplication
    public function getEmployersCursor(UserInterface $user)
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...
185
    {
186
        $qb = $this->createQueryBuilder();
187
        $qb->field('refs.employees')->equals($user->getId());
188
189
        $q  = $qb->getQuery();
190
        $c  = $q->execute();
191
192
        return $c;
193
    }
194
195
    public function create(array $data = null)
196
    {
197
        $entity = parent::create($data);
198
        $entity->isDraft(true);
199
        return $entity;
200
    }
201
202
    /**
203
     * creates a new Organization, no matter if a organization with this name already exists,
204
     * also creates a new Name, but link this Name to another OrganizationName-Link, if this Name already exists
205
     * @param $name
206
     */
207
    public function createWithName($name)
208
    {
209
        $entity = parent::create();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (create() instead of createWithName()). Are you sure this is correct? If so, you might want to change this to $this->create().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
210
        $repositoryNames = $this->dm->getRepository('Organizations\Entity\OrganizationName');
211
        $entityName = $repositoryNames->create();
0 ignored issues
show
Bug introduced by
The method create() does not exist on Doctrine\ODM\MongoDB\DocumentRepository. Did you maybe mean createQueryBuilder()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
212
        $entityName->setName($name);
213
        $entity->setOrganizationName($entityName);
214
        return $entity;
215
    }
216
217
    /**
218
     * @param string $query
219
     * @param UserInterface    $user
220
     * @return array
221
     */
222
    public function getTypeAheadResults($query, $user)
223
    {
224
        $organizationNames = array();
225
226
        $organizationNameQb = $this->getDocumentManager()->createQueryBuilder('Organizations\Entity\OrganizationName');
227
        $organizationNameQb->hydrate(false)
228
            ->select(array('id', 'name'))
229
            ->field('name')->equals(new \MongoRegex('/' . $query . '/i'))
230
            ->sort('name')
231
            ->limit(5);
232
233
        $organizationNameResults = $organizationNameQb->getQuery()->execute();
234
235
        foreach ($organizationNameResults as $id => $item) {
236
            $organizationNames[$id] = $item;
237
        }
238
239
        $organizations = array();
240
241
        $userOrg = $user->getOrganization();
242
243
        $qb = $this->createQueryBuilder();
244
        $qb->hydrate(false)
245
            ->select(array('contact.city', 'contact.street', 'contact.houseNumber', 'organizationName'))
246
            ->limit(5)
247
            ->addAnd(
248
                $qb->expr()->field('permissions.view')->equals($user->getId())
249
                                ->field('organizationName')->in(array_keys($organizationNames))
250
            );
251
252
253
        if ($userOrg->hasAssociation()) {
254
            $qb->addAnd(
255
                $qb->expr()->addOr($qb->expr()->field('parent')->equals($userOrg->getId()))
256
                           ->addOr($qb->expr()->field('_id')->equals($userOrg->getId()))
257
            );
258
        }
259
260
        $result = $qb->getQuery()->execute();
261
262
        foreach ($result as $id => $item) {
263
            $organizations[$id] = $item;
264
            $organizationNameId = (string)$organizations[$id]['organizationName'];
265
            $organizations[$id]['organizationName'] = $organizationNames[$organizationNameId];
266
        }
267
268
        return $organizations;
269
    }
270
271
    /**
272
     * Look for an drafted Document of a given user
273
     *
274
     * @param $user
275
     * @return \Organizations\Entity\Organization|null
0 ignored issues
show
Documentation introduced by
Should the return type not be object|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...
276
     */
277 View Code Duplication
    public function findDraft($user)
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...
278
    {
279
        if ($user instanceof UserInterface) {
280
            $user = $user->getId();
281
        }
282
283
        $document = $this->findOneBy(
284
            array(
285
            'isDraft' => true,
286
            'user' => $user
287
            )
288
        );
289
290
        if (!empty($document)) {
291
            return $document;
292
        }
293
294
        return null;
295
    }
296
    
297
    /**
298
     * Get organizations for given user ID
299
     *
300
     * @param string $userId
301
     * @param int $limit
0 ignored issues
show
Documentation introduced by
Should the type for parameter $limit 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...
302
     * @return Cursor
303
     * @since 0.27
304
     */
305 View Code Duplication
    public function getUserOrganizations($userId, $limit = null)
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...
306
    {
307
        $qb = $this->createQueryBuilder(null)
0 ignored issues
show
Unused Code introduced by
The call to Organization::createQueryBuilder() has too many arguments starting with null.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
308
            ->field('user')->equals($userId)
309
            ->sort(['DateCreated.date' => -1]);
310
    
311
        if (isset($limit)) {
312
            $qb->limit($limit);
313
        }
314
    
315
        return $qb->getQuery()->execute();
316
    }
317
}
318