1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sinergi\Users\Group; |
4
|
|
|
|
5
|
|
|
use Interop\Container\ContainerInterface; |
6
|
|
|
use Sinergi\Users\Container; |
7
|
|
|
use Sinergi\Users\Group\Exception\InvalidGroupException; |
8
|
|
|
use Sinergi\Users\User\UserEntityInterface; |
9
|
|
|
use Sinergi\Users\User\UserRepositoryInterface; |
10
|
|
|
use Sinergi\Users\User\UserValidatorInterface; |
11
|
|
|
|
12
|
|
|
class GroupController |
13
|
|
|
{ |
14
|
|
|
private $container; |
15
|
|
|
|
16
|
|
|
public function __construct(ContainerInterface $container) |
17
|
|
|
{ |
18
|
|
|
if ($container instanceof Container) { |
19
|
|
|
$this->container = $container; |
20
|
|
|
} else { |
21
|
|
|
$this->container = new Container($container); |
22
|
|
|
} |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function createGroup(GroupEntityInterface $group, array $users = null): GroupEntityInterface |
26
|
|
|
{ |
27
|
|
|
$userErrors = []; |
28
|
|
|
$hasErrors = false; |
29
|
|
|
if (is_array($users) && count($users)) { |
30
|
|
|
/** @var UserValidatorInterface $userValidator */ |
31
|
|
|
$userValidator = $this->container->get(UserValidatorInterface::class); |
32
|
|
|
foreach ($users as $user) { |
33
|
|
|
$userErrors[] = $userValidator($user); |
34
|
|
|
if (count(end($userErrors))) { |
35
|
|
|
$hasErrors = true; |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** @var GroupValidatorInterface $groupValidator */ |
41
|
|
|
$groupValidator = $this->container->get(GroupValidatorInterface::class); |
42
|
|
|
$errors = $groupValidator($group); |
43
|
|
|
|
44
|
|
|
if (count($errors)) { |
45
|
|
|
$hasErrors = true; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
if ($hasErrors) { |
49
|
|
|
throw new InvalidGroupException(array_merge($errors, ['users' => $userErrors])); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** @var GroupRepositoryInterface $groupRepository */ |
53
|
|
|
$groupRepository = $this->container->get(GroupRepositoryInterface::class); |
54
|
|
|
$groupRepository->save($group); |
55
|
|
|
|
56
|
|
|
/** @var UserRepositoryInterface $userRepository */ |
57
|
|
|
$userRepository = $this->container->get(UserRepositoryInterface::class); |
58
|
|
|
|
59
|
|
|
if (is_array($users) && count($users)) { |
60
|
|
|
|
61
|
|
|
/** @var UserEntityInterface $user */ |
62
|
|
|
foreach ($users as $user) { |
63
|
|
|
$user->setGroupId($group->getId()); |
64
|
|
|
$userRepository->save($user); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
$group->setUserRepository($userRepository); |
69
|
|
|
$group->getUsers(); |
70
|
|
|
return $group; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|