Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Commit 251b699

Browse files
committed
Traits: ElasticSearchAuditable
1 parent 4bec1da commit 251b699

File tree

1 file changed

+108
-0
lines changed

1 file changed

+108
-0
lines changed
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
<?php
2+
3+
/**
4+
* This file is part of the Laravel Auditing package.
5+
*
6+
* @author Arpan Rank <arpan@iconscout.com>
7+
* @copyright 2018
8+
*
9+
* For the full copyright and license information,
10+
* please view the LICENSE.md file that was distributed
11+
* with this source code.
12+
*/
13+
14+
namespace Iconscout\Auditing\Traits;
15+
16+
use Elasticsearch\ClientBuilder;
17+
use Illuminate\Support\Facades\Config;
18+
use Illuminate\Database\Eloquent\Collection;
19+
20+
trait ElasticSearchAuditable
21+
{
22+
/**
23+
* @var string
24+
*/
25+
protected $client = null;
26+
27+
/**
28+
* @var string
29+
*/
30+
protected $index = null;
31+
32+
/**
33+
* @var string
34+
*/
35+
protected $type = null;
36+
37+
/**
38+
* ElasticSearch constructor.
39+
*/
40+
public function __construct()
41+
{
42+
parent::__construct();
43+
44+
$this->client = ClientBuilder::create()->setHosts(Config::get('audit.drivers.es.client.hosts', ['localhost:9200']))->build();
45+
$this->index = Config::get('audit.drivers.es.index', 'laravel_auditing');
46+
$this->type = Config::get('audit.drivers.es.type', 'audits');
47+
}
48+
49+
public function esAudits($page = 1, $perPage = 10)
50+
{
51+
$from = ($page - 1) * $perPage;
52+
53+
$params = [
54+
'index' => $this->index,
55+
'type' => $this->type,
56+
'size' => $perPage,
57+
'from' => $from,
58+
'body' => [
59+
'query' => [
60+
'bool' => [
61+
'must' => [
62+
[
63+
'term' => [
64+
'auditable_id' => $this->id
65+
]
66+
],
67+
[
68+
'term' => [
69+
'auditable_type' => $this->getMorphClass()
70+
]
71+
]
72+
]
73+
]
74+
],
75+
'sort' => [
76+
'created_at' => [
77+
'order' => 'desc'
78+
]
79+
],
80+
'track_scores' => true
81+
]
82+
];
83+
84+
$results = $this->client->search($params);
85+
$hits = $results['hits'];
86+
87+
$collection = Collection::make();
88+
89+
foreach ($hits['hits'] as $key => $result) {
90+
$audit['id'] = $result['_id'];
91+
$audit = array_merge($audit, $result['_source']);
92+
$audit['score'] = $result['_score'];
93+
94+
$collection->put($key, $audit);
95+
}
96+
97+
return [
98+
'total' => $hits['total'],
99+
'per_page' => $perPage,
100+
'data' => $collection
101+
];
102+
}
103+
104+
public function getEsAuditsAttribute()
105+
{
106+
return $this->esAudits();
107+
}
108+
}

0 commit comments

Comments
 (0)