Passed
Push — master ( f9e6b3...5e8c5a )
by Julito
09:39
created

ResourceControllerTrait::getUser()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
nc 4
nop 0
dl 0
loc 16
rs 10
c 1
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
namespace Chamilo\CoreBundle\Traits;
6
7
use Chamilo\CoreBundle\Entity\AbstractResource;
8
use Chamilo\CoreBundle\Entity\ResourceInterface;
9
use Chamilo\CoreBundle\Entity\ResourceNode;
10
use Chamilo\CoreBundle\Entity\User;
11
use Chamilo\CoreBundle\Repository\ResourceFactory;
12
use Chamilo\CoreBundle\Repository\ResourceNodeRepository;
13
use Chamilo\CoreBundle\Repository\ResourceRepository;
14
use Doctrine\ORM\EntityNotFoundException;
15
use Psr\Container\ContainerInterface;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
18
19
trait ResourceControllerTrait
20
{
21
    /** @var ContainerInterface */
22
    protected $container;
23
24
    public function getRepositoryFromRequest(Request $request): ResourceRepository
25
    {
26
        $tool = $request->get('tool');
27
        $type = $request->get('type');
28
29
        return $this->getRepository($tool, $type);
30
    }
31
32
    public function getResourceNodeRepository(): ResourceNodeRepository
33
    {
34
        return $this->container->get(ResourceNodeRepository::class);
35
    }
36
37
    public function getResourceRepositoryFactory(): ResourceFactory
38
    {
39
        return $this->container->get(ResourceFactory::class);
40
    }
41
42
    public function getRepository($tool, $type): ResourceRepository
43
    {
44
        $name = $this->getResourceRepositoryFactory()->getRepositoryService($tool, $type);
45
46
        return $this->container->get($name);
47
    }
48
49
    public function denyAccessUnlessValidResource(AbstractResource $resource = null)
50
    {
51
        if (null === $resource) {
52
            throw new EntityNotFoundException($this->trans('Resource doesn\'t exists.'));
0 ignored issues
show
Bug introduced by
It seems like trans() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

52
            throw new EntityNotFoundException($this->/** @scrutinizer ignore-call */ trans('Resource doesn\'t exists.'));
Loading history...
53
        }
54
55
        $resourceNode = $resource->getResourceNode();
56
57
        if (null === $resourceNode) {
58
            throw new EntityNotFoundException($this->trans('Resource doesn\'t have a node.'));
59
        }
60
    }
61
62
    public function getResourceParams(Request $request): array
63
    {
64
        $tool = $request->get('tool');
65
        $type = $request->get('type');
66
        $id = (int) $request->get('id');
67
68
        $courseId = null;
69
        $sessionId = null;
70
71
        if ($this->hasCourse()) {
0 ignored issues
show
Bug introduced by
It seems like hasCourse() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

71
        if ($this->/** @scrutinizer ignore-call */ hasCourse()) {
Loading history...
72
            $courseId = $this->getCourse()->getId();
0 ignored issues
show
Bug introduced by
It seems like getCourse() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

72
            $courseId = $this->/** @scrutinizer ignore-call */ getCourse()->getId();
Loading history...
73
            $session = $this->getCourseSession();
0 ignored issues
show
Bug introduced by
It seems like getCourseSession() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

73
            /** @scrutinizer ignore-call */ 
74
            $session = $this->getCourseSession();
Loading history...
74
            $sessionId = $session ? $session->getId() : 0;
75
        }
76
77
        return [
78
            'id' => $id,
79
            'tool' => $tool,
80
            'type' => $type,
81
            'cid' => $courseId,
82
            'sid' => $sessionId,
83
        ];
84
    }
85
86
    protected function getParentResourceNode(Request $request): ResourceNode
87
    {
88
        $parentNodeId = $request->get('id');
89
90
        $parentResourceNode = null;
91
        if (empty($parentNodeId)) {
92
            if ($this->hasCourse()) {
93
                $parentResourceNode = $this->getCourse()->getResourceNode();
94
            } else {
95
                if ($this->container->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
96
                    /** @var User $user */
97
                    $parentResourceNode = $this->getUser()->getResourceNode();
98
                }
99
            }
100
        } else {
101
            $repo = $this->container->get('doctrine')->getRepository(ResourceNode::class);
102
            $parentResourceNode = $repo->find($parentNodeId);
103
        }
104
105
        if (null === $parentResourceNode) {
106
            throw new AccessDeniedException();
107
        }
108
109
        return $parentResourceNode;
110
    }
111
112
    protected function getUser()
113
    {
114
        if (!$this->container->has('security.token_storage')) {
115
            throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
116
        }
117
118
        if (null === $token = $this->container->get('security.token_storage')->getToken()) {
119
            return null;
120
        }
121
122
        if (!\is_object($user = $token->getUser())) {
123
            // e.g. anonymous authentication
124
            return null;
125
        }
126
127
        return $user;
128
    }
129
130
    private function setBreadCrumb(Request $request, ResourceNode $resourceNode)
131
    {
132
        return false;
133
        $tool = $request->get('tool');
0 ignored issues
show
Unused Code introduced by
$tool = $request->get('tool') is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
134
        $resourceNodeId = $request->get('id');
135
        $routeParams = $this->getResourceParams($request);
136
        $baseNodeId = $this->getCourse()->getResourceNode()->getId();
137
138
        if (!empty($resourceNodeId)) {
139
            $breadcrumb = $this->getBreadCrumb();
140
            $toolParams = $routeParams;
141
            $toolParams['id'] = null;
142
143
            // Root tool link
144
            $breadcrumb->addChild(
145
                $this->trans($tool),
146
                [
147
                    'uri' => $this->generateUrl('chamilo_core_resource_index', $toolParams),
148
                ]
149
            );
150
151
            $repo = $this->getRepositoryFromRequest($request);
152
            $settings = $repo->getResourceSettings();
153
154
            /** @var ResourceInterface $originalResource */
155
            //$originalResource = $repo->findOneBy(['resourceNode' => $resourceNodeId]);
156
            if (null === $resourceNode) {
157
                return;
158
            }
159
            //var_dump($resourceNode->getTitle());            throw new \Exception('22');
160
            $parentList = $resourceNode->getPathForDisplayToArray($baseNodeId);
161
162
//            var_dump($originalParent->getPath(), $originalParent->getPathForDisplay());
163
164
//            $parentList = [];
165
            /*          while (null !== $parent) {
166
                          if ($type !== $parent->getResourceType()->getName()) {
167
                              break;
168
                          }
169
                          $parent = $parent->getParent();
170
                          if ($parent) {
171
                              $resource = $repo->findOneBy(['resourceNode' => $parent->getId()]);
172
                              if ($resource) {
173
                                  $parentList[] = $resource;
174
                              }
175
                          }
176
                      }
177
                      $parentList = array_reverse($parentList);
178
                      foreach ($parentList as $item) {
179
                          $params = $routeParams;
180
                          $params['id'] = $item->getResourceNode()->getId();
181
                          $breadcrumb->addChild(
182
                              $item->getResourceName(),
183
                              [
184
                                  'uri' => $this->generateUrl('chamilo_core_resource_list', $params),
185
                              ]
186
                          );
187
                      }*/
188
189
            foreach ($parentList as $id => $title) {
190
                $params = $routeParams;
191
                $params['id'] = $id;
192
                $breadcrumb->addChild(
193
                    $title,
194
                    [
195
                        'uri' => $this->generateUrl('chamilo_core_resource_list', $params),
196
                    ]
197
                );
198
            }
199
200
            $params = $routeParams;
201
            $params['id'] = $resourceNode->getId();
202
            if (false === $settings->isAllowNodeCreation() || $resourceNode->hasResourceFile()) {
203
                $breadcrumb->addChild($resourceNode->getTitle());
204
            } else {
205
                $breadcrumb->addChild(
206
                    $resourceNode->getTitle(),
207
                    [
208
                        'uri' => $this->generateUrl('chamilo_core_resource_list', $params),
209
                    ]
210
                );
211
            }
212
        }
213
    }
214
}
215