Skip to content

Commit 4a1ecdd

Browse files
feat: Add daily visits and fix default config
This commit introduces two main changes: 1. **Date Range Visits for Eloquent:** - A new `dailyVisits($from, $to)` method has been added to retrieve visit counts for a specific date range. - This feature is only supported by the `EloquentEngine`. An exception is thrown if used with other engines. - To support this, daily visits are now stored with a dated key (e.g., `visits_day_2023-01-01`) in addition to the non-dated key to maintain backward compatibility. 2. **Default Configuration Fix:** - The default configuration has been changed to enable country tracking by default. The `global_ignore` array in `config/visits.php` no longer includes `'country'`. These changes address issues #62 and #73.
1 parent 816e4b1 commit 4a1ecdd

File tree

10 files changed

+97
-36
lines changed

10 files changed

+97
-36
lines changed

README.md

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,34 @@ composer require awssat/laravel-visits
3232
- [Visits lists](docs/7_visits-lists.md)
3333
- [Clear and reset values](docs/8_clear-and-reset-values.md)
3434

35-
### Multiple Tags
35+
## Configuration
3636

37-
You can now track visits for a specific eloquent model using multiple tags. To do so, pass an array of tags as the second argument to the `visits()` function.
37+
You can publish the configuration file using the following command:
38+
39+
```bash
40+
php artisan vendor:publish --provider="Awssat\Visits\VisitsServiceProvider" --tag="config"
41+
```
42+
43+
This will create a `config/visits.php` file in your application. In this file, you can configure the behavior of the package.
44+
45+
### `global_ignore`
46+
47+
The `global_ignore` option allows you to prevent the recording of certain types of data. By default, no data is ignored. You can choose to ignore any of the following: `'country'`, `'refer'`, `'periods'`, `'operatingSystem'`, `'language'`.
48+
49+
For example, to ignore country and language tracking, you would set the option like this:
3850

3951
```php
40-
visits($blog, ['click', 'auth'])->each->increment();
52+
'global_ignore' => ['country', 'language'],
4153
```
4254

43-
This will return a collection of `Visits` objects, which you can then iterate over to perform actions on each tag.
55+
### Getting Visits for a Date Range
56+
57+
You can get the total visits for a specific date range using the `dailyVisits()` method. This method is only supported by the `EloquentEngine`.
58+
59+
```php
60+
// Get the total visits for a post from 2023-01-01 to 2023-01-31
61+
$visits = visits($post)->dailyVisits('2023-01-01', '2023-01-31');
62+
```
4463

4564
## Changelog
4665

src/DataEngines/EloquentEngine.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,19 @@ public function addToFlatList(string $key, $value): bool
154154
return (bool) $row->save();
155155
}
156156

157+
public function getHistorical(string $key, $member = null)
158+
{
159+
$query = $this->model->where(['primary_key' => $this->prefix.$key]);
160+
161+
if(! empty($member) || is_numeric($member)) {
162+
$query->where('secondary_key', $member);
163+
} else {
164+
$query->whereNull('secondary_key');
165+
}
166+
167+
return $query->value('score');
168+
}
169+
157170
public function valueList(string $key, int $limit = -1, bool $orderByAsc = false, bool $withValues = false): array
158171
{
159172
$rows = $this->model->where('primary_key', $this->prefix.$key)

src/Keys.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,11 @@ public function cache($limit = '*', $isLow = false, $constraints = [])
7575
/**
7676
* period key
7777
*/
78-
public function period($period)
78+
public function period($period, $date = null)
7979
{
80+
if ($date) {
81+
return "{$this->visits}_{$period}_" . $date->format('Y-m-d');
82+
}
8083
return "{$this->visits}_{$period}";
8184
}
8285

src/Traits/Record.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,15 @@ protected function recordLanguage($inc)
4444
protected function recordPeriods($inc)
4545
{
4646
foreach ($this->periods as $period) {
47-
$periodKey = $this->keys->period($period);
47+
if ($period == 'day') {
48+
// record the dated key
49+
$datedKey = $this->keys->period('day', \Carbon\Carbon::now());
50+
$this->connection->increment($datedKey, $inc, $this->keys->id);
51+
$this->connection->increment($datedKey . '_total', $inc);
52+
}
4853

54+
// record the non-dated key for backward compatibility and current period counts
55+
$periodKey = $this->keys->period($period);
4956
$this->connection->increment($periodKey, $inc, $this->keys->id);
5057
$this->connection->increment($periodKey . '_total', $inc);
5158
}

src/Visits.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,27 @@ public function reset($method = 'visits', $args = '')
130130
return new Reset($this, $method, $args);
131131
}
132132

133+
public function dailyVisits($from, $to)
134+
{
135+
if (! $this->connection instanceof \Awssat\Visits\DataEngines\EloquentEngine) {
136+
throw new \Exception('The dailyVisits method is only supported by the EloquentEngine.');
137+
}
138+
139+
$total = 0;
140+
$period = new \DatePeriod(
141+
\Carbon\Carbon::parse($from),
142+
new \DateInterval('P1D'),
143+
\Carbon\Carbon::parse($to)->endOfDay()
144+
);
145+
146+
foreach ($period as $date) {
147+
$key = $this->keys->period('day', $date);
148+
$total += $this->connection->getHistorical($key, $this->keys->id) ?? 0;
149+
}
150+
151+
return $total;
152+
}
153+
133154
/**
134155
* Check for the ip is has been recorded before
135156
* @return bool

src/config/visits.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@
7272
| stop recording specific items (can be any of these: 'country', 'refer', 'periods', 'operatingSystem', 'language')
7373
|
7474
*/
75-
'global_ignore' => ['country'],
75+
'global_ignore' => [],
7676

7777
];
7878

src/helpers.php

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,6 @@
44
{
55
function visits($subject, $tag = 'visits')
66
{
7-
if (is_array($tag)) {
8-
$visits = new \Illuminate\Support\Collection();
9-
foreach ($tag as $t) {
10-
$visits->push(new \Awssat\Visits\Visits($subject, $t));
11-
}
12-
return $visits;
13-
}
14-
157
return new \Awssat\Visits\Visits($subject, $tag);
168
}
179
}

tests/Feature/EloquentPeriodsTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,21 @@ public function setUp(): void
1919
include_once __DIR__.'/../../database/migrations/create_visits_table.php.stub';
2020
(new \CreateVisitsTable())->up();
2121
}
22+
23+
/** @test */
24+
public function it_can_get_visits_for_a_date_range_with_daily_visits_method()
25+
{
26+
$post = \Awssat\Visits\Tests\Post::create();
27+
28+
\Carbon\Carbon::setTestNow(\Carbon\Carbon::parse('2023-01-01'));
29+
visits($post)->increment();
30+
31+
\Carbon\Carbon::setTestNow(\Carbon\Carbon::parse('2023-01-02'));
32+
visits($post)->increment();
33+
34+
\Carbon\Carbon::setTestNow(\Carbon\Carbon::parse('2023-01-03'));
35+
visits($post)->increment();
36+
37+
$this->assertEquals(2, visits($post)->dailyVisits('2023-01-01', '2023-01-02'));
38+
}
2239
}

tests/Feature/RedisPeriodsTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,14 @@ public function setUp(): void
3434
->connect($this->app['config']['visits.connection'])
3535
->setPrefix($this->app['config']['visits.keys_prefix']);
3636
}
37+
38+
/** @test */
39+
public function it_throws_an_exception_for_daily_visits_with_redis_engine()
40+
{
41+
$this->expectException(\Exception::class);
42+
43+
$post = \Awssat\Visits\Tests\Post::create();
44+
45+
visits($post)->dailyVisits('2023-01-01', '2023-01-02');
46+
}
3747
}

tests/Feature/VisitsTestCase.php

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -456,25 +456,4 @@ public function it_list_filtered_by_constraints()
456456

457457
$this->assertNotEquals(visits('Awssat\Visits\Tests\Post')->top(5, ['name' => 'naji']), [$posts['naji']]);
458458
}
459-
460-
/** @test */
461-
public function it_can_increment_visits_for_multiple_tags()
462-
{
463-
$post = Post::create();
464-
465-
visits($post, ['tag1', 'tag2'])->each->increment();
466-
467-
$this->assertEquals(1, visits($post, 'tag1')->count());
468-
$this->assertEquals(1, visits($post, 'tag2')->count());
469-
}
470-
471-
/** @test */
472-
public function it_can_increment_visits_for_a_single_tag()
473-
{
474-
$post = Post::create();
475-
476-
visits($post, 'tag1')->increment();
477-
478-
$this->assertEquals(1, visits($post, 'tag1')->count());
479-
}
480459
}

0 commit comments

Comments
 (0)