/** * Dodatkowe filtry Twig zwiazane z formatowaniem danych uzytkownika * * @return array */ public function getFilters() { return [new Twig_SimpleFilter('format_date', function ($dateTime, $diffForHumans = true) { $format = Auth::check() ? auth()->user()->date_format : '%Y-%m-%d %H:%M'; if (!$dateTime instanceof Carbon) { $dateTime = new Carbon($dateTime); } $now = Carbon::now(); if (!$diffForHumans) { return $dateTime->formatLocalized($format); } elseif ($dateTime->diffInHours($now) < 1) { return $dateTime->diffForHumans(null, true) . ' temu'; } elseif ($dateTime->isToday()) { return 'dziś, ' . $dateTime->format('H:i'); } elseif ($dateTime->isYesterday()) { return 'wczoraj, ' . $dateTime->format('H:i'); } else { return $dateTime->formatLocalized($format); } }), new Twig_SimpleFilter('timestamp', function ($dateTime) { if ($dateTime instanceof Carbon) { return $dateTime->getTimestamp(); } else { return strtotime($dateTime); } })]; }
public function getDateAdmissionAttribute() { $now = new Carbon(); $dt = new Carbon($this->created_at); $dt->setLocale('es'); return $dt->diffForHumans($now); }
public function getTransactionsByMember(Corporation $corp, array $member_ids, Carbon $date) { $start = $date->copy(); $start->subMonth()->setTime(0, 0, 0); $end = $date->copy(); $end->setTime(23, 59, 59); $sql = 'SELECT jt.owner_id2, group_concat(DISTINCT jt.id) as ids FROM journal_transactions as jt LEFT JOIN accounts as acc on jt.account_id=acc.id WHERE acc.corporation_id = :corp_id AND jt.owner_id2 in ( :owner_ids ) AND jt.date >= :start_date AND jt.date <= :end_date GROUP BY jt.owner_id2'; $rsm = new ResultSetMappingBuilder($this->getEntityManager()); $rsm->addRootEntityFromClassMetadata('AppBundle\\Entity\\JournalTransaction', 'jt'); $rsm->addFieldResult('jt', 'owner_id2', 'owner_id2'); $rsm->addFieldResult('jt', 'ids', 'id'); $q = $this->getEntityManager()->createNativeQuery($sql, $rsm); $q->setParameter('corp_id', $corp->getId()); $q->setParameter('owner_ids', $member_ids, Connection::PARAM_INT_ARRAY); $q->setParameter('start_date', $start); $q->setParameter('end_date', $end); $results = $q->getResult(); $real_res = []; foreach ($results as $res) { $ids = explode(',', $res->getId()); $rt = $this->createQueryBuilder('jt')->select('sum(jt.amount) as total_amount')->where('jt.id in (:j_ids)')->setParameter('j_ids', $ids)->getQuery()->getResult(); $r = $this->createQueryBuilder('jt')->select('jt')->where('jt.id in (:j_ids)')->setParameter('j_ids', $ids)->getQuery()->getResult(); $real_res[] = ['user' => $res->getOwnerId2(), 'total' => $rt, 'orig_ids' => $r]; } return $real_res; }
protected function checkStamp($style, $data) { switch ($style) { case 1: $search = \App\Firstcache::where('star', $data['star'])->where('size', $data['size'])->where('class', $data['class'])->where('planet', $data['planet'])->where('step', $data['step'])->first(); break; case 2: $search = \App\Secondcache::where('style', $data['style'])->first(); break; case 3: $search = \App\Thirdcache::where('star', $data['star'])->where('size', $data['size'])->where('class', $data['class'])->first(); break; case 0: $search = \App\Zerocache::where('id', '>', 0)->first(); break; } if ($search) { $created = new Carbon($search->created_at); $now = Carbon::now(); if ($created->diffInMinutes($now) > 180) { $search->delete(); return false; } $this->chart = unserialize($search->data); return true; } return false; }
public function change_password($tmp_code = null) { $tmp_check = false; if (!Auth::check()) { $code_created = new Carbon($this->tmp_code_created); $tmp_check = !empty($this->tmp_code) && $this->tmp_code == $tmp_code && $code_created->diff(new Carbon())->days <= 7; if (!$tmp_check) { FormMessage::add('tmp_code', 'The code was incorrect'); return false; } } $details = Request::all(); $rules = array('new_password' => 'required|confirmed|min:4'); if (!($tmp_check || Auth::check() && Auth::action('user.edit') && Auth::user()->id != $this->id)) { $rules['current_password'] = '******'; } $v = Validator::make($details, $rules); if ($v->passes()) { // check password if (!empty($rules['current_password']) && !Hash::check($details['current_password'], $this->password)) { FormMessage::add('current_password', 'The current password was incorrect'); return false; } // if user can change his password then change it if (Auth::action('account.password', ['user_id' => $this->id]) || Auth::check() && Auth::action('user.edit')) { $this->password = Hash::make($details['new_password']); $this->tmp_code = ''; $this->save(); return true; } } else { FormMessage::set($v->messages()); } return false; }
/** * @param null|Carbon $date * @return null|string */ protected function normalizeDateTime($date) { if (!$date) { return null; } return $date->format('Y-m-d H:i'); }
function update_episodes($parent_id, $rss) { foreach ($rss->channel->item as $item) { if (!$item->enclosure) { continue; } $enclosure = $item->enclosure->attributes(); $pubDate = new Carbon($item->pubDate->__toString()); $arr = array('parent_id' => $parent_id, 'title' => $this->sanitize($item->title->__toString()), 'pubDate' => $pubDate->format('U'), 'guid' => $item->guid->__toString(), 'link' => $item->link->__toString(), 'description' => $this->sanitize($item->description->__toString()), 'enclosure' => array('length' => $enclosure['length']->__toString(), 'type' => $enclosure['type']->__toString(), 'url' => $enclosure['url']->__toString()), 'itunes' => array('image' => '', 'duration' => $item->children('itunes', true)->duration->__toString(), 'explicit' => $item->children('itunes', true)->explicit->__toString(), 'keywords' => $this->sanitize($item->children('itunes', true)->keywords->__toString()), 'subtitle' => $this->sanitize($item->children('itunes', true)->subtitle->__toString())), 'raw' => $item->asXml()); $node = $item->children('itunes', true)->image; // Needed to force evaluation if ($node) { $itunes_image = $node->attributes(); $arr['itunes']['image'] = $itunes_image['href']->__toString(); } $items[] = $arr; } usort($items, function ($a, $b) { if ($a['pubDate'] == $b['pubDate']) { return 0; } if ($a['pubDate'] < $b['pubDate']) { return 1; } return -1; }); $items = array_slice($items, 0, RECAST_EPISODE_LIMIT); for ($i = 0; $i < count($items); $i++) { self::process_episode($items[$i]); } $args = array('posts_per_page' => -1, 'offset' => 0, 'post_type' => 'episode', 'meta_key' => 'podcast_id', 'meta_value' => $parent_id); $q = new WP_Query($args); update_post_meta($parent_id, 'episode_count', $q->found_posts); }
public function canReserveNow(User $user, Trip $trip) { $bonus = $this->karmaService->bonus($user); $departure = new Carbon($trip->leaves_at); $canReserveAt = $departure->subMinutes(self::BOOKING_TIME + $bonus); return !$canReserveAt->isFuture(); }
public function setEnd(Carbon $endDate) { $end = new Google_Service_Calendar_EventDateTime(); $end->setTimeZone("Europe/Madrid"); $end->setDateTime($endDate->toAtomString()); $this->attributes->setEnd($end); }
/** * @param string $year * @param string $month * * @param bool $shared * * @return \Illuminate\View\View */ public function month($year = '2014', $month = '1', $shared = false) { $start = new Carbon($year . '-' . $month . '-01'); $subTitle = trans('firefly.reportForMonth', ['month' => $start->formatLocalized($this->monthFormat)]); $subTitleIcon = 'fa-calendar'; $end = clone $start; $incomeTopLength = 8; $expenseTopLength = 8; if ($shared == 'shared') { $shared = true; $subTitle = trans('firefly.reportForMonthShared', ['month' => $start->formatLocalized($this->monthFormat)]); } $end->endOfMonth(); $accounts = $this->helper->getAccountReport($start, $end, $shared); $incomes = $this->helper->getIncomeReport($start, $end, $shared); $expenses = $this->helper->getExpenseReport($start, $end, $shared); $budgets = $this->helper->getBudgetReport($start, $end, $shared); $categories = $this->helper->getCategoryReport($start, $end, $shared); $balance = $this->helper->getBalanceReport($start, $end, $shared); $bills = $this->helper->getBillReport($start, $end); Session::flash('gaEventCategory', 'report'); Session::flash('gaEventAction', 'month'); Session::flash('gaEventLabel', $start->format('F Y')); return view('reports.month', compact('start', 'shared', 'subTitle', 'subTitleIcon', 'accounts', 'incomes', 'incomeTopLength', 'expenses', 'expenseTopLength', 'budgets', 'balance', 'categories', 'bills')); }
public function save(Request $request) { $titulo = $request->titulo; $idtutor = $request->idtutor; $idrevisor = $request->idrevisor; $idlinea = $request->type; $descripcion = $request->descripcion; //obtenemos el campo file definido en el formulario $file = $request->file('archivo'); //obtenemos el nombre del archivo $nombre = $file->getClientOriginalName(); $url = storage_path('app/') . $nombre; $messages = ['mimes' => 'Solo se permiten Archivos .pdf, .doc, .docx.']; $validator = Validator::make(['titulo' => $titulo, 'file' => $file, 'nombre' => $nombre], ['titulo' => 'required|max:255', 'file' => 'mimes:doc,docx,pdf'], $messages); $message = 'f'; if ($validator->fails()) { return redirect('sistema/nuevotrabajo')->withErrors($validator); } $carbon = new Carbon(); //indicamos que queremos guardar un nuevo archivo en el disco local \Storage::disk('local')->put($nombre, \File::get($file)); $nuevo_Trabajo = new Trabajo(); $nuevo_Trabajo->titulo = $titulo; $nuevo_Trabajo->nombreArchivo = $nombre; $nuevo_Trabajo->rutaArchivo = $url; $nuevo_Trabajo->user_id = Auth::user()->id; $nuevo_Trabajo->tutor_id = $idtutor; $nuevo_Trabajo->linea_id = $idlinea; $nuevo_Trabajo->Descripcion = $descripcion; $nuevo_Trabajo->fecha = $carbon->now(new \DateTimeZone('America/La_Paz')); $nuevo_Trabajo->save(); return redirect('sistema/nuevotrabajo')->with(['success' => ' ']); }
public function store() { $id = $this->request->input('id'); $input = $this->request->only(['provider', 'text', 'link', 'image']); $categories = $this->request->input('categories'); $inputSchedule = $this->request->only(['schedule_date', 'schedule_time']); if ($input['provider'] == 'weblink' && !$input['link']) { throw new Exception('The "link" argument is missing', 1); } $post = (int) $id ? Post::find($id)->fill($input) : new Post($input); if ($inputSchedule['schedule_date']) { $time = explode(':', $inputSchedule['schedule_time']); $date = new Carbon($inputSchedule['schedule_date']); if (count($time) > 1) { $date->setTime($time[0], $time[1]); } if ($date->timestamp > time()) { $post->posted_at = $date; } } else { $post->posted_at = new Carbon(); } $post->user_id = $this->auth->id(); $post->save(); if (count($categories)) { $post->categories()->sync($categories); } else { $post->categories()->detach(); } $post->provider_id = $post->id; $success = $post->save(); $job = (new PublishPost($post))->onQueue('publish'); $queued = $this->dispatch($job); return compact('success', 'queued'); }
/** * @param Request $request * @param $id * @param $code * * @return array|RedirectResponse * @Template() */ public function checkinAction(Request $request, $id, $code) { /* @var $ticket Ticket */ $ticket = $this->ticketRepo->getTicketByIdAndCode($id, $code)->getOrThrow(new NotFoundHttpException('Unknown ticket.')); // Do not allow double checkins if ($ticket->isCheckedIn()) { throw new BadRequestException('Already checked in!'); } // Do not allow checkins on the wrong day /* @var $event Event */ $event = $this->eventRepo->getNextEvent()->getOrThrow(new AccesDeniedHttpException('No event.')); $now = new Carbon(); $start = Carbon::createFromTimestamp($event->getStart()->getTimestamp()); $start->setTime(0, 0, 0); if ($ticket->isSunday()) { $start->modify('+1day'); } $end = clone $start; $end->setTime(23, 59, 59); if (!$now->between($start, $end)) { throw new BadRequestException('Wrong day!'); } // Record checkin $command = new CheckinCommand(); $command->ticket = $ticket; $this->commandBus->handle($command); return array('ticket' => $ticket); }
/** * Execute the console command. * * @return mixed */ public function fire() { // $map = Map::findOrFail($this->argument('map')); $minimap = $map->minimap; if (!$minimap->locked || $this->option('force')) { // Call dibs on editing this minimap $supernow = new Carbon(); $this->info('[' . Carbon::now() . '] Locking and processing map ' . $map->id); $minimap->updated_at = new \DateTime(); $minimap->locked = true; $minimap->save(); // Load the tiles. May take some time. =) $tiles = Tile::where('mapid', $map->id)->where('posz', 7)->get(); // Prepare the canvas, maestro! \OTWorlds\MinimapPainter::$filename = $minimap->path; \OTWorlds\MinimapPainter::load($map->width, $map->height); foreach ($tiles as $tile) { \OTWorlds\MinimapPainter::paint(intval($tile->posx), intval($tile->posy), intval($tile->itemid)); } // Finish up \OTWorlds\MinimapPainter::save(); // Let other processes edit this map again $minimap->locked = false; $minimap->save(); $donenow = new Carbon(); $this->info('[' . $donenow->now() . '] Done. Processed ' . $tiles->count() . ' tiles in ' . $donenow->diffInSeconds($supernow) . ' seconds.'); } else { $this->error('Minimap is locked. Either another process is using it, or the last one crashed. Use --force to ignore.'); } }
public function add($start = null, $end = null) { $groups = CustomerGroup::lists('groupname', 'id'); $start = new Carbon($start); $end = new Carbon($end); return view('event.add')->with('groups', $groups)->with('start', $start->toTimeString())->with('end', $end->toTimeString())->with('dayOfWeek', $start->dayOfWeek)->with('daysOfWeek', $this->daysOfWeek())->with('body', 'event-edit'); }
public function getExtend($uid, $period) { /* @var $user User */ $user = User::find($uid); if (empty($user->announcement_stream)) { Flash::error('Пользователь не подписан на рассылку.'); return Redirect::to('admin/subscriptions'); } // Already has an active subscription. if ($user->announcement_expires && $user->announcement_expires->isFuture()) { $user->announcement_expires = $user->announcement_expires->addDays($period); } // Subscription expired. if ($user->announcement_expires && $user->announcement_expires->isPast()) { // Start tomorrow. $start = new Carbon(); $start->setTime(0, 0, 0)->addDays(1); $user->announcement_start = $start; // Expire in $period from tomorrow. $expires = clone $start; $expires->addDays($period); $user->announcement_expires = $expires; } $user->save(); Flash::success('Подписка продленна.'); return Redirect::to('admin/subscriptions'); }
public function compare() { // get a list of all months: $months = array(); $first = BaseController::getFirst(); $first->modify('first day of this month midnight'); $today = new Carbon('now'); $today->modify('first day of this month midnight'); $prev = clone $today; $prev->sub(new DateInterval('P2D')); $prev->modify('first day of this month midnight'); while ($first <= $today) { $index = $first->format('Y-m-d'); $months[$index] = $first->format('F Y'); $first->add(new DateInterval('P1M')); } // account list: $accs = Auth::user()->accounts()->get(); $accounts = array(0 => '(all accounts)'); foreach ($accs as $acc) { $accounts[intval($acc->id)] = Crypt::decrypt($acc->name); } $account = Setting::getSetting('defaultCheckingAccount'); return View::make('pages.compare')->with('months', $months)->with('thisMonth', $today)->with('prevMonth', $prev)->with('account', $account)->with('accounts', $accounts); }
private function queuePostMatchEmail(\PlayFooty\Event $event) { Log::info(__METHOD__); $postMatchDate = new Carbon($event->event_date . " " . $event->start_time); $postMatchDate->addDay(1)->setTime(10, 00); Queue::later($postMatchDate, new SendPostMatchEmail($event)); }
public function calculateModuleExpenditure($id, $fromDate, $toDate) { $module = Module::find($id); $activities = $module->activities; $activityCosts = array(); $totalModuleCost = 0; foreach ($activities as $activity) { $sessions = $activity->sessions()->whereBetween('date_of_session', array($fromDate, $toDate))->orderBy('date_of_session')->get(); $totalHoursPerPerson = 0; $activityTitle = $activity->title; $role = $activity->role_type; //the 'role' the PHD student was for the given 'session' if ($role == 'Demonstrator') { $payRate = 12.21; } elseif ($role = 'Teaching') { $payRate = 10.58; } foreach ($sessions as $session) { $startTime = new Carbon($session->start_time); //http://carbon.nesbot.com/docs/#api-humandiff $endTime = new Carbon($session->end_time); //http://carbon.nesbot.com/docs/#api-humandiff $totalHoursPerPerson += $startTime->diffInHours($endTime); //http://carbon.nesbot.com/docs/#api-humandiff } if (array_key_exists($activityTitle, $activityCosts)) { $activityCosts[$activityTitle] += $totalHoursPerPerson * $activity->quant_ppl_needed * $payRate; } else { $activityCosts[$activityTitle] = $totalHoursPerPerson * $activity->quant_ppl_needed * $payRate; //this 0verwrites 0ld values2d } $totalModuleCost += $totalHoursPerPerson * $activity->quant_ppl_needed * $payRate; } return view('calculateModuleExpenditureResults')->with(['module' => $module, 'totalModuleCost' => $totalModuleCost, 'activityCosts' => $activityCosts]); }
public function showAll() { $key = cacheKey('Beneficiaries', 'showAll'); if (Cache::has($key)) { $data = Cache::get($key); } else { $data = array(); $beneficiaries = Auth::user()->beneficiaries()->orderBy('id', 'ASC')->get(); // to get the avg per month we first need the number of months foreach ($beneficiaries as $ben) { $name = Crypt::decrypt($ben->name); $bene = array('id' => intval($ben->id), 'name' => $name); $now = new Carbon('now'); $thisMonth = $ben->transactions()->where(DB::Raw('DATE_FORMAT(`date`,"%m-%Y")'), '=', $now->format('m-Y'))->sum('amount'); $bene['month'] = floatval($thisMonth); $data[] = $bene; } unset($name); $name = array(); // order by alfabet // Obtain a list of columns foreach ($data as $key => $row) { $id[$key] = $row['id']; $name[$key] = $row['name']; } array_multisort($name, SORT_ASC, $id, SORT_DESC, $data); Cache::put($key, $data, 1440); } return View::make('beneficiaries.all')->with('beneficiaries', $data); }
/** * @param Carbon $date * @param string $chunk * @return ChannelProgramming * @throws \Exception */ private static function parseChannelChunk(Carbon $date, $chunk) { $res = new ChannelProgramming(); $channelName = self::str_between_exclude($chunk, '<div class="tabla_topic">', '</div>'); $channelName = trim(strip_tags($channelName)); if (!$channelName) { throw new \Exception('parse error: no channel name'); } $res->setChannelName($channelName); $content = self::str_between_exclude($chunk, '<ul class="prog_tabla">', '</ul>'); if (!$content) { throw new \Exception('parse error: no content'); } $content = str_replace('</li>', "\n", $content); $content = str_replace("\t", '', $content); $content = strip_tags($content); $programs = explode("\n", trim($content)); $foundHour = 0; $addDays = 0; /** @var ChannelEvent $event */ $event = null; foreach ($programs as $prog) { if (!$prog) { continue; } preg_match('/^(?<hh>[\\d]+)+\\:(?<mm>[\\d]+)+$/ui', $prog, $match); if (!empty($match['hh']) && !empty($match['mm'])) { $event = new ChannelEvent(); $time = explode(' ', $prog)[0]; $timeParts = explode(':', $time); if ($timeParts[0] < $foundHour) { // new day $addDays = 1; } $foundHour = $timeParts[0]; $event->starts_at = $date->copy(); $event->starts_at->addDays($addDays); $event->starts_at->hour = $timeParts[0]; $event->starts_at->minute = $timeParts[1]; continue; } if (!$event) { continue; } $event->title = $prog; $res->addEvent($event); } // guesstimate end time for each event $events = $res->getEvents(); for ($i = 0; $i < count($events); $i++) { if (!empty($events[$i + 1])) { $events[$i]->ends_at = $events[$i + 1]->starts_at->copy(); } else { // HACK: we dont know end of last event, so we add 2 hours $events[$i]->ends_at = $events[$i]->starts_at->copy()->addHours(2); } } $res->setEvents($events); return $res; }
/** * @param Collection $accounts * @param Carbon $start * @param Carbon $end * * @return array */ public function expenseAccounts(Collection $accounts, Carbon $start, Carbon $end) { $data = ['count' => 1, 'labels' => [], 'datasets' => [['label' => trans('firefly.spent'), 'data' => []]]]; bcscale(2); $start->subDay(); $ids = $this->getIdsFromCollection($accounts); $startBalances = Steam::balancesById($ids, $start); $endBalances = Steam::balancesById($ids, $end); $accounts->each(function (Account $account) use($startBalances, $endBalances) { $id = $account->id; $startBalance = $this->isInArray($startBalances, $id); $endBalance = $this->isInArray($endBalances, $id); $diff = bcsub($endBalance, $startBalance); $account->difference = round($diff, 2); }); $accounts = $accounts->sortByDesc(function (Account $account) { return $account->difference; }); foreach ($accounts as $account) { if ($account->difference > 0) { $data['labels'][] = $account->name; $data['datasets'][0]['data'][] = $account->difference; } } return $data; }
/** * @param Carbon $time * @return Carbon */ protected function shiftEndTime($time) { if ($time->lt($this->day_shift_end_time)) { return $this->day_shift_end_time; } return $this->night_shift_end_time; }
public function updateBudgetPrediction($event) { $event->name = Crypt::decrypt($event->name); // remove all budget prediction points, if any $event->budgetpredictionpoints()->delete(); $similar = array(); // get all similar budgets from the past: $budgets = Auth::user()->budgets()->where('date', '<=', $event->date)->get(); foreach ($budgets as $budget) { $budget->name = Crypt::decrypt($budget->name); if ($budget->name == $event->name) { $similar[] = $budget->id; } } if (count($similar) > 0) { // get all transactions for these budgets: $amounts = array(); $transactions = Auth::user()->transactions()->orderBy('date', 'DESC')->where('onetime', '=', 0)->whereIn('budget_id', $similar)->get(); foreach ($transactions as $t) { $date = new Carbon($t->date); $day = intval($date->format('d')); $amounts[$day] = isset($amounts[$day]) ? $amounts[$day] + floatval($t->amount) * -1 : floatval($t->amount) * -1; } // then make sure it's "average". foreach ($amounts as $day => $amount) { // save as budget prediction point. $bpp = new Budgetpredictionpoint(); $bpp->budget_id = $event->id; $bpp->amount = $amount / count($similar); $bpp->day = $day; $bpp->save(); } } }
public static function startDateCannotBeAfterEndDate(Carbon $startDate, Carbon $endDate) { $startDateFormatted = $startDate->format('d-m-Y'); $endDateFormatted = $endDate->format('d-m-Y'); $message = "Start date `{$startDateFormatted}` cannot be after end date `{$endDateFormatted}`."; return new self($message); }
public function getView(Pirep $pirep) { // Calculate some data bits (keep it out of the view) $extras = []; // Airborne Time $takeoff = new Carbon($pirep->departure_time); $landing = new Carbon($pirep->landing_time); $extras['airborneTime'] = $takeoff->diff($landing); // Blocks Time $offBlocks = new Carbon($pirep->off_blocks_time); $onBlocks = new Carbon($pirep->on_blocks_time); $extras['blocksTime'] = $offBlocks->diff($onBlocks); // Total Time $start = new Carbon($pirep->pirep_start_time); $finish = new Carbon($pirep->pirep_end_time); $extras['totalTime'] = $start->diff($finish); // Planned Route $routeService = new Route(); $extras['routePoints'] = $routeService->getAllPointsForRoute($pirep->booking->route); // Format Text Log (ugly, I know!) $extras['log'] = str_replace('[', ' [', $pirep->log); // Display the PIREP! return view('pireps/single', ['pirep' => $pirep, 'extras' => $extras, 'staffBar' => true]); }
public function testCheckIn() { $json = '{ "watched_at": "2014-08-06T01:11:37.953Z", "sharing": { "facebook": true, "twitter": true, "tumblr": false }, "movie": { "title": "Guardians of the Galaxy", "year": 2014, "ids": { "trakt": 28, "slug": "guardians-of-the-galaxy-2014", "imdb": "tt2015381", "tmdb": 118340 } } }'; $client = Mockery::mock(stdClass::class . ", " . ClientInterface::class); $request = Mockery::mock(stdClass::class . ", " . RequestInterface::class); $response = Mockery::mock(stdClass::class . ", " . ResponseInterface::class); $client->shouldReceive("createRequest")->once()->andReturn($request); $response->shouldReceive("getStatusCode")->once()->andReturn(200); $response->shouldReceive("json")->once()->andReturn(json_decode($json)); $client->shouldReceive("send")->once()->andReturn($response); $auth = mock_auth(); $trakt = new Trakt($auth, $client); $checkIn = $trakt->checkIn; $this->assertInstanceOf("Wubs\\Trakt\\Api\\CheckIn", $checkIn); $response = $checkIn->create(get_token(), movie($client), "nooo way!", ['facebook' => false, 'twitter' => false, 'tumblr' => false], "1200", "blablabla", "1.1", $this->today->format("Y-m-d")); $this->assertInstanceOf("Wubs\\Trakt\\Response\\CheckIn", $response); }
public function getSinglePirep(Pirep $pirep) { // Do we have access to this PIREP? if ($pirep->booking->pilot->id !== PilotRepository::getCurrentPilot()->id) { return redirect('/pireps'); } // Calculate some data bits (keep it out of the view) $extras = []; // Airborne Time $takeoff = new Carbon($pirep->departure_time); $landing = new Carbon($pirep->landing_time); $extras['airborneTime'] = $takeoff->diff($landing); // Blocks Time $offBlocks = new Carbon($pirep->off_blocks_time); $onBlocks = new Carbon($pirep->on_blocks_time); $extras['blocksTime'] = $offBlocks->diff($onBlocks); // Total Time $start = new Carbon($pirep->pirep_start_time); $finish = new Carbon($pirep->pirep_end_time); $extras['totalTime'] = $start->diff($finish); // Planned Route $routeService = new Route(); $extras['routePoints'] = $routeService->getAllPointsForRoute($pirep->booking->route); // Format Text Log (ugly, I know!) $extras['log'] = str_replace('[', ' [', $pirep->log); // Display the PIREP! return view('pireps/single', ['pirep' => $pirep, 'extras' => $extras]); }
public function store($projectId, Request $request) { $date = new Carbon($request->date); $project = Project::findOrFail($projectId); $project->costEstimations()->create(['settled_at' => $date]); return redirect()->route('projects.cost-estimations.show', [$projectId, $date->toDateString()]); }
/** * Execute the console command. * * @return mixed */ public function handle() { $today = Carbon::today(); $nextMonth = Carbon::today()->addMonth(); $monday = new Carbon('next monday'); $sunday = new Carbon('next monday'); $sunday->addDays(6); echo $sunday; $planningen = Planning::where('first_day', '>', $today)->get(); var_dump($planningen); while ($monday < $nextMonth) { $not_exists = true; foreach ($planningen as $planning) { if ($monday >= $planning->first_day && $monday <= $planning->last_day) { $not_exists = false; } } if ($not_exists) { $newPlanning = new Planning(); $newPlanning->first_day = $monday; $newPlanning->last_day = $sunday; $newPlanning->save(); } $monday->addWeek(); $sunday->addWeek(); } }