示例#1
0
 /**
  * @param OrdersImportItem $import_item
  *
  * @return array ['reg_nmb' => <string>,'model' => <string>, 'color' => <string>]
  */
 private function parseCarInfo(OrdersImportItem $import_item)
 {
     $car_info = array_map('trim', explode(';', $import_item->car_info));
     $reg_nmb = $model = $color = null;
     // Known formats
     if (count($car_info) == 3) {
         if (Entity\Car::isRegNmb($car_info[0])) {
             // reg_nmb; model; color
             list($reg_nmb, $model, $color) = $car_info;
         } else {
             // vendor; model; reg_nmb
             $model = $car_info[0] . ' ' . $car_info[1];
             $reg_nmb = $car_info[2];
         }
     }
     return array('reg_nmb' => $reg_nmb, 'model' => $model, 'color' => $color);
 }
 /**
  * @param Employes2ImportItem $item
  * @param AbstractItemImportResult $item_result
  *
  * @return AbstractItemImportResult
  */
 protected function _processImportItem($item, &$item_result)
 {
     $merge_phones = $merge_cars = false;
     $employe = $this->findEmployes($item);
     if (empty($employe)) {
         $employe = new Entity\Employe();
     } elseif ($this->getOption('update_existing')) {
         if (count($employe) > 1) {
             return $item_result->addMessage('More than one employe was found with the given data');
         } else {
             $employe = array_pop($employe);
             if ($employe->getExternalId() !== (int) $item->external_id) {
                 $merge_phones = $merge_cars = true;
             }
         }
     } else {
         return $item_result->addMessage('An employe with given external_id already exists');
     }
     // Обработка компаний
     $_taxis_str = trim($item->taxis);
     $taxis = array();
     if (!empty($_taxis_str)) {
         $str_taxis = array_map('trim', explode(',', $_taxis_str));
         $notfound_str_taxis = array();
         /** @var ORM\EntityRepository */
         $rep = $this->_em->getRepository('TaxiPrizeTaxiBundle:TaxiCompany');
         // TODO: Делать один запрос, перебирать массив результатов.
         foreach ($str_taxis as $str_taxi) {
             if (in_array($str_taxi, $notfound_str_taxis, true)) {
                 continue;
             }
             $taxi = $rep->findOneBy(array('name' => $str_taxi));
             if (empty($taxi)) {
                 $notfound_str_taxis[] = $str_taxi;
             } else {
                 $taxis[$taxi->getId()] = $taxi;
             }
         }
         if (!empty($notfound_str_taxis)) {
             if ($this->getOption('create_notfound_taxi_company')) {
                 $new_taxis = array();
                 foreach ($notfound_str_taxis as $str_taxi) {
                     $taxi = new Entity\TaxiCompany();
                     $taxi->setName($str_taxi);
                     // 						$this->_em->persist($taxi);
                     $taxis[] = $taxi;
                     $new_taxis[] = $taxi;
                 }
                 // 					$this->_em->flush();
             } elseif (!$this->getOption('import_with_notfound_taxi_companies')) {
                 return $item_result->addMessage('Following taxis are not found: ' . implode(', ', $notfound_str_taxis));
             }
         }
         // 			$employe->setTaxiCompanies($taxis);
     } elseif (!$this->getOption('import_without_taxi_companies')) {
         return $item_result->addMessage('Import without taxi companies is not allowed');
     }
     if (!empty($taxis)) {
         // Обработка ролей
         $_roles_str = trim($item->roles);
         if (!empty($_roles_str)) {
             $str_roles = array_map('trim', explode(',', $_roles_str));
             array_unique($str_roles);
             $notfound_str_roles = $str_name_roles = $str_title_roles = array();
             foreach ($str_roles as $str_role) {
                 if ($this->isRoleName($str_role)) {
                     $str_name_roles[] = $str_role;
                 } else {
                     $str_title_roles[] = $str_role;
                 }
             }
             // Отыскание несуществующих ролей
             $qb = $this->_em->createQueryBuilder();
             $found_by_name = $qb->select('r')->from('TaxiPrizeTaxiBundle:EmployeRole', 'r', 'r.name')->where('r.name IN (:role_names)')->setParameter('role_names', $str_name_roles)->getQuery()->execute();
             $qb = $this->_em->createQueryBuilder();
             $found_by_title = $qb->select('r')->from('TaxiPrizeTaxiBundle:EmployeRole', 'r', 'r.title')->where('r.title IN (:role_titles)')->setParameter('role_titles', $str_title_roles)->getQuery()->execute();
             $found_roles = array_merge($found_by_name, $found_by_title);
             $need_roles = $found_roles;
             $name_keys = array_keys($found_by_name);
             $title_keys = array_keys($found_by_title);
             $notfound_str_name_roles = array_diff($str_name_roles, $name_keys);
             $notfound_str_title_roles = array_diff($str_title_roles, $title_keys);
             $notfound_str_roles = array_merge($notfound_str_name_roles, $notfound_str_title_roles);
             if (!empty($notfound_str_roles)) {
                 if ($this->getOption('create_notfound_role')) {
                     $new_roles = array();
                     foreach ($notfound_str_roles as $str_role) {
                         $role = new Entity\EmployeRole();
                         $this->isRoleName($str_role) ? $role->setName($str_role) : $role->setTitle($str_role);
                         // 							$this->_em->persist($role);
                         $new_roles[] = $role;
                         $need_roles[] = $role;
                     }
                     // 						$this->_em->flush();
                 } else {
                     return $item_result->addMessage('Following roles are not found: ' . implode(', ', $notfound_str_roles));
                 }
             }
             // Добавление несуществующих связей сотрудник - роль - компания
             $new_ecrs = array();
             $rep = $this->_em->getRepository('TaxiPrizeTaxiBundle:EmployeCompanyRole');
             foreach ($taxis as $taxi) {
                 if (is_null($employe->getId())) {
                     // Сотрудник новый, без сомнений добавляем все роли во все компании.
                     foreach ($need_roles as $role) {
                         $ecr = new Entity\EmployeCompanyRole($employe, $taxi, $role);
                         $new_ecrs[] = $ecr;
                         // 							$this->_em->persist($ecr);
                     }
                 } else {
                     // Перед добавлением связки проверяем её существование
                     foreach ($found_roles as $role) {
                         if (is_null($rep->findOneBy(array('employe' => $employe, 'company' => $taxi, 'role' => $role)))) {
                             $ecr = new Entity\EmployeCompanyRole($employe, $taxi, $role);
                             $new_ecrs[] = $ecr;
                         }
                     }
                     if (isset($new_roles)) {
                         // Добавляем связки с новыми ролями
                         foreach ($new_roles as $role) {
                             $ecr = new Entity\EmployeCompanyRole($employe, $taxi, $role);
                             $new_ecrs[] = $ecr;
                         }
                     }
                 }
             }
         }
     }
     // Обработка автомобилей
     $_cars_str = trim($item->car_reg_nmbs);
     if (!empty($_cars_str)) {
         $cars = array();
         $str_cars = array_map('trim', explode(',', $_cars_str));
         $notfound_str_cars = array();
         /** @var ORM\EntityRepository */
         $rep = $this->_em->getRepository('TaxiPrizeTaxiBundle:Car');
         // TODO: Делать один запрос, перебирать массив результатов.
         foreach ($str_cars as $str_car) {
             $res = $rep->findOneBy(array('regNmb' => $str_car));
             if (empty($res)) {
                 $notfound_str_cars[] = $str_car;
             } else {
                 $cars[] = $res;
             }
         }
         if (!empty($notfound_str_cars)) {
             if ($this->getOption(self::OPTION_CREATE_NOTFOUND_CAR)) {
                 foreach ($notfound_str_cars as $str_car) {
                     $car = new Entity\Car();
                     $car->setRegNmb($str_car);
                     $this->_em->persist($car);
                     $cars[] = $car;
                 }
             }
         }
         if ($merge_cars) {
             foreach ($cars as $car) {
                 if (!$employe->getCars()->contains($car)) {
                     $employe->addCar($car);
                 }
             }
         } else {
             $employe->setCars($cars);
         }
     }
     // Остальные данные
     list($second_name, $first_name) = $this->parseName($item);
     $employe->setExternalId($item->external_id)->setSecondName($second_name)->setFirstName($first_name)->setImportName($item->name)->setCallsign($item->callsign)->setBalance(round(floatval($item->balance), 2))->setLastLocationChange($this->getRelocationDateTime($item))->setState($item->state);
     // Телефоны
     $phones = array_map('trim', preg_split('#[\\s,]+#', $item->phones));
     if ($merge_phones) {
         $phones_cmpr = $employe->getWorkPhones(true);
         foreach ($phones as $phone) {
             if (!in_array(Entity\Client::compressPhone($phone), $phones_cmpr)) {
                 $employe->addWorkPhone($phone);
             }
         }
     } else {
         $employe->setWorkPhones($phones);
     }
     // Сохранение подготовленных сущностей.
     // Первичный ключ EmployeCompanyRole состоит из внешних ключей, поэтому адресуемые сущности должны быть сохранены раньше.
     if (isset($new_taxis) && !empty($new_taxis)) {
         foreach ($new_taxis as $taxi) {
             $this->_em->persist($taxi);
         }
     }
     if (isset($new_roles) && !empty($new_roles)) {
         foreach ($new_roles as $role) {
             $this->_em->persist($role);
         }
     }
     $this->_em->beginTransaction();
     try {
         $this->_em->persist($employe);
         $this->_em->flush();
         if (isset($new_ecrs) && !empty($new_ecrs)) {
             foreach ($new_ecrs as $ecr) {
                 $this->_em->persist($ecr);
             }
         }
         $this->_em->flush();
         $this->_em->getConnection()->commit();
         return $item_result->setSuccessful();
     } catch (\Exception $e) {
         $this->_em->getConnection()->rollBack();
         throw $e;
     }
 }