Example #1
1
 /**
  * Class constructor.
  */
 public function __construct(ProjectService $projectService)
 {
     parent::__construct();
     $this->setAttribute('method', 'post');
     $this->setAttribute('class', 'form-horizontal');
     $this->setAttribute('id', 'create-report');
     /*
      * Create an array with possible periods. This will trigger a date but display a period (semester)
      */
     $semesterOptions = [];
     foreach ($projectService->parseYearRange() as $year) {
         /*
          * Use the Report object to parse the data
          */
         $report = new Report();
         $report->setDatePeriod(\DateTime::createFromFormat('Y-m-d', $year . '-03-01'));
         $semesterOptions[$year . '-1'] = $report->parseName();
         $report->setDatePeriod(\DateTime::createFromFormat('Y-m-d', $year . '-09-01'));
         $semesterOptions[$year . '-2'] = $report->parseName();
     }
     $this->add(['type' => 'Zend\\Form\\Element\\Select', 'name' => 'period', 'options' => ['label' => _("txt-report-period"), 'help-block' => _("txt-report-period-explanation"), 'value_options' => $semesterOptions], 'attributes' => ['class' => "form-control", 'id' => "period"]]);
     $this->add(['type' => 'Zend\\Form\\Element\\Text', 'name' => 'item', 'options' => ['label' => _("txt-document-name"), 'help-block' => _("txt-document-name-explanation")], 'attributes' => ['placeholder' => _("txt-please-give-a-document-name")]]);
     $this->add(['type' => '\\Zend\\Form\\Element\\File', 'name' => 'file', 'options' => ["label" => "txt-file", "help-block" => _("txt-file-requirements")]]);
     $this->add(['type' => 'Zend\\Form\\Element\\Submit', 'name' => 'submit', 'attributes' => ['class' => "btn btn-primary", 'value' => _("txt-create")]]);
     $this->add(['type' => 'Zend\\Form\\Element\\Submit', 'name' => 'cancel', 'attributes' => ['class' => "btn btn-warning", 'value' => _("txt-cancel")]]);
 }
Example #2
1
 /**
  * Creates token
  * @param string $type Type of the token
  * @param string $name Name of the token unique for selected type
  * @param callable|AlgorithmInterface $algorithm Algorithm of the token generation
  * @param int|\DateTime|Expression $expire Expiration date of the token
  * @return static
  */
 public static function create($type, $name, $algorithm = null, $expire = null)
 {
     if ($algorithm === null) {
         $algorithm = new RandomString();
     }
     $token = static::findOne(['type' => $type, 'name' => $name]);
     if ($token == null) {
         $token = new static();
     }
     $token->type = $type;
     $token->name = $name;
     if (is_callable($algorithm)) {
         $token->token = call_user_func($algorithm);
     } else {
         $token->token = $algorithm->generate();
     }
     if (is_integer($expire)) {
         $token->expire_at = \DateTime::createFromFormat('U', $expire, new \DateTimeZone('UTC'))->setTimezone(new \DateTimeZone('MSK'))->format('Y-m-d H:i:s');
     } elseif ($expire instanceof \DateTime) {
         $token->expire_at = $expire->format('Y-m-d h:i:s');
     } else {
         $token->expire_at = $expire;
     }
     $token->created_at = new Expression('NOW()');
     $token->save(false);
     return $token;
 }
Example #3
0
 public function setAssignments()
 {
     $request = self::$_appInstance->request();
     $post_data = json_decode($request->post('data'));
     $table = 'student_exam_assignment';
     if (!isset($post_data[0])) {
         $results['message'] = 'เกิดข้อผิดพลาดในการบันทึกข้อมูล';
         $results['error'] = true;
     }
     $date = new DateTime("now");
     $startAssignment = $date->createFromFormat('d/m/Y', $post_data[0]->startAssignment)->format('Y-m-d');
     $endAssignment = $date->createFromFormat('d/m/Y', $post_data[0]->endAssignment)->format('Y-m-d');
     $isError = true;
     foreach ($post_data as $savedata) {
         # code...
         $data['student_course_id'] = $savedata->student_course_id;
         $data['assign_by'] = $savedata->assign_by;
         $data['exam_random_history_id'] = $savedata->exam_random_history_id;
         $data['start_assignment'] = $startAssignment;
         $data['end_assignment'] = $endAssignment;
         $data['assign_date'] = $date->format('Y-m-d H:i:s');
         if (!self::isAlreadyExist($data)) {
             $id = PDOAdpter::getInstance()->insert($data, $table);
             $isError = !isset($id);
             $results['message'] = $isError ? 'เกิดข้อผิดพลาดในการบันทึกข้อมูล' : 'บันทึกข้อมูลเสร็จเรียบร้อย';
         } else {
             $results['message'] = "พบข้อมูลซ้ำในระบบฐานข้อมูล";
         }
     }
     $results['route'] = 'list_of_exams.php';
     $results['isError'] = $isError;
     echo json_encode($results);
 }
Example #4
0
 /**
  * @param int $numberOfMonths
  * @return array|bool
  */
 public function getLastMonths($numberOfMonths = 12)
 {
     $statistics = [];
     $date = new \DateTime();
     $startDate = time() - $numberOfMonths * 60 * 60 * 24 * 30;
     $this->setTableName('comments');
     $rows = $this->fetchAll('time >= "' . date('Y-m-01 H:i:s', $startDate) . '"')->toArray();
     foreach ($rows as $row) {
         $row['time'] = $date->createFromFormat('Y-m-d H:i:s', $row['time'])->format('Y') . ' Q' . floor(date("m", $date->createFromFormat('Y-m-d H:i:s', $row['time'])->getTimestamp()) / 3);
         $statistics[$row['time']]['comments']++;
     }
     $this->setTableName('posts');
     $rows = $this->fetchAll('time >= "' . date('Y-m-01 H:i:s', $startDate) . '"')->toArray();
     foreach ($rows as $row) {
         $row['time'] = $date->createFromFormat('Y-m-d H:i:s', $row['time'])->format('Y') . ' Q' . floor(date("m", $date->createFromFormat('Y-m-d H:i:s', $row['time'])->getTimestamp()) / 3);
         $statistics[$row['time']]['posts']++;
     }
     $this->setTableName('notifications');
     $rows = $this->fetchAll('time >= "' . date('Y-m-01 H:i:s', $startDate) . '"')->toArray();
     foreach ($rows as $row) {
         $row['time'] = $date->createFromFormat('Y-m-d H:i:s', $row['time'])->format('Y') . ' Q' . floor(date("m", $date->createFromFormat('Y-m-d H:i:s', $row['time'])->getTimestamp()) / 3);
         $statistics[$row['time']]['notifications']++;
     }
     $this->setTableName('users');
     $rows = $this->fetchAll('registered >= "' . date('Y-m-01 H:i:s', $startDate) . '"')->toArray();
     foreach ($rows as $row) {
         $row['time'] = $row['registered'];
         $row['time'] = $date->createFromFormat('Y-m-d H:i:s', $row['time'])->format('Y') . ' Q' . floor(date("m", $date->createFromFormat('Y-m-d H:i:s', $row['time'])->getTimestamp()) / 3);
         $statistics[$row['time']]['users']++;
     }
     return $statistics;
 }
Example #5
0
 protected function handleTypeConversions($value, $typeOfField)
 {
     if ($typeOfField == 'datetime') {
         return \DateTime::createFromFormat('d/m/Y', $value);
     }
     return parent::handleTypeConversions($value, $typeOfField);
 }
 /**
  * @param String The line to parse
  */
 public function __construct($string)
 {
     parent::__construct($string);
     $result = new COSResult();
     $result->setFileIdentifier(trim($this->columns[self::OFFSET_FILE_ID]));
     $result->setPaymentId(trim($this->columns[self::OFFSET_PAYMENT_ID]));
     $result->setTransactionId(trim($this->columns[self::OFFSET_TRANSACTION_ID]));
     $result->setInstrumentType(trim($this->columns[self::OFFSET_INSTRUMENT_TYPE]));
     $result->setInstrumentNumber(trim($this->columns[self::OFFSET_INSTRUMENT_NUMBER]));
     //datetime is now patched to return d/m/Y
     $datetime = \DateTime::createFromFormat('d/m/y', trim($this->columns[self::OFFSET_INSTRUMENT_DATE]));
     if (!$datetime) {
         $datetime = \DateTime::createFromFormat('d/m/Y', trim($this->columns[self::OFFSET_INSTRUMENT_DATE]));
     }
     $result->setDateTime($datetime);
     $result->setCurrency(trim($this->columns[self::OFFSET_CURRENCY]));
     $result->setAmount(trim($this->columns[self::OFFSET_AMOUNT]));
     //debit_date is now patched to return d/m/Y
     $debit_date = \DateTime::createFromFormat('d/m/y', trim($this->columns[self::OFFSET_DEBIT_DATE]));
     if (!$debit_date) {
         $debit_date = \DateTime::createFromFormat('d/m/Y', trim($this->columns[self::OFFSET_DEBIT_DATE]));
     }
     $result->setDebitDate($debit_date);
     $result->setStatus(trim($this->columns[self::OFFSET_STATUS]));
     //status_date is now patched to return d/m/Y
     $status_date = \DateTime::createFromFormat('d/m/y', trim($this->columns[self::OFFSET_STATUS_DATE]));
     if (!$status_date) {
         $status_date = \DateTime::createFromFormat('d/m/Y', trim($this->columns[self::OFFSET_STATUS_DATE]));
     }
     $result->setStatusDate($status_date);
     $result->setBeneficiaryId(trim($this->columns[self::OFFSET_BENEFICIARY_ID]));
     $result->setFullname(trim($this->columns[self::OFFSET_BENEFICIARY_NAME]));
     $this->cosResult = $result;
 }
Example #7
0
 protected function buildData($line, $line_number = null)
 {
     $row = parent::buildData($line, $line_number);
     if (isset($row[$this->structConfig['config']['date_field']])) {
         if ($row['type'] == 'mmsc') {
             $datetime = DateTime::createFromFormat($this->structConfig['config']['date_format'], preg_replace('/^(\\d+)\\+(\\d)$/', '$1+0$2:00', $row[$this->structConfig['config']['date_field']]));
             $matches = array();
             if (preg_match("/^\\+*(\\d+)\\//", $row['recipent_addr'], $matches)) {
                 $row['called_number'] = $matches[1];
             }
         } else {
             if (isset($row[$this->structConfig['config']['date_field']])) {
                 $offset = (isset($this->structConfig['config']['date_offset']) && isset($row[$this->structConfig['config']['date_offset']]) ? ($row[$this->structConfig['config']['date_offset']] > 0 ? "+" : "") . $row[$this->structConfig['config']['date_offset']] : "00") . ':00';
                 $datetime = DateTime::createFromFormat($this->structConfig['config']['date_format'], $row[$this->structConfig['config']['date_field']] . $offset);
             }
         }
         if (isset($row[$this->structConfig['config']['calling_number_field']])) {
             $row[$this->structConfig['config']['calling_number_field']] = Billrun_Util::msisdn($row[$this->structConfig['config']['calling_number_field']]);
         }
         if (isset($row[$this->structConfig['config']['called_number_field']])) {
             $row[$this->structConfig['config']['called_number_field']] = Billrun_Util::msisdn($row[$this->structConfig['config']['called_number_field']]);
         }
         $row['urt'] = new MongoDate($datetime->format('U'));
     }
     return $row;
 }
 /**
  * @param RequestInterface $request
  * @param ResponseInterface $response
  * @return CacheEntry|null entry to save, null if can't cache it
  */
 protected function getCacheObject(RequestInterface $request, ResponseInterface $response)
 {
     if (!isset($this->statusAccepted[$response->getStatusCode()])) {
         // Don't cache it
         return;
     }
     $cacheControl = new KeyValueHttpHeader($response->getHeader('Cache-Control'));
     $varyHeader = new KeyValueHttpHeader($response->getHeader('Vary'));
     if ($varyHeader->has('*')) {
         // This will never match with a request
         return;
     }
     if ($cacheControl->has('no-store')) {
         // No store allowed (maybe some sensitives data...)
         return;
     }
     if ($cacheControl->has('no-cache')) {
         // Stale response see RFC7234 section 5.2.1.4
         $entry = new CacheEntry($request, $response, new \DateTime('-1 seconds'));
         return $entry->hasValidationInformation() ? $entry : null;
     }
     foreach ($this->ageKey as $key) {
         if ($cacheControl->has($key)) {
             return new CacheEntry($request, $response, new \DateTime('+' . (int) $cacheControl->get($key) . 'seconds'));
         }
     }
     if ($response->hasHeader('Expires')) {
         $expireAt = \DateTime::createFromFormat(\DateTime::RFC1123, $response->getHeaderLine('Expires'));
         if ($expireAt !== false) {
             return new CacheEntry($request, $response, $expireAt);
         }
     }
     return new CacheEntry($request, $response, new \DateTime('-1 seconds'));
 }
Example #9
0
function printTweet($tweet, $boolean, $key)
{
    global $happyValueArray;
    $datetime = $tweet['created_at'];
    $new_date = DateTime::createFromFormat('D M d H:i:s O Y', $datetime);
    $new_date = $new_date->format('M d');
    if ($boolean) {
        echo '<div class="container">';
        echo '<div class="row">';
        echo '<div class="col-md-1">';
        echo "<a href={$tweet['user']['url']}><img src={$tweet['user']['profile_image_url']} height='42' width='42'></a>";
        echo '</div>';
        echo '<div class="cold-md-11">';
        echo "<a href={$tweet['user']['url']}>{$tweet['user']['screen_name']}</a> • {$new_date}<br>{$tweet['text']} || Happy = <b><i>" . $happyValueArray[$key] . "</b></i>";
        echo '</div> </div> </div> <br>';
    } else {
        echo '<div class="container">';
        echo '<div class="row">';
        echo '<div class="col-md-1">';
        echo "<a href={$tweet['user']['url']}><img src={$tweet['user']['profile_image_url']} height='42' width='42'></a>";
        echo '</div>';
        echo '<div class="cold-md-11">';
        echo "<a href={$tweet['user']['url']}>{$tweet['user']['screen_name']}</a> • {$new_date}<br>{$tweet['text']}";
        echo '</div> </div> </div> <br>';
    }
}
Example #10
0
 public function get_last_update()
 {
     global $conf;
     $update_file = file_get_contents($conf['updatefile']);
     $last_update = DateTime::createFromFormat('d.m.Y H:i:s', $update_file);
     return $last_update;
 }
 private static function getNearestWeekday($currentYear, $currentMonth, $targetDay)
 {
     $vmbiuiwr = "targetDay";
     ${${"GLOBALS"}["tchumjbel"]} = str_pad(${$vmbiuiwr}, 2, "0", STR_PAD_LEFT);
     $qvlloj = "lastDayOfMonth";
     ${"GLOBALS"}["akfjkh"] = "currentWeekday";
     ${${"GLOBALS"}["eagven"]} = \DateTime::createFromFormat("Y-m-d", "{$currentYear}-{$currentMonth}-{$tday}");
     ${${"GLOBALS"}["akfjkh"]} = (int) $target->format("N");
     if (${${"GLOBALS"}["lbniwfpf"]} < 6) {
         return ${${"GLOBALS"}["eagven"]};
     }
     ${$qvlloj} = $target->format("t");
     ${"GLOBALS"}["tdhsywdt"] = "i";
     foreach (array(-1, 1, -2, 2) as ${${"GLOBALS"}["tdhsywdt"]}) {
         ${"GLOBALS"}["rkhwmmreckl"] = "adjusted";
         ${"GLOBALS"}["vlvpyeexjroc"] = "adjusted";
         ${${"GLOBALS"}["rkhwmmreckl"]} = ${${"GLOBALS"}["cliypxb"]} + ${${"GLOBALS"}["pmnsmmcihwt"]};
         if (${${"GLOBALS"}["vlvpyeexjroc"]} > 0 && ${${"GLOBALS"}["quxzvrczu"]} <= ${${"GLOBALS"}["bppewpecifg"]}) {
             ${"GLOBALS"}["neicmchryn"] = "adjusted";
             ${"GLOBALS"}["bqllkuevy"] = "currentYear";
             $target->setDate(${${"GLOBALS"}["bqllkuevy"]}, ${${"GLOBALS"}["vrhapbb"]}, ${${"GLOBALS"}["neicmchryn"]});
             if ($target->format("N") < 6 && $target->format("m") == ${${"GLOBALS"}["vrhapbb"]}) {
                 return ${${"GLOBALS"}["eagven"]};
             }
         }
     }
 }
Example #12
0
 public function testOutputObject()
 {
     $this->_user->setId(1);
     $this->_user->setSurname('John');
     $this->_user->setLastname('Doe');
     $birthDate = \DateTime::createFromFormat('Y-m-d', '1982-07-05');
     $this->_user->setBirthdate($birthDate);
     $group = new Entity\Group();
     $group->setId(1);
     $group->setName('admin');
     $this->_user->addGroup($group);
     $expected = new \stdClass();
     $expected->id = 1;
     $expected->url = '/users/1';
     $expected->surname = 'John';
     $expected->lastname = 'Doe';
     $expected->birthdate = '1982-07-05';
     $expectedGroup = new \stdClass();
     $expectedGroup->id = 1;
     $expectedGroup->url = "/groups/1";
     $expectedGroup->name = "admin";
     $expectedGroup->created = $group->getCreated()->format(\Pollex\Entity\Base::DATE_FORMAT);
     $expectedGroup->updated = $group->getUpdated()->format(\Pollex\Entity\Base::DATE_FORMAT);
     $expected->groups = array($expectedGroup);
     $expected->created = $this->_user->getCreated()->format(Entity\Base::DATE_FORMAT);
     $expected->updated = $this->_user->getUpdated()->format(Entity\Base::DATE_FORMAT);
     $this->assertEquals($expected, $this->_user->getOutputObject());
 }
Example #13
0
 /**
  * Generate the special date
  */
 protected function generate()
 {
     $this->description = 'Oudjaarsdag';
     $this->startDate = \DateTime::createFromFormat('Y-m-d', $this->year . '-12-31');
     $this->endDate = \DateTime::createFromFormat('Y-m-d', $this->year . '-12-31');
     $this->totalLength = 1;
 }
Example #14
0
 /**
  * Returns the driver birth date.
  *
  * @return \DateTime|null
  */
 public function getBirthDate()
 {
     if (empty($this->birthDate)) {
         return null;
     }
     return \DateTime::createFromFormat('Y-m-d|', $this->birthDate);
 }
Example #15
0
 public function testLatins()
 {
     $objSign = new ZodiacSign(\DateTime::createFromFormat('Y-m-d', '2000-03-21'));
     $this->assertEquals('aries', $objSign->getLatin());
     $objSign = new ZodiacSign(\DateTime::createFromFormat('Y-m-d', '2000-04-20'));
     $this->assertEquals('taurus', $objSign->getLatin());
     $objSign = new ZodiacSign(\DateTime::createFromFormat('Y-m-d', '2000-05-21'));
     $this->assertEquals('gemini', $objSign->getLatin());
     $objSign = new ZodiacSign(\DateTime::createFromFormat('Y-m-d', '2000-06-21'));
     $this->assertEquals('cancer', $objSign->getLatin());
     $objSign = new ZodiacSign(\DateTime::createFromFormat('Y-m-d', '2000-07-23'));
     $this->assertEquals('leo', $objSign->getLatin());
     $objSign = new ZodiacSign(\DateTime::createFromFormat('Y-m-d', '2000-08-23'));
     $this->assertEquals('virgo', $objSign->getLatin());
     $objSign = new ZodiacSign(\DateTime::createFromFormat('Y-m-d', '2000-09-23'));
     $this->assertEquals('libra', $objSign->getLatin());
     $objSign = new ZodiacSign(\DateTime::createFromFormat('Y-m-d', '2000-10-23'));
     $this->assertEquals('scorpio', $objSign->getLatin());
     $objSign = new ZodiacSign(\DateTime::createFromFormat('Y-m-d', '2000-11-22'));
     $this->assertEquals('sagittarius', $objSign->getLatin());
     $objSign = new ZodiacSign(\DateTime::createFromFormat('Y-m-d', '2000-12-22'));
     $this->assertEquals('capricorn', $objSign->getLatin());
     $objSign = new ZodiacSign(\DateTime::createFromFormat('Y-m-d', '2000-01-20'));
     $this->assertEquals('aquarius', $objSign->getLatin());
     $objSign = new ZodiacSign(\DateTime::createFromFormat('Y-m-d', '2000-02-19'));
     $this->assertEquals('pisces', $objSign->getLatin());
 }
Example #16
0
 public function parseDateValue($value)
 {
     $res = false;
     if (preg_match('/^\\d\\d\\d\\d-\\d\\d-\\d\\d( \\d\\d:\\d\\d(:\\d\\d){0,1}){0,1}$/', $value, $matches)) {
         switch (count($matches)) {
             case 1:
                 if (!$this->time_required) {
                     $res = DateTime::createFromFormat('Y-m-d H:i:s', $value . ' 00:00:00');
                 }
                 break;
             case 2:
                 $res = DateTime::createFromFormat('Y-m-d H:i:s', $value . ':00');
                 break;
             case 3:
                 $res = DateTime::createFromFormat('Y-m-d H:i:s', $value);
                 break;
             default:
                 $res = false;
         }
     }
     // check there were no warnings because of invalid date values (strict checking)
     if ($res) {
         $errs = DateTime::getLastErrors();
         if (!empty($errs['warning_count'])) {
             $res = false;
         }
     }
     return $res;
 }
Example #17
0
 /**
  * Checks if menu is for today
  * @param string $data
  * @param string $charset
  * @return bool true if it is for today else otherwise
  */
 protected function isForToday($data, $charset)
 {
     $i = 0;
     /** @var \DOMElement $node */
     foreach ($this->getCrawler($data, $charset)->filter(static::$selectorDate) as $node) {
         $i++;
         if ($i == 2) {
             preg_match('/[0-9]{1,2}.\\s*[0-9]{1,2}.\\s*[0-9]{4,4}/', $node->nodeValue, $matches);
             if (isset($matches[0])) {
                 $date = $matches[0];
             }
             continue;
         }
     }
     if (!empty($date) && is_string($date)) {
         $date = preg_replace('/[[:space:]]+/', '', $date);
         $date = \DateTime::createFromFormat('j.n.Y', $date);
         if ($date !== false) {
             $today = new \DateTime('today');
             $tomorrow = new \DateTime('tomorrow');
             if ($date < $today || $date >= $tomorrow) {
                 return false;
             }
         }
     }
     return true;
 }
Example #18
0
 public function postOrders()
 {
     $input_start_date = \Input::get('start_date');
     if ($input_start_date == "") {
         $input_start_date = "01/01/1900";
     }
     $start_date = \DateTime::createFromFormat('d/m/Y', $input_start_date);
     $input_end_date = \Input::get('end_date');
     if ($input_end_date == "") {
         $end_date = new \DateTime("NOW");
     } else {
         $end_date = \DateTime::createFromFormat('d/m/Y', $input_end_date);
     }
     $data = Order::where('created_at', '>=', $start_date)->where('created_at', '<=', $end_date)->orderBy('created_at', 'desc')->get();
     if (count($data) == 0) {
         $errors = new \Illuminate\Support\MessageBag();
         $errors->add('downloadError', "There's no data within the dates specified.");
         return \Redirect::to('admin/orders')->withErrors($errors);
     }
     \Excel::create('Redmin_Orders_Report', function ($excel) use($data) {
         $excel->sheet('Orders Report', function ($sheet) use($data) {
             $sheet->loadView('redminportal::reports/orders')->with('data', $data);
         });
     })->download('xlsx');
 }
Example #19
0
 /**
  * Constructor
  *
  * The date to be validated and the $date must be in the format $format
  * 
  * @param string $format Format both dates must be in
  * @return \Validator\Rule\Date
  * @throws \InvalidArgumentException If the timezone is invalid
  * @access public
  */
 public function __construct($format)
 {
     if (\DateTime::createFromFormat($format, '1/1/12', new \DateTimeZone('UTC')) === false) {
         $this->error_exception('InvalidArgumentException', sprintf('Invalid date format (%s)', $format));
     }
     $this->format = $format;
 }
 /**
  * Get json routing information for feasibility, for example:
  * /service/ride/repeatedFeasible?fromDate=01.06.2014&toDate=01.07.2025
  *      &weekday=1&time=12:23&direction=1&duration=23&additionalTime=2
  *
  * @Route("/ride/repeatedFeasible", name="tixiapp_service_ride_repeated_feasible")
  * @Method({"GET"})
  * @param Request $request
  * @return \Symfony\Component\HttpFoundation\JsonResponse
  */
 public function getRepeatedFeasibilityAction(Request $request)
 {
     /**@var $rideManagement RideManagement */
     $rideManagement = $this->container->get('tixi_app.ridemanagement');
     $fromDateStr = $request->get('fromDate');
     $toDateStr = $request->get('toDate');
     $timeStr = $request->get('time');
     $dayTime = \DateTime::createFromFormat('d.m.Y H:i', $fromDateStr . ' ' . $timeStr);
     if ($toDateStr !== '') {
         $toDate = \DateTime::createFromFormat('d.m.Y', $toDateStr);
     } else {
         $toDate = DateTimeService::getMaxDateTime();
     }
     if (!$dayTime) {
         $response = new JsonResponse();
         $response->setData(array('status' => '-1'));
         return $response;
     }
     $weekday = $request->get('weekday');
     $direction = $request->get('direction');
     $duration = $request->get('duration');
     $additionalTime = $request->get('additionalTime');
     try {
         $isFeasible = $rideManagement->checkRepeatedFeasibility($dayTime, $toDate, $weekday, $direction, $duration, $additionalTime);
     } catch (\Exception $e) {
         $response = new JsonResponse();
         $response->setData(array('status' => '-1'));
         return $response;
     }
     $response = new JsonResponse();
     $response->setData(array('status' => '0', 'isFeasible' => $isFeasible));
     return $response;
 }
 /**
  * @dataProvider provideSeedAndExpectedReturn
  */
 public function testPersonalIdentityNumberUsesBirthDateIfProvided($seed, $birthdate, $expected)
 {
     $faker = $this->faker;
     $faker->seed($seed);
     $pin = $faker->personalIdentityNumber(\DateTime::createFromFormat('ymd', $birthdate));
     $this->assertEquals($expected, $pin);
 }
 /**
  * Virtual "sleep" that doesn't actually slow execution, only advances DBDateTime::now()
  *
  * @param int $minutes
  */
 protected function sleep($minutes)
 {
     $now = DBDatetime::now();
     $date = DateTime::createFromFormat('Y-m-d H:i:s', $now->getValue());
     $date->modify("+{$minutes} minutes");
     DBDatetime::set_mock_now($date->format('Y-m-d H:i:s'));
 }
 public function updateSchedule()
 {
     // grab user input
     $reservename = $this->security->xss_clean($this->input->post('reservename'));
     $envtype = $this->security->xss_clean($this->input->post('envtype'));
     $start = $this->security->xss_clean($this->input->post('start'));
     $end = $this->security->xss_clean($this->input->post('end'));
     $status = $this->security->xss_clean($this->input->post('status'));
     $reservetype = $this->security->xss_clean($this->input->post('reservetype'));
     $calendarid = $this->security->xss_clean($this->input->post('calendarid'));
     $this->db->set('reservename', $reservename);
     $this->db->set('envid', $envtype);
     $dateChange = DateTime::createFromFormat('m/d/Y H:i:s', $start . ' 00:00:00');
     $mysql_start_date = $dateChange->format('Y-m-d H:i:s');
     $this->db->set('starttime', $mysql_start_date);
     $dateChange = DateTime::createFromFormat('m/d/Y H:i:s', $end . ' 00:00:00');
     $mysql_end_date = $dateChange->format('Y-m-d H:i:s');
     $this->db->set('endtime', $mysql_end_date);
     $this->db->set('reservetype', $reservetype);
     if ($status != "") {
         $this->db->set('status', $status);
     }
     $this->db->where('calendarid', $calendarid);
     $this->db->update('calendar');
     return;
 }
Example #24
0
 public function testFormatYaml()
 {
     $server = ['HTTP_ACCEPT' => 'application/yaml', 'REQUEST_METHOD' => 'GET', 'SCRIPT_FILENAME' => 'my/base/path/my/request/uri/filename', 'REQUEST_URI' => 'my/base/path/my/request/uri', 'PHP_SELF' => 'my/base/path'];
     $request = new Request(["callback" => ""], [], [], [], [], $server);
     $apiResult = new Result($request);
     $response = (new Parser())->parse($apiResult->createResponse()->getContent());
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_ARRAY, $response);
     $this->assertArrayHasKey("meta", $response);
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_ARRAY, $response["meta"]);
     $this->assertArrayHasKey("response", $response);
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_ARRAY, $response["response"]);
     $this->assertEquals(0, count($response["response"]));
     $this->assertArrayHasKey("api_version", $response["meta"]);
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $response["meta"]["api_version"]);
     $this->assertEquals(V1::VERSION, $response["meta"]["api_version"]);
     $this->assertArrayHasKey("request", $response["meta"]);
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $response["meta"]["request"]);
     $this->assertEquals("GET my/base/path/my/request/uri", $response["meta"]["request"]);
     $this->assertArrayHasKey("response_time", $response["meta"]);
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $response["meta"]["response_time"]);
     $this->assertDateAtom($response["meta"]["response_time"]);
     $dateObj1 = \DateTime::createFromFormat(DATE_ATOM, $response["meta"]["response_time"]);
     $dateObj2 = new \DateTime();
     $this->assertLessThan(3, abs($dateObj1->format('U') - $dateObj2->format('U')), 'No more than 3sec between now and the query');
     $this->assertArrayHasKey("http_code", $response["meta"]);
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_INT, $response["meta"]["http_code"]);
     $this->assertEquals(200, $response["meta"]["http_code"]);
     $this->assertArrayHasKey("error_message", $response["meta"]);
     $this->assertNull($response["meta"]["error_message"]);
     $this->assertArrayHasKey("error_details", $response["meta"]);
     $this->assertNull($response["meta"]["error_details"]);
     $this->assertArrayHasKey("charset", $response["meta"]);
     $this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $response["meta"]["charset"]);
     $this->assertEquals("UTF-8", $response["meta"]["charset"]);
 }
Example #25
0
 /**
  * Check date time
  * @param string $datetime
  * @param string $format
  * @return boolean
  */
 public function checkDateTime($datetime, $format = 'full')
 {
     if (in_array($format, ['short', 'full'])) {
         $format = $this->getFormat($format);
     }
     return \DateTime::createFromFormat($format, $datetime) !== false;
 }
Example #26
0
    public function testCommitHydratorHappyPath()
    {
        $sha = "c3c8d149d63338c1215e0b06c839768cdf1933d5";
        $data = <<<EOF
tree b4ac469697c1e0f5fbb5702befc59fd7a90970a0
parent b3bf978c063bc6491919a97d1f6d6c9a6c074a2d
parent deadbeefcafec0ffee19a97d1f6d6c9a6c074a2d
parent cafebabe063bc6491919a97d1f6d6c9a6c074a2d
author Magnus Nordlander <*****@*****.**> 1316430078 +0200
committer Magnus Nordlander <*****@*****.**> 1316430078 +0200

Updated to version 2.1.2
EOF;
        $raw_object = M::mock('Gittern\\Transport\\RawObject', array('getSha' => $sha, 'getData' => $data));
        $hydrator = new CommitHydrator(M::mock('Gittern\\Repository'));
        $commit = $hydrator->hydrate($raw_object);
        $this->assertEquals($sha, $commit->getSha());
        $this->assertEquals("b4ac469697c1e0f5fbb5702befc59fd7a90970a0", $commit->getTree()->getSha());
        $parents = $commit->getParents();
        $this->assertEquals("b3bf978c063bc6491919a97d1f6d6c9a6c074a2d", $parents[0]->getSha());
        $user = new GitObject\User('Magnus Nordlander', "*****@*****.**");
        $this->assertEquals($user, $commit->getAuthor());
        $this->assertEquals($user, $commit->getCommitter());
        $timestamp = \DateTime::createFromFormat('U O', '1316430078 +0200');
        $this->assertEquals($timestamp, $commit->getAuthorTime());
        $this->assertEquals($timestamp, $commit->getCommitTime());
    }
Example #27
0
function QuickUpdate()
{
    $ret = array();
    try {
        $id = getPref("calendarId");
        //echo getPref("CalendarStartTime")."|";
        //echo getPref("CalendarEndTime")."|";
        //echo msg(datestring)."|";
        $start_time = DateTime::createFromFormat(msg(datestring) . " H:i", getPref("CalendarStartTime"));
        $end_time = DateTime::createFromFormat(msg(datestring) . " H:i", getPref("CalendarEndTime"));
        $clientzone = getPref('timezone');
        $serverzone = TIMEZONE_INDEX;
        $zonediff = $serverzone - $clientzone;
        $rcount = DbUpdateCalendar($id, addtime($start_time, $zonediff, 0, 0)->format("Y-m-d H:i:s"), addtime($end_time, $zonediff, 0, 0)->format("Y-m-d H:i:s"), $clientzone);
        if ($rcount > 0) {
            $ret["IsSuccess"] = true;
            $ret["Msg"] = msg("successmsg");
        } else {
            $ret["IsSuccess"] = false;
            $ret["Msg"] = msg("dberror");
        }
    } catch (Exception $e) {
        $ret["IsSuccess"] = false;
        $ret["Msg"] = $e->getMessage();
    }
    echo json_encode($ret);
}
Example #28
0
 public function testSerializeDate()
 {
     $now = time();
     $input = \DateTime::createFromFormat('U', $now);
     $output = Serializer::serialize($input);
     $this->assertEquals($now . 't', $output);
 }
Example #29
-1
 /**
  * @inheritdoc
  */
 public function parseFileListing($output)
 {
     $lines = array_values(array_filter(explode("\n", $output)));
     $members = array();
     // BSDTar outputs two differents format of date according to the mtime
     // of the member. If the member is younger than six months the year is not shown.
     // On 4.5+ FreeBSD system the day is displayed first
     $dateFormats = array('M d Y', 'M d H:i', 'd M Y', 'd M H:i');
     foreach ($lines as $line) {
         $matches = array();
         // drw-rw-r--  0 toto titi     0 Jan  3  1980 practice/
         // -rw-rw-r--  0 toto titi     10240 Jan 22 13:31 practice/records
         if (!preg_match_all("#" . self::PERMISSIONS . "\\s+" . self::HARD_LINK . "\\s+" . self::OWNER . "\\s" . self::GROUP . "\\s+" . self::FILESIZE . "\\s+" . self::DATE . "\\s+" . self::FILENAME . "#", $line, $matches, PREG_SET_ORDER)) {
             continue;
         }
         $chunks = array_shift($matches);
         if (8 !== count($chunks)) {
             continue;
         }
         $date = null;
         foreach ($dateFormats as $format) {
             $date = \DateTime::createFromFormat($format, $chunks[6]);
             if (false === $date) {
                 continue;
             } else {
                 break;
             }
         }
         if (false === $date) {
             throw new RuntimeException(sprintf('Failed to parse mtime date from %s', $line));
         }
         $members[] = array('location' => $chunks[7], 'size' => $chunks[5], 'mtime' => $date, 'is_dir' => 'd' === $chunks[1][0]);
     }
     return $members;
 }
 /**
  * Обработать файл
  */
 public function processFile()
 {
     $file = file_get_contents($this->getAddress());
     $coding = mb_detect_encoding($file, mb_detect_order(), true);
     if (!$coding) {
         $file = iconv("WINDOWS-1251", "UTF-8", $file);
         file_put_contents($this->getAddress(), $file);
     }
     $file = fopen($this->getAddress(), 'r');
     $isFirst = true;
     $accidents = [];
     while (($data = fgetcsv($file, null, ';')) !== FALSE) {
         if ($isFirst) {
             $isFirst = false;
             continue;
         }
         $item = ['description' => $data[1], 'lng' => str_replace(',', '.', $data[2]), 'lat' => str_replace(',', '.', $data[3]), 'date' => \DateTime::createFromFormat('d.m.Y H:m', $data[0])->format('Y-m-d H:m:s')];
         if ($item['description'] == 'ДТП БЕЗ ПОТЕРПIЛИХ') {
             $item['status'] = Enum::ACCIDENT_STATUS_VICTIMS;
         } elseif ($item['description'] == 'ДТП З ПОТЕРПIЛИМИ') {
             $item['status'] = Enum::ACCIDENT_STATUS_DEATHS;
         } else {
             continue;
         }
         $accidents[] = $item;
     }
     return Accident::find()->insetBatchAccidents($accidents);
 }