Completed
Push — master ( 58043b...413e7c )
by Sergi Tur
06:39
created

UserMigrations::migrateUsers()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 38
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 28
nc 7
nop 2
dl 0
loc 38
rs 8.439
c 1
b 0
f 0
1
<?php
2
3
namespace Acacha\Users\Services;
4
5
use Acacha\Users\Events\ProgressBarStatusHasBeenUpdated;
6
use Acacha\Users\Models\ProgressBatch;
7
use Illuminate\Support\Collection;
8
use Psr\Log\InvalidArgumentException;
9
use Scool\EbreEscoolModel\User;
10
use Acacha\Users\Events\UserHasBeenMigrated;
11
use Acacha\Users\Exceptions\MigrationException;
12
use Illuminate\Database\QueryException;
13
14
/**
15
 * Class UserMigrations.
16
 *
17
 * @package Acacha\Users\Services
18
 */
19
class UserMigrations
20
{
21
22
    /**
23
     * Migrate users.
24
     *
25
     * @param array|User $usersToMigrate
26
     * @param $batch
27
     */
28
    public function migrate($usersToMigrate, $batch)
29
    {
30
        if (is_array($usersToMigrate) || $usersToMigrate instanceof Collection) {
31
            $this->migrateUsers($usersToMigrate, $batch);
32
            return;
33
        }
34
        if ($usersToMigrate instanceof User) {
35
            $this->migrateUser($usersToMigrate, $batch->id);
36
            return;
37
        }
38
        throw new InvalidArgumentException();
39
    }
40
41
    /**
42
     * Migrate users.
43
     *
44
     * @param $usersToMigrate
45
     * @param $batch
46
     */
47
    public function migrateUsers($usersToMigrate, $batch)
48
    {
49
        $max_execution_time = ini_get('max_execution_time');
50
        set_time_limit ( 0);
51
52
        if (count($usersToMigrate) == 0 ) return;
53
54
        info('Users migration : A new batch user migration ( id: ' . $batch->id .') has been initialized!');
55
        $progressIncrement = $this->progressIncrement($usersToMigrate);
56
57
        $progress= 0; $migratedUsers=0; $errorUsers=0;
58
59
        foreach ($usersToMigrate as $user) {
60
            if ($batch->stopped()) {
61
                info('Users migration : A batch user migration ( id: ' . $batch->id .') has been stopped!');
62
                event(new ProgressBarStatusHasBeenUpdated('users-migration-progress-bar', $progress,'Migration stopped!' ));
63
                return;
64
            }
65
            info('Users migration : Migrating user username: ' . $user->username .'!');
66
            event(new ProgressBarStatusHasBeenUpdated('users-migration-progress-bar',$progress,'Migrating user ' . $user->username));
67
            try {
68
                $this->migrateUser($user, $batch->id);
69
                event(new ProgressBarStatusHasBeenUpdated('users-migration-progress-bar', $progress,'User ' . $user->username . ' migrated' ));
70
                $migratedUsers++;
71
                info('Users migration : User username: ' . $user->username .' migrated correctly!');
72
            } catch (MigrationException $e) {
73
                event(new ProgressBarStatusHasBeenUpdated('users-migration-progress-bar', $progress,'User ' . $user->username . ' not migrated. ' . $e->getMessage() ));
74
                $errorUsers++;
75
                info('Users migration : ERROR migrating user username: ' . $user->username .'!');
76
            }
77
            $progress= $progress + $progressIncrement;
78
        }
79
80
        event(new ProgressBarStatusHasBeenUpdated('users-migration-progress-bar', 100,'Migration finished!' ));
81
        $this->finishMigrationBatch($batch, $migratedUsers,$errorUsers);
82
        info('Users migration : A batch user migration ( id: ' . $batch->id .') has been finished!');
83
        set_time_limit ( $max_execution_time);
84
    }
85
86
    /**
87
     * Migrate User.
88
     *
89
     * @param $user
90
     * @param $batchId
91
     * @return null
92
     * @throws MigrationException
93
     */
94
    public function migrateUser($user, $batchId)
95
    {
96
        $newUser = null;
97
        if ($email = $user->getEmailFromUser()) {
98
            try {
99
                $newUser = \App\User::create([
100
                    'name' => $user->username,
101
                    'email' => $email,
102
                    'password' => bcrypt('secret')
103
                ]);
104
                event(new UserHasBeenMigrated($user->id, $user->toJson(), $newUser, $batchId));
105
                return $newUser;
106
            } catch( QueryException $e) {
107
                event(new UserHasBeenMigrated($user->id, $user->toJson(), null, $batchId));
108
                throw new MigrationException($e->getMessage());
109
            }
110
        } else {
111
            event(new UserHasBeenMigrated($user->id, $user->toJson(), null, $batchId));
112
            throw new MigrationException("Source User doesn't have email");
113
        }
114
    }
115
116
    /**
117
     * Finish migration batch.
118
     *
119
     * @param ProgressBatch $batch
120
     * @param $migratedUsers
121
     * @param $errorUsers
122
     */
123
    protected function finishMigrationBatch(ProgressBatch $batch , $migratedUsers, $errorUsers)
124
    {
125
        $batch->accomplished = $migratedUsers;
0 ignored issues
show
Documentation introduced by
The property accomplished does not exist on object<Acacha\Users\Models\ProgressBatch>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
126
        $batch->incidences = $errorUsers;
0 ignored issues
show
Documentation introduced by
The property incidences does not exist on object<Acacha\Users\Models\ProgressBatch>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
127
        $batch->finish();
0 ignored issues
show
Bug introduced by
The method finish() does not exist on Acacha\Users\Models\ProgressBatch. Did you maybe mean validateFinish()?

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...
128
        $batch->save();
129
    }
130
131
    /**
132
     * Calculate progress increment.
133
     *
134
     * @return float|int
135
     */
136
    protected function progressIncrement($usersToMigrate)
137
    {
138
        return 100/count($usersToMigrate);
139
    }
140
}