Passed
Push — master ( fc13ff...4dcdf9 )
by Julito
12:40
created

AbstractMigrationChamilo::removeSettingCurrent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 1
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
namespace Chamilo\CoreBundle\Migrations;
6
7
use Chamilo\CoreBundle\Entity\AbstractResource;
8
use Chamilo\CoreBundle\Entity\ResourceInterface;
9
use Chamilo\CoreBundle\Entity\ResourceLink;
10
use Chamilo\CoreBundle\Entity\SettingsCurrent;
11
use Chamilo\CoreBundle\Entity\SettingsOptions;
12
use Chamilo\CoreBundle\Entity\User;
13
use Chamilo\CoreBundle\Repository\Node\UserRepository;
14
use Chamilo\CoreBundle\Repository\ResourceRepository;
15
use Chamilo\CoreBundle\Repository\SessionRepository;
16
use Chamilo\CourseBundle\Repository\CGroupRepository;
17
use Doctrine\DBAL\Connection;
18
use Doctrine\Migrations\AbstractMigration;
19
use Doctrine\ORM\EntityManager;
20
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
21
use Symfony\Component\DependencyInjection\ContainerInterface;
22
use Symfony\Component\HttpFoundation\File\UploadedFile;
23
24
/**
25
 * Class AbstractMigrationChamilo.
26
 */
27
abstract class AbstractMigrationChamilo extends AbstractMigration implements ContainerAwareInterface
28
{
29
    public const BATCH_SIZE = 20;
30
    private $manager;
31
    private $container;
32
33
    public function setEntityManager(EntityManager $manager)
34
    {
35
        $this->manager = $manager;
36
    }
37
38
    public function setContainer(ContainerInterface $container = null)
39
    {
40
        $this->container = $container;
41
    }
42
43
    /**
44
     * @return ContainerInterface
45
     */
46
    public function getContainer()
47
    {
48
        return $this->container;
49
    }
50
51
    public function getAdmin(): User
52
    {
53
        $container = $this->getContainer();
54
        $em = $this->getEntityManager();
55
        $connection = $em->getConnection();
56
        $userRepo = $container->get(UserRepository::class);
57
58
        $sql = 'SELECT id, user_id FROM admin ORDER BY id LIMIT 1';
59
        $result = $connection->executeQuery($sql);
60
        $adminRow = $result->fetchAssociative();
61
        $adminId = $adminRow['user_id'];
62
63
        return $userRepo->find($adminId);
64
    }
65
66
    /**
67
     * @return EntityManager
68
     */
69
    public function getEntityManager()
70
    {
71
        if (empty($this->manager)) {
72
            //$params = $this->connection->getParams();
73
            /*
74
            $dbParams = [
75
                'driver' => 'pdo_mysql',
76
                'host' => $this->connection->getHost(),
77
                'user' => $this->connection->getUsername(),
78
                'password' => $this->connection->getPassword(),
79
                'dbname' => $this->connection->getDatabase(),
80
                'port' => $this->connection->getPort(),
81
            ];*/
82
            /*$database = new \Database();
83
            $database->connect(
84
                $params,
85
                __DIR__.'/../../',
86
                __DIR__.'/../../'
87
            );
88
            $this->manager = $database->getManager();*/
89
        }
90
91
        return $this->manager;
92
    }
93
94
    /**
95
     * Speeds up SettingsCurrent creation.
96
     *
97
     * @param string $variable            The variable itself
98
     * @param string $subKey              The subkey
99
     * @param string $type                The type of setting (text, radio, select, etc)
100
     * @param string $category            The category (Platform, User, etc)
101
     * @param string $selectedValue       The default value
102
     * @param string $title               The setting title string name
103
     * @param string $comment             The setting comment string name
104
     * @param string $scope               The scope
105
     * @param string $subKeyText          Text if there is a subKey
106
     * @param int    $accessUrl           What URL it is for
107
     * @param bool   $accessUrlChangeable Whether it can be changed on each url
108
     * @param bool   $accessUrlLocked     Whether the setting for the current URL is
109
     *                                    locked to the current value
110
     * @param array  $options             Optional array in case of a radio-type field,
111
     *                                    to insert options
112
     */
113
    public function addSettingCurrent(
114
        $variable,
115
        $subKey,
116
        $type,
117
        $category,
118
        $selectedValue,
119
        $title,
120
        $comment,
121
        $scope = '',
122
        $subKeyText = '',
123
        $accessUrl = 1,
124
        $accessUrlChangeable = false,
125
        $accessUrlLocked = true,
126
        $options = []
127
    ) {
128
        $setting = new SettingsCurrent();
129
        $setting
130
            ->setVariable($variable)
131
            ->setSubkey($subKey)
132
            ->setType($type)
133
            ->setCategory($category)
134
            ->setSelectedValue($selectedValue)
135
            ->setTitle($title)
136
            ->setComment($comment)
137
            ->setScope($scope)
138
            ->setSubkeytext($subKeyText)
139
            ->setUrl($accessUrl)
140
            ->setAccessUrlChangeable($accessUrlChangeable)
141
            ->setAccessUrlLocked($accessUrlLocked);
142
143
        $this->getEntityManager()->persist($setting);
144
145
        if (count($options) > 0) {
146
            foreach ($options as $option) {
147
                if (empty($option['text'])) {
148
                    if ('true' == $option['value']) {
149
                        $option['text'] = 'Yes';
150
                    } else {
151
                        $option['text'] = 'No';
152
                    }
153
                }
154
155
                $settingOption = new SettingsOptions();
156
                $settingOption
157
                    ->setVariable($variable)
158
                    ->setValue($option['value'])
159
                    ->setDisplayText($option['text']);
160
161
                $this->getEntityManager()->persist($settingOption);
162
            }
163
        }
164
        $this->getEntityManager()->flush();
165
    }
166
167
    /**
168
     * @param string $variable
169
     */
170
    public function getConfigurationValue($variable)
171
    {
172
        global $_configuration;
173
        if (isset($_configuration[$variable])) {
174
            return $_configuration[$variable];
175
        }
176
177
        return false;
178
    }
179
180
    /**
181
     * Remove a setting completely.
182
     *
183
     * @param string $variable The setting variable name
184
     */
185
    public function removeSettingCurrent($variable)
186
    {
187
        //to be implemented
188
    }
189
190
    public function addLegacyFileToResource(
191
        string $filePath,
192
        ResourceRepository $repo,
193
        AbstractResource $resource,
194
        $id,
195
        $fileName = '',
196
        $description = ''
197
    ) {
198
        if (!is_dir($filePath)) {
199
            $class = get_class($resource);
200
            $documentPath = basename($filePath);
201
            if (file_exists($filePath)) {
202
                $mimeType = mime_content_type($filePath);
203
                if (empty($fileName)) {
204
                    $fileName = basename($documentPath);
205
                }
206
                $file = new UploadedFile($filePath, $fileName, $mimeType, null, true);
207
                if ($file) {
0 ignored issues
show
introduced by
$file is of type Symfony\Component\HttpFoundation\File\UploadedFile, thus it always evaluated to true.
Loading history...
208
                    $repo->addFile($resource, $file);
209
                } else {
210
                    $this->warnIf(true, "Cannot migrate $class #$id path: $documentPath ");
211
                }
212
            } else {
213
                $this->warnIf(true, "Cannot migrate $class #'.$id.' file not found: $documentPath");
214
            }
215
        }
216
    }
217
218
    public function fixItemProperty(
219
        $tool,
220
        $repo,
221
        $course,
222
        $admin,
223
        ResourceInterface $resource,
224
        $parent,
225
        array $items = []
226
    ) {
227
        $container = $this->getContainer();
228
        $doctrine = $container->get('doctrine');
229
        $em = $doctrine->getManager();
230
        /** @var Connection $connection */
231
        $connection = $em->getConnection();
232
233
        $courseId = $course->getId();
234
        $id = $resource->getResourceIdentifier();
235
236
        if (empty($items)) {
237
            $sql = "SELECT * FROM c_item_property
238
                    WHERE tool = '$tool' AND c_id = $courseId AND ref = $id";
239
            $result = $connection->executeQuery($sql);
240
            $items = $result->fetchAllAssociative();
241
        }
242
243
        // For some reason the resource doesnt have a c_item_property value.
244
        if (empty($items)) {
245
            return false;
246
        }
247
248
        $container = $this->getContainer();
249
        $doctrine = $container->get('doctrine');
250
        $em = $doctrine->getManager();
251
        $sessionRepo = $container->get(SessionRepository::class);
252
        $groupRepo = $container->get(CGroupRepository::class);
253
        $userRepo = $container->get(UserRepository::class);
254
255
        $resource->setParent($parent);
0 ignored issues
show
Bug introduced by
The method setParent() does not exist on Chamilo\CoreBundle\Entity\ResourceInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Chamilo\CoreBundle\Entity\ResourceInterface. ( Ignorable by Annotation )

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

255
        $resource->/** @scrutinizer ignore-call */ 
256
                   setParent($parent);
Loading history...
256
        $resourceNode = null;
257
        $userList = [];
258
        $groupList = [];
259
        $sessionList = [];
260
        foreach ($items as $item) {
261
            $visibility = $item['visibility'];
262
            $userId = $item['insert_user_id'];
263
            $sessionId = $item['session_id'] ?? 0;
264
            $groupId = $item['to_group_id'] ?? 0;
265
266
            $newVisibility = ResourceLink::VISIBILITY_PENDING;
267
            switch ($visibility) {
268
                case 0:
269
                    $newVisibility = ResourceLink::VISIBILITY_PENDING;
270
                    break;
271
                case 1:
272
                    $newVisibility = ResourceLink::VISIBILITY_PUBLISHED;
273
                    break;
274
                case 2:
275
                    $newVisibility = ResourceLink::VISIBILITY_DELETED;
276
                    break;
277
            }
278
279
            if (isset($userList[$userId])) {
280
                $user = $userList[$userId];
281
            } else {
282
                $user = $userList[$userId] = $userRepo->find($userId);
283
            }
284
285
            if (null === $user) {
286
                $user = $admin;
287
            }
288
289
            $session = null;
290
            if (!empty($sessionId)) {
291
                if (isset($sessionList[$sessionId])) {
292
                    $session = $sessionList[$sessionId];
293
                } else {
294
                    $session = $sessionList[$sessionId] = $sessionRepo->find($sessionId);
295
                }
296
            }
297
298
            $group = null;
299
            if (!empty($groupId)) {
300
                if (isset($groupList[$groupId])) {
301
                    $group = $groupList[$groupId];
302
                } else {
303
                    $group = $groupList[$groupId] = $groupRepo->find($groupId);
304
                }
305
            }
306
307
            if (null === $resourceNode) {
308
                $resourceNode = $repo->addResourceNode($resource, $user, $parent);
309
                $em->persist($resourceNode);
310
            }
311
            $resource->addCourseLink($course, $session, $group, $newVisibility);
0 ignored issues
show
Bug introduced by
The method addCourseLink() does not exist on Chamilo\CoreBundle\Entity\ResourceInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Chamilo\CoreBundle\Entity\User. Are you sure you never get one of those? ( Ignorable by Annotation )

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

311
            $resource->/** @scrutinizer ignore-call */ 
312
                       addCourseLink($course, $session, $group, $newVisibility);
Loading history...
312
            $em->persist($resource);
313
        }
314
315
        return true;
316
    }
317
}
318