Пример #1
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     /** @var EntityManager em */
     $em = $this->getContainer()->get('doctrine')->getManager();
     $users = $em->getRepository('ESNUserBundle:User')->findBy(array("esner" => 1));
     $concerned_users = new ArrayCollection();
     /** @var User $user */
     foreach ($users as $user) {
         /** @var EsnerFollow $follow */
         $follow = $user->getFollow();
         if ($follow) {
             $trial = $follow->getTrialstarted();
             $end_trial = $trial;
             date_add($trial, date_interval_create_from_date_string('21 days'));
             $now = new \DateTime();
             if ($end_trial->format('d/m/Y') == $now->format('d/m/Y')) {
                 $concerned_users->add($user);
             }
         }
     }
     /** @var User $concerned_user */
     foreach ($concerned_users as $concerned_user) {
         $message = \Swift_Message::newInstance()->setSubject('[ESN Lille][ERP] Periode d\'essaie terminé pour ' . $concerned_user->getFullname())->setFrom($this->getContainer()->getParameter('mailer_from'))->setTo($user->getEmail())->setBody($this->getContainer()->get('templating')->render('ESNHRBundle:Emails:trial_ended.html.twig', array('user' => $concerned_user)), 'text/html');
         $this->getContainer()->get('mailer')->send($message);
     }
 }
Пример #2
0
 /**
  * @Route("/rooms/{id}", name="showRoom")
  * @param string $id
  * @param Request $request
  * @throws \Exception
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function roomsAction($id, Request $request)
 {
     if ($id == 'random') {
         $page = $this->getDoctrine()->getRepository('AppBundle:Pages')->getRandomPage();
         if (!$page) {
             return $this->render('default/empty.html.twig');
         }
     } else {
         $page = $this->getDoctrine()->getRepository('AppBundle:Pages')->find($id);
         if (!$page) {
             throw $this->createNotFoundException('No page found for request param ' . $id);
         }
     }
     $imagesCollector = new ImagesViewCollector();
     $bookingEntity = new Booking();
     $calculator = new Calculator();
     $context = new CalculationContext();
     $context->setPricePerNight($page->getRawValue('priceNight'));
     $now = new \DateTime();
     $context->setCheckInDate($now->format('Y-m-d'));
     $context->setCheckOutDate($now->modify('+1 day')->format('Y-m-d'));
     $calcResult = $calculator->calculate($context);
     $bookingEntity->setGuestsCount($calcResult['guestsCount']);
     $bookingEntity->setPriceString($calcResult['pricePerNight']);
     $bookingEntity->setCheckinDate($calcResult['checkinDate']);
     $bookingEntity->setCheckoutDate($calcResult['checkoutDate']);
     $bookingEntity->setPage($page);
     $bookingEntity->setPageId($page->getId());
     $form = $this->createForm(new BookingForm('/add-booking/' . $page->getId()), $bookingEntity);
     $form->handleRequest($request);
     return $this->render('default/index.html.twig', array('page' => $page, 'images' => $imagesCollector->collect($page), 'bookingCalc' => $calcResult, 'form' => $form->createView()));
 }
 /**
  * @param FormBuilderInterface $builder
  * @param array $options
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     #Data atual.
     $dataHoje = new \DateTime("now");
     #Formatação do número do protocolo em ano, mês, dia, minuto e segundo.
     $codId = $dataHoje->format("Ymdhis");
     $builder->add('codIndentificadorDocumento', 'text', array('label' => 'Registro Documento *', 'required' => false, 'data' => $codId, 'constraints' => array(new NotNull(array('message' => 'Código identificador inválido.'))), 'attr' => array('readonly' => true, 'widget_col' => '4', "class" => "")))->add('numOficio', 'text', array('label' => 'Número do ofício *', 'attr' => array('widget_col' => '4')))->add('observacaoDocumento', 'textarea', array('label' => 'Observação: ', 'required' => false, 'attr' => array('placeholder' => 'Observação', 'widget_col' => '6', 'class' => 'mask_letras', 'onkeyup' => 'mascara( this, alphanum )')))->add('dataEntradaDocumento', 'datetime', array('label' => false, 'required' => false, 'data' => $dataHoje, 'constraints' => array(new DateTime(array('message' => 'Formato de Data não é válido'))), 'attr' => array('widget_col' => '2', 'hidden' => true)))->add('empresa', 'entity', array('label' => 'Empresa de Origem', 'required' => false, 'empty_value' => "Selecione a empresa", 'class' => 'Serbinario\\Bundles\\ProtocoloBundle\\Entity\\Empresas', 'attr' => array('widget_col' => '4', 'class' => '')))->add('tipoDocumentosTipoDocumento', 'entity', array('label' => 'Tipo do Documento * ', 'required' => false, 'empty_value' => "Selecione o tipo", 'class' => 'Serbinario\\Bundles\\ProtocoloBundle\\Entity\\TipoDocumentos', 'constraints' => array(new NotNull(array('message' => 'Você deve fornecer um tipo de documento'))), 'attr' => array('widget_col' => '4', 'class' => '')))->add('secretariasSecretaria', 'entity', array('label' => 'Secretaria de Origem', 'empty_value' => "Selecione a secretaria", 'required' => false, 'class' => 'Serbinario\\Bundles\\ProtocoloBundle\\Entity\\Secretarias', 'attr' => array('widget_col' => '4')))->add('actions', 'form_actions', ['buttons' => ['save' => ['type' => 'submit', 'options' => ['label' => 'Salvar']], 'cancel' => ['type' => 'button', 'options' => ['label' => 'Voltar']]]]);
 }
 /**
  * @return WorkingMonth[]
  */
 public function findProspectiveWorkingMonths()
 {
     $startMonth = new \DateTime();
     $startMonth->modify('first day of this month');
     $qb = parent::createQueryBuilder('e');
     $qb->where('e.date >= :startMonth')->andWhere('e.isDeleted = 0')->setParameter('startMonth', $startMonth->format('Y-m-d'));
     return $qb->getQuery()->getResult();
 }
Пример #5
0
 public function getStringPeriode()
 {
     $dateDebut = new DateTime($this->getDateDebutPeriod());
     $dateFinale = new DateTime($this->getDateFinalePeriode());
     $dateDiff = $dateDebut->diff($dateFinale);
     #echo 'Nombre de temp : '.$interval->format('%y ans,%m mois, %d jour, %h heures, %i minutes %s secondes')
     $this->periode = $dateDiff->format("%m mois");
     return $this->periode;
 }
 /**
  * @covers: RI\FileManagerBundle\Manager\UploadDirectoryManager::getNewPath
  * @covers: RI\FileManagerBundle\Manager\UploadDirectoryManager::getAbsoluteUploadDirPath
  * @covers: RI\FileManagerBundle\Manager\UploadDirectoryManager::generateNewFileName
  * @covers: RI\FileManagerBundle\Manager\UploadDirectoryManager::createDestinationDir
  */
 public function testGetNewPath_IfFileExist()
 {
     $date = new \DateTime();
     $expectedPath = sprintf('/upload/%s/%s/%s/7/79/790f1bfea8585c9bc2e7b6267cb212e1.jpg', $date->format('y'), $date->format('m'), $date->format('d'));
     $expectedPathSecondFile = sprintf('/upload/%s/%s/%s/7/79/8b912a2bf1302f5a1170d3e57d8f8caf.jpg', $date->format('y'), $date->format('m'), $date->format('d'));
     $this->assertEquals($expectedPath, $this->uploadDirectoryManager->getNewPath('hello_world.jpg'));
     copy(__DIR__ . '/hello_world.jpg', sprintf('/tmp/web/upload/%s/%s/%s/7/79/790f1bfea8585c9bc2e7b6267cb212e1.jpg', $date->format('y'), $date->format('m'), $date->format('d')));
     $this->assertEquals($expectedPathSecondFile, $this->uploadDirectoryManager->getNewPath('hello_world.jpg'));
 }
Пример #7
0
 protected function import(InputInterface $input, OutputInterface $output, $agency_to_import)
 {
     // Getting php array of data from CSV
     $data = $this->get($input, $output, $agency_to_import);
     // Getting doctrine manager
     $em = $this->getContainer()->get('doctrine')->getManager();
     // Turning off doctrine default logs queries for saving memory
     $em->getConnection()->getConfiguration()->setSQLLogger(null);
     // Define the size of record, the frequency for persisting the data and the current index of records
     $size = count($data);
     $batchSize = 20;
     $i = 1;
     // Starting progress
     $progress = new ProgressBar($output, $size);
     $progress->start();
     // Processing on each row of data
     foreach ($data as $row) {
         //Create new collaborator, find his agency, format his birth date
         $collaborator = new Collaborator();
         $birthDate = \DateTime::createFromFormat('d/m/Y', $row['Date_Naissance']);
         $agency = $em->getRepository('CharlestownAgencyBundle:Agency')->find($row['group_name']);
         //Update is infos
         $collaborator->setUsername($row['users_login']);
         $collaborator->setPlainPassword($row['password']);
         $collaborator->setEmail($row['users_email']);
         $collaborator->setLastName($row['users_surname']);
         $collaborator->setFirstName($row['users_name']);
         $collaborator->setEnabled($row['active']);
         $collaborator->setAgency($agency);
         $collaborator->setAddress($row['adresse']);
         $collaborator->setPc($row['code_postal']);
         $collaborator->setTown($row['ville']);
         $collaborator->setPortPhoneNumber($row['portable']);
         $collaborator->setPhoneNumber($row['telephone']);
         $collaborator->setBirthDate($birthDate);
         // Do stuff here !
         // Persisting the current user
         $em->persist($collaborator);
         // Each 20 users persisted we flush everything
         if ($i % $batchSize === 0) {
             $em->flush();
             // Detaches all objects from Doctrine for memory save
             $em->clear();
             // Advancing for progress display on console
             $progress->advance($batchSize);
             $now = new \DateTime();
             $output->writeln(' of users imported ... | ' . $now->format('d-m-Y G:i:s'));
         }
         $i++;
     }
     // Flushing and clear data on queue
     $em->flush();
     $em->clear();
     // Ending the progress bar process
     $progress->finish();
 }
 /**
  * Creates a new Carpooling entity.
  *
  * @Route("/covoiturage/create", name="social_carpooling_create")
  * @Method("POST")
  * @Template("CharlestownCarpoolingBundle:Carpooling:new.html.twig")
  */
 public function createAction(Request $request)
 {
     $entity = new Carpooling();
     $em = $this->getDoctrine()->getManager();
     $entity->setStartPlace($request->get('depart'));
     $entity->setEndPlace($request->get('arrivé'));
     if ($request->get('recurrent') == "oui") {
         $hour = new \DateTime();
         $hour->setTime(substr($request->get('hour'), 0, 2), substr($request->get('hour'), 3, 2));
         $entity->setDateTravel($hour);
         if ($request->get('monday') == "on") {
             $entity->setMonday(true);
         } else {
             $entity->setMonday(false);
         }
         if ($request->get('tuesday') == "on") {
             $entity->setTuesday(true);
         } else {
             $entity->setTuesday(false);
         }
         if ($request->get('wednesday') == "on") {
             $entity->setWednesday(true);
         } else {
             $entity->setWednesday(false);
         }
         if ($request->get('thursday') == "on") {
             $entity->setThursday(true);
         } else {
             $entity->setThursday(false);
         }
         if ($request->get('friday') == "on") {
             $entity->setFriday(true);
         } else {
             $entity->setFriday(false);
         }
         if ($request->get('saturday') == "on") {
             $entity->setSaturday(true);
         } else {
             $entity->setSaturday(false);
         }
         if ($request->get('sunday') == "on") {
             $entity->setSunday(true);
         } else {
             $entity->setSunday(false);
         }
         $entity->setRecurrent(true);
     } else {
         $entity->setDateTravel($request->get("datetime"));
         $entity->setRecurrent(false);
     }
     $entity->setDriver($this->getUser());
     $em->persist($entity);
     $em->flush();
     return $this->redirect($this->generateUrl('social_my_carpooling'));
 }
 protected function import(InputInterface $input, OutputInterface $output)
 {
     // Getting php array of data from CSV
     $data = $this->get($input, $output);
     // Getting doctrine manager
     $em = $this->getContainer()->get('doctrine')->getManager();
     // Turning off doctrine default logs queries for saving memory
     $em->getConnection()->getConfiguration()->setSQLLogger(null);
     // Define the size of record, the frequency for persisting the data and the current index of records
     $size = count($data);
     $batchSize = 10;
     $i = 1;
     // Starting progress
     $progress = new ProgressBar($output, $size);
     $progress->start();
     // Processing on each row of data
     foreach ($data as $row) {
         //Create new collaborator, find his agency
         $collaborator = new Collaborator();
         $agency = $em->getRepository('CharlestownAgencyBundle:Agency')->find($row['code_agence']);
         //Update is infos
         $collaborator->setUsername($row['id']);
         $collaborator->setPlainPassword($row['password']);
         $collaborator->setAgency($agency);
         $collaborator->setEmail($row['mail']);
         $collaborator->setLastName($row['nom']);
         $collaborator->setFirstName($row['prenom']);
         $collaborator->setPortPhoneNumber($row['portable']);
         $collaborator->setPhoneNumber($row['fixe']);
         $collaborator->addRole('ROLE_USER');
         $collaborator->addRole('ROLE_ADMIN');
         $collaborator->addRole('ROLE_AE');
         $collaborator->addRole('ROLE_EVENT');
         $collaborator->setEnabled(true);
         // Persisting the current user
         $em->persist($collaborator);
         // Each 20 users persisted we flush everything
         if ($i % $batchSize === 0) {
             $em->flush();
             // Detaches all objects from Doctrine for memory save
             $em->clear();
             // Advancing for progress display on console
             $progress->advance($batchSize);
             $now = new \DateTime();
             $output->writeln(' of admins imported ... | ' . $now->format('d-m-Y G:i:s'));
         }
         $i++;
     }
     // Flushing and clear data on queue
     $em->flush();
     $em->clear();
     // Ending the progress bar process
     $progress->finish();
 }
 public function getJobsAction(Request $request)
 {
     $time = explode("-", $request->query->get('date'));
     $date = new \DateTime();
     $date->setDate($time[0], $time[1], $time[2]);
     $user = $this->getUser();
     $response = new JsonResponse();
     $workTimes = $this->container->get('work_time')->getWorkerSchedule($user, $date);
     $response->setData($workTimes);
     return $response;
 }
 public function addEntry($timestamp, $value, $insulin, $be)
 {
     $entry = new DiaborgEntry();
     $datetime = new \DateTime();
     $datetime->setTimestamp($timestamp);
     $entry->setTimestamp($datetime);
     $entry->setValue($value);
     $entry->setInsulin($insulin);
     $entry->setBe($be);
     $this->addEntity($entry);
 }
Пример #12
0
 /**
  * @Route("/addOrder/{user_id}/{product_id}/{count}")
  */
 public function addOrderAction($user_id, $product_id, $count)
 {
     $date = new \DateTime("now");
     $order = new Order($user_id, $product_id, $date->format('d-m-Y'), $count);
     print_r($order);
     $em = $this->getDoctrine()->getManager();
     $em->persist($order);
     $em->flush();
     $result = array("response" => "true");
     $response = new Response(json_encode($result));
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     // Showing when the script is launched
     $now = new \DateTime();
     $output->writeln('<comment>Start : ' . $now->format('d-m-Y G:i:s') . ' ---</comment>');
     $type = "collaborator";
     $this->import($input, $output, $type);
     $type = "customer";
     $this->import($input, $output, $type);
     // Showing when the script is over
     $now = new \DateTime();
     $output->writeln('<comment>End : ' . $now->format('d-m-Y G:i:s') . ' ---</comment>');
 }
Пример #14
0
 /**
  * @Route("/", name="homepage")
  */
 public function indexAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $topics = $this->getDoctrine()->getRepository('AppBundle:Topics')->findByTopEighteen();
     $authors = $this->getDoctrine()->getRepository('AppBundle:Authors')->findByTopEighteen();
     $homepic = $this->getDoctrine()->getRepository('AppBundle:Quotes')->findByPicHome(2);
     $date = new \DateTime();
     # todo: rank-aar ne shvvj xaryylax
     $query = $em->createQuery("SELECT p\n            FROM AppBundle:Authors p\n            WHERE p.born LIKE :date")->setParameter('date', '%' . $date->format('-m-d'));
     $birthdays = $query->setMaxResults(5)->getResult();
     // replace this example code with whatever you need
     return $this->render('default/index.html.twig', array('topics' => $topics, 'authors' => $authors, 'birthdays' => $birthdays, 'homepic' => $homepic, 'menu' => '1'));
 }
Пример #15
0
 /**
  * @Route("/", name="homepage")
  */
 public function indexAction(Request $request)
 {
     $user = new User();
     $alert = null;
     $form = $this->createFormBuilder($user)->add('username', TextType::class)->add('password', PasswordType::class)->add('login', SubmitType::class, array('label' => 'Login'))->add('create', SubmitType::class, array('label' => 'Create'))->getForm();
     $form->handleRequest($request);
     $session = new Session();
     $cookie_token = $session->get('package_user_token');
     if ($form->isSubmitted() && $form->isValid() || $cookie_token) {
         // ... perform some action, such as saving the task to the database
         $sm = $this->getDoctrine();
         $user = $sm->getRepository('AppBundle:User')->findOneByUsername($user->getUsername());
         if ($form->get('create')->isClicked() == 'create') {
             if ($user == null) {
                 $user = new User();
                 $user->setUsername($form->get('username')->getData());
                 $passw = $form->get('password')->getData();
                 $user->setPassword($passw);
                 $date = new \DateTime();
                 $token = $passw + $date->getTimestamp();
                 $user->setToken($token);
                 $session->set('package_user_token', $token);
                 $sm->getManager()->persist($user);
                 $sm->getManager()->flush();
                 return $this->redirect($this->generateUrl('packages_index'));
             } else {
                 $alert = "This username already exists.";
             }
         } else {
             if ($form->get('login')->isClicked() == 'login' || $cookie_token) {
                 if ($cookie_token) {
                     $user = $sm->getRepository('AppBundle:User')->findOneByToken($cookie_token);
                 }
                 if ($user != null) {
                     $passwForm = md5($form->get('password')->getData());
                     if (strcmp($passwForm, $user->getPassword()) === 0) {
                         $token = $user->getToken();
                         $session->set('package_user_token', $token);
                         return $this->redirect($this->generateUrl('packages_index'));
                     } else {
                         $alert = "Password doesn't match.";
                     }
                 } else {
                     $alert = "This username doesn't exists.";
                 }
             }
         }
     }
     return $this->render('default/index.html.twig', array('form' => $form->createView(), 'alert' => $alert));
 }
Пример #16
0
 public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder, array $options)
 {
     for ($i = 0; $i < 5; $i++) {
         foreach ($options['weekDates'] as $index => $weekDate) {
             $dateTime = new \DateTime($weekDate);
             $builder->add('project_' . $i . '_' . $index, EntityType::class, ['class' => 'Admin\\FrontendBundle\\Entity\\Project', 'placeholder' => '', 'attr' => ['class' => 'select2'], 'required' => false]);
             $builder->add('time_from_' . $i . '_' . $index, TextType::class, ['required' => false, 'attr' => ['class' => 'timerFrom', 'data-date' => $dateTime->format('Y-m-d')]]);
             $builder->add('time_to_' . $i . '_' . $index, TextType::class, ['required' => false, 'attr' => ['class' => 'timerTo', 'data-date' => $dateTime->format('Y-m-d')]]);
             $builder->add('km_' . $i . '_' . $index, TextType::class, ['required' => false, 'attr' => ['class' => 'col-md-2']]);
             $builder->add('pay_type_' . $i . '_' . $index, EntityType::class, ['class' => 'Admin\\FrontendBundle\\Entity\\AttendancePayType', 'placeholder' => '', 'attr' => ['class' => 'select2'], 'required' => false]);
         }
     }
     $builder->add('submit', SubmitType::class, array('label' => 'Save', 'attr' => array('class' => 'btn btn-primary')));
     parent::buildForm($builder, $options);
 }
 /**
  * Displays a form to edit an existing Product entity.
  *
  * @Route("/{id}/edit", name="product_edit")
  * @Method({"GET", "POST"})
  */
 public function editAction(Request $request, Product $product)
 {
     $deleteForm = $this->createDeleteForm($product);
     $editForm = $this->createForm(ProductType::class, $product);
     $editForm->handleRequest($request);
     if ($editForm->isSubmitted() && $editForm->isValid()) {
         $em = $this->getDoctrine()->getManager();
         $nowUtc = new \DateTime('now', new \DateTimeZone('Asia/Dhaka'));
         $product->setDateModified($nowUtc->format("d-M-Y h:i:s"));
         $em->persist($product);
         $em->flush();
         return $this->redirectToRoute('product_edit', array('id' => $product->getId()));
     }
     return $this->render('product/edit.html.twig', array('product' => $product, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView()));
 }
 /**
  * Transforms a value from the transformed representation to its original
  * representation.
  *
  * This method is called when {@link Form::bind()} is called to transform the requests tainted data
  * into an acceptable format for your data processing/model layer.
  *
  * This method must be able to deal with empty values. Usually this will
  * be an empty string, but depending on your implementation other empty
  * values are possible as well (such as empty strings). The reasoning behind
  * this is that value transformers must be chainable. If the
  * reverseTransform() method of the first value transformer outputs an
  * empty string, the second value transformer must be able to process that
  * value.
  *
  * By convention, reverseTransform() should return NULL if an empty string
  * is passed.
  *
  * @param mixed $value The value in the transformed representation
  *
  * @return mixed The value in the original representation
  *
  * @throws UnexpectedTypeException       when the argument is not of the expected type
  * @throws TransformationFailedException when the transformation fails
  */
 public function reverseTransform($value)
 {
     if (!$value instanceof \DateTime) {
         return $value;
     }
     if (null == $value) {
         return null;
     }
     if ($this->widgetType == 'date') {
         $value = new \DateTime($value->format('Y-m-d'));
     }
     if ($this->widgetType == 'time' or $this->widgetType == 'day') {
         $value = new \DateTime('1970-01-01 ' . $value->format('H:i:s'));
     }
     return $value;
 }
Пример #19
0
 /**
  * @Route("/addMess/{from}/{to}/{mes}")
  */
 public function addAction($from, $to, $mes)
 {
     $message = new Message();
     $message->setFromId($from);
     $message->setToId($to);
     $message->setMessage($mes);
     $message->setStatus(0);
     $message->setDateTime(new \DateTime("now"));
     $date = new \DateTime("now");
     $date->format('Y-m-d h-m-s');
     print_r($date);
     $mrepo = $this->getDoctrine()->getManager();
     $mrepo->persist($message);
     $mrepo->flush();
     return new Response();
 }
Пример #20
0
 /**
  * {@inheritdoc}
  */
 public function validate($value, Constraint $constraint)
 {
     if (!$constraint instanceof DateTime) {
         throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\DateTime');
     }
     if (null === $value || '' === $value || $value instanceof \DateTime) {
         return;
     }
     if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
         throw new UnexpectedTypeException($value, 'string');
     }
     $value = (string) $value;
     \DateTime::createFromFormat($constraint->format, $value);
     $errors = \DateTime::getLastErrors();
     if (0 < $errors['error_count']) {
         $this->context->buildViolation($constraint->message)->setParameter('{{ value }}', $this->formatValue($value))->setCode(DateTime::INVALID_FORMAT_ERROR)->addViolation();
         return;
     }
     foreach ($errors['warnings'] as $warning) {
         if ('The parsed date was invalid' === $warning) {
             $this->context->buildViolation($constraint->message)->setParameter('{{ value }}', $this->formatValue($value))->setCode(DateTime::INVALID_DATE_ERROR)->addViolation();
         } elseif ('The parsed time was invalid' === $warning) {
             $this->context->buildViolation($constraint->message)->setParameter('{{ value }}', $this->formatValue($value))->setCode(DateTime::INVALID_TIME_ERROR)->addViolation();
         } else {
             $this->context->buildViolation($constraint->message)->setParameter('{{ value }}', $this->formatValue($value))->setCode(DateTime::INVALID_FORMAT_ERROR)->addViolation();
         }
     }
 }
 public function triggerItemAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $response = array('error' => false, 'message' => "Item has been activated!");
     try {
         $req = $this->get('request')->request;
         $fighterId = $req->get('fighter_id');
         $inventoryId = $req->get('inventory_id');
         /** @var FighterRepository $fighterRepository */
         $fighterRepository = $em->getRepository('GameBaseBundle:Fighter');
         $fighter = $fighterRepository->getFighterById($fighterId);
         if (!$fighter) {
             throw new \Exception("The fighter does not exist.");
         } else {
             if ($fighter->getManager()->getId() != $_SESSION['manager']->getId()) {
                 throw new \Exception("You do not own this fighter.");
             }
         }
         /** @var InventoryRepository $inventoryRepository */
         $inventoryRepository = $em->getRepository('GameBaseBundle:Inventory');
         $inventory = $inventoryRepository->getInventoryById($inventoryId);
         if (!$inventory) {
             throw new \Exception("Inventory id does not exist.");
         } else {
             if ($inventory->getManager()->getId() != $_SESSION['manager']->getId()) {
                 throw new \Exception("You do not own that item,");
             } elseif ($inventory->getQuantity() <= 0) {
                 throw new \Exception("You have already wasted all the items of this type.");
             }
         }
         $stats = $fighter->getStats();
         /** @var Item $item */
         $item = $inventory->getItem();
         $inventory->setQuantity($inventory->getQuantity() - 1);
         $stats->setStamina($stats->getStamina() + $item->getStamina())->setStrength($stats->getStrength() + $item->getStrength())->setAgility($stats->getAgility() + $item->getAgility())->setIntelligence($stats->getIntelligence() + $item->getIntelligence())->setStrike($stats->getStrike() + $item->getStrike())->setKicking($stats->getKicking() + $item->getStamina())->setGrappling($stats->getGrappling() + $item->getGrappling())->setTakedown($stats->getTakedown() + $item->getTakedown());
         $endTimeS = new \DateTime();
         $endTimeS->add(new \DateInterval('PT' . $item->getDuration() . 'M'));
         $effect = new Effect();
         $effect->setFighter($fighter)->setItem($item)->setStartTime(new \DateTime())->setEndTime($endTimeS);
         $em->persist($effect);
         $em->flush();
     } catch (\Exception $e) {
         $response['error'] = true;
         $response['message'] = $e->getMessage();
     }
     return new JsonResponse($response);
 }
Пример #22
0
 /**
  * @param $spot
  * Efface toutes les données plus vielle que today
  */
 static function deleteOldData($spot, $em)
 {
     // On check toutes les notesDate
     $listePrecedenteNotes = $spot->getNotesDate();
     if ($listePrecedenteNotes != null && count($listePrecedenteNotes) > 0) {
         //la liste n'est pas vide
         $today = new \DateTime('now');
         $today->setTime(0, 0, 0);
         foreach ($listePrecedenteNotes as $precedenteNotes) {
             if ($precedenteNotes->getDatePrev() < $today) {
                 // avant today -> on efface
                 $em->remove($precedenteNotes);
             }
         }
         $em->flush();
     }
 }
 /**
  *
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function indexAction(Request $request)
 {
     $start = $end = null;
     if (!$request->get('start')) {
         $start = new \DateTime('now');
         //6 last months
         $start->sub(new \DateInterval('P3M'));
     } else {
         $start = \DateTime::createFromFormat('d/m/Y', $request->get('start'));
     }
     if (!$request->get('end')) {
         $end = new \DateTime('now');
     } else {
         $end = \DateTime::createFromFormat('d/m/Y', $request->get('end'));
     }
     /** @var Section $section */
     $section = $this->container->get('section_manager')->getCurrentSection();
     /** @var UserRepository $userRepo */
     $userRepo = $this->getDoctrine()->getManager()->getRepository('BuddySystemUserBundle:User');
     $emails = array();
     $emails["all"] = $emails["is"] = $emails["local"] = $emails["notmatched"] = "";
     /** @var User $user */
     foreach ($userRepo->findBy(array("section" => $section)) as $user) {
         if ($user->getJoindate()) {
             if ($start && $user->getJoindate() >= $start && $end && $user->getJoindate() <= $end) {
                 $emails["all"] .= $user->getEmail() . ", ";
                 if ($user->isLocal()) {
                     $emails["local"] .= $user->getEmail() . ", ";
                 }
                 if (!$user->isLocal()) {
                     $emails["is"] .= $user->getEmail() . ", ";
                 }
                 if (!$user->isMatched()) {
                     $emails["notmatched"] .= $user->getEmail() . ", ";
                 }
             }
         }
     }
     $emails["all"] = substr($emails["all"], 0, -2);
     $emails["local"] = substr($emails["local"], 0, -2);
     $emails["is"] = substr($emails["is"], 0, -2);
     $emails["notmatched"] = substr($emails["notmatched"], 0, -2);
     return $this->render('BuddySystemMembersBundle:Mailing:index.html.twig', array("emails" => $emails));
 }
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $manager)
 {
     $config = new Config();
     $config->setCle('currency');
     $config->setValeur('€');
     $manager->persist($config);
     $manager->flush();
     $config2 = new Config();
     $config2->setCle('currentBudget');
     $config2->setValeur('');
     $manager->persist($config2);
     $manager->flush();
     $date = new \DateTime('0-0-0');
     $date->setDate(0, 2, 0);
     $declarationTVA = new DeclarationTva();
     $declarationTVA->setCommentaire("Déclaration de tva poubelle pour les factures un peu douteuses");
     $declarationTVA->setDate($date);
     $declarationTVA->setSoldePrecedent(0);
     $declarationTVA->setSoldeFinal(0);
 }
Пример #25
0
 public function _header()
 {
     $date = new \DateTime();
     $this->setFont('Arial', 'B', 16);
     $this->cell(0, 8, 'Référence', 0, 1);
     $this->setFont('Arial', '', 16);
     $this->multicell(0, 8, $this->entity->getWork()->getPlace(), 0);
     $this->cell(0, 8, 'Code : ' . $this->entity->getWork()->getDoor()->getCode(), 0);
     $this->cell(0, 8, 'Imprimé le ' . $date->format('d/m/Y'), 0, 1, 'R');
     $quote = $this->entity->getWork()->getQuote();
     if ($quote === null) {
         $this->cell(0, 8, 'Complet', 0, 1, 'R');
     } else {
         $this->cell(0, 8, 'Devis n°' . $quote->getNumber(), 0, 1, 'R');
     }
     if ($this->entity->getTime() > 0) {
         $this->cell(0, 8, 'Temps prévu (heure/technicien) : ' . $this->entity->getTime(), 0, 1, 'R');
     }
     $this->ln(12);
 }
Пример #26
0
 public function createAuthTokenFromCode(AuthCodeInterface $authCode)
 {
     $code = $this->base64url_encode($this->random_string(17));
     $oauth = $this->container->getParameter("rest.config")["authentication"]["oauth"];
     $parameter = $oauth["persistence"];
     $auth_token_entity = $parameter["auth_token_entity"];
     /** @var AuthTokenInterface $entity */
     $entity = new $auth_token_entity();
     $entity->setAuthToken($code);
     $entity->setScopes($authCode->getScopes());
     $entity->setConsumer($authCode->getConsumer());
     $entity->setUser($authCode->getUser());
     $dt = new \DateTime();
     $entity->setValidTill($dt->getTimestamp() + $oauth["token_lifetime"]);
     $manager = $this->getDoctrine()->getManager();
     $manager->persist($entity);
     $manager->remove($authCode);
     $manager->flush();
     return $entity;
 }
Пример #27
0
 public function onKernelRequest(GetResponseEvent $event)
 {
     if ($event->isMasterRequest()) {
         $request = $event->getRequest();
         $routePath = $request->getRequestUri();
         if (strpos($routePath, 'api')) {
             $userId = $request->query->get('resources')['id'];
             if ($userId) {
                 $user = $this->em->getRepository('UserBundle:User')->findOneById($userId);
                 $lastUse = new Online();
                 $lastUse = $this->em->createQueryBuilder()->select('u')->from('AppBundle:Online', 'u')->orderBy('u.time', 'DESC')->where('u.user = :userId')->setParameter('userId', $userId)->setMaxResults(1)->getQuery()->getOneOrNullResult();
                 $date = new \DateTime();
                 $now = new \DateTime();
                 $date = $lastUse->getTime();
                 $diff = $now->getTimestamp() - $date->getTimestamp();
                 $now = (string) $now->format('Y-m-d');
                 $date = (string) $date->format('Y-m-d');
                 if ($now == $date) {
                     $todayUse = $lastUse->getTodayUse();
                     if ($diff > 3600) {
                         $diff = 0;
                     }
                     $todayUse = $todayUse + $diff;
                     $lastUse->setUser($user);
                     $lastUse->setTime(new \DateTime());
                     $lastUse->setTodayUse($todayUse);
                     $this->em->persist($lastUse);
                     $this->em->flush();
                 } else {
                     $online = new Online();
                     $online->setUser($user);
                     $online->setTime(new \DateTime());
                     $online->setTodayUse('0');
                     $this->em->persist($online);
                     $this->em->flush();
                 }
             }
         }
     }
 }
 public function dateInterval($date, $locale)
 {
     $comment_date = new \DateTime($date);
     $dateNow = new \DateTime('NOW');
     $interval = $dateNow->diff($comment_date);
     $periodes = [$interval->format('%y'), $interval->format('%m'), $interval->format('%d'), $interval->format('%h'), $interval->format('%i')];
     $unity_en = [['year', 'years'], ['month', 'months'], ['day', 'days'], ['hour', 'hours'], ['minute', 'minutes']];
     $unity_fr = [['an', 'ans'], ['mois', 'mois'], ['jour', 'jours'], ['heure', 'heures'], ['minute', 'minutes']];
     $periodesLength = count($periodes);
     for ($i = 0; $i < $periodesLength; $i++) {
         if (intval($periodes[$i]) >= 1 && $i < count($periodes)) {
             $locale_unity = $locale == "fr" ? $unity_fr : $unity_en;
             $u = $periodes[$i] > 1 ? $locale_unity[$i][1] : $locale_unity[$i][0];
             return $periodes[$i] . ' ' . $u;
         }
     }
     if ($locale == 'fr') {
         return "moins d'une minute";
     } else {
         return 'less than a minute';
     }
 }
Пример #29
0
 public function comprobarLicitacionesFecha()
 {
     $fecha = new \DateTime('now');
     $contarLicitacion = $this->em->createQuery('SELECT COUNT(x.nombre) FROM AppMediBundle:Licitacion x WHERE x.fechaTermino < :fecha AND x.estado IN (1,2)')->setParameter('fecha', $fecha->format('Y-m-d H:i:s'));
     $contarLicitacion = $contarLicitacion->getSingleScalarResult();
     return $contarLicitacion;
 }
Пример #30
0
 /**
  * @param \DateTime $date
  * @return bool
  */
 public function isOpen(\DateTime $date = null)
 {
     if ($date === null) {
         $date = new \DateTime();
     }
     $week = $this->toArray();
     $day = strtolower($date->format('w'));
     /** @var OpeningHours $today */
     $today = $week[$day];
     if (!$today->getClosed()) {
         $opening = clone $date;
         $closing = clone $date;
         $opening->modify('today ' . $today->getOpens());
         $closing->modify('today ' . $today->getCloses());
         if ($closing < $opening) {
             $closing->modify('+1 day');
         }
         if ($date >= $opening && $date < $closing) {
             return true;
         }
     }
     if ($day - 1 < 0) {
         /** @var OpeningHours $yesterday */
         $today = $week[6];
     } else {
         $today = $week[$day - 1];
     }
     if (!$today->getClosed()) {
         $opening = clone $date;
         $closing = clone $date;
         $opening->modify('yesterday ' . $today->getOpens());
         $closing->modify('yesterday ' . $today->getCloses());
         if ($closing < $opening) {
             $closing->modify('+1 day');
         }
         if ($date >= $opening && $date < $closing) {
             return true;
         }
     }
     return false;
 }