Last active
August 29, 2015 14:02
-
-
Save JSila/36277262723bafe0c439 to your computer and use it in GitHub Desktop.
Laravel: Count visits (visit of movie resource in this case)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace App\Http\Middleware; | |
use App\Movie; | |
use Carbon\Carbon; | |
use Closure; | |
use Illuminate\Http\Response; | |
use Illuminate\Session\Store; | |
class CountMovieVisits { | |
/** | |
* @var Store | |
*/ | |
protected $session; | |
/** | |
* @var Movie | |
*/ | |
protected $movie; | |
/** | |
* @param Store $session | |
* @param Movie $movie | |
*/ | |
function __construct(Store $session, Movie $movie) | |
{ | |
$this->session = $session; | |
$this->movie = $movie; | |
} | |
/** | |
* Handle an incoming request. | |
* Checks if we are on page for showing single resource and | |
* increment its visit number if timestamp is later than 2 hours. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return Response | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
$slug = $request->route('movies'); | |
$timestamp = $this->session->get('visits.' . $slug); | |
if ( ! $this->isRecentVisit($timestamp)) | |
{ | |
$this->movie->whereSlug($slug)->first()->increment('visits'); | |
$this->session->put('visits.' . $slug, Carbon::now()); | |
} | |
return $next($request); | |
} | |
/** | |
* Checks if timestamp is earlier than now minus 2 hours. | |
* | |
* @param Carbon $timestamp | |
* @return bool | |
*/ | |
private function isRecentVisit($timestamp) | |
{ | |
$earlierTimestamp = Carbon::now()->subHours(2); | |
return ! is_null($timestamp) && $timestamp->gt($earlierTimestamp); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment