| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentForm\App\Services\Analytics; |
| 4 |
|
| 5 |
use FluentForm\App\Models\FormAnalytics; |
| 6 |
use FluentForm\App\Models\FormMeta; |
| 7 |
use FluentForm\App\Services\Browser\Browser; |
| 8 |
use FluentForm\Framework\Helpers\ArrayHelper; |
| 9 |
|
| 10 |
class AnalyticsService |
| 11 |
{ |
| 12 |
|
| 13 |
public function reset($formId) |
| 14 |
{ |
| 15 |
FormAnalytics::where('form_id', $formId)->delete(); |
| 16 |
FormMeta::where('meta_key', '_total_views')->where('form_id',$formId)->delete(); |
| 17 |
|
| 18 |
return ([ |
| 19 |
'message' => __('Form Analytics has been successfully reset', 'fluentform'), |
| 20 |
]); |
| 21 |
} |
| 22 |
|
| 23 |
public function store($formId) |
| 24 |
{ |
| 25 |
$userId = null; |
| 26 |
if ($user = wp_get_current_user()) { |
| 27 |
$userId = $user->ID; |
| 28 |
} |
| 29 |
$browser = new Browser(); |
| 30 |
$request = wpFluentForm('request'); |
| 31 |
|
| 32 |
$data = [ |
| 33 |
'count' => 1, |
| 34 |
'form_id' => $formId, |
| 35 |
'user_id' => $userId, |
| 36 |
'ip' => $request->getIp(), |
| 37 |
'browser' => $browser->getBrowser(), |
| 38 |
'platform' => $browser->getPlatform(), |
| 39 |
'created_at' => current_time('mysql'), |
| 40 |
'source_url' => esc_url_raw($request->server('HTTP_REFERER', '')), |
| 41 |
]; |
| 42 |
|
| 43 |
$query = FormAnalytics::where('ip', $data['ip']) |
| 44 |
->where('form_id', $data['form_id']) |
| 45 |
->where('source_url', $data['source_url']); |
| 46 |
|
| 47 |
if (($record = $query->first())) { |
| 48 |
$query->update(['count' => ++$record->count]); |
| 49 |
} else { |
| 50 |
FormAnalytics::insert($data); |
| 51 |
$this->increaseTotalViews($formId); |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
/** |
| 57 |
* Store (create/update) total view of a form |
| 58 |
* |
| 59 |
* @param int $formId |
| 60 |
*/ |
| 61 |
private function increaseTotalViews($formId) |
| 62 |
{ |
| 63 |
$hasCount = FormMeta::where('meta_key', '_total_views') |
| 64 |
->where('form_id', $formId) |
| 65 |
->first(); |
| 66 |
|
| 67 |
if ($hasCount) { |
| 68 |
FormMeta::where('id', $hasCount->id) |
| 69 |
->update([ |
| 70 |
'value' => intval($hasCount->value) + 1, |
| 71 |
]); |
| 72 |
} else { |
| 73 |
FormMeta::insert([ |
| 74 |
'value' => 1, |
| 75 |
'form_id' => $formId, |
| 76 |
'meta_key' => '_total_views', |
| 77 |
]); |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
} |
| 82 |
|