PHP - PHP AYUDA CON EL REGISTRO

 
Vista:
sin imagen de perfil

PHP AYUDA CON EL REGISTRO

Publicado por Manuel Flores (3 intervenciones) el 09/02/2017 22:48:00
El error viene al extraer el id del cv de createCv()....

deberia insertarme un cv para un usuario por lo que ahora me inserta 2 para un usuario ... uno con datos llenos y el otro con vacios solo contiene id del cv y id del usuario

AYUDA.....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
<?php
 
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;
 
class CreateUserCommand extends Command
{
    private $input;
    private $output;
    private $suscriptions = [];
 
    protected function configure()
    {
        $this
            ->setName('app:create-users')
            ->setDescription('Creates new users.')
            ->setHelp("This command allows you to create new users into algo")
            ->addOption('countryAbrev',
                'c',
                InputOption::VALUE_REQUIRED,
                'Set the country Abreviation for the user(s)')
            ->addOption('numberOfUsers',
                'u',
                InputArgument::OPTIONAL,
                'Set how many users you are going to create')
            ->addOption('password',
                'p',
                InputArgument::OPTIONAL,
                'Set the default password for the user(s)')
            ->addOption('membershipId',
                'm',
                InputArgument::OPTIONAL,
                'Set the membership id for the user(s)');
            /*Cambio Viernes
            ->addOption('numberOfExperiences',
                'e',
                InputArgument::OPTIONAL,
                'Set how many experiences you are going to create');*/
    }
 
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->output = $output;
        $io = new SymfonyStyle($input, $output);
        $membershipType = 0;
        $numberOfUsers = 1;
        //Cambio Viernes
        //$experiencias = 1;
        $password = '';
        $countryAbrev = $this->getCountryAbrev();
        $noInteraction = $this->getNoInteractiveMode();
        if (!empty($noInteraction)) {
            $membershipType = $this->getMembershipId();
            $numberOfUsers = $this->getNumberOfUsers();
            //Cambio Viernes
            //$numberOfExperiences = $this->getNumberOfExperiences();
            $password = $this->getPasswordArg();
        } else {
            list($countryAbrev, $numberOfUsers, $membershipType, $password) =
                $this->getInteractiveMode($input, $output, $io);
        }
        if (empty($countryAbrev)) {
            $io->caution('You must set the countryAbrev option');
            return;
        }
        $suscripcion = null;
        if ($membershipType > 0) {
            $suscripcion = Suscripcion::find_by_id_and_estado($membershipType, 1);
            if (!$suscripcion instanceof Suscripcion) {
                $io->caution('The suscription type does not exists');
            } elseif ($suscripcion->idtipo_de_usuario != 1) {
                $io->caution('Invalid suscription for users');
                $suscripcion = null;
            }
        }
        $results = [];
        for ($i = 0; $i < $numberOfUsers; ++$i) {
            //Cambio Viernes $experiencias
            //for ($j = 0; $j < $numberOfExperiences; ++$j){
                    try {
                        $user = $this->createUser($countryAbrev, $suscripcion, $password);
                        $cvs = $this->createCv($user);
                        $experience = $this->createExpLaboral($cvs);
                        if ($user) {
                            $results[] = 'User name: ' . utf8_encode($user->nombre) . ' ' .
                                utf8_encode($user->apellido) . "\n" . 'Email: ' . $user->usuario;
                        }
                    } catch (Exception $e) {
                        $io->caution($e->getMessage());
                        break;
                    }
                }
                if (!empty($results)) {
                    $io->success($results);
                }
            }
        //}
 
    private function createUser($countryAbrev, $suscription, $password)
    {
        static $pais = '';
        $success = false;
        if ($pais == '') {
            $pais = Pais::find_by_abreviatura($countryAbrev);
        }
 
        $password = trim($password);
        if (!empty($pais)) {
            $lang = strtolower($pais->lang);
            $lang = $lang == 'sp' ? 'es' : $lang;
            $lang = $lang == 'po' ? 'pt' : $lang;
            $lang = $lang . '_' . strtoupper($lang);
            $entrada = array("H","M");
            $faker = Faker\Factory::create($lang);
            $usuario = new Usuario();
            $usuario->usuario = $faker->email;
            $usuario->otro_email = $usuario->usuario;
            $usuario->nombre = utf8_decode($faker->firstName);
            $usuario->fechanac = $faker->dateTimeBetween($startDate = '-60 years', $endDate = '-19 years');
            $usuario->pass = !empty($password) ? $password : $faker->password;
            $usuario->apellido = utf8_decode($faker->lastName);
            $usuario->idpaises = $pais->id;
            $usuario->ciudad = utf8_decode($faker->city);
            $usuario->ciudad_o_estado = utf8_decode($faker->state);
            $usuario->localidad_barrio = utf8_decode($faker->country);
            $usuario->domicilio = utf8_decode($faker->address);
            $usuario->cp = $faker->postcode;
            $usuario->sexo = $entrada[array_rand($entrada)];
            $usuario->telefono = $faker->phoneNumber;
            $usuario->celular = $faker->phoneNumber;
            try {
                $usuario->save(false);
                $success = $usuario;
                if (!empty($usuario->id) && $suscription instanceof Suscripcion) {
                    SuscripcionUsuario::create([
                        'IdUsuario' => $usuario->id,
                        'IdSuscripcion' => $suscription->id,
                        'Fecha_hora' => date('Y-m-d H:i:s'),
                        'Fecha_ultima_actualizacion' => date('Y-m-d'),
                        'Fecha_vencimiento' => date('Y-m-d',
                            strtotime('+ ' . $suscription->frecuencia . 'months')),
                        'Notificacion_enviada' => 1,
                        'Estado' => 1,
                    ]);
                }
            } catch (Exception $e) {
                trigger_error($e->getMessage(), E_USER_WARNING);
            }
        } else {
            throw new Exception("Invalid country Abreviation", 1);
        }
        return $success;
    }
 
    private function getInteractiveMode($input, $output, $io)
    {
        $helper = $this->getHelper('question');
        $countryAbrevQuestion = new Question('Set the country for the user(s)[mx]: ',
            'mx');
        $countryAbrev = trim($helper->ask($input, $output, $countryAbrevQuestion));
        $passwordQuestion = new Question('Set a default password: ', '');
        $password = $helper->ask($input, $output, $passwordQuestion);
        $numberOfUsersQuestion = new Question('How many users you want to create? ',
        1, '/^[0-9]{1,}$/');
        $numberOfUsers = $helper->ask($input, $output, $numberOfUsersQuestion);
        $numberOfUsers = ($numberOfUsers < 1) ? 1 : $numberOfUsers;
        /*NUEVAS EXPERIENCIAS
        $numberOfExperiencesQuestion = new Question('How many experiences for each user you want to create? ',
            1, '/^[0-9]{1,}$/');
        $numberOfExperiences = $helper->ask($input, $output, $numberOfExperiencesQuestion);
        $numberOfExperiences = ($numberOfExperiences < 1) ? 1 : $numberOfExperiences;
        AQUI TERMINAN*/
        $addMembership = $io->confirm('Do you want to assign a membership? ', false);
        $membershipId = 0;
        if ($addMembership) {
            $this->getSuscriptions();
            $choices = ["0)\tfor none"];
            foreach ($this->suscriptions as $id => $name) {
                $choices[] = sprintf("%d)\t%s", $id, $name);
            }
            $io->newLine();
            $io->text('Please choise the membership');
            $io->newLine();
            $io->listing($choices);
            $isValid = false;
            $membershipIdQuestion = new Question('Write the Id ', 0,
                '/^[0-9]{1,}$/');
            $suscriptionIds = array_keys($this->suscriptions);
            while (!$isValid) {
                $membershipId = $helper->ask($input, $output, $membershipIdQuestion);
                $membershipId = $membershipId < 0 ? 0 : $membershipId;
                $isValid = $membershipId == 0 | in_array($membershipId,
                        $suscriptionIds);
            }
        }
        return [$countryAbrev, $numberOfUsers, $membershipId, $password];
    }
 
    private $cv = 0;
    private function createCv($usuario)
    {
        $faker = Faker\Factory::create();
        $this->cv = new Cv();
        //$GLOBALS['cv'] = new Cv();
        //$GLOBALS['cv']->idusuario = $usuario->id;
        $this->cv->idusuario = $usuario->id;
        try {
            $usuario->save(false);
            $success = $usuario;
            if (!empty($usuario->id)) {
                Cv::create([
                    'Id' => $this->cv->id,
                    //'Id' => $GLOBALS['cv']->id,
                    'IdUsuario' => $usuario->id,
                    'Titulo' => 'CV de ' . "" . $usuario->nombre,
                    'Salario' => $faker->numberBetween($min = 5000, $max = 15000),
                    'Fecha_Creacion' => date('Y-m-d'),
                ]);
            }
        } catch (Exception $e) {
            trigger_error($e->getMessage(), E_USER_WARNING);
        } finally {
            return $success;
        }
    }
 
    private function createExpLaboral()
    {
        $faker = Faker\Factory::create();
        $expLaboral = new Explaboral();
        $expLaboral->idcvs = $this->cv->id;
        //$expLaboral->idcvs = $GLOBALS['cv']->id;
        try {
            $this->cv->save(false);
            $success = $this->cv->id;
            //$success = $GLOBALS['cv'];
            if (!empty($this->cv->id)) {
            //if (!empty($GLOBALS['cv']->id)) {
                Explaboral::create([
                    'Id' => $expLaboral->id,
                    'IdCVS' => $this->cv->id,
                    //'IdCVS' => $GLOBALS['cv']->id,
                    'Nombre_de_la_Empresa' => utf8_decode($faker->company),
                    'IdRubro_de_la_Empresa' => 0,
                    'Nombre_del_Puesto' => utf8_decode($faker->jobTitle),
                    'IdJerarquia_del_Puesto' => 0,
                    'IdArea_de_trabajo' => 0,
                    'IdPersonal_a_cargo' => 0,
                    'FechaInicio' => $faker->dateTimeBetween($startDate = '-60 years', $endDate = '-40 years'),
                    'FechaFin' => $faker->dateTimeBetween($startDate = '-40 years', $endDate = '-35 years'),
                ]);
            }
        } catch (Exception $e) {
            trigger_error($e->getMessage(), E_USER_WARNING);
        } finally {
            return $success;
        }
    }
 
    private function getMembershipId()
    {
        $membershipId = (int)$this->input->getOption('membershipId');
        $membershipId = $membershipId < 0 ? 0 : $membershipId;
        return $membershipId;
    }
 
    private function getNumberOfUsers()
    {
        $users = (int)$this->input->getOption('numberOfUsers');
        return ($users < 1) ? 1 : $users;
    }
 
   /*Cambio Viernes
    private function getNumberOfExperiences()
    {
        $exp = (int)$this->input->getOption('numberOfExperiences');
            return ($exp < 1) ? 1 : $exp;
    }
   */
 
    private function getPasswordArg()
    {
        return $this->input->getOption('password');
    }
 
    private function getNoInteractiveMode()
    {
        return $this->input->getOption("no-interaction");
    }
 
    private function getCountryAbrev()
    {
        return $this->input->getOption('countryAbrev');
    }
 
    private function getSuscriptions()
    {
        $suscriptions = Suscripcion::find('all', [
            'select' => 'SUSCRIPCION.Id AS Id, SUSCRIPCION.Nombre AS Nombre,' .
                'TIPO_DE_SUSCRIPCION.Nombre AS Tipo',
            'conditions' => 'IdTipo_de_usuario = 1 AND SUSCRIPCION.Estado = 1' .
                ' AND TIPO_DE_SUSCRIPCION.Estado = 1 AND Frecuencia > 0',
            'joins' => 'LEFT JOIN TIPO_DE_SUSCRIPCION ON ' .
                'SUSCRIPCION.IdTipo_de_suscripcion = TIPO_DE_SUSCRIPCION.Id',
            'order' => 'TIPO_DE_SUSCRIPCION.Id ASC, Orden ASC',
        ]);
        foreach ($suscriptions as $suscription) {
            $this->suscriptions[$suscription->id] = sprintf("%s (%s)",
                utf8_encode($suscription->nombre), utf8_encode($suscription->tipo));
        }
    }
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder