Skip to content

Commit

Permalink
Add HasTelescopeTags trait
Browse files Browse the repository at this point in the history
When Laravel Telescope records an entry for a Job/Event/Exception, it automatically associates the record with tags for all the Eloquent models included in the object.
These tags can then be monitored, making it easy to filter records related to one specific model.
This doesn't work for Actions, since the included models are dynamic attributes and not hard-coded properties.
Adding this trait to an Action fixes that, since Telescope will call the object's `tags` method if one exists.

This is just a proof of concept, since I'm a new Telescope user. I just thought it might be useful to others.
It *should* identify every model present in the attributes, whether they're single models, arrays or collections. If the models have any relationships loaded, their tags are also included recursively (I'm not sure if this is a wise decision - I just did it because it was fun).

Let me know if you're interested in this addition. I'm very open to suggestions, and it obviously also needs to be tested.
  • Loading branch information
mortenscheel authored Aug 21, 2020
1 parent ea9d021 commit 372d65f
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/Concerns/HasTelescopeTags
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace Lorisleiva\Actions\Concerns;

/**
* Trait HasTelescopeTags
* @package Lorisleiva\Actions\Concerns
* @mixin \Lorisleiva\Actions\Action
*/
trait HasTelescopeTags
{
/**
* Get a list of Telescope tags for every Eloquent model included in the Action attributes
* Tags for loaded relationships are included recursively
* @param array|null $items
* @return array
*/
public function tags(array $items = null): array
{
if ($items === null) {
$items = $this->all();
}
return collect($items)
->map(function($item) {
if ($item instanceof \Illuminate\Database\Eloquent\Model) {
$model_tag = sprintf('%s:%s', \get_class($item), $item->getKey());
$relationship_tags = $this->tags($item->getRelations());
return array_merge(
[$model_tag],
[$relationship_tags]
);
}
if (\is_iterable($item)) {
if ($item instanceof \Illuminate\Support\Enumerable) {
$item = $item->all();
}
return $this->tags($item);
}
return null;
})
->flatten() // Convert nested tags to single dimensional array
->filter() // Remove null values
->unique() // Models might occur more than once
->values() // Force to non-associative array
->toArray();
}
}

0 comments on commit 372d65f

Please sign in to comment.