Skip to content

Commit

Permalink
Merge pull request #53 from mortenscheel/patch-2
Browse files Browse the repository at this point in the history
Add HasTelescopeTags trait
  • Loading branch information
lorisleiva authored Oct 17, 2020
2 parents aed0e62 + 372d65f commit 2cba8e9
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 2cba8e9

Please sign in to comment.