Skip to content

Commit

Permalink
Support rendering model attributes in Antlers
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanmitchell committed Oct 1, 2024
1 parent 5e637d7 commit 70d1358
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/View/Antlers/Language/Runtime/PathDataManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use Exception;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
Expand Down Expand Up @@ -1014,6 +1016,21 @@ public static function reduce($value, $isPair = true, $reduceBuildersAndAugmenta
$reductionStack[] = $reductionValue->all();
GlobalRuntimeState::$isEvaluatingData = false;

continue;
} elseif ($reductionValue instanceof Model) {
GlobalRuntimeState::$isEvaluatingData = true;
$data = $reductionValue->toArray();

foreach (get_class_methods($reductionValue) as $method) {
if ((new \ReflectionMethod($reductionValue, $method))->getReturnType()?->getName() === Attribute::class) {
$method = Str::snake($method);
$data[$method] = $reductionValue->$method;
}
}

$reductionStack[] = $data;
GlobalRuntimeState::$isEvaluatingData = false;

continue;
} elseif ($reductionValue instanceof Arrayable) {
GlobalRuntimeState::$isEvaluatingData = true;
Expand Down
44 changes: 44 additions & 0 deletions tests/Antlers/Runtime/ModelTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace Tests\Antlers\Runtime;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Collection;
use Mockery;
use PHPUnit\Framework\Attributes\Test;
use Statamic\Contracts\Query\Builder;
use Statamic\Tags\Tags;
use Statamic\View\Antlers\Language\Runtime\GlobalRuntimeState;
use Statamic\View\Antlers\Language\Runtime\NodeProcessor;
use Tests\Antlers\Fixtures\Addon\Modifiers\IsBuilder;
use Tests\Antlers\Fixtures\Addon\Tags\VarTestTags as VarTest;
use Tests\Antlers\ParserTestCase;

class ModelTest extends ParserTestCase
{
public function test_model_attributes_are_returned()
{
$model = FakeModel::make();
$model->title = 'Title';

$data = [
'model' => $model,
];

$template = <<<'EOT'
{{ model:title }}{{ model:foo_bar }}
EOT;

$this->assertSame('TitleFooBar', $this->renderString($template, $data));
}
}

class FakeModel extends \Illuminate\Database\Eloquent\Model
{
public function fooBar(): Attribute
{
return Attribute::make(
get: fn() => 'FooBar',
);
}
}

0 comments on commit 70d1358

Please sign in to comment.