repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
SymfonyCasts/dynamic-forms | https://github.com/SymfonyCasts/dynamic-forms/blob/c32e79bced902f12006a1238cca1834cfbcd5faf/.php-cs-fixer.dist.php | .php-cs-fixer.dist.php | <?php
if (!file_exists(__DIR__.'/src') || !file_exists(__DIR__.'/tests')) {
exit(0);
}
$finder = (new \PhpCsFixer\Finder())
->in([__DIR__.'/src', __DIR__.'/tests'])
;
return (new \PhpCsFixer\Config())
->setRules(array(
'@Symfony' => true,
'@Symfony:risky' => true,
'phpdoc_to_comment' => false,
'header_comment' => [
'header' => <<<EOF
This file is part of the SymfonyCasts DynamicForms package.
Copyright (c) SymfonyCasts <https://symfonycasts.com/>
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF
]
))
->setRiskyAllowed(true)
->setFinder($finder)
;
| php | MIT | c32e79bced902f12006a1238cca1834cfbcd5faf | 2026-01-05T05:10:27.898649Z | false |
SymfonyCasts/dynamic-forms | https://github.com/SymfonyCasts/dynamic-forms/blob/c32e79bced902f12006a1238cca1834cfbcd5faf/src/DynamicFormBuilder.php | src/DynamicFormBuilder.php | <?php
/*
* This file is part of the SymfonyCasts DynamicForms package.
* Copyright (c) SymfonyCasts <https://symfonycasts.com/>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfonycasts\DynamicForms;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\ClearableErrorsInterface;
use Symfony\Component\Form\DataMapperInterface;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormConfigInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\RequestHandlerInterface;
use Symfony\Component\Form\ResolvedFormTypeInterface;
use Symfony\Component\PropertyAccess\PropertyPathInterface;
/**
* Wraps the normal form builder & to add addDynamic() to it.
*
* @author Ryan Weaver
*/
class DynamicFormBuilder implements FormBuilderInterface, \IteratorAggregate
{
/**
* @var DependentFieldConfig[]
*/
private array $dependentFieldConfigs = [];
/**
* The actual form that this builder is turned into.
*/
private FormInterface $form;
private array $preSetDataDependencyData = [];
private array $postSubmitDependencyData = [];
public function __construct(private FormBuilderInterface $builder)
{
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$this->form = $event->getForm();
$this->preSetDataDependencyData = [];
$this->initializeListeners();
// A fake hidden field where we can "store" an error if a dependent form
// field is suddenly invalid because its previous data was invalid
// and a field it depends on just changed (e.g. user selected "Michigan"
// as a state, then the user changed "Country" from "USA" to "Mexico"
// and so now "Michigan" is invalid). In this case, we clear the error
// on the actual field, but store a "fake" error here, which won't be
// rendered, but will prevent the form from being valid.
if (!$this->form->has('__dynamic_error')) {
$this->form->add('__dynamic_error', HiddenType::class, [
'mapped' => false,
'error_bubbling' => false,
]);
}
}, 100);
$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
$this->postSubmitDependencyData = [];
});
// guarantee later than core ValidationListener
$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
$this->clearDataOnTransformationError($event);
}, -1);
}
public function addDependent(string $name, string|array $dependencies, callable $callback): self
{
$dependencies = (array) $dependencies;
$this->dependentFieldConfigs[] = new DependentFieldConfig($name, $dependencies, $callback);
return $this;
}
public function storePreSetDataDependencyData(FormEvent $event): void
{
$dependency = $event->getForm()->getName();
$this->preSetDataDependencyData[$dependency] = $event->getData();
$this->executeReadyCallbacks($this->preSetDataDependencyData, FormEvents::PRE_SET_DATA);
}
public function storePostSubmitDependencyData(FormEvent $event): void
{
$dependency = $event->getForm()->getName();
$this->postSubmitDependencyData[$dependency] = $event->getForm()->getData();
$this->executeReadyCallbacks($this->postSubmitDependencyData, FormEvents::POST_SUBMIT);
}
public function clearDataOnTransformationError(FormEvent $event): void
{
$form = $event->getForm();
$transformationErrorsCleared = false;
foreach ($this->dependentFieldConfigs as $dependentFieldConfig) {
if (!$form->has($dependentFieldConfig->name)) {
continue;
}
$subForm = $form->get($dependentFieldConfig->name);
if ($subForm->getTransformationFailure() && $subForm instanceof ClearableErrorsInterface) {
$subForm->clearErrors();
$transformationErrorsCleared = true;
}
}
if ($transformationErrorsCleared) {
// We've cleared the error, but the bad data remains on the field.
// We need to make sure that the form doesn't submit successfully,
// but we also don't want to render a validation error on any field.
// So, we jam the error into a hidden field, which doesn't render errors.
if ($form->get('__dynamic_error')->isValid()) {
$form->get('__dynamic_error')->addError(new FormError('Some dynamic fields have errors.'));
}
}
}
private function executeReadyCallbacks(array $availableDependencyData, string $eventName): void
{
foreach ($this->dependentFieldConfigs as $dependentFieldConfig) {
if ($dependentFieldConfig->isReady($availableDependencyData, $eventName)) {
$dynamicField = $dependentFieldConfig->execute($availableDependencyData, $eventName);
$name = $dependentFieldConfig->name;
if (!$dynamicField->shouldBeAdded()) {
$this->form->remove($name);
continue;
}
$this->builder->add($name, $dynamicField->getType(), $dynamicField->getOptions());
$this->initializeListeners([$name]);
// auto initialize mimics FormBuilder::getForm() behavior
$field = $this->builder->get($name)->setAutoInitialize(false)->getForm();
$this->form->add($field);
}
}
}
private function initializeListeners(?array $fieldsToConsider = null): void
{
$registeredFields = [];
foreach ($this->dependentFieldConfigs as $dynamicField) {
foreach ($dynamicField->dependencies as $dependency) {
if ($fieldsToConsider && !\in_array($dependency, $fieldsToConsider)) {
continue;
}
// skip dependencies that are possibly not *yet* part of the form
if (!$this->builder->has($dependency)) {
continue;
}
if (\in_array($dependency, $registeredFields)) {
continue;
}
$registeredFields[] = $dependency;
$this->builder->get($dependency)->addEventListener(FormEvents::PRE_SET_DATA, [$this, 'storePreSetDataDependencyData']);
$this->builder->get($dependency)->addEventListener(FormEvents::POST_SUBMIT, [$this, 'storePostSubmitDependencyData']);
}
}
}
/*
* ----------------------------------------
*
* Pure decoration methods below.
*
* ----------------------------------------
*/
public function count(): int
{
return $this->builder->count();
}
/**
* @param string|FormBuilderInterface $child
*/
public function add($child, ?string $type = null, array $options = []): static
{
$this->builder->add($child, $type, $options);
return $this;
}
public function create(string $name, ?string $type = null, array $options = []): FormBuilderInterface
{
return $this->builder->create($name, $type, $options);
}
public function get(string $name): FormBuilderInterface
{
return $this->builder->get($name);
}
public function remove(string $name): static
{
$this->builder->remove($name);
return $this;
}
public function has(string $name): bool
{
return $this->builder->has($name);
}
public function all(): array
{
return $this->builder->all();
}
public function getForm(): FormInterface
{
return $this->builder->getForm();
}
public function addEventListener(string $eventName, callable $listener, int $priority = 0): static
{
$this->builder->addEventListener($eventName, $listener, $priority);
return $this;
}
public function addEventSubscriber(EventSubscriberInterface $subscriber): static
{
$this->builder->addEventSubscriber($subscriber);
return $this;
}
public function addViewTransformer(DataTransformerInterface $viewTransformer, bool $forcePrepend = false): static
{
$this->builder->addViewTransformer($viewTransformer, $forcePrepend);
return $this;
}
public function resetViewTransformers(): static
{
$this->builder->resetViewTransformers();
return $this;
}
public function addModelTransformer(DataTransformerInterface $modelTransformer, bool $forceAppend = false): static
{
$this->builder->addModelTransformer($modelTransformer, $forceAppend);
return $this;
}
public function resetModelTransformers(): static
{
$this->builder->resetModelTransformers();
return $this;
}
public function setAttribute(string $name, mixed $value): static
{
$this->builder->setAttribute($name, $value);
return $this;
}
public function setAttributes(array $attributes): static
{
$this->builder->setAttributes($attributes);
return $this;
}
public function setDataMapper(?DataMapperInterface $dataMapper = null): static
{
$this->builder->setDataMapper($dataMapper);
return $this;
}
public function setDisabled(bool $disabled): static
{
$this->builder->setDisabled($disabled);
return $this;
}
public function setEmptyData(mixed $emptyData): static
{
$this->builder->setEmptyData($emptyData);
return $this;
}
public function setErrorBubbling(bool $errorBubbling): static
{
$this->builder->setErrorBubbling($errorBubbling);
return $this;
}
public function setInheritData(bool $inheritData): static
{
$this->builder->setInheritData($inheritData);
return $this;
}
public function setMapped(bool $mapped): static
{
$this->builder->setMapped($mapped);
return $this;
}
public function setMethod(string $method): static
{
$this->builder->setMethod($method);
return $this;
}
/**
* @param string|PropertyPathInterface|null $propertyPath
*/
public function setPropertyPath($propertyPath): static
{
$this->builder->setPropertyPath($propertyPath);
return $this;
}
public function setRequired(bool $required): static
{
$this->builder->setRequired($required);
return $this;
}
public function setAction(?string $action): static
{
$this->builder->setAction($action);
return $this;
}
public function setCompound(bool $compound): static
{
$this->builder->setCompound($compound);
return $this;
}
public function setDataLocked(bool $locked): static
{
$this->builder->setDataLocked($locked);
return $this;
}
public function setFormFactory(FormFactoryInterface $formFactory): static
{
$this->builder->setFormFactory($formFactory);
return $this;
}
public function setType(?ResolvedFormTypeInterface $type): static
{
$this->builder->setType($type);
return $this;
}
public function setRequestHandler(?RequestHandlerInterface $requestHandler): static
{
$this->builder->setRequestHandler($requestHandler);
return $this;
}
public function getAttribute(string $name, mixed $default = null): mixed
{
return $this->builder->getAttribute($name, $default);
}
public function hasAttribute(string $name): bool
{
return $this->builder->hasAttribute($name);
}
public function getAttributes(): array
{
return $this->builder->getAttributes();
}
public function getDataMapper(): ?DataMapperInterface
{
return $this->builder->getDataMapper();
}
public function getEventDispatcher(): EventDispatcherInterface
{
return $this->builder->getEventDispatcher();
}
public function getName(): string
{
return $this->builder->getName();
}
public function getPropertyPath(): ?PropertyPathInterface
{
return $this->builder->getPropertyPath();
}
public function getRequestHandler(): RequestHandlerInterface
{
return $this->builder->getRequestHandler();
}
public function getType(): ResolvedFormTypeInterface
{
return $this->builder->getType();
}
public function setByReference(bool $byReference): static
{
$this->builder->setByReference($byReference);
return $this;
}
public function setData(mixed $data): static
{
$this->builder->setData($data);
return $this;
}
public function setAutoInitialize(bool $initialize): static
{
$this->builder->setAutoInitialize($initialize);
return $this;
}
public function getFormConfig(): FormConfigInterface
{
return $this->builder->getFormConfig();
}
public function setIsEmptyCallback(?callable $isEmptyCallback): static
{
$this->builder->setIsEmptyCallback($isEmptyCallback);
return $this;
}
public function getMapped(): bool
{
return $this->builder->getMapped();
}
public function getByReference(): bool
{
return $this->builder->getByReference();
}
public function getInheritData(): bool
{
return $this->builder->getInheritData();
}
public function getCompound(): bool
{
return $this->builder->getCompound();
}
public function getViewTransformers(): array
{
return $this->builder->getViewTransformers();
}
public function getModelTransformers(): array
{
return $this->builder->getModelTransformers();
}
public function getRequired(): bool
{
return $this->builder->getRequired();
}
public function getDisabled(): bool
{
return $this->builder->getDisabled();
}
public function getErrorBubbling(): bool
{
return $this->builder->getErrorBubbling();
}
public function getEmptyData(): mixed
{
return $this->builder->getEmptyData();
}
public function getData(): mixed
{
return $this->builder->getData();
}
public function getDataClass(): ?string
{
return $this->builder->getDataClass();
}
public function getDataLocked(): bool
{
return $this->builder->getDataLocked();
}
public function getFormFactory(): FormFactoryInterface
{
return $this->builder->getFormFactory();
}
public function getAction(): string
{
return $this->builder->getAction();
}
public function getMethod(): string
{
return $this->builder->getMethod();
}
public function getAutoInitialize(): bool
{
return $this->builder->getAutoInitialize();
}
public function getOptions(): array
{
return $this->builder->getOptions();
}
public function hasOption(string $name): bool
{
return $this->builder->hasOption($name);
}
public function getOption(string $name, mixed $default = null): mixed
{
return $this->builder->getOption($name, $default);
}
public function getIsEmptyCallback(): ?callable
{
return $this->builder->getIsEmptyCallback();
}
public function getIterator(): \Traversable
{
return $this->builder;
}
}
| php | MIT | c32e79bced902f12006a1238cca1834cfbcd5faf | 2026-01-05T05:10:27.898649Z | false |
SymfonyCasts/dynamic-forms | https://github.com/SymfonyCasts/dynamic-forms/blob/c32e79bced902f12006a1238cca1834cfbcd5faf/src/DependentField.php | src/DependentField.php | <?php
/*
* This file is part of the SymfonyCasts DynamicForms package.
* Copyright (c) SymfonyCasts <https://symfonycasts.com/>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfonycasts\DynamicForms;
/**
* Used to configure a dependent/dynamic field.
*
* If ->add() is not called, the field won't be included.
*/
class DependentField
{
private ?string $type = null;
private array $options = [];
private bool $shouldBeAdded = false;
public function add(?string $type = null, array $options = []): static
{
$this->type = $type;
$this->options = $options;
$this->shouldBeAdded = true;
return $this;
}
public function getType(): ?string
{
return $this->type;
}
public function getOptions(): array
{
return $this->options;
}
public function shouldBeAdded(): bool
{
return $this->shouldBeAdded;
}
}
| php | MIT | c32e79bced902f12006a1238cca1834cfbcd5faf | 2026-01-05T05:10:27.898649Z | false |
SymfonyCasts/dynamic-forms | https://github.com/SymfonyCasts/dynamic-forms/blob/c32e79bced902f12006a1238cca1834cfbcd5faf/src/DependentFieldConfig.php | src/DependentFieldConfig.php | <?php
/*
* This file is part of the SymfonyCasts DynamicForms package.
* Copyright (c) SymfonyCasts <https://symfonycasts.com/>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfonycasts\DynamicForms;
use Symfony\Component\Form\FormEvents;
/**
* Holds the configuration for a dynamic field & what listeners have been executed.
*/
class DependentFieldConfig
{
public array $callbackExecuted = [
FormEvents::PRE_SET_DATA => false,
FormEvents::POST_SUBMIT => false,
];
public function __construct(
public string $name,
public array $dependencies,
public \Closure $callback,
) {
}
public function isReady(array $availableDependencyData, string $eventName): bool
{
if (!\array_key_exists($eventName, $this->callbackExecuted)) {
throw new \InvalidArgumentException(\sprintf('Invalid event name "%s"', $eventName));
}
if ($this->callbackExecuted[$eventName]) {
return false;
}
foreach ($this->dependencies as $dependency) {
if (!\array_key_exists($dependency, $availableDependencyData)) {
return false;
}
}
return true;
}
public function execute(array $availableDependencyData, string $eventName): DependentField
{
$configurableFormBuilder = new DependentField();
$this->callbackExecuted[$eventName] = true;
$dependencyData = array_map(fn (string $dependency) => $availableDependencyData[$dependency], $this->dependencies);
$this->callback->__invoke($configurableFormBuilder, ...$dependencyData);
return $configurableFormBuilder;
}
}
| php | MIT | c32e79bced902f12006a1238cca1834cfbcd5faf | 2026-01-05T05:10:27.898649Z | false |
SymfonyCasts/dynamic-forms | https://github.com/SymfonyCasts/dynamic-forms/blob/c32e79bced902f12006a1238cca1834cfbcd5faf/tests/DependentFieldConfigTest.php | tests/DependentFieldConfigTest.php | <?php
/*
* This file is part of the SymfonyCasts DynamicForms package.
* Copyright (c) SymfonyCasts <https://symfonycasts.com/>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfonycasts\DynamicForms\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\FormEvents;
use Symfonycasts\DynamicForms\DependentField;
use Symfonycasts\DynamicForms\DependentFieldConfig;
class DependentFieldConfigTest extends TestCase
{
public function testIsReadyReturnsCorrectlyBasedOnDependencies(): void
{
$fieldConfig = new DependentFieldConfig('state', ['country'], fn () => null);
$this->assertFalse($fieldConfig->isReady([], FormEvents::PRE_SET_DATA));
$this->assertTrue($fieldConfig->isReady(['country' => 'United States'], FormEvents::PRE_SET_DATA));
$this->assertTrue($fieldConfig->isReady(['country' => 'United States'], FormEvents::POST_SUBMIT));
$this->assertTrue($fieldConfig->isReady(['country' => 'United States', 'extra' => 'field'], FormEvents::POST_SUBMIT));
}
public function testIsReadyReturnFalseIfCallbackExecuted(): void
{
$fieldConfig = new DependentFieldConfig('state', ['country'], fn () => null);
$this->assertTrue($fieldConfig->isReady(['country' => 'United States'], FormEvents::PRE_SET_DATA));
$fieldConfig->execute(['country' => 'United States'], FormEvents::PRE_SET_DATA);
$this->assertFalse($fieldConfig->isReady(['country' => 'United States'], FormEvents::PRE_SET_DATA));
$this->assertTrue($fieldConfig->isReady(['country' => 'United States'], FormEvents::POST_SUBMIT));
}
public function testExecuteCallsCallback(): void
{
$argsPassedToCallback = null;
$fieldConfig = new DependentFieldConfig('state', ['country', 'shouldHideRandomStates'], function ($configurableFormBuilder, $country, $shouldHideRandomStates) use (&$argsPassedToCallback) {
$argsPassedToCallback = [$configurableFormBuilder, $country, $shouldHideRandomStates];
});
$fieldConfig->execute(['country' => 'United States', 'shouldHideRandomStates' => true], FormEvents::PRE_SET_DATA);
$this->assertNotNull($argsPassedToCallback);
$this->assertInstanceOf(DependentField::class, $argsPassedToCallback[0]);
$this->assertSame('United States', $argsPassedToCallback[1]);
$this->assertTrue($argsPassedToCallback[2]);
}
}
| php | MIT | c32e79bced902f12006a1238cca1834cfbcd5faf | 2026-01-05T05:10:27.898649Z | false |
SymfonyCasts/dynamic-forms | https://github.com/SymfonyCasts/dynamic-forms/blob/c32e79bced902f12006a1238cca1834cfbcd5faf/tests/FunctionalTest.php | tests/FunctionalTest.php | <?php
/*
* This file is part of the SymfonyCasts DynamicForms package.
* Copyright (c) SymfonyCasts <https://symfonycasts.com/>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfonycasts\DynamicForms\Tests;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfonycasts\DynamicForms\Tests\fixtures\DynamicFormsTestKernel;
use Zenstruck\Browser\Test\HasBrowser;
class FunctionalTest extends KernelTestCase
{
use HasBrowser;
public function testDynamicFields()
{
$browser = $this->browser();
$browser->visit('/form')
// check for the hidden field
->assertSeeElement('#test_dynamic_form___dynamic_error')
->assertSee('Is Form Valid: no')
// Breakfast is the pre-selected meal
->assertSee('What is for Breakfast?')
->assertContains('<option value="bacon">')
->assertNotContains('<option value="pizza">')
->assertNotContains('What size pizza?')
;
// change the meal to dinner
$browser->selectFieldOption('Meal', 'Dinner')
->click('Submit Form')
// changing the field doesn't cause any issues
->assertSee('Is Form Valid: yes')
->assertNotContains('<option value="bacon">')
->assertContains('<option value="pizza">')
->assertNotContains('What size pizza?')
;
// now select Pizza!
$browser->selectFieldOption('Main food', 'Pizza')
->click('Submit Form')
->assertSee('Is Form Valid: yes')
->assertContains('<option value="pizza" selected="selected">')
->assertContains('What size pizza?')
;
// select the size
$browser->selectFieldOption('Pizza size', '14 inch')
->click('Submit Form')
->assertSee('Is Form Valid: yes')
->assertContains('<option value="pizza" selected="selected">')
->assertContains('<option value="14" selected="selected">')
;
// now change the meal to breakfast
$browser->selectFieldOption('Meal', 'Breakfast')
->click('Submit Form')
// form is not valid: the mainFood submitted an invalid value
->assertSee('Is Form Valid: no')
->assertContains('<option value="bacon">')
->assertNotContains('<option value="pizza"')
->assertNotContains('What size pizza?')
;
// select a valid food for breakfast
$browser->selectFieldOption('Main food', 'Bacon')
->click('Submit Form')
// form is valid again
->assertSee('Is Form Valid: yes')
;
// change the meal again
$browser->selectFieldOption('Meal', 'Lunch')
->click('Submit Form')
// form is not valid: the mainFood=bacon is invalid for lunch
->assertSee('Is Form Valid: no')
;
}
protected static function getKernelClass(): string
{
return DynamicFormsTestKernel::class;
}
}
| php | MIT | c32e79bced902f12006a1238cca1834cfbcd5faf | 2026-01-05T05:10:27.898649Z | false |
SymfonyCasts/dynamic-forms | https://github.com/SymfonyCasts/dynamic-forms/blob/c32e79bced902f12006a1238cca1834cfbcd5faf/tests/fixtures/TestDynamicForm.php | tests/fixtures/TestDynamicForm.php | <?php
/*
* This file is part of the SymfonyCasts DynamicForms package.
* Copyright (c) SymfonyCasts <https://symfonycasts.com/>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfonycasts\DynamicForms\Tests\fixtures;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\EnumType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfonycasts\DynamicForms\DependentField;
use Symfonycasts\DynamicForms\DynamicFormBuilder;
use Symfonycasts\DynamicForms\Tests\fixtures\Enum\DynamicTestFood;
use Symfonycasts\DynamicForms\Tests\fixtures\Enum\DynamicTestMeal;
use Symfonycasts\DynamicForms\Tests\fixtures\Enum\DynamicTestPizzaSize;
class TestDynamicForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder = new DynamicFormBuilder($builder);
$builder->add('meal', EnumType::class, [
'class' => DynamicTestMeal::class,
'choice_label' => fn (DynamicTestMeal $meal): string => $meal->getReadable(),
'placeholder' => 'Which meal is it?',
]);
$builder->add('upperCasePizzaSizes', CheckboxType::class, [
'mapped' => false,
]);
// addDynamic(string $name, array $dependencies, callable $callback): self
$builder->addDependent('mainFood', ['meal'], function (DependentField $field, ?DynamicTestMeal $meal) {
$field->add(EnumType::class, [
'class' => DynamicTestFood::class,
'placeholder' => null === $meal ? 'Select a meal first' : \sprintf('What is for %s?', $meal->getReadable()),
'choices' => $meal?->getFoodChoices(),
'choice_label' => fn (DynamicTestFood $food): string => $food->getReadable(),
'disabled' => null === $meal,
]);
});
$builder->addDependent('pizzaSize', ['mainFood', 'upperCasePizzaSizes'], function (DependentField $field, ?DynamicTestFood $food, bool $upperCasePizzaSizes) {
if (DynamicTestFood::Pizza !== $food) {
return;
}
$field->add(EnumType::class, [
'class' => DynamicTestPizzaSize::class,
'placeholder' => $upperCasePizzaSizes ? strtoupper('What size pizza?') : 'What size pizza?',
'choice_label' => fn (DynamicTestPizzaSize $pizzaSize): string => $upperCasePizzaSizes ? strtoupper($pizzaSize->getReadable()) : $pizzaSize->getReadable(),
'required' => true,
]);
});
}
}
| php | MIT | c32e79bced902f12006a1238cca1834cfbcd5faf | 2026-01-05T05:10:27.898649Z | false |
SymfonyCasts/dynamic-forms | https://github.com/SymfonyCasts/dynamic-forms/blob/c32e79bced902f12006a1238cca1834cfbcd5faf/tests/fixtures/DynamicFormsTestKernel.php | tests/fixtures/DynamicFormsTestKernel.php | <?php
/*
* This file is part of the SymfonyCasts DynamicForms package.
* Copyright (c) SymfonyCasts <https://symfonycasts.com/>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfonycasts\DynamicForms\Tests\fixtures;
use Psr\Log\NullLogger;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
use Symfonycasts\DynamicForms\Tests\fixtures\Enum\DynamicTestMeal;
use Twig\Environment;
class DynamicFormsTestKernel extends Kernel
{
use MicroKernelTrait;
public function form(Environment $twig, FormFactoryInterface $formFactory, Request $request): Response
{
$form = $formFactory->create(TestDynamicForm::class, [
'meal' => DynamicTestMeal::Breakfast,
]);
$form->handleRequest($request);
return new Response($twig->render('form.html.twig', [
'form' => $form->createView(),
'isFormValid' => $form->isSubmitted() && $form->isValid(),
]));
}
public function registerBundles(): iterable
{
return [
new FrameworkBundle(),
new TwigBundle(),
];
}
public function getProjectDir(): string
{
return __DIR__;
}
protected function configureContainer(ContainerConfigurator $container): void
{
$container->extension('framework', [
'secret' => 'foo000',
'http_method_override' => false,
'test' => true,
'handle_all_throwables' => true,
'php_errors' => [
'log' => true,
],
]);
$container->extension('twig', [
'default_path' => '%kernel.project_dir%/templates',
]);
}
protected function build(ContainerBuilder $container): void
{
$container->register('logger', NullLogger::class);
}
protected function configureRoutes(RoutingConfigurator $routes): void
{
$routes->add('form', '/form')->controller('kernel::form');
}
}
| php | MIT | c32e79bced902f12006a1238cca1834cfbcd5faf | 2026-01-05T05:10:27.898649Z | false |
SymfonyCasts/dynamic-forms | https://github.com/SymfonyCasts/dynamic-forms/blob/c32e79bced902f12006a1238cca1834cfbcd5faf/tests/fixtures/Enum/DynamicTestPizzaSize.php | tests/fixtures/Enum/DynamicTestPizzaSize.php | <?php
/*
* This file is part of the SymfonyCasts DynamicForms package.
* Copyright (c) SymfonyCasts <https://symfonycasts.com/>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfonycasts\DynamicForms\Tests\fixtures\Enum;
enum DynamicTestPizzaSize: int
{
case Small = 12;
case Medium = 14;
case Large = 16;
public function getReadable(): string
{
return match ($this) {
self::Small => '12 inch',
self::Medium => '14 inch',
self::Large => '16 inch',
};
}
}
| php | MIT | c32e79bced902f12006a1238cca1834cfbcd5faf | 2026-01-05T05:10:27.898649Z | false |
SymfonyCasts/dynamic-forms | https://github.com/SymfonyCasts/dynamic-forms/blob/c32e79bced902f12006a1238cca1834cfbcd5faf/tests/fixtures/Enum/DynamicTestFood.php | tests/fixtures/Enum/DynamicTestFood.php | <?php
/*
* This file is part of the SymfonyCasts DynamicForms package.
* Copyright (c) SymfonyCasts <https://symfonycasts.com/>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfonycasts\DynamicForms\Tests\fixtures\Enum;
enum DynamicTestFood: string
{
case Eggs = 'eggs';
case Bacon = 'bacon';
case Strawberries = 'strawberries';
case Croissant = 'croissant';
case Bagel = 'bagel';
case Kiwi = 'kiwi';
case Avocado = 'avocado';
case Waffles = 'waffles';
case Pancakes = 'pancakes';
case Salad = 'salad';
case Tea = 'teaοΈ';
case Sandwich = 'sandwich';
case Cheese = 'cheese';
case Sushi = 'sushi';
case Pizza = 'pizza';
case Pint = 'pint';
case Pasta = 'pasta';
public function getReadable(): string
{
return match ($this) {
self::Eggs => 'Eggs π³',
self::Bacon => 'Bacon π₯',
self::Strawberries => 'Strawberries π',
self::Croissant => 'Croissant π₯',
self::Bagel => 'Bagel π₯―',
self::Kiwi => 'Kiwi π₯',
self::Avocado => 'Avocado π₯',
self::Waffles => 'Waffles π§',
self::Pancakes => 'Pancakes π₯',
self::Salad => 'Salad π₯',
self::Tea => 'Tea βοΈ',
self::Sandwich => 'Sandwich π₯ͺ',
self::Cheese => 'Cheese π§',
self::Sushi => 'Sushi π±',
self::Pizza => 'Pizza π',
self::Pint => 'A Pint πΊ',
self::Pasta => 'Pasta π',
};
}
}
| php | MIT | c32e79bced902f12006a1238cca1834cfbcd5faf | 2026-01-05T05:10:27.898649Z | false |
SymfonyCasts/dynamic-forms | https://github.com/SymfonyCasts/dynamic-forms/blob/c32e79bced902f12006a1238cca1834cfbcd5faf/tests/fixtures/Enum/DynamicTestMeal.php | tests/fixtures/Enum/DynamicTestMeal.php | <?php
/*
* This file is part of the SymfonyCasts DynamicForms package.
* Copyright (c) SymfonyCasts <https://symfonycasts.com/>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfonycasts\DynamicForms\Tests\fixtures\Enum;
enum DynamicTestMeal: string
{
case Breakfast = 'breakfast';
case SecondBreakfast = 'second_breakfast';
case Elevenses = 'elevenses';
case Lunch = 'lunch';
case Dinner = 'dinner';
public function getReadable(): string
{
return match ($this) {
self::Breakfast => 'Breakfast',
self::SecondBreakfast => 'Second Breakfast',
self::Elevenses => 'Elevenses',
self::Lunch => 'Lunch',
self::Dinner => 'Dinner',
};
}
/**
* @return list<DynamicTestFood>
*/
public function getFoodChoices(): array
{
return match ($this) {
self::Breakfast => [DynamicTestFood::Eggs, DynamicTestFood::Bacon, DynamicTestFood::Strawberries, DynamicTestFood::Croissant],
self::SecondBreakfast => [DynamicTestFood::Bagel, DynamicTestFood::Kiwi, DynamicTestFood::Avocado, DynamicTestFood::Waffles],
self::Elevenses => [DynamicTestFood::Pancakes, DynamicTestFood::Strawberries, DynamicTestFood::Tea],
self::Lunch => [DynamicTestFood::Sandwich, DynamicTestFood::Cheese, DynamicTestFood::Sushi],
self::Dinner => [DynamicTestFood::Pizza, DynamicTestFood::Pint, DynamicTestFood::Pasta],
};
}
}
| php | MIT | c32e79bced902f12006a1238cca1834cfbcd5faf | 2026-01-05T05:10:27.898649Z | false |
ACloudGuru-Resources/Course_Introduction_to_Ansible | https://github.com/ACloudGuru-Resources/Course_Introduction_to_Ansible/blob/da108e5c5f9e8377f833504f63d127a0e24a7d46/04_05_Introduction_To_Ansible/index.php | 04_05_Introduction_To_Ansible/index.php | <?
echo "<h1>Hello, World! This is my Ansible page.</h1>";
?> | php | MIT | da108e5c5f9e8377f833504f63d127a0e24a7d46 | 2026-01-05T05:10:39.085933Z | false |
ACloudGuru-Resources/Course_Introduction_to_Ansible | https://github.com/ACloudGuru-Resources/Course_Introduction_to_Ansible/blob/da108e5c5f9e8377f833504f63d127a0e24a7d46/05_02_Introduction_To_Ansible/index.php | 05_02_Introduction_To_Ansible/index.php | <?
echo "<h1>Hello, World! This is my Ansible page.</h1>";
?> | php | MIT | da108e5c5f9e8377f833504f63d127a0e24a7d46 | 2026-01-05T05:10:39.085933Z | false |
ACloudGuru-Resources/Course_Introduction_to_Ansible | https://github.com/ACloudGuru-Resources/Course_Introduction_to_Ansible/blob/da108e5c5f9e8377f833504f63d127a0e24a7d46/06_05_Introduction_To_Ansible/index.php | 06_05_Introduction_To_Ansible/index.php | <?
echo "<h1>Hello, World! This is my Ansible page.</h1>";
?> | php | MIT | da108e5c5f9e8377f833504f63d127a0e24a7d46 | 2026-01-05T05:10:39.085933Z | false |
ACloudGuru-Resources/Course_Introduction_to_Ansible | https://github.com/ACloudGuru-Resources/Course_Introduction_to_Ansible/blob/da108e5c5f9e8377f833504f63d127a0e24a7d46/04_06_Introduction_To_Ansible/index.php | 04_06_Introduction_To_Ansible/index.php | <?
echo "<h1>Hello, World! This is my Ansible page.</h1>";
?> | php | MIT | da108e5c5f9e8377f833504f63d127a0e24a7d46 | 2026-01-05T05:10:39.085933Z | false |
ACloudGuru-Resources/Course_Introduction_to_Ansible | https://github.com/ACloudGuru-Resources/Course_Introduction_to_Ansible/blob/da108e5c5f9e8377f833504f63d127a0e24a7d46/06_04_Introduction_To_Ansible/index.php | 06_04_Introduction_To_Ansible/index.php | <?
echo "<h1>Hello, World! This is my Ansible page.</h1>";
?> | php | MIT | da108e5c5f9e8377f833504f63d127a0e24a7d46 | 2026-01-05T05:10:39.085933Z | false |
ACloudGuru-Resources/Course_Introduction_to_Ansible | https://github.com/ACloudGuru-Resources/Course_Introduction_to_Ansible/blob/da108e5c5f9e8377f833504f63d127a0e24a7d46/04_03_Introduction_To_Ansible/index.php | 04_03_Introduction_To_Ansible/index.php | <?
echo "<h1>Hello, World! This is my Ansible page.</h1>";
?> | php | MIT | da108e5c5f9e8377f833504f63d127a0e24a7d46 | 2026-01-05T05:10:39.085933Z | false |
ACloudGuru-Resources/Course_Introduction_to_Ansible | https://github.com/ACloudGuru-Resources/Course_Introduction_to_Ansible/blob/da108e5c5f9e8377f833504f63d127a0e24a7d46/06_01_Introduction_To_Ansible/index.php | 06_01_Introduction_To_Ansible/index.php | <?
echo "<h1>Hello, World! This is my Ansible page.</h1>";
?>
| php | MIT | da108e5c5f9e8377f833504f63d127a0e24a7d46 | 2026-01-05T05:10:39.085933Z | false |
ACloudGuru-Resources/Course_Introduction_to_Ansible | https://github.com/ACloudGuru-Resources/Course_Introduction_to_Ansible/blob/da108e5c5f9e8377f833504f63d127a0e24a7d46/06_01_Introduction_To_Ansible/roles/webservers/files/index.php | 06_01_Introduction_To_Ansible/roles/webservers/files/index.php | <?
echo "<h1>Hello, World! This is my ansible page.</h1>";
?> | php | MIT | da108e5c5f9e8377f833504f63d127a0e24a7d46 | 2026-01-05T05:10:39.085933Z | false |
ACloudGuru-Resources/Course_Introduction_to_Ansible | https://github.com/ACloudGuru-Resources/Course_Introduction_to_Ansible/blob/da108e5c5f9e8377f833504f63d127a0e24a7d46/05_03_Introduction_To_Ansible/index.php | 05_03_Introduction_To_Ansible/index.php | <?
echo "<h1>Hello, World! This is my Ansible page.</h1>";
?> | php | MIT | da108e5c5f9e8377f833504f63d127a0e24a7d46 | 2026-01-05T05:10:39.085933Z | false |
ACloudGuru-Resources/Course_Introduction_to_Ansible | https://github.com/ACloudGuru-Resources/Course_Introduction_to_Ansible/blob/da108e5c5f9e8377f833504f63d127a0e24a7d46/06_02_Introduction_To_Ansible/index.php | 06_02_Introduction_To_Ansible/index.php | <?
echo "<h1>Hello, World! This is my Ansible page.</h1>";
?> | php | MIT | da108e5c5f9e8377f833504f63d127a0e24a7d46 | 2026-01-05T05:10:39.085933Z | false |
ACloudGuru-Resources/Course_Introduction_to_Ansible | https://github.com/ACloudGuru-Resources/Course_Introduction_to_Ansible/blob/da108e5c5f9e8377f833504f63d127a0e24a7d46/05_01_Introduction_To_Ansible/index.php | 05_01_Introduction_To_Ansible/index.php | <?
echo "<h1>Hello, World! This is my Ansible page.</h1>";
?> | php | MIT | da108e5c5f9e8377f833504f63d127a0e24a7d46 | 2026-01-05T05:10:39.085933Z | false |
ACloudGuru-Resources/Course_Introduction_to_Ansible | https://github.com/ACloudGuru-Resources/Course_Introduction_to_Ansible/blob/da108e5c5f9e8377f833504f63d127a0e24a7d46/04_04_Introduction_To_Ansible/index.php | 04_04_Introduction_To_Ansible/index.php | <?
echo "<h1>Hello, World! This is my Ansible page.</h1>";
?> | php | MIT | da108e5c5f9e8377f833504f63d127a0e24a7d46 | 2026-01-05T05:10:39.085933Z | false |
ACloudGuru-Resources/Course_Introduction_to_Ansible | https://github.com/ACloudGuru-Resources/Course_Introduction_to_Ansible/blob/da108e5c5f9e8377f833504f63d127a0e24a7d46/06_06_Introduction_To_Ansible/index.php | 06_06_Introduction_To_Ansible/index.php | <?
echo "<h1>Hello, World! This is my Ansible page.</h1>";
?> | php | MIT | da108e5c5f9e8377f833504f63d127a0e24a7d46 | 2026-01-05T05:10:39.085933Z | false |
ACloudGuru-Resources/Course_Introduction_to_Ansible | https://github.com/ACloudGuru-Resources/Course_Introduction_to_Ansible/blob/da108e5c5f9e8377f833504f63d127a0e24a7d46/06_03_Introduction_To_Ansible/index.php | 06_03_Introduction_To_Ansible/index.php | <?
echo "<h1>Hello, World! This is my Ansible page.</h1>";
?> | php | MIT | da108e5c5f9e8377f833504f63d127a0e24a7d46 | 2026-01-05T05:10:39.085933Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/GenerateBlueprint.php | src/GenerateBlueprint.php | <?php
namespace StatamicRadPack\Runway;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Statamic\Fields\Blueprint;
class GenerateBlueprint
{
protected static array $columnMappings = [
'integer' => 'integer',
'tinyint' => 'integer',
'bigint' => 'integer',
'varchar' => 'text',
'text' => 'textarea',
// 'json' => 'array',
'timestamp' => 'date',
];
public static function generate(Resource $resource): Blueprint
{
$mainSection = [];
$sidebarSection = [];
collect(Schema::getColumns($resource->databaseTable()))
->reject(fn (array $column) => in_array($column['name'], ['id', 'created_at', 'updated_at']))
->map(fn (array $column) => [
'name' => $column['name'],
'type' => static::getMatchingFieldtype($column),
'nullable' => $column['nullable'],
'default' => $column['default'],
])
->reject(fn (array $field) => is_null($field['type']))
->each(function (array $field) use (&$mainSection, &$sidebarSection) {
$blueprintField = [
'handle' => $field['name'],
'field' => [
'type' => $field['type'],
'display' => (string) Str::of($field['name'])->headline(),
],
];
if (! $field['nullable']) {
$blueprintField['field']['validate'] = 'required';
}
if (in_array($field['name'], ['slug'])) {
$sidebarSection[] = $blueprintField;
return;
}
$mainSection[] = $blueprintField;
});
return \Statamic\Facades\Blueprint::make($resource->handle())
->setNamespace('runway')
->setContents([
'tabs' => [
'main' => ['fields' => $mainSection],
'sidebar' => ['fields' => $sidebarSection],
],
])
->save();
}
protected static function getMatchingFieldtype(array $column): ?string
{
$mapping = Arr::get(static::$columnMappings, $column['type_name']);
if (! $mapping) {
return null;
}
if (Arr::get($column, 'name') === 'slug') {
return 'slug';
}
if (Arr::get($column, 'type') === 'tinyint(1)') {
return 'toggle';
}
return $mapping;
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Relationships.php | src/Relationships.php | <?php
namespace StatamicRadPack\Runway;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Schema;
use Statamic\Fields\Field;
use Statamic\Support\Traits\Hookable;
use StatamicRadPack\Runway\Fieldtypes\HasManyFieldtype;
class Relationships
{
use Hookable;
public function __construct(protected Model $model, protected array $values = []) {}
public static function for(Model $model): self
{
return new static($model);
}
public function with(array $values): self
{
$this->values = $values;
return $this;
}
public function save(): void
{
$this->model->runwayResource()->blueprint()->fields()->all()
->reject(fn (Field $field) => $field->visibility() === 'computed' || ! $field->get('save', true))
->filter(fn (Field $field) => $field->fieldtype() instanceof HasManyFieldtype)
->each(function (Field $field): void {
$relationshipName = $this->model->runwayResource()->eloquentRelationships()->get($field->handle());
$values = $this->values[$field->handle()] ?? [];
match (get_class($relationship = $this->model->{$relationshipName}())) {
HasMany::class => $this->saveHasManyRelationship($field, $relationship, $values),
BelongsToMany::class => $this->saveBelongsToManyRelationship($field, $relationship, $values),
default => $this->runHooks('saveCustomRelationship', compact('field', 'relationship', 'values')),
};
});
}
protected function saveHasManyRelationship(Field $field, Relation $relationship, array $values): void
{
$relatedResource = Runway::findResource($field->fieldtype()->config('resource'));
$deleted = $relationship->whereNotIn($relatedResource->primaryKey(), $values)->get()
->each(fn (Model $model) => match ($this->getUnlinkBehaviorForHasManyRelationship($relationship)) {
'unlink' => $model->update([$relationship->getForeignKeyName() => null]),
'delete' => $model->delete(),
})
->map->getKey()
->all();
$models = $relationship->get();
collect($values)
->reject(fn ($id) => $models->pluck($relatedResource->primaryKey())->contains($id))
->reject(fn ($id) => in_array($id, $deleted))
->each(fn ($id) => $relatedResource->model()->find($id)?->update([
$relationship->getForeignKeyName() => $this->model->getKey(),
]));
if ($field->fieldtype()->config('reorderable') && $orderColumn = $field->fieldtype()->config('order_column')) {
collect($values)
->map(fn ($id) => $relatedResource->model()->find($id))
->reject(fn (Model $model, int $index) => $model->getAttribute($orderColumn) === $index)
->each(fn (Model $model, int $index) => $model->update([$orderColumn => $index]));
}
}
private function getUnlinkBehaviorForHasManyRelationship(HasMany $relationship): string
{
$foreignKey = $relationship->getQualifiedForeignKeyName();
$foreignTable = explode('.', $foreignKey)[0];
$foreignColumn = explode('.', $foreignKey)[1];
$column = collect(Schema::getColumns($foreignTable))
->first(fn (array $column) => $column['name'] === $foreignColumn);
return Arr::get($column, 'nullable') ? 'unlink' : 'delete';
}
protected function saveBelongsToManyRelationship(Field $field, Relation $relationship, array $values): void
{
if ($field->fieldtype()->config('reorderable') && $orderColumn = $field->fieldtype()->config('order_column')) {
$values = collect($values)->mapWithKeys(fn ($id, $index) => [$id => [$orderColumn => $index]])->all();
}
$relationship->sync($values);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Resource.php | src/Resource.php | <?php
namespace StatamicRadPack\Runway;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Statamic\Facades\Blink;
use Statamic\Facades\Search;
use Statamic\Fields\Blueprint;
use Statamic\Fields\Field;
use Statamic\Statamic;
use StatamicRadPack\Runway\Exceptions\PublishedColumnMissingException;
use StatamicRadPack\Runway\Fieldtypes\BelongsToFieldtype;
use StatamicRadPack\Runway\Fieldtypes\HasManyFieldtype;
class Resource
{
public function __construct(
protected string $handle,
protected Model $model,
protected string $name,
protected Collection $config
) {}
public function handle(): string
{
return $this->handle;
}
public function model(): Model
{
return $this->model;
}
public function newEloquentQuery(): Builder
{
return $this->model->newQuery()->runway();
}
public function newEloquentQueryBuilderWithEagerLoadedRelationships(): Builder
{
return $this
->newEloquentQuery()
->with(
collect($this->eagerLoadingRelationships())
->mapWithKeys(function (string $relationship): array {
if ($relationship === 'runwayUri') {
return [$relationship => fn ($query) => null];
}
return [$relationship => fn ($query) => $query->runway()];
})
->all()
);
}
public function name()
{
return $this->name;
}
public function singular(): string
{
return $this->config->get('singular') ?? Str::singular($this->name);
}
public function plural(): string
{
return $this->config->get('plural') ?? Str::plural($this->name);
}
public function blueprint(): Blueprint
{
$blueprint = Blueprint::find("runway::{$this->handle}");
if (! $blueprint) {
$blueprint = GenerateBlueprint::generate($this);
}
return $blueprint;
}
public function config(): Collection
{
return $this->config;
}
public function hidden(): bool
{
return $this->config->get('hidden', false);
}
public function route(): ?string
{
return $this->config->get('route');
}
public function template(): string
{
return $this->config->get('template', 'default');
}
public function layout(): string
{
return $this->config->get('layout', 'layout');
}
public function graphqlEnabled(): bool
{
if (! Statamic::pro()) {
return false;
}
return $this->config->get('graphql', false);
}
public function hasVisibleBlueprint(): bool
{
return $this->blueprint()->hidden() === false;
}
public function readOnly(): bool
{
return $this->config->get('read_only', false);
}
public function orderBy(): string
{
return $this->config->get('order_by', $this->primaryKey());
}
public function orderByDirection(): string
{
return $this->config->get('order_by_direction', 'asc');
}
public function titleField()
{
if ($titleField = $this->config()->get('title_field')) {
return $titleField;
}
return $this->listableColumns()
->filter(function ($handle) {
$field = $this->blueprint()->field($handle);
return in_array($field->type(), ['text', 'textarea', 'slug']);
})
->first();
}
public function hasPublishStates(): bool
{
return is_string($published = $this->config->get('published'))
|| $published === true;
}
public function publishedColumn(): ?string
{
if (! $this->hasPublishStates()) {
return null;
}
$column = is_string($this->config->get('published'))
? $this->config->get('published')
: 'published';
if (! in_array($column, $this->databaseColumns())) {
throw new PublishedColumnMissingException($this->databaseTable(), $column);
}
return $column;
}
public function defaultPublishState(): ?bool
{
if (! $this->hasPublishStates()) {
return null;
}
if ($this->revisionsEnabled()) {
return false;
}
return $this->config->get('default_publish_state', 'published') === 'published';
}
public function nestedFieldPrefixes(): Collection
{
return collect($this->config->get('nested_field_prefixes'));
}
public function nestedFieldPrefix(string $field): ?string
{
return $this->nestedFieldPrefixes()
->reject(fn ($prefix) => $field === $prefix)
->filter(fn ($prefix) => Str::startsWith($field, $prefix))
->first();
}
/**
* Maps Eloquent relationships to their respective blueprint fields.
*/
public function eloquentRelationships(): Collection
{
return $this->blueprint()->fields()->all()
->filter(function (Field $field) {
return $field->fieldtype() instanceof BelongsToFieldtype
|| $field->fieldtype() instanceof HasManyFieldtype;
})
->mapWithKeys(function (Field $field) {
$eloquentRelationship = $field->handle();
// If the field has a `relationship_name` config key, use that instead.
// Sometimes a column name will be different to the relationship name
// (the method on the model) so our magic won't be able to figure out what's what.
// Eg. standard_parent_id -> parent
if ($field->get('relationship_name')) {
return [$field->handle() => $field->get('relationship_name')];
}
// If field handle is `author_id`, strip off the `_id`
if (str_contains($eloquentRelationship, '_id')) {
$eloquentRelationship = Str::replaceLast('_id', '', $eloquentRelationship);
}
// If field handle contains an underscore, convert the name to camel case
if (str_contains($eloquentRelationship, '_')) {
$eloquentRelationship = Str::camel($eloquentRelationship);
}
return [$field->handle() => $eloquentRelationship];
})
->merge(['runwayUri'])
->filter(fn ($eloquentRelationship) => method_exists($this->model(), $eloquentRelationship));
}
/**
* Defines the relationships which should be eager loaded when querying the model.
*/
public function eagerLoadingRelationships(): array
{
if ($eagerLoadingRelationships = $this->config->get('with')) {
return $eagerLoadingRelationships;
}
return $this->eloquentRelationships()->values()->toArray();
}
public function listableColumns(): Collection
{
return $this->blueprint()->fields()->all()
->filter(fn (Field $field) => $field->isListable())
->map->handle()
->values();
}
public function hasRouting(): bool
{
return ! is_null($this->route())
&& in_array(\StatamicRadPack\Runway\Routing\Traits\RunwayRoutes::class, class_uses_recursive($this->model()));
}
public function primaryKey(): string
{
return $this->model()->getKeyName();
}
public function routeKey(): string
{
return $this->model()->getRouteKeyName() ?? 'id';
}
public function databaseTable(): string
{
return $this->model()->getTable();
}
public function databaseColumns(): array
{
return Blink::once('runway-database-columns-'.$this->databaseTable(), function () {
return $this->model()->getConnection()->getSchemaBuilder()->getColumnListing($this->databaseTable());
});
}
public function revisionsEnabled(): bool
{
if (! config('statamic.revisions.enabled') || ! Statamic::pro() || ! $this->hasPublishStates()) {
return false;
}
return $this->config->get('revisions', false);
}
public function searchIndex()
{
if (! $index = $this->config->get('search_index', false)) {
return;
}
return Search::index($index);
}
public function hasSearchIndex()
{
return $this->searchIndex() !== null;
}
public function toArray(): array
{
return [
'handle' => $this->handle(),
'model' => get_class($this->model()),
'name' => $this->name(),
'blueprint' => $this->blueprint(),
'hidden' => $this->hidden(),
'route' => $this->route(),
'has_publish_states' => $this->hasPublishStates(),
'published_column' => $this->publishedColumn(),
];
}
public function __get($name)
{
return $this->model()->{$name};
}
public function __call($name, $arguments)
{
return $this->model()->{$name}(...$arguments);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/ServiceProvider.php | src/ServiceProvider.php | <?php
namespace StatamicRadPack\Runway;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Spatie\ErrorSolutions\Contracts\SolutionProviderRepository;
use Statamic\API\Middleware\Cache;
use Statamic\Console\Commands\StaticWarm;
use Statamic\Facades\Blueprint;
use Statamic\Facades\CP\Nav;
use Statamic\Facades\GraphQL;
use Statamic\Facades\Permission;
use Statamic\Facades\Search;
use Statamic\Http\Middleware\RequireStatamicPro;
use Statamic\Providers\AddonServiceProvider;
use Statamic\Statamic;
use StatamicRadPack\Runway\GraphQL\NestedFieldsType;
use StatamicRadPack\Runway\Http\Controllers\ApiController;
use StatamicRadPack\Runway\Ignition\SolutionProviders\TraitMissing;
use StatamicRadPack\Runway\Policies\ResourcePolicy;
use StatamicRadPack\Runway\Routing\RunwayUri;
use StatamicRadPack\Runway\Search\Provider as SearchProvider;
use StatamicRadPack\Runway\Search\Searchable;
class ServiceProvider extends AddonServiceProvider
{
protected $vite = [
'publicDirectory' => 'dist',
'hotFile' => 'vendor/runway/hot',
'input' => [
'resources/js/cp.js',
],
];
public function boot()
{
parent::boot();
$this->loadViewsFrom(__DIR__.'/../resources/views', 'runway');
$this->mergeConfigFrom(__DIR__.'/../config/runway.php', 'runway');
if (! config('runway.disable_migrations')) {
$this->loadMigrationsFrom(__DIR__.'/../database/migrations');
}
$this->publishes([
__DIR__.'/../config/runway.php' => config_path('runway.php'),
], 'runway-config');
$this->registerIgnitionSolutionProviders();
Statamic::booted(function () {
if ($this->shouldDiscoverResources()) {
Runway::discoverResources();
}
$this
->registerRouteBindings()
->registerPermissions()
->registerPolicies()
->registerNavigation()
->registerBlueprints()
->registerSearchProvider()
->bootGraphQl()
->bootApi()
->bootModelEventListeners()
->bootDataRepository();
});
}
protected function registerIgnitionSolutionProviders(): void
{
try {
$this->app->make(SolutionProviderRepository::class)
->registerSolutionProvider(TraitMissing::class);
} catch (BindingResolutionException $e) {
//
}
}
protected function registerRouteBindings(): self
{
Route::bind('resource', function ($value) {
if (! Statamic::isCpRoute()) {
return $value;
}
return Runway::findResource($value);
});
return $this;
}
protected function registerPermissions(): self
{
Permission::group('runway', 'Runway', function () {
foreach (Runway::allResources() as $resource) {
Permission::register("view {$resource->handle()}", function ($permission) use ($resource) {
$permission
->label($this->permissionLabel('view', $resource))
->children([
Permission::make("edit {$resource->handle()}")
->label($this->permissionLabel('edit', $resource))
->children(array_filter([
Permission::make("create {$resource->handle()}")
->label($this->permissionLabel('create', $resource)),
$resource->hasPublishStates()
? Permission::make("publish {$resource->handle()}")
->label($this->permissionLabel('publish', $resource))
: null,
Permission::make("delete {$resource->handle()}")
->label($this->permissionLabel('delete', $resource)),
])),
]);
});
}
});
return $this;
}
protected function registerPolicies(): self
{
Gate::policy(Resource::class, ResourcePolicy::class);
return $this;
}
protected function registerNavigation(): self
{
Nav::extend(function ($nav) {
Runway::allResources()
->reject(fn ($resource) => $resource->hidden())
->each(function (Resource $resource) use (&$nav) {
$nav->create($resource->name())
->section('Content')
->route('runway.index', ['resource' => $resource->handle()])
->can('view', $resource);
});
});
return $this;
}
protected function registerBlueprints(): self
{
try {
Blueprint::addNamespace('runway', base_path('resources/blueprints/runway'));
if (! app()->runningInConsole()) {
Runway::allResources()->each(fn (Resource $resource) => $resource->blueprint());
}
} catch (QueryException $e) {
// A QueryException will be thrown when using the Eloquent Driver, where the `blueprints` table is
// yet to be migrated (for example: during a fresh install). We'll catch the exception here and
// ignore it to prevent any errors during the `composer dump-autoload` command.
Log::warning('Runway attempted to register its blueprint namespace. However, it seems the `blueprints` table has yet to be migrated.');
}
return $this;
}
protected function bootGraphQl(): self
{
Runway::allResources()
->each(function (Resource $resource) {
$this->app->bind("runway_graphql_types_{$resource->handle()}", fn () => new \StatamicRadPack\Runway\GraphQL\ResourceType($resource));
GraphQL::addType("runway_graphql_types_{$resource->handle()}");
$resource->nestedFieldPrefixes()->each(fn (string $nestedFieldPrefix) => GraphQL::addType(new NestedFieldsType($resource, $nestedFieldPrefix)));
})
->filter
->graphqlEnabled()
->each(function (Resource $resource) {
$this->app->bind("runway_graphql_queries_{$resource->handle()}_index", fn () => new \StatamicRadPack\Runway\GraphQL\ResourceIndexQuery($resource));
$this->app->bind("runway_graphql_queries_{$resource->handle()}_show", fn () => new \StatamicRadPack\Runway\GraphQL\ResourceShowQuery($resource));
GraphQL::addQuery("runway_graphql_queries_{$resource->handle()}_index");
GraphQL::addQuery("runway_graphql_queries_{$resource->handle()}_show");
});
return $this;
}
protected function bootApi(): self
{
if (config('statamic.api.enabled')) {
Route::middleware([
RequireStatamicPro::class,
Cache::class,
])->group(function () {
Route::middleware(config('statamic.api.middleware'))
->name('statamic.api.')
->prefix(config('statamic.api.route'))
->group(function () {
Route::name('runway.index')->get('runway/{resourceHandle}', [ApiController::class, 'index']);
Route::name('runway.show')->get('runway/{resourceHandle}/{model}', [ApiController::class, 'show']);
});
});
}
return $this;
}
protected function registerSearchProvider(): self
{
SearchProvider::register();
return $this;
}
protected function bootModelEventListeners(): self
{
Runway::allResources()
->map(fn ($resource) => get_class($resource->model()))
->each(function ($class) {
Event::listen('eloquent.saved: '.$class, fn ($model) => Search::updateWithinIndexes(new Searchable($model)));
Event::listen('eloquent.deleted: '.$class, fn ($model) => Search::deleteFromIndexes(new Searchable($model)));
});
return $this;
}
protected function bootDataRepository(): self
{
if (Runway::usesRouting()) {
$this->app->get(\Statamic\Contracts\Data\DataRepository::class)
->setRepository('runway-resources', Routing\ResourceRoutingRepository::class);
StaticWarm::hook('additional', function ($urls, $next) {
return $next($urls->merge(RunwayUri::select('uri')->pluck('uri')->all()));
});
}
return $this;
}
protected function permissionLabel($permission, $resource): string
{
$translationKey = "runway.permissions.{$permission}";
$label = trans($translationKey, [
'resource' => $resource->name(),
]);
if ($label == $translationKey) {
return match ($permission) {
'view' => "View {$resource->name()}",
'edit' => "Edit {$resource->name()}",
'create' => "Create {$resource->name()}",
'publish' => "Manage {$resource->name()} Publish State",
'delete' => "Delete {$resource->name()}"
};
}
return $label;
}
protected function shouldDiscoverResources(): bool
{
if (Str::startsWith(request()->path(), '_ignition/')) {
return false;
}
return true;
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Runway.php | src/Runway.php | <?php
namespace StatamicRadPack\Runway;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use StatamicRadPack\Runway\Exceptions\ResourceNotFound;
use StatamicRadPack\Runway\Exceptions\TraitMissingException;
class Runway
{
protected static array $resources = [];
protected static array $registeredResources = [];
public static function discoverResources(): self
{
static::$resources = collect(config('runway.resources'))
->merge(static::$registeredResources)
->mapWithKeys(function ($config, $model) {
$config = collect($config);
$handle = $config->get('handle', Str::snake(class_basename($model)));
throw_if(
! in_array(Traits\HasRunwayResource::class, class_uses_recursive($model)),
new TraitMissingException($model),
);
$resource = new Resource(
handle: $handle,
model: $model instanceof Model ? $model : new $model,
name: $config['name'] ?? Str::title($handle),
config: $config,
);
return [$handle => $resource];
})
->filter()
->toArray();
return new static;
}
public static function allResources(): Collection
{
return collect(static::$resources);
}
public static function findResource(string $resourceHandle): ?Resource
{
$resource = collect(static::$resources)->get($resourceHandle);
if (! $resource) {
throw new ResourceNotFound($resourceHandle);
}
return $resource;
}
public static function findResourceByModel(object $model): ?Resource
{
$resource = collect(static::$resources)->filter(fn (Resource $resource) => $model::class === $resource->model()::class)->first();
if (! $resource) {
throw new ResourceNotFound($model::class);
}
return $resource;
}
public static function registerResource(string $model, array $config): self
{
static::$registeredResources[$model] = $config;
static::discoverResources();
return new static;
}
public static function clearRegisteredResources(): self
{
static::$registeredResources = [];
return new static;
}
public static function usesRouting(): bool
{
return static::allResources()->filter->hasRouting()->count() >= 1;
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Routing/ResourceResponse.php | src/Routing/ResourceResponse.php | <?php
namespace StatamicRadPack\Runway\Routing;
use Facades\Statamic\View\Cascade;
use Illuminate\Contracts\Support\Responsable;
use Statamic\Events\ResponseCreated;
use Statamic\Facades\Site;
use Statamic\View\View;
class ResourceResponse implements Responsable
{
protected $request;
protected $with = [];
public function __construct(protected $data) {}
public function toResponse($request)
{
$this->request = $request;
$this->addViewPaths();
$response = response()->make($this->contents());
ResponseCreated::dispatch($response, $this->data);
return $response;
}
protected function addViewPaths()
{
$finder = view()->getFinder();
$site = method_exists($this->data, 'site')
? $this->data->site()->handle()
: Site::current()->handle();
$paths = collect($finder->getPaths())->flatMap(function ($path) use ($site) {
return [
$path.'/'.$site,
$path,
];
})->filter()->values()->all();
$finder->setPaths($paths);
return $this;
}
protected function contents()
{
return (new View)
->template($this->data->template())
->layout($this->data->layout())
->with($this->with)
->cascadeContent($this->data)
->render();
}
protected function cascade()
{
return Cascade::instance()->withContent($this->data)->hydrate();
}
public function with($data)
{
$this->with = $data;
return $this;
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Routing/MorphOneWithStringKey.php | src/Routing/MorphOneWithStringKey.php | <?php
namespace StatamicRadPack\Runway\Routing;
use Illuminate\Database\Eloquent\Relations\MorphOne;
class MorphOneWithStringKey extends MorphOne
{
public function addConstraints()
{
if (static::$constraints) {
$this->getQuery()->where($this->morphType, $this->morphClass)
->where($this->foreignKey, (string) $this->getParentKey());
}
}
public function addEagerConstraints(array $models)
{
$keys = array_map('strval', $this->getKeys($models, $this->localKey));
$this->getQuery()->where($this->morphType, $this->morphClass)
->whereIn($this->foreignKey, $keys);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Routing/Routable.php | src/Routing/Routable.php | <?php
namespace StatamicRadPack\Runway\Routing;
use Statamic\Contracts\Routing\UrlBuilder;
use Statamic\Facades\Site;
use Statamic\Facades\URL;
use Statamic\Support\Str;
/**
* This class is a direct copy of the Statamic\Routing\Routable trait,
* just without the `slug` method & property which conflict with Eloquent
* attributes of the same name.
*
* See: https://github.com/statamic-rad-pack/runway/pull/429
*/
trait Routable
{
abstract public function route();
abstract public function routeData();
public function uri()
{
if (! $route = $this->route()) {
return null;
}
return app(UrlBuilder::class)->content($this)->build($route);
}
public function url()
{
if ($this->isRedirect()) {
return $this->redirectUrl();
}
return $this->urlWithoutRedirect();
}
public function urlWithoutRedirect()
{
if (! $url = $this->absoluteUrlWithoutRedirect()) {
return null;
}
return URL::makeRelative($url);
}
public function absoluteUrl()
{
if ($this->isRedirect()) {
return $this->absoluteRedirectUrl();
}
return $this->absoluteUrlWithoutRedirect();
}
public function absoluteUrlWithoutRedirect()
{
return $this->makeAbsolute($this->uri());
}
public function isRedirect()
{
return ($url = $this->redirectUrl())
&& $url !== 404;
}
public function redirectUrl()
{
if ($redirect = $this->redirect) {
return (new \Statamic\Routing\ResolveRedirect)($redirect, $this);
}
}
public function absoluteRedirectUrl()
{
return $this->makeAbsolute($this->redirectUrl());
}
private function makeAbsolute($url)
{
if (! $url) {
return null;
}
if (! Str::startsWith($url, '/')) {
return $url;
}
$url = vsprintf('%s/%s', [
rtrim(Site::selected()->absoluteUrl(), '/'),
ltrim($url, '/'),
]);
return $url === '/' ? $url : rtrim($url, '/');
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Routing/RoutingModel.php | src/Routing/RoutingModel.php | <?php
namespace StatamicRadPack\Runway\Routing;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Database\Eloquent\Model;
use Statamic\Contracts\Data\Augmentable;
use Statamic\Contracts\Data\Augmented;
use Statamic\Data\ContainsSupplementalData;
use Statamic\Data\HasAugmentedData;
use StatamicRadPack\Runway\Data\AugmentedModel;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Runway;
class RoutingModel implements Augmentable, Responsable
{
use ContainsSupplementalData, HasAugmentedData;
public function __construct(protected Model $model)
{
$this->supplements = collect();
}
public function model(): Model
{
return $this->model;
}
public function route(): ?string
{
if (! $this->model->runwayUri) {
return null;
}
return $this->model->runwayUri->uri;
}
public function routeData(): array
{
return [
'id' => $this->model->{$this->model->getKeyName()},
];
}
public function uri(): ?string
{
return $this->model->routableUri();
}
public function urlWithoutRedirect(): ?string
{
return $this->uri();
}
public function toResponse($request)
{
return (new ResourceResponse($this))
->with($this->supplements->all())
->toResponse($request);
}
public function resource(): ?Resource
{
return Runway::findResourceByModel($this->model);
}
public function template(): string
{
return $this->resource()->template();
}
public function layout(): string
{
return $this->resource()->layout();
}
public function id()
{
return $this->model->getKey();
}
public function getRouteKey()
{
return $this->model->getAttributeValue($this->model->getRouteKeyName());
}
public function newAugmentedInstance(): Augmented
{
return new AugmentedModel($this->model);
}
public function __get($key)
{
return $this->model->{$key};
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Routing/RunwayUri.php | src/Routing/RunwayUri.php | <?php
namespace StatamicRadPack\Runway\Routing;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class RunwayUri extends Model
{
protected $fillable = ['uri', 'model_type', 'model_id'];
public function model(): MorphTo
{
return $this->morphTo()->runway();
}
public function getTable()
{
return config('runway.uris_table', 'runway_uris');
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Routing/ResourceRoutingRepository.php | src/Routing/ResourceRoutingRepository.php | <?php
namespace StatamicRadPack\Runway\Routing;
class ResourceRoutingRepository
{
public function findByUri(string $uri)
{
$runwayUri = RunwayUri::where('uri', $uri)->first();
if (! $runwayUri) {
return null;
}
if ($runwayUri->model->runwayResource()->hasPublishStates() && $runwayUri->model->publishedStatus() !== 'published') {
return null;
}
return $runwayUri->model->routingModel();
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Routing/Traits/RunwayRoutes.php | src/Routing/Traits/RunwayRoutes.php | <?php
namespace StatamicRadPack\Runway\Routing\Traits;
use Illuminate\Support\Str;
use Statamic\Facades\Antlers;
use Statamic\StaticCaching\Cacher;
use Statamic\Support\Arr;
use StatamicRadPack\Runway\Routing\MorphOneWithStringKey;
use StatamicRadPack\Runway\Routing\Routable;
use StatamicRadPack\Runway\Routing\RoutingModel;
use StatamicRadPack\Runway\Routing\RunwayUri;
use StatamicRadPack\Runway\Runway;
trait RunwayRoutes
{
protected $routingModel;
use Routable {
uri as routableUri;
}
public function routingModel(): RoutingModel
{
$this->routingModel = new RoutingModel($this);
return $this->routingModel;
}
public function route(): ?string
{
if (! $this->runwayUri) {
return null;
}
return $this->runwayUri->uri;
}
public function routeData()
{
return $this->routingModel()->routeData();
}
public function uri(): ?string
{
return $this->routingModel()->uri();
}
public function toResponse($request)
{
return $this->routingModel()->toResponse($request);
}
public function template(): string
{
return $this->routingModel()->template();
}
public function layout(): string
{
return $this->routingModel()->layout();
}
public function getRouteKey()
{
return $this->routingModel()->getRouteKey();
}
public function runwayUri(): MorphOneWithStringKey
{
return new MorphOneWithStringKey(RunwayUri::query(), $this, 'model_type', 'model_id', $this->getKeyName());
}
public static function bootRunwayRoutes()
{
static::saved(function ($model) {
$resource = Runway::findResourceByModel($model);
if (! $resource->hasRouting()) {
return;
}
$uri = Antlers::parser()
->parse($resource->route(), $model->toAugmentedArray())
->__toString();
$uri = Str::start($uri, '/');
if ($model->runwayUri()->exists()) {
$model->runwayUri()->first()->update(['uri' => $uri]);
} else {
$model->runwayUri()->create(['uri' => $uri]);
}
app(Cacher::class)->invalidateUrl($uri);
app(Cacher::class)->invalidateUrls(
Arr::get(config('statamic.static_caching.invalidation.rules'), "runway.{$resource->handle()}.urls")
);
});
static::deleting(function ($model) {
if ($model->runwayUri) {
$model->runwayUri()->delete();
}
});
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Tags/RunwayTag.php | src/Tags/RunwayTag.php | <?php
namespace StatamicRadPack\Runway\Tags;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Statamic\Extensions\Pagination\LengthAwarePaginator;
use Statamic\Facades\Blink;
use Statamic\Tags\Tags;
use StatamicRadPack\Runway\Exceptions\ResourceNotFound;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Runway;
class RunwayTag extends Tags
{
protected static $handle = 'runway';
protected $resource;
protected function parseResource(?string $resourceHandle = null): Resource
{
$from = $resourceHandle ?? $this->params->get(['from', 'in', 'resource']);
try {
return Runway::findResource(Str::studly($from));
} catch (ResourceNotFound) {
try {
return Runway::findResource(Str::lower($from));
} catch (ResourceNotFound) {
return Runway::findResource($from);
}
}
}
public function wildcard(?string $resourceHandle = null): array
{
$this->resource = $this->parseResource($resourceHandle);
return $this->results($this->query());
}
public function count(): int
{
$this->resource = $this->parseResource();
return $this->query()->count();
}
protected function query(): Builder
{
$query = $this->resource->query()
->when(
$this->params->get('status'),
fn ($query, $status) => $query->whereStatus($status),
fn ($query) => $query->whereStatus('published')
)
->when(
$this->params->get('with'),
fn ($query) => $query->with(explode('|', (string) $this->params->get('with'))),
fn ($query) => $query->with($this->resource->eagerLoadingRelationships())
);
if ($select = $this->params->get('select')) {
$query->select(explode(',', (string) $select));
}
if ($scopes = $this->params->get('scope')) {
$scopes = explode('|', (string) $scopes);
foreach ($scopes as $scope) {
$scopeName = explode(':', $scope)[0];
$scopeArguments = isset(explode(':', $scope)[1])
? explode(',', explode(':', $scope)[1])
: [];
foreach ($scopeArguments as $key => $scopeArgument) {
if ($fromContext = $this->context->get($scopeArgument)) {
if ($fromContext instanceof \Statamic\Fields\Value) {
$fromContext = $fromContext->raw();
}
$scopeArguments[$key] = $fromContext;
}
}
$query->{$scopeName}(...$scopeArguments);
}
}
if ($this->params->has('where') && $where = $this->params->get('where')) {
$key = explode(':', (string) $where)[0];
$value = explode(':', (string) $where)[1];
if ($this->resource->eloquentRelationships()->has($key)) {
// eloquentRelationships() returns a Collection of keys/values, the keys are the field names
// & the values are the Eloquent relationship names. We need to get the relationship name
// for the whereHas query.
$relationshipName = $this->resource->eloquentRelationships()->get($key);
$relationshipResource = Runway::findResource($this->resource->blueprint()->field($key)->config()['resource']);
$query->whereHas($relationshipName, function ($query) use ($value, $relationshipResource) {
$query->whereIn($relationshipResource->databaseTable().'.'.$relationshipResource->primaryKey(), Arr::wrap($value));
});
} else {
$query->where($this->resource->model()->getColumnForField($key), $value);
}
}
if ($this->params->has('where_in') && $whereIn = $this->params->get('where_in')) {
$key = explode(':', (string) $whereIn)[0];
$value = explode(':', (string) $whereIn)[1];
$query->whereIn($this->resource->model()->getColumnForField($key), explode(',', $value));
}
if ($this->params->has('sort') && ! empty($this->params->get('sort'))) {
if (Str::contains($this->params->get('sort'), ':')) {
$sortColumn = explode(':', (string) $this->params->get('sort'))[0];
$sortDirection = explode(':', (string) $this->params->get('sort'))[1];
} else {
$sortColumn = $this->params->get('sort');
$sortDirection = 'asc';
}
$query->orderBy($this->resource->model()->getColumnForField($sortColumn), $sortDirection);
}
return $query;
}
protected function results($query)
{
if ($this->params->get('paginate') || $this->params->get('limit')) {
$paginator = $query->paginate($this->params->get('limit'));
$paginator = app()->makeWith(LengthAwarePaginator::class, [
'items' => $paginator->items(),
'total' => $paginator->total(),
'perPage' => $paginator->perPage(),
'currentPage' => $paginator->currentPage(),
'options' => $paginator->getOptions(),
])->withQueryString();
$results = $paginator->items();
} else {
$results = $query->get();
}
if (! $this->params->has('as')) {
return $this->augmentModels($results);
}
return [
$this->params->get('as') => $this->augmentModels($results),
'paginate' => isset($paginator) ? $this->getPaginationData($paginator) : null,
'no_results' => collect($results)->isEmpty(),
];
}
protected function augmentModels($query): array
{
return collect($query)
->map(function ($model, $key) {
return Blink::once("Runway::Tag::AugmentModels::{$this->resource->handle()}::{$model->{$this->resource->primaryKey()}}", function () use ($model) {
return $model->toAugmentedArray();
});
})
->toArray();
}
protected function getPaginationData($paginator): array
{
return [
'total_items' => $paginator->total(),
'items_per_page' => $paginator->perPage(),
'total_pages' => $paginator->lastPage(),
'current_page' => $paginator->currentPage(),
'prev_page' => $paginator->previousPageUrl(),
'next_page' => $paginator->nextPageUrl(),
'auto_links' => $paginator->render('pagination::default'),
'links' => $paginator->renderArray(),
];
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Scopes/Fields.php | src/Scopes/Fields.php | <?php
namespace StatamicRadPack\Runway\Scopes;
use Illuminate\Support\Collection;
use Statamic\Fields\Field;
use Statamic\Query\Scopes\Filters\Fields as BaseFieldsFilter;
use StatamicRadPack\Runway\Runway;
class Fields extends BaseFieldsFilter
{
protected static $handle = 'runway-fields';
public function visibleTo($key): bool
{
return $key === 'runway';
}
public function apply($query, $values): void
{
$resource = Runway::findResource($this->context['resource']);
$this->getFields()
->filter(function ($field, $handle) use ($values) {
return isset($values[$handle]);
})
->each(function (Field $field) use ($query, $values, $resource) {
$filter = $field->fieldtype()->filter();
$values = $filter->fields()->addValues($values[$field->handle()])->process()->values();
$filter->apply($query, $resource->model()->getColumnForField($field->handle()), $values);
});
}
protected function getFields(): Collection
{
$resource = Runway::findResource($this->context['resource']);
return $resource->blueprint()->fields()->all()
->filter->isFilterable()
->reject(function (Field $field) use ($resource) {
return in_array($field->handle(), $resource->model()->getAppends(), true)
&& ! $resource->model()->hasSetMutator($field->handle())
&& ! $resource->model()->hasAttributeSetMutator($field->handle());
});
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Scopes/Status.php | src/Scopes/Status.php | <?php
namespace StatamicRadPack\Runway\Scopes;
use Illuminate\Support\Collection;
use Statamic\Query\Scopes\Filters\Status as BaseStatusFilter;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Runway;
class Status extends BaseStatusFilter
{
protected static $handle = 'runway-status';
public function visibleTo($key): bool
{
return in_array($key, ['runway']) && $this->resource()->hasPublishStates();
}
protected function options(): Collection
{
return collect([
'published' => __('Published'),
// 'scheduled' => __('Scheduled'),
// 'expired' => __('Expired'),
'draft' => __('Draft'),
]);
}
protected function resource(): Resource
{
return Runway::findResource($this->context['resource']);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Scopes/Fields/Models.php | src/Scopes/Fields/Models.php | <?php
namespace StatamicRadPack\Runway\Scopes\Fields;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Statamic\Query\Scopes\Filters\Fields\FieldtypeFilter;
use Statamic\Support\Arr;
use Statamic\Support\Str;
use StatamicRadPack\Runway\Runway;
class Models extends FieldtypeFilter
{
public function fieldItems(): array
{
$resource = Runway::findResource($this->fieldtype->config('resource'));
return [
'field' => [
'type' => 'select',
'options' => [
$resource->primaryKey() => __(Str::upper($resource->primaryKey())),
$resource->titleField() => $resource->blueprint()->field($resource->titleField())->display(),
],
'default' => $resource->titleField(),
],
'operator' => [
'type' => 'select',
'options' => [
'like' => __('Contains'),
'not like' => __('Doesn\'t contain'),
'=' => __('Is'),
'!=' => __('Isn\'t'),
],
'default' => 'like',
],
'value' => [
'type' => 'text',
'placeholder' => __('Value'),
'if' => [
'operator' => 'not empty',
],
],
];
}
public function apply($query, $handle, $values): void
{
$field = $values['field'];
$operator = $values['operator'];
$value = $values['value'];
if ($operator === 'like' || $operator === 'not like') {
$value = Str::ensureLeft($value, '%');
$value = Str::ensureRight($value, '%');
}
$relatedResource = Runway::findResource($this->fieldtype->config('resource'));
$ids = $relatedResource->model()->query()
->where($field, $operator, $value)
->select($relatedResource->primaryKey())
->get()
->pluck($relatedResource->primaryKey())
->toArray();
// When we're dealing with an Eloquent query builder, we can take advantage of `whereHas` to filter.
// Otherwise, we'll just filter the IDs directly.
if (method_exists($query, 'getModel')) {
// This is the resource of the Eloquent model that the filter is querying.
$queryingResource = Runway::findResourceByModel($query->getModel());
$query->whereHas($queryingResource->eloquentRelationships()->get($this->fieldtype->field()->handle()), function (Builder $query) use ($relatedResource, $ids) {
$query->whereIn($relatedResource->primaryKey(), $ids);
});
} else {
$query->whereIn($this->fieldtype->field()->handle(), $ids);
}
}
public function badge($values): string
{
$field = $this->fieldtype->field()->display();
$selectedField = $values['field'];
$operator = $values['operator'];
$translatedField = Arr::get($this->fieldItems(), "field.options.{$selectedField}");
$translatedOperator = Arr::get($this->fieldItems(), "operator.options.{$operator}");
$value = $values['value'];
return $field.' '.$translatedField.' '.strtolower($translatedOperator).' '.$value;
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Exceptions/TraitMissingException.php | src/Exceptions/TraitMissingException.php | <?php
namespace StatamicRadPack\Runway\Exceptions;
class TraitMissingException extends \Exception
{
public function __construct(public string $model)
{
parent::__construct("The HasRunwayResource trait is missing from the [{$model}] model");
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Exceptions/EmptyBlueprintException.php | src/Exceptions/EmptyBlueprintException.php | <?php
namespace StatamicRadPack\Runway\Exceptions;
use Spatie\Ignition\Contracts\BaseSolution;
use Spatie\Ignition\Contracts\ProvidesSolution;
use Spatie\Ignition\Contracts\Solution;
class EmptyBlueprintException extends \Exception implements ProvidesSolution
{
public function __construct(protected string $resourceHandle)
{
parent::__construct("There are no fields defined in the {$this->resourceHandle} blueprint.");
}
public function getSolution(): Solution
{
return BaseSolution::create("Add fields to the {$this->resourceHandle} blueprint")
->setSolutionDescription('Before you can view this resource in the Control Panel, you need to define fields in its blueprint.')
->setDocumentationLinks([
'Edit blueprint' => cp_route('blueprints.edit', ['namespace' => 'runway', 'handle' => $this->resourceHandle]),
'Review the docs' => 'https://runway.duncanmcclean.com/blueprints',
]);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Exceptions/ResourceNotFound.php | src/Exceptions/ResourceNotFound.php | <?php
namespace StatamicRadPack\Runway\Exceptions;
class ResourceNotFound extends \Exception
{
public function __construct(protected string $resourceHandle)
{
parent::__construct("Runway could not find [{$resourceHandle}]. Please ensure its configured properly and you're using the correct handle.");
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Exceptions/PublishedColumnMissingException.php | src/Exceptions/PublishedColumnMissingException.php | <?php
namespace StatamicRadPack\Runway\Exceptions;
class PublishedColumnMissingException extends \Exception
{
public function __construct(public string $table, public string $column)
{
parent::__construct("The [{$this->column}] publish column is missing from the {$this->table} table.");
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Requests/CP/UpdateRequest.php | src/Http/Requests/CP/UpdateRequest.php | <?php
namespace StatamicRadPack\Runway\Http\Requests\CP;
use Illuminate\Foundation\Http\FormRequest;
use Statamic\Facades\User;
class UpdateRequest extends FormRequest
{
public function authorize()
{
$resource = $this->route('resource');
if ($resource->readOnly()) {
return false;
}
$model = $resource->model()->find($this->model);
return User::current()->can('edit', [$resource, $model]);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Requests/CP/StoreRequest.php | src/Http/Requests/CP/StoreRequest.php | <?php
namespace StatamicRadPack\Runway\Http\Requests\CP;
use Illuminate\Foundation\Http\FormRequest;
use Statamic\Facades\User;
class StoreRequest extends FormRequest
{
public function authorize()
{
$resource = $this->route('resource');
if (! $resource->hasVisibleBlueprint() || $resource->readOnly()) {
return false;
}
return User::current()->can('create', $resource);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Requests/CP/EditRequest.php | src/Http/Requests/CP/EditRequest.php | <?php
namespace StatamicRadPack\Runway\Http\Requests\CP;
use Illuminate\Foundation\Http\FormRequest;
use Statamic\Facades\User;
class EditRequest extends FormRequest
{
public function authorize()
{
$resource = $this->route('resource');
$model = $resource->model()::find($this->model);
return User::current()->can('edit', [$resource, $model]);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Requests/CP/IndexRequest.php | src/Http/Requests/CP/IndexRequest.php | <?php
namespace StatamicRadPack\Runway\Http\Requests\CP;
use Illuminate\Foundation\Http\FormRequest;
use Statamic\Facades\User;
class IndexRequest extends FormRequest
{
public function authorize()
{
$resource = $this->route('resource');
return User::current()->can('view', $resource);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Requests/CP/CreateRequest.php | src/Http/Requests/CP/CreateRequest.php | <?php
namespace StatamicRadPack\Runway\Http\Requests\CP;
use Illuminate\Foundation\Http\FormRequest;
use Statamic\Facades\User;
class CreateRequest extends FormRequest
{
public function authorize()
{
$resource = $this->route('resource');
if (! $resource->hasVisibleBlueprint() || $resource->readOnly()) {
return false;
}
return User::current()->can('create', $resource);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Controllers/ApiController.php | src/Http/Controllers/ApiController.php | <?php
namespace StatamicRadPack\Runway\Http\Controllers;
use Facades\Statamic\API\FilterAuthorizer;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Statamic\Exceptions\NotFoundHttpException;
use Statamic\Http\Controllers\API\ApiController as StatamicApiController;
use StatamicRadPack\Runway\Exceptions\ResourceNotFound;
use StatamicRadPack\Runway\Http\Resources\ApiResource;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Runway;
class ApiController extends StatamicApiController
{
private $config;
protected $resourceConfigKey = 'runway';
protected $routeResourceKey = 'resourceHandle';
protected $filterPublished = true;
protected $resourceHandle;
public function index($resourceHandle)
{
$this->abortIfDisabled();
$resource = $this->resource($resourceHandle);
$this->resourceHandle = $resource->handle();
$results = $this->filterSortAndPaginate($resource->model()->query());
$results = ApiResource::collection($results);
$results->setCollection(
$results->getCollection()->transform(fn ($result) => $result->withBlueprintFields($this->getFieldsFromBlueprint($resource)))
);
return $results;
}
public function show($resourceHandle, $model)
{
$this->abortIfDisabled();
$resource = $this->resource($resourceHandle);
$this->resourceHandle = $resource->handle();
if (! $model = $resource->model()->whereStatus('published')->find($model)) {
throw new NotFoundHttpException;
}
return ApiResource::make($model)->withBlueprintFields($this->getFieldsFromBlueprint($resource));
}
protected function allowedFilters()
{
return FilterAuthorizer::allowedForSubResources('api', $this->resourceConfigKey, Str::plural($this->resourceHandle));
}
private function resource(string $resourceHandle): Resource
{
try {
try {
return Runway::findResource($resourceHandle);
} catch (ResourceNotFound $e) {
return Runway::findResource(Str::singular($resourceHandle));
}
} catch (ResourceNotFound $e) {
throw new NotFoundHttpException;
}
}
private function getFieldsFromBlueprint(Resource $resource): Collection
{
return $resource->blueprint()->fields()->all();
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Controllers/CP/ModelActionController.php | src/Http/Controllers/CP/ModelActionController.php | <?php
namespace StatamicRadPack\Runway\Http\Controllers\CP;
use Illuminate\Http\Request;
use Statamic\Facades\Action;
use Statamic\Http\Controllers\CP\ActionController;
use StatamicRadPack\Runway\Resource;
class ModelActionController extends ActionController
{
use Traits\ExtractsFromModelFields;
protected $resource;
public function runAction(Request $request, Resource $resource)
{
$this->resource = $resource;
return parent::run($request);
}
public function bulkActionsList(Request $request, Resource $resource)
{
$this->resource = $resource;
return parent::bulkActions($request);
}
protected function getSelectedItems($items, $context)
{
return $this->resource->findMany($items);
}
protected function getItemData($model, $context): array
{
$blueprint = $this->resource->blueprint();
[$values] = $this->extractFromFields($model, $this->resource, $blueprint);
return [
'title' => $model->getAttribute($this->resource->titleField()),
'values' => array_merge($values, ['id' => $model->getKey()]),
'itemActions' => Action::for($model, $context),
];
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Controllers/CP/ResourceListingController.php | src/Http/Controllers/CP/ResourceListingController.php | <?php
namespace StatamicRadPack\Runway\Http\Controllers\CP;
use Illuminate\Database\Eloquent\Builder;
use Statamic\Facades\User;
use Statamic\Http\Controllers\CP\CpController;
use Statamic\Http\Requests\FilteredRequest;
use Statamic\Query\Builder as BaseStatamicBuilder;
use Statamic\Query\Scopes\Filters\Concerns\QueriesFilters;
use StatamicRadPack\Runway\Http\Resources\CP\Models;
use StatamicRadPack\Runway\Resource;
class ResourceListingController extends CpController
{
use QueriesFilters, Traits\HasListingColumns;
public function index(FilteredRequest $request, Resource $resource)
{
$blueprint = $resource->blueprint();
if (! User::current()->can('view', $resource)) {
abort(403);
}
$query = $resource->newEloquentQueryBuilderWithEagerLoadedRelationships();
$query->when($query->hasNamedScope('runwayListing'), fn ($query) => $query->runwayListing());
$searchQuery = $request->search ?? false;
$query = $this->applySearch($resource, $query, $searchQuery);
$query->when(method_exists($query, 'getQuery') && $query->getQuery()->orders, function ($query) use ($request, $resource) {
if ($request->input('sort')) {
$query->reorder($resource->model()->getColumnForField($request->input('sort')), $request->input('order'));
}
}, fn ($query) => $query->orderBy($resource->model()->getColumnForField($request->input('sort', $resource->orderBy())), $request->input('order', $resource->orderByDirection())));
$activeFilterBadges = $this->queryFilters($query, $request->filters, [
'resource' => $resource->handle(),
'blueprints' => [$blueprint],
]);
$results = $query->paginate($request->input('perPage', config('statamic.cp.pagination_size')));
if ($searchQuery && $resource->hasSearchIndex()) {
$results->setCollection($results->getCollection()->map(fn ($item) => $item->getSearchable()->model()));
}
return (new Models($results))
->runwayResource($resource)
->blueprint($resource->blueprint())
->setColumnPreferenceKey("runway.{$resource->handle()}.columns")
->additional([
'meta' => [
'activeFilterBadges' => $activeFilterBadges,
],
]);
}
private function applySearch(Resource $resource, Builder $query, string $searchQuery): Builder|BaseStatamicBuilder
{
if (! $searchQuery) {
return $query;
}
if ($resource->hasSearchIndex() && ($index = $resource->searchIndex())) {
return $index->ensureExists()->search($searchQuery);
}
return $query->runwaySearch($searchQuery);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Controllers/CP/ModelRevisionsController.php | src/Http/Controllers/CP/ModelRevisionsController.php | <?php
namespace StatamicRadPack\Runway\Http\Controllers\CP;
use Illuminate\Http\Request;
use Statamic\Facades\User;
use Statamic\Http\Controllers\CP\CpController;
use StatamicRadPack\Runway\Http\Resources\CP\Model;
use StatamicRadPack\Runway\Resource;
class ModelRevisionsController extends CpController
{
use Traits\ExtractsFromModelFields;
public function index(Request $request, Resource $resource, $model)
{
$model = $resource->newEloquentQuery()
->where($resource->model()->qualifyColumn($resource->routeKey()), $model)
->first();
$revisions = $model
->revisions()
->reverse()
->prepend($this->workingCopy($model))
->filter()
->each(function ($revision) use ($model) {
$revision->attribute('item_url', $model->runwayRevisionUrl($revision));
});
// The first non manually created revision would be considered the "current"
// version. It's what corresponds to what's in the content directory.
optional($revisions->first(function ($revision) {
return $revision->action() != 'revision';
}))->attribute('current', true);
return $revisions
->groupBy(function ($revision) {
return $revision->date()->clone()->startOfDay()->format('U');
})->map(function ($revisions, $day) {
return compact('day', 'revisions');
})->reverse()->values();
}
public function store(Request $request, Resource $resource, $model)
{
$model = $resource->newEloquentQuery()
->where($resource->model()->qualifyColumn($resource->routeKey()), $model)
->first();
$model->createRevision([
'message' => $request->message,
'user' => User::fromUser($request->user()),
]);
return new Model($model);
}
public function show(Request $request, Resource $resource, $model, $revisionId)
{
$model = $resource->newEloquentQuery()
->where($resource->model()->qualifyColumn($resource->routeKey()), $model)
->first();
$revision = $model->revision($revisionId);
$model = $model->makeFromRevision($revision);
// TODO: Most of this is duplicated with EntriesController@edit. DRY it off.
$blueprint = $model->runwayResource()->blueprint();
[$values, $meta] = $this->extractFromFields($model, $resource, $blueprint);
return [
'title' => $model->getAttribute($resource->titleField()),
'editing' => true,
'actions' => [
'save' => $model->runwayUpdateUrl(),
'publish' => $model->runwayPublishUrl(),
'unpublish' => $model->runwayUnpublishUrl(),
'revisions' => $model->runwayRevisionsUrl(),
'restore' => $model->runwayRestoreRevisionUrl(),
'createRevision' => $model->runwayCreateRevisionUrl(),
],
'values' => $values,
'meta' => $meta,
'permalink' => $resource->hasRouting() ? $model->uri() : null,
'resourceHasRoutes' => $resource->hasRouting(),
'blueprint' => $blueprint->toPublishArray(),
'resource' => $resource,
'readOnly' => true,
];
}
protected function workingCopy($model)
{
if ($model->published()) {
return $model->workingCopy();
}
return $model
->makeWorkingCopy()
->date($model->updated_at)
->user(null);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Controllers/CP/PublishedModelsController.php | src/Http/Controllers/CP/PublishedModelsController.php | <?php
namespace StatamicRadPack\Runway\Http\Controllers\CP;
use Illuminate\Http\Request;
use Statamic\Facades\User;
use Statamic\Http\Controllers\CP\CpController;
use StatamicRadPack\Runway\Http\Resources\CP\Model as ModelResource;
use StatamicRadPack\Runway\Resource;
class PublishedModelsController extends CpController
{
use Traits\ExtractsFromModelFields;
public function store(Request $request, Resource $resource, $model)
{
$model = $resource->newEloquentQuery()
->where($resource->model()->qualifyColumn($resource->routeKey()), $model)
->first();
$model = $model->publish([
'message' => $request->message,
'user' => User::fromUser($request->user()),
]);
$blueprint = $model->runwayResource()->blueprint();
[$values] = $this->extractFromFields($model, $resource, $blueprint);
return [
'data' => array_merge((new ModelResource($model->fresh()))->resolve()['data'], [
'values' => $values,
]),
];
}
public function destroy(Request $request, Resource $resource, $model)
{
$model = $resource->newEloquentQuery()
->where($resource->model()->qualifyColumn($resource->routeKey()), $model)
->first();
$model = $model->unpublish([
'message' => $request->message,
'user' => User::fromUser($request->user()),
]);
$blueprint = $model->runwayResource()->blueprint();
[$values] = $this->extractFromFields($model, $resource, $blueprint);
return [
'data' => array_merge((new ModelResource($model->fresh()))->resolve()['data'], [
'values' => $values,
]),
];
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Controllers/CP/ResourceActionController.php | src/Http/Controllers/CP/ResourceActionController.php | <?php
namespace StatamicRadPack\Runway\Http\Controllers\CP;
use Statamic\Http\Controllers\CP\ActionController;
use StatamicRadPack\Runway\Runway;
class ResourceActionController extends ActionController
{
protected function getSelectedItems($items, $context)
{
return $items->map(fn ($item) => Runway::findResource($item));
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Controllers/CP/RestoreModelRevisionController.php | src/Http/Controllers/CP/RestoreModelRevisionController.php | <?php
namespace StatamicRadPack\Runway\Http\Controllers\CP;
use Illuminate\Http\Request;
use Statamic\Http\Controllers\CP\CpController;
use Statamic\Revisions\WorkingCopy;
use StatamicRadPack\Runway\Resource;
class RestoreModelRevisionController extends CpController
{
public function __invoke(Request $request, Resource $resource, $model)
{
$model = $resource->model()
->where($resource->model()->qualifyColumn($resource->routeKey()), $model)
->first();
if (! $target = $model->revision($request->revision)) {
dd('no such revision', $request->revision);
// todo: handle invalid revision reference
}
if ($model->published()) {
WorkingCopy::fromRevision($target)->date(now())->save();
} else {
$model->makeFromRevision($target)->published(false)->save();
}
session()->flash('success', __('Revision restored'));
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Controllers/CP/ResourceController.php | src/Http/Controllers/CP/ResourceController.php | <?php
namespace StatamicRadPack\Runway\Http\Controllers\CP;
use Illuminate\Support\Facades\DB;
use Statamic\CP\Breadcrumbs;
use Statamic\CP\Column;
use Statamic\Exceptions\NotFoundHttpException;
use Statamic\Facades\Action;
use Statamic\Facades\Scope;
use Statamic\Facades\User;
use Statamic\Http\Controllers\CP\CpController;
use StatamicRadPack\Runway\Http\Requests\CP\CreateRequest;
use StatamicRadPack\Runway\Http\Requests\CP\EditRequest;
use StatamicRadPack\Runway\Http\Requests\CP\IndexRequest;
use StatamicRadPack\Runway\Http\Requests\CP\StoreRequest;
use StatamicRadPack\Runway\Http\Requests\CP\UpdateRequest;
use StatamicRadPack\Runway\Http\Resources\CP\Model as ModelResource;
use StatamicRadPack\Runway\Relationships;
use StatamicRadPack\Runway\Resource;
class ResourceController extends CpController
{
use Traits\ExtractsFromModelFields, Traits\HasListingColumns, Traits\PreparesModels;
public function index(IndexRequest $request, Resource $resource)
{
return view('runway::index', [
'resource' => $resource,
'canCreate' => User::current()->can('create', $resource)
&& $resource->hasVisibleBlueprint()
&& ! $resource->readOnly(),
'createUrl' => cp_route('runway.create', ['resource' => $resource->handle()]),
'createLabel' => __('Create :resource', ['resource' => $resource->singular()]),
'columns' => $resource->blueprint()->columns()
->when($resource->hasPublishStates(), function ($collection) {
$collection->put('status', Column::make('status')
->listable(true)
->visible(true)
->defaultVisibility(true)
->sortable(false));
})
->setPreferred("runway.{$resource->handle()}.columns")
->rejectUnlisted()
->values(),
'filters' => Scope::filters('runway', ['resource' => $resource->handle()]),
'actionUrl' => cp_route('runway.models.actions.run', ['resource' => $resource->handle()]),
'primaryColumn' => $this->getPrimaryColumn($resource),
'actions' => Action::for($resource, ['view' => 'form']),
]);
}
public function create(CreateRequest $request, Resource $resource)
{
$blueprint = $resource->blueprint();
$fields = $blueprint->fields();
$fields = $fields->preProcess();
$viewData = [
'title' => __('Create :resource', ['resource' => $resource->singular()]),
'breadcrumbs' => new Breadcrumbs([[
'text' => $resource->plural(),
'url' => cp_route('runway.index', [
'resource' => $resource->handle(),
]),
]]),
'actions' => [
'save' => cp_route('runway.store', ['resource' => $resource->handle()]),
],
'resource' => $request->wantsJson() ? $resource->toArray() : $resource,
'blueprint' => $blueprint->toPublishArray(),
'values' => $fields->values()->merge([
$resource->publishedColumn() => $resource->defaultPublishState(),
])->all(),
'meta' => $fields->meta(),
'resourceHasRoutes' => $resource->hasRouting(),
'canManagePublishState' => User::current()->can('publish', $resource),
];
if ($request->wantsJson()) {
return $viewData;
}
return view('runway::create', $viewData);
}
public function store(StoreRequest $request, Resource $resource)
{
$resource
->blueprint()
->fields()
->addValues($request->all())
->validator()
->validate();
$model = $resource->model();
$this->prepareModelForSaving($resource, $model, $request);
if ($resource->revisionsEnabled()) {
$saved = $model->store([
'message' => $request->message,
'user' => User::current(),
]);
} else {
$saved = DB::transaction(function () use ($model, $request) {
$model->save();
Relationships::for($model)->with($request->all())->save();
return true;
});
}
return [
'data' => (new ModelResource($model->fresh()))->resolve()['data'],
'saved' => $saved,
];
}
public function edit(EditRequest $request, Resource $resource, $model)
{
$model = $resource->newEloquentQuery()->firstWhere($resource->model()->qualifyColumn($resource->routeKey()), $model);
if (! $model) {
throw new NotFoundHttpException;
}
$model = $model->fromWorkingCopy();
$blueprint = $resource->blueprint();
[$values, $meta] = $this->extractFromFields($model, $resource, $blueprint);
$viewData = [
'title' => $model->getAttribute($resource->titleField()),
'reference' => $model->reference(),
'method' => 'patch',
'breadcrumbs' => new Breadcrumbs([[
'text' => $resource->plural(),
'url' => cp_route('runway.index', [
'resource' => $resource->handle(),
]),
]]),
'resource' => $resource,
'actions' => [
'save' => $model->runwayUpdateUrl(),
'publish' => $model->runwayPublishUrl(),
'unpublish' => $model->runwayUnpublishUrl(),
'revisions' => $model->runwayRevisionsUrl(),
'restore' => $model->runwayRestoreRevisionUrl(),
'createRevision' => $model->runwayCreateRevisionUrl(),
'editBlueprint' => cp_route('blueprints.edit', ['namespace' => 'runway', 'handle' => $resource->handle()]),
],
'blueprint' => $blueprint->toPublishArray(),
'values' => $values,
'meta' => $meta,
'readOnly' => $resource->readOnly(),
'status' => $model->publishedStatus(),
'permalink' => $resource->hasRouting() ? $model->uri() : null,
'resourceHasRoutes' => $resource->hasRouting(),
'currentModel' => [
'id' => $model->getKey(),
'reference' => $model->reference(),
'title' => $model->{$resource->titleField()},
'edit_url' => $request->url(),
],
'canManagePublishState' => User::current()->can('publish', $resource),
'itemActions' => Action::for($model, ['resource' => $resource->handle(), 'view' => 'form']),
'revisionsEnabled' => $resource->revisionsEnabled(),
'hasWorkingCopy' => $model->hasWorkingCopy(),
];
if ($request->wantsJson()) {
return $viewData;
}
return view('runway::edit', $viewData);
}
public function update(UpdateRequest $request, Resource $resource, $model)
{
$resource->blueprint()->fields()->setParent($model)->addValues($request->all())->validator()->validate();
$model = $resource->newEloquentQuery()->firstWhere($resource->model()->qualifyColumn($resource->routeKey()), $model);
$model = $model->fromWorkingCopy();
$this->prepareModelForSaving($resource, $model, $request);
if ($resource->revisionsEnabled() && $model->published()) {
$saved = $model
->makeWorkingCopy()
->user(User::current())
->save();
$model = $model->fromWorkingCopy();
} else {
$saved = DB::transaction(function () use ($model, $request) {
$model->save();
Relationships::for($model)->with($request->all())->save();
return true;
});
$model->refresh();
}
[$values] = $this->extractFromFields($model, $resource, $resource->blueprint());
return [
'data' => array_merge((new ModelResource($model))->resolve()['data'], [
'values' => $values,
]),
'saved' => $saved,
];
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Controllers/CP/Traits/ExtractsFromModelFields.php | src/Http/Controllers/CP/Traits/ExtractsFromModelFields.php | <?php
namespace StatamicRadPack\Runway\Http\Controllers\CP\Traits;
use Illuminate\Database\Eloquent\Model;
use Statamic\Fields\Blueprint;
use StatamicRadPack\Runway\Resource;
trait ExtractsFromModelFields
{
use PreparesModels;
protected function extractFromFields(Model $model, Resource $resource, Blueprint $blueprint)
{
$values = $this->prepareModelForPublishForm($resource, $model);
$fields = $blueprint
->fields()
->setParent($model)
->addValues($values->all())
->preProcess();
$values = $fields->values()->merge([
'id' => $model->getKey(),
$resource->publishedColumn() => $model->published(),
]);
return [$values->all(), $fields->meta()->all()];
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Controllers/CP/Traits/HasListingColumns.php | src/Http/Controllers/CP/Traits/HasListingColumns.php | <?php
namespace StatamicRadPack\Runway\Http\Controllers\CP\Traits;
use Illuminate\Support\Arr;
use Statamic\Facades\User;
use Statamic\Fields\Field;
use StatamicRadPack\Runway\Exceptions\EmptyBlueprintException;
use StatamicRadPack\Runway\Resource;
trait HasListingColumns
{
protected function getPrimaryColumn(Resource $resource): string
{
if ($resource->blueprint()->fields()->all()->isEmpty()) {
throw new EmptyBlueprintException($resource->handle());
}
if (Arr::has(User::current()->preferences(), "runway.{$resource->handle()}.columns")) {
return collect($resource->blueprint()->fields()->all())
->filter(function (Field $field) use ($resource) {
return in_array($field->handle(), Arr::get(User::current()->preferences(), "runway.{$resource->handle()}.columns"));
})
->reject(function (Field $field) {
return $field->fieldtype()->indexComponent() === 'relationship' || $field->type() === 'section';
})
->map->handle()
->prepend($resource->titleField())
->first();
}
return $resource->titleField();
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Controllers/CP/Traits/PreparesModels.php | src/Http/Controllers/CP/Traits/PreparesModels.php | <?php
namespace StatamicRadPack\Runway\Http\Controllers\CP\Traits;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Statamic\Fields\Field;
use Statamic\Fieldtypes\Revealer;
use Statamic\Fieldtypes\Section;
use Statamic\Support\Arr;
use StatamicRadPack\Runway\Fieldtypes\BelongsToFieldtype;
use StatamicRadPack\Runway\Fieldtypes\HasManyFieldtype;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Support\Json;
trait PreparesModels
{
protected function prepareModelForPublishForm(Resource $resource, Model $model): Collection
{
$blueprint = $resource->blueprint();
// Re-casts any `object` casts to `array`.
$model->mergeCasts(
collect($model->getCasts())
->map(fn ($value) => $value === 'object' ? 'array' : $value)
->toArray()
);
return $blueprint->fields()->all()
->mapWithKeys(function (Field $field) use ($resource, $model) {
$value = $model->getAttribute($field->handle());
// When it's a nested field, we need to get the value from the nested JSON object, using data_get().
if ($nestedFieldPrefix = $resource->nestedFieldPrefix($field->handle())) {
$key = Str::after($field->handle(), "{$nestedFieldPrefix}_");
$value = data_get($model, "{$nestedFieldPrefix}.{$key}");
}
// When $value is a Carbon instance, format it with the format defined in the blueprint.
if ($value instanceof CarbonInterface) {
$format = $field->get('format', 'Y-m-d H:i');
$value = $value->format($format);
}
// When $value is a JSON string, we need to decode it.
if (is_string($value) && json_validate($value)) {
$value = json_decode((string) $value, true);
}
// When the resource is a User model, handle the special role & group fields.
if ($this->isUserResource($resource)) {
if ($field->handle() === 'roles') {
$value = DB::table(config('statamic.users.tables.role_user'))
->where('user_id', $model->getKey())
->pluck('role_id')
->all();
}
if ($field->handle() === 'groups') {
$value = DB::table(config('statamic.users.tables.group_user'))
->where('user_id', $model->getKey())
->pluck('group_id')
->all();
}
}
if ($field->fieldtype() instanceof HasManyFieldtype) {
$value = $model->{$resource->eloquentRelationships()->get($field->handle())}()
->runway()
->get();
// Use IDs from the model's $runwayRelationships property, if there are any.
if (array_key_exists($field->handle(), $model->runwayRelationships)) {
$value = Arr::get($model->runwayRelationships, $field->handle());
}
// When re-ordering is enabled, ensure the models are returned in the correct order.
if ($field->get('reorderable', false)) {
$orderColumn = $field->get('order_column');
$relationshipName = $resource->eloquentRelationships()->get($field->handle());
$value = $model->{$relationshipName}()
->reorder($orderColumn, 'ASC')
->get();
}
}
return [$field->handle() => $value];
});
}
protected function prepareModelForSaving(Resource $resource, Model &$model, Request $request): void
{
$blueprint = $resource->blueprint();
$blueprint
->fields()
->setParent($model)
->all()
->filter(fn (Field $field) => $this->shouldSaveField($field))
->when($resource->hasPublishStates(), function ($collection) use ($resource) {
$collection->put($resource->publishedColumn(), new Field($resource->publishedColumn(), ['type' => 'toggle']));
})
->each(function (Field $field) use ($resource, &$model, $request) {
$processedValue = $field->fieldtype()->process($request->get($field->handle()));
if ($field->fieldtype() instanceof HasManyFieldtype) {
$model->runwayRelationships[$field->handle()] = $processedValue;
return;
}
// Skip the field if it exists in the model's $appends array AND there's no mutator for it on the model.
if (in_array($field->handle(), $model->getAppends(), true) && ! $model->hasSetMutator($field->handle()) && ! $model->hasAttributeSetMutator($field->handle())) {
return;
}
// If it's a BelongsTo field and the $processedValue is an array, then we want the first item in the array.
if ($field->fieldtype() instanceof BelongsToFieldtype && is_array($processedValue)) {
$processedValue = Arr::first($processedValue);
}
// When the resource is a User model, handle the special role & group fields.
if ($this->isUserResource($resource)) {
if ($field->handle() === 'roles') {
DB::table(config('statamic.users.tables.role_user'))
->where('user_id', $model->getKey())
->delete();
DB::table(config('statamic.users.tables.role_user'))
->insert(
collect($processedValue)
->map(fn ($role) => ['user_id' => $model->getKey(), 'role_id' => $role])
->all()
);
return;
}
if ($field->handle() === 'groups') {
DB::table(config('statamic.users.tables.group_user'))
->where('user_id', $model->getKey())
->delete();
DB::table(config('statamic.users.tables.group_user'))
->insert(
collect($processedValue)
->map(fn ($group) => ['user_id' => $model->getKey(), 'group_id' => $group])
->all()
);
return;
}
}
// When $processedValue is null and there's no cast set on the model, we should JSON encode it.
if (
is_array($processedValue)
&& ! $resource->nestedFieldPrefix($field->handle())
&& ! $model->hasCast($field->handle(), ['json', 'array', 'collection', 'object', 'encrypted:array', 'encrypted:collection', 'encrypted:object'])
) {
$processedValue = json_encode($processedValue, JSON_THROW_ON_ERROR);
}
// When it's a nested field, we need to set the value on the nested JSON object.
// Otherwise, it'll attempt to set the model's "root" attributes.
if ($nestedFieldPrefix = $resource->nestedFieldPrefix($field->handle())) {
$key = Str::after($field->handle(), "{$nestedFieldPrefix}_");
$model->setAttribute("{$nestedFieldPrefix}->{$key}", $processedValue);
return;
}
$model->setAttribute($field->handle(), $processedValue);
});
}
protected function shouldSaveField(Field $field): bool
{
if ($field->fieldtype() instanceof Section || $field->fieldtype() instanceof Revealer) {
return false;
}
if ($field->visibility() === 'computed') {
return false;
}
if ($field->get('save', true) === false) {
return false;
}
return true;
}
protected function isUserResource(Resource $resource): bool
{
$guard = config('statamic.users.guards.cp', 'web');
$guardProvider = config("auth.guards.{$guard}.provider", 'users');
$providerModel = config("auth.providers.{$guardProvider}.model", 'App\\Models\\User');
return $providerModel === get_class($resource->model());
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Resources/ApiResource.php | src/Http/Resources/ApiResource.php | <?php
namespace StatamicRadPack\Runway\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
use StatamicRadPack\Runway\Resource;
class ApiResource extends JsonResource
{
public $blueprintFields;
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
* @return array
*/
public function toArray($request)
{
$keys = [
...$this->blueprintFields->map->handle()->all(),
...$this->resource->runwayResource()->nestedFieldPrefixes()->all(),
];
$augmentedArray = $this->resource
->toAugmentedCollection($keys)
->withRelations($this->blueprintFields->filter->isRelationship()->keys()->all())
->withShallowNesting()
->toArray();
return array_merge($augmentedArray, [
$this->resource->getKeyName() => $this->resource->getKey(),
]);
}
/**
* Set the fields that should be returned by this resource
*
* @return self
*/
public function withBlueprintFields(Collection $fields)
{
$this->blueprintFields = $fields;
return $this;
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Resources/CP/Models.php | src/Http/Resources/CP/Models.php | <?php
namespace StatamicRadPack\Runway\Http\Resources\CP;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Support\Collection;
use Statamic\CP\Column;
use Statamic\Fields\Blueprint;
use Statamic\Http\Resources\CP\Concerns\HasRequestedColumns;
use StatamicRadPack\Runway\Resource;
class Models extends ResourceCollection
{
use HasRequestedColumns;
public $collects = ListedModel::class;
protected $runwayResource;
protected $blueprint;
protected $columns;
protected $columnPreferenceKey;
public function runwayResource(Resource $resource): self
{
$this->runwayResource = $resource;
return $this;
}
public function blueprint(Blueprint $blueprint): self
{
$this->blueprint = $blueprint;
return $this;
}
public function setColumnPreferenceKey(string $key): self
{
$this->columnPreferenceKey = $key;
return $this;
}
public function setColumns(): self
{
$columns = $this->runwayResource->blueprint()->columns()->map(function (Column $column) {
if ($this->runwayResource->model()->hasAppended($column->field())) {
$column->sortable(false);
}
return $column;
});
if ($this->runwayResource->hasPublishStates()) {
$status = Column::make('status')
->listable(true)
->visible(true)
->defaultVisibility(true)
->defaultOrder($columns->count() + 1)
->sortable(false);
$columns->put('status', $status);
}
if ($key = $this->columnPreferenceKey) {
$columns->setPreferred($key);
}
$this->columns = $columns->rejectUnlisted()->values();
return $this;
}
public function toArray($request): Collection
{
$this->setColumns();
return $this->collection->each(function ($model) {
$model
->blueprint($this->blueprint)
->runwayResource($this->runwayResource)
->columns($this->requestedColumns());
});
}
public function with($request): array
{
return [
'meta' => [
'columns' => $this->visibleColumns(),
],
];
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Resources/CP/FieldtypeModels.php | src/Http/Resources/CP/FieldtypeModels.php | <?php
namespace StatamicRadPack\Runway\Http\Resources\CP;
use Illuminate\Pagination\AbstractPaginator;
use StatamicRadPack\Runway\Fieldtypes\BaseFieldtype;
class FieldtypeModels extends Models
{
private BaseFieldtype $fieldtype;
public $collects = FieldtypeListedModel::class;
public function __construct($resource, BaseFieldtype $fieldtype)
{
$this->fieldtype = $fieldtype;
parent::__construct($resource);
}
protected function collectResource($resource)
{
$collection = parent::collectResource($resource);
if ($collection instanceof AbstractPaginator) {
$collection->getCollection()->each->fieldtype($this->fieldtype);
} else {
$collection->each->fieldtype($this->fieldtype);
}
return $collection;
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Resources/CP/FieldtypeListedModel.php | src/Http/Resources/CP/FieldtypeListedModel.php | <?php
namespace StatamicRadPack\Runway\Http\Resources\CP;
use StatamicRadPack\Runway\Fieldtypes\BaseFieldtype;
class FieldtypeListedModel extends ListedModel
{
private BaseFieldtype $fieldtype;
public function fieldtype(BaseFieldtype $fieldtype): self
{
$this->fieldtype = $fieldtype;
return $this;
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Resources/CP/ListedModel.php | src/Http/Resources/CP/ListedModel.php | <?php
namespace StatamicRadPack\Runway\Http\Resources\CP;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Statamic\Facades\Action;
use Statamic\Facades\User;
use Statamic\Fields\Blueprint;
use StatamicRadPack\Runway\Fieldtypes\BelongsToFieldtype;
use StatamicRadPack\Runway\Resource;
use UnitEnum;
class ListedModel extends JsonResource
{
protected $blueprint;
protected $runwayResource;
protected $columns;
public function blueprint(Blueprint $blueprint): self
{
$this->blueprint = $blueprint;
return $this;
}
public function runwayResource(Resource $runwayResource): self
{
$this->runwayResource = $runwayResource;
return $this;
}
public function columns($columns): self
{
$this->columns = $columns;
return $this;
}
public function toArray($request): array
{
$model = $this->resource;
return [
'id' => $model->getKey(),
'title' => $model->getAttribute($this->runwayResource->titleField()),
'published' => $this->resource->published(),
'status' => $this->resource->publishedStatus(),
'edit_url' => $model->runwayEditUrl(),
'permalink' => $this->runwayResource->hasRouting() ? $model->uri() : null,
'editable' => User::current()->can('edit', [$this->runwayResource, $model]),
'viewable' => User::current()->can('view', [$this->runwayResource, $model]),
'actions' => Action::for($model, ['resource' => $this->runwayResource->handle()]),
'collection' => ['dated' => false],
$this->merge($this->values()),
];
}
protected function values($extra = []): Collection
{
return $this->columns->mapWithKeys(function ($column) use ($extra) {
$key = $column->field;
$field = $this->blueprint->field($key);
// When it's a Belongs To field, the field handle won't be the relationship name.
// We need to resolve it to the relationship name to get the value from the model.
if ($field && $field->fieldtype() instanceof BelongsToFieldtype) {
$relationName = $this->runwayResource->eloquentRelationships()->get($key);
$value = $this->resource->$relationName;
}
// When it's a nested field, we need to get the value from the nested JSON object, using data_get().
elseif ($field && $nestedFieldPrefix = $this->runwayResource->nestedFieldPrefix($field->handle())) {
$fieldKey = Str::after($field->handle(), "{$nestedFieldPrefix}_");
$value = data_get($this->resource, "{$nestedFieldPrefix}.{$fieldKey}");
} else {
$value = $extra[$key] ?? $this->resource->getAttribute($key);
if ($value instanceof UnitEnum) {
$value = $value->value;
}
}
if (! $field) {
return [$key => $value];
}
$value = $field->setValue($value)
->setParent($this->resource)
->preProcessIndex()
->value();
return [$key => $value];
});
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Resources/CP/Model.php | src/Http/Resources/CP/Model.php | <?php
namespace StatamicRadPack\Runway\Http\Resources\CP;
use Illuminate\Http\Resources\Json\JsonResource;
class Model extends JsonResource
{
public function toArray($request)
{
$runwayResource = $this->resource->runwayResource();
$data = [
'id' => $this->resource->getKey(),
'reference' => $this->resource->reference(),
'title' => $this->resource->{$runwayResource->titleField()},
'permalink' => $runwayResource->hasRouting() ? $this->resource->absoluteUrl() : null,
'status' => $this->resource->publishedStatus(),
'published' => $this->resource->published(),
'edit_url' => $this->resource->runwayEditUrl(),
'resource' => [
'handle' => $runwayResource->handle(),
],
];
return ['data' => $data];
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Http/Resources/CP/FieldtypeModel.php | src/Http/Resources/CP/FieldtypeModel.php | <?php
namespace StatamicRadPack\Runway\Http\Resources\CP;
use Illuminate\Http\Resources\Json\JsonResource;
use Statamic\Facades\Parse;
use StatamicRadPack\Runway\Fieldtypes\BaseFieldtype;
class FieldtypeModel extends JsonResource
{
private BaseFieldtype $fieldtype;
public function __construct($resource, BaseFieldtype $fieldtype)
{
$this->fieldtype = $fieldtype;
parent::__construct($resource);
}
public function toArray($request)
{
$data = [
'id' => $this->resource->getKey(),
'reference' => $this->resource->reference(),
'title' => $this->makeTitle($this->resource),
'status' => $this->resource->publishedStatus(),
'edit_url' => $this->resource->runwayEditUrl(),
];
return ['data' => $data];
}
protected function makeTitle($model): ?string
{
if (! $titleFormat = $this->fieldtype->config('title_format')) {
$firstListableColumn = $this->resource->runwayResource()->titleField();
return $model->augmentedValue($firstListableColumn);
}
return Parse::template($titleFormat, $model->toAugmentedArray());
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/UpdateScripts/MigrateBlueprints.php | src/UpdateScripts/MigrateBlueprints.php | <?php
namespace StatamicRadPack\Runway\UpdateScripts;
use Illuminate\Support\Facades\Artisan;
use Statamic\UpdateScripts\UpdateScript;
class MigrateBlueprints extends UpdateScript
{
public function shouldUpdate($newVersion, $oldVersion)
{
return $this->isUpdatingTo('6.0.0');
}
public function update()
{
Artisan::call('runway:migrate-blueprints');
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/UpdateScripts/AddManagePublishStatesPermission.php | src/UpdateScripts/AddManagePublishStatesPermission.php | <?php
namespace StatamicRadPack\Runway\UpdateScripts;
use Statamic\Facades\Role;
use Statamic\UpdateScripts\UpdateScript;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Runway;
class AddManagePublishStatesPermission extends UpdateScript
{
public function shouldUpdate($newVersion, $oldVersion)
{
return $this->isUpdatingTo('7.6.0');
}
public function update()
{
Role::all()->each(function ($role) {
Runway::allResources()
->filter->hasPublishStates()
->filter(fn (Resource $resource) => $role->hasPermission("create {$resource->handle()}"))
->each(fn (Resource $resource) => $role->addPermission("publish {$resource->handle()}"));
$role->save();
});
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/UpdateScripts/ChangePermissionNames.php | src/UpdateScripts/ChangePermissionNames.php | <?php
namespace StatamicRadPack\Runway\UpdateScripts;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Statamic\Facades\Yaml;
use Statamic\UpdateScripts\UpdateScript;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Runway;
class ChangePermissionNames extends UpdateScript
{
public function shouldUpdate($newVersion, $oldVersion)
{
return $this->isUpdatingTo('4.0.0');
}
public function update()
{
if (config('statamic.users.repository') !== 'file') {
$this->console()->warn("Runway has made updates to it's permissions. You'll need to update your user permissions manually.");
$this->console()->warn('Please see the upgrade guide for more information: TODO');
return;
}
$roles = Yaml::file(config('statamic.users.repositories.file.paths.roles'))->parse();
$roles = collect($roles)
->map(function ($role) {
$role['permissions'] = collect($role['permissions'] ?? [])
->map(function ($permission) {
Runway::allResources()->each(function (Resource $resource) use (&$permission) {
$permission = Str::of($permission)
->replace("View {$resource->plural()}", "view {$resource->handle()}")
->replace("Edit {$resource->plural()}", "edit {$resource->handle()}")
->replace("Create new {$resource->singular()}", "create {$resource->handle()}")
->replace("Delete {$resource->singular()}", "delete {$resource->handle()}")
->__toString();
});
return $permission;
})
->values()
->toArray();
return $role;
})
->toArray();
$yaml = Yaml::dump($roles);
File::put(config('statamic.users.repositories.file.paths.roles'), $yaml);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Traits/HasRunwayResource.php | src/Traits/HasRunwayResource.php | <?php
namespace StatamicRadPack\Runway\Traits;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Support\Str;
use Statamic\Contracts\Data\Augmented;
use Statamic\Contracts\Revisions\Revision;
use Statamic\Fields\Field;
use Statamic\Fields\Value;
use Statamic\Fieldtypes\Section;
use Statamic\GraphQL\ResolvesValues;
use Statamic\Revisions\Revisable;
use Statamic\Support\Arr;
use Statamic\Support\Traits\FluentlyGetsAndSets;
use StatamicRadPack\Runway\Data\AugmentedModel;
use StatamicRadPack\Runway\Data\HasAugmentedInstance;
use StatamicRadPack\Runway\Fieldtypes\HasManyFieldtype;
use StatamicRadPack\Runway\Relationships;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Runway;
trait HasRunwayResource
{
use FluentlyGetsAndSets, HasAugmentedInstance, Revisable;
use ResolvesValues {
resolveGqlValue as traitResolveGqlValue;
}
public array $runwayRelationships = [];
public function newAugmentedInstance(): Augmented
{
return new AugmentedModel($this);
}
public function shallowAugmentedArrayKeys()
{
return [$this->runwayResource()->primaryKey(), $this->runwayResource()->titleField(), 'api_url'];
}
public function runwayResource(): Resource
{
return Runway::findResourceByModel($this);
}
public function reference(): string
{
return "runway::{$this->runwayResource()->handle()}::{$this->getKey()}";
}
public function scopeRunway(Builder $query)
{
return $query;
}
public function scopeRunwaySearch(Builder $query, string $searchQuery)
{
$this->runwayResource()->blueprint()->fields()->all()
->filter(fn (Field $field) => $this->getConnection()->getSchemaBuilder()->hasColumn($this->getTable(), $field->handle()))
->reject(fn (Field $field) => $field->visibility() === 'computed')
->each(fn (Field $field) => $query->orWhere($this->getColumnForField($field->handle()), 'LIKE', '%'.$searchQuery.'%'));
}
public function publishedStatus(): ?string
{
if (! $this->runwayResource()->hasPublishStates()) {
return null;
}
if (! $this->published()) {
return 'draft';
}
return 'published';
}
public function scopeWhereStatus(Builder $query, string $status): void
{
if (! $this->runwayResource()->hasPublishStates()) {
return;
}
switch ($status) {
case 'published':
$query->where($this->runwayResource()->publishedColumn(), true);
break;
case 'draft':
$query->where($this->runwayResource()->publishedColumn(), false);
break;
case 'scheduled':
throw new \Exception("Runway doesn't currently support the [scheduled] status.");
case 'expired':
throw new \Exception("Runway doesn't currently support the [expired] status.");
default:
throw new \Exception("Invalid status [$status]");
}
}
public function resolveGqlValue($field)
{
if ($this->runwayResource()->handle() && $field === 'status') {
return $this->publishedStatus();
}
$value = $this->traitResolveGqlValue($field);
// When it's a nested field, we need to resolve the inner values as well.
// We're handling this in the same way that the traitResolveGqlValue method does.
if ($this->runwayResource()->nestedFieldPrefixes()->contains($field)) {
$value = collect($value)->map(function ($value) {
if ($value instanceof Value) {
$value = $value->value();
}
if ($value instanceof \Statamic\Contracts\Query\Builder) {
$value = $value->get();
}
return $value;
});
}
return $value;
}
public function getColumnForField(string $field): string
{
foreach ($this->runwayResource()->nestedFieldPrefixes() as $nestedFieldPrefix) {
if (Str::startsWith($field, "{$nestedFieldPrefix}_")) {
$key = Str::after($field, "{$nestedFieldPrefix}_");
return "{$nestedFieldPrefix}->{$key}";
}
}
return $field;
}
public function runwayEditUrl(): string
{
return cp_route('runway.update', [
'resource' => $this->runwayResource()->handle(),
'model' => $this->{$this->runwayResource()->routeKey()},
]);
}
public function runwayUpdateUrl(): string
{
return cp_route('runway.update', [
'resource' => $this->runwayResource()->handle(),
'model' => $this->{$this->runwayResource()->routeKey()},
]);
}
public function runwayPublishUrl(): string
{
return cp_route('runway.published.store', [
'resource' => $this->runwayResource()->handle(),
'model' => $this->{$this->runwayResource()->routeKey()},
]);
}
public function runwayUnpublishUrl(): string
{
return cp_route('runway.published.destroy', [
'resource' => $this->runwayResource()->handle(),
'model' => $this->{$this->runwayResource()->routeKey()},
]);
}
public function runwayRevisionsUrl(): string
{
return cp_route('runway.revisions.index', [
'resource' => $this->runwayResource()->handle(),
'model' => $this->{$this->runwayResource()->routeKey()},
]);
}
public function runwayRevisionUrl(Revision $revision): string
{
return cp_route('runway.revisions.show', [
'resource' => $this->runwayResource()->handle(),
'model' => $this->{$this->runwayResource()->routeKey()},
'revisionId' => $revision->id(),
]);
}
public function runwayRestoreRevisionUrl(): string
{
return cp_route('runway.restore-revision', [
'resource' => $this->runwayResource()->handle(),
'model' => $this->{$this->runwayResource()->routeKey()},
]);
}
public function runwayCreateRevisionUrl(): string
{
return cp_route('runway.revisions.store', [
'resource' => $this->runwayResource()->handle(),
'model' => $this->{$this->runwayResource()->routeKey()},
]);
}
protected function revisionKey(): string
{
return vsprintf('resources/%s/%s', [
$this->runwayResource()->handle(),
$this->getKey(),
]);
}
protected function revisionAttributes(): array
{
$data = $this->runwayResource()->blueprint()->fields()->setParent($this)->all()
->reject(fn (Field $field) => $field->fieldtype() instanceof Section)
->reject(fn (Field $field) => $field->visibility() === 'computed')
->reject(fn (Field $field) => $field->get('save', true) === false)
->reject(fn (Field $field) => $this->runwayResource()->nestedFieldPrefix($field->handle()))
->mapWithKeys(function (Field $field) {
$handle = $field->handle();
if ($field->fieldtype() instanceof HasManyFieldtype) {
return [$handle => Arr::get($this->runwayRelationships, $handle, [])];
}
return [$handle => $this->getAttribute($handle)];
})
->merge($this->runwayResource()->nestedFieldPrefixes()->mapWithKeys(fn ($nestedFieldPrefix) => [
$nestedFieldPrefix => $this->getAttribute($nestedFieldPrefix),
]))
->all();
return [
'id' => $this->getKey(),
'published' => $this->published(),
'data' => $data,
];
}
public function makeFromRevision($revision): self
{
$model = clone $this;
if (! $revision) {
return $model;
}
$attrs = $revision->attributes();
$model->published($attrs['published']);
$blueprint = $this->runwayResource()->blueprint();
collect($attrs['data'])->each(function ($value, $key) use (&$model, $blueprint) {
$field = $blueprint->field($key);
if ($field?->fieldtype() instanceof HasManyFieldtype) {
$model->runwayRelationships[$key] = $value;
return;
}
$model->setAttribute($key, $value);
});
return $model;
}
public function revisionsEnabled(): bool
{
return $this->runwayResource()->revisionsEnabled();
}
public function published($published = null)
{
if (! $this->runwayResource()->hasPublishStates()) {
return func_num_args() === 0 ? null : $this;
}
if (func_num_args() === 0) {
return (bool) $this->getAttribute($this->runwayResource()->publishedColumn());
}
$this->setAttribute($this->runwayResource()->publishedColumn(), $published);
return $this;
}
public function publish($options = [])
{
if ($this->revisionsEnabled()) {
$model = $this->publishWorkingCopy($options);
Relationships::for($model)->with($model->runwayRelationships)->save();
return $model;
}
if ($this->runwayResource()->hasPublishStates()) {
$saved = $this->published(true)->save();
if (! $saved) {
return false;
}
}
return $this;
}
public function unpublish($options = [])
{
if ($this->revisionsEnabled()) {
return $this->unpublishWorkingCopy($options);
}
if ($this->runwayResource()->hasPublishStates()) {
$saved = $this->published(false)->save();
if (! $saved) {
return false;
}
}
return $this;
}
/**
* We don't need to do anything here, since:
* - The updated_at timestamp is updated automatically by the database.
* - We don't have an updated_by column to store the user who last modified the model.
*
* @return $this
*/
public function updateLastModified($user = false): self
{
return $this;
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Actions/Publish.php | src/Actions/Publish.php | <?php
namespace StatamicRadPack\Runway\Actions;
use Illuminate\Database\Eloquent\Model;
use Statamic\Actions\Action;
class Publish extends Action
{
public static function title()
{
return __('Publish');
}
public function visibleTo($item)
{
return $this->context['view'] === 'list'
&& $item instanceof Model
&& $item->runwayResource()->readOnly() !== true
&& $item->published() === false;
}
public function visibleToBulk($items)
{
return $items->every(fn ($item) => $this->visibleTo($item));
}
public function authorize($user, $item)
{
return $user->can("publish {$item->runwayResource()->handle()}");
}
public function confirmationText()
{
/** @translation */
return 'Are you sure you want to publish this model?|Are you sure you want to publish these :count models?';
}
public function buttonText()
{
/** @translation */
return 'Publish Model|Publish :count Models';
}
public function run($models, $values)
{
$failures = $models->reject(fn ($model) => $model->published(true)->save());
$total = $models->count();
if ($failures->isNotEmpty()) {
$success = $total - $failures->count();
if ($total === 1) {
throw new \Exception(__('Model could not be published'));
} elseif ($success === 0) {
throw new \Exception(__('Model could not be published'));
} else {
throw new \Exception(__(':success/:total models were published', ['total' => $total, 'success' => $success]));
}
}
return trans_choice('Model published|Models published', $total);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Actions/DeleteModel.php | src/Actions/DeleteModel.php | <?php
namespace StatamicRadPack\Runway\Actions;
use Illuminate\Database\Eloquent\Model;
use Statamic\Actions\Action;
use StatamicRadPack\Runway\Exceptions\ResourceNotFound;
use StatamicRadPack\Runway\Runway;
class DeleteModel extends Action
{
protected $dangerous = true;
public static function title()
{
return __('Delete');
}
public function visibleTo($item)
{
try {
$resource = Runway::findResourceByModel($item);
} catch (ResourceNotFound $e) {
return false;
}
return $item instanceof Model && $resource->readOnly() !== true;
}
public function visibleToBulk($items)
{
return $items
->map(fn ($item) => $this->visibleTo($item))
->filter(fn ($isVisible) => $isVisible === true)
->count() === $items->count();
}
public function authorize($user, $item)
{
$resource = Runway::findResourceByModel($item);
return $user->can('delete', [$resource, $item]);
}
public function buttonText()
{
/* @translation */
return 'Delete|Delete :count items?';
}
public function confirmationText()
{
/* @translation */
return 'Are you sure you want to want to delete this?|Are you sure you want to delete these :count items?';
}
public function bypassesDirtyWarning(): bool
{
return true;
}
public function run($items, $values)
{
$failures = $items->reject(fn ($model) => $model->delete());
$total = $items->count();
if ($failures->isNotEmpty()) {
$success = $total - $failures->count();
if ($total === 1) {
throw new \Exception(__('Item could not be deleted'));
} elseif ($success === 0) {
throw new \Exception(__('Items could not be deleted'));
} else {
throw new \Exception(__(':success/:total items were deleted', ['total' => $total, 'success' => $success]));
}
}
return trans_choice('Item deleted|Items deleted', $total);
}
public function redirect($items, $values)
{
if ($this->context['view'] !== 'form') {
return;
}
$item = $items->first();
return cp_route('runway.index', ['resource' => Runway::findResourceByModel($item)->handle()]);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Actions/DuplicateModel.php | src/Actions/DuplicateModel.php | <?php
namespace StatamicRadPack\Runway\Actions;
use Illuminate\Database\Eloquent\Model;
use Statamic\Actions\Action;
use StatamicRadPack\Runway\Exceptions\ResourceNotFound;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Runway;
class DuplicateModel extends Action
{
private $newItems;
public static function title()
{
return __('Duplicate');
}
public function visibleTo($item)
{
try {
$resource = Runway::findResourceByModel($item);
} catch (ResourceNotFound $e) {
return false;
}
return $item instanceof Model && $resource->hasVisibleBlueprint() && $resource->readOnly() !== true;
}
public function visibleToBulk($items)
{
return $items
->map(fn ($item) => $this->visibleTo($item))
->filter(fn ($isVisible) => $isVisible === true)
->count() === $items->count();
}
public function authorize($user, $item)
{
$resource = Runway::findResourceByModel($item);
return $user->can('create', $resource);
}
public function buttonText()
{
/* @translation */
return 'Duplicate|Duplicate :count items?';
}
public function dirtyWarningText()
{
/** @translation */
return 'Any unsaved changes will not be duplicated into the new model.';
}
public function run($items, $values)
{
$resource = Runway::findResourceByModel($items->first());
$this->newItems = $items->map(fn ($original) => $this->duplicateModel($original, $resource));
}
private function duplicateModel(Model $original, Resource $resource): Model
{
$model = $original->replicate($resource->blueprint()->fields()->all()->reject->shouldBeDuplicated()->keys()->all());
if ($resource->titleField()) {
$model->setAttribute($resource->titleField(), $original->getAttribute($resource->titleField()).' (Duplicate)');
}
if ($resource->hasPublishStates()) {
$model->published(false);
}
$model->save();
return $model;
}
public function redirect($items, $values)
{
if ($this->context['view'] !== 'form') {
return;
}
$item = $this->newItems->first();
return $item->runwayEditUrl();
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Actions/Unpublish.php | src/Actions/Unpublish.php | <?php
namespace StatamicRadPack\Runway\Actions;
use Illuminate\Database\Eloquent\Model;
use Statamic\Actions\Action;
class Unpublish extends Action
{
public static function title()
{
return __('Unpublish');
}
public function visibleTo($item)
{
return $this->context['view'] === 'list'
&& $item instanceof Model
&& $item->runwayResource()->readOnly() !== true
&& $item->published() === true;
}
public function visibleToBulk($items)
{
return $items->every(fn ($item) => $this->visibleTo($item));
}
public function authorize($user, $item)
{
return $user->can("publish {$item->runwayResource()->handle()}");
}
public function confirmationText()
{
/** @translation */
return 'Are you sure you want to unpublish this model?|Are you sure you want to unpublish these :count models?';
}
public function buttonText()
{
/** @translation */
return 'Unpublish Model|Unpublish :count Models';
}
public function run($models, $values)
{
$failures = $models->reject(fn ($model) => $model->published(false)->save());
$total = $models->count();
if ($failures->isNotEmpty()) {
$success = $total - $failures->count();
if ($total === 1) {
throw new \Exception(__('Model could not be unpublished'));
} elseif ($success === 0) {
throw new \Exception(__('Models could not be unpublished'));
} else {
throw new \Exception(__(':success/:total models were unpublished', ['total' => $total, 'success' => $success]));
}
}
return trans_choice('Model unpublished|Models unpublished', $total);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Ignition/Solutions/AddTraitToModel.php | src/Ignition/Solutions/AddTraitToModel.php | <?php
namespace StatamicRadPack\Runway\Ignition\Solutions;
use Archetype\Facades\PHPFile;
use Illuminate\Support\Str;
use Spatie\Ignition\Contracts\RunnableSolution;
use StatamicRadPack\Runway\Traits\HasRunwayResource;
class AddTraitToModel implements RunnableSolution
{
public function __construct(protected $model = null) {}
public function getSolutionTitle(): string
{
$model = Str::after($this->model, 'App\\Models\\');
return "Add HasRunwayResource trait to the {$model} model";
}
public function getSolutionDescription(): string
{
return 'You need to add the `HasRunwayResource` trait to your model in order to use it with Runway.';
}
public function getDocumentationLinks(): array
{
return [
'Learn more' => 'https://runway.duncanmcclean.com/resources#content-defining-resources',
];
}
public function getSolutionActionDescription(): string
{
return 'Runway can attempt to add it for you.';
}
public function getRunButtonText(): string
{
return 'Add trait';
}
public function run(array $parameters = []): void
{
PHPFile::load($parameters['model'])
->add()->use([HasRunwayResource::class])
->add()->useTrait('HasRunwayResource')
->save();
}
public function getRunParameters(): array
{
return [
'model' => $this->model,
];
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Ignition/SolutionProviders/TraitMissing.php | src/Ignition/SolutionProviders/TraitMissing.php | <?php
namespace StatamicRadPack\Runway\Ignition\SolutionProviders;
use Spatie\Ignition\Contracts\HasSolutionsForThrowable;
use StatamicRadPack\Runway\Ignition\Solutions\AddTraitToModel;
use Throwable;
class TraitMissing implements HasSolutionsForThrowable
{
public function canSolve(Throwable $throwable): bool
{
return $throwable instanceof \StatamicRadPack\Runway\Exceptions\TraitMissingException;
}
public function getSolutions(Throwable $throwable): array
{
return [new AddTraitToModel($throwable->model)];
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Fieldtypes/BaseFieldtype.php | src/Fieldtypes/BaseFieldtype.php | <?php
namespace StatamicRadPack\Runway\Fieldtypes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
use Statamic\CP\Column;
use Statamic\Facades\Blink;
use Statamic\Facades\Scope;
use Statamic\Facades\Search;
use Statamic\Fieldtypes\Relationship;
use Statamic\Http\Requests\FilteredRequest;
use Statamic\Query\Scopes\Filter;
use Statamic\Search\Index;
use Statamic\Search\QueryBuilder as SearchQueryBuilder;
use Statamic\Search\Result;
use StatamicRadPack\Runway\Http\Resources\CP\FieldtypeModel;
use StatamicRadPack\Runway\Http\Resources\CP\FieldtypeModels;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Runway;
use StatamicRadPack\Runway\Scopes\Fields\Models;
abstract class BaseFieldtype extends Relationship
{
protected $canEdit = true;
protected $canCreate = true;
protected $canSearch = true;
protected $categories = ['relationship'];
protected $formComponent = 'runway-publish-form';
protected $itemComponent = 'runway-related-item';
protected $formComponentProps = [
'initialReference' => 'reference',
'initialBlueprint' => 'blueprint',
'initialValues' => 'values',
'initialMeta' => 'meta',
'initialTitle' => 'title',
'resource' => 'resource',
'breadcrumbs' => 'breadcrumbs',
'initialActions' => 'actions',
'method' => 'method',
'initialReadOnly' => 'readOnly',
'initialPermalink' => 'permalink',
'canManagePublishState' => 'canManagePublishState',
'resourceHasRoutes' => 'resourceHasRoutes',
'revisionsEnabled' => 'revisionsEnabled',
];
protected function configFieldItems(): array
{
return [
'mode' => [
'display' => __('Mode'),
'instructions' => __('statamic::fieldtypes.relationship.config.mode'),
'type' => 'radio',
'default' => 'default',
'options' => [
'default' => __('Stack Selector'),
'select' => __('Select Dropdown'),
'typeahead' => __('Typeahead Field'),
],
'width' => 50,
],
'resource' => [
'display' => __('Resource'),
'instructions' => __('Specify the Runway Resource to be used for this field.'),
'type' => 'select',
'options' => collect(Runway::allResources())
->mapWithKeys(fn ($resource) => [$resource->handle() => $resource->name()])
->toArray(),
'width' => 50,
'validate' => 'required',
],
'relationship_name' => [
'display' => __('Relationship Name'),
'instructions' => __('The name of the Eloquent Relationship this field should use. When left empty, Runway will attempt to guess it based on the field handle.'),
'type' => 'text',
'width' => 50,
],
'create' => [
'display' => __('Allow Creating'),
'instructions' => __('statamic::fieldtypes.entries.config.create'),
'type' => 'toggle',
'default' => true,
'width' => 50,
],
'with' => [
'display' => __('Eager Loaded Relationships'),
'instructions' => __('Specify any relationship which should be eager loaded when this field is augmented.'),
'type' => 'list',
'default' => [],
'width' => 50,
],
'title_format' => [
'display' => __('Title Format'),
'instructions' => __('Configure the title format used for displaying results in the fieldtype. You can use Antlers to pull in model data.'),
'type' => 'text',
'width' => 50,
],
'search_index' => [
'display' => __('Search Index'),
'instructions' => __('An appropriate search index will be used automatically where possible, but you may define an explicit one.'),
'type' => 'text',
],
'query_scopes' => [
'display' => __('Query Scopes'),
'instructions' => __('Select which query fields should be applied when retrieving selectable models.'),
'type' => 'taggable',
'options' => Scope::all()
->reject(fn ($scope) => $scope instanceof Filter)
->map->handle()
->values()
->all(),
],
];
}
public function icon()
{
return File::get(__DIR__.'/../../resources/svg/database.svg');
}
public function preload()
{
return array_merge(parent::preload(), [
'unlinkBehavior' => $this->getUnlinkBehavior(),
]);
}
private function getUnlinkBehavior(): string
{
$relationshipName = $this->config('relationship_name') ?? $this->field->handle();
if (
$this->field->parent() instanceof Model
&& $this instanceof HasManyFieldtype
&& method_exists($this->field->parent(), $relationshipName)
) {
$relationship = $this->field->parent()->{$relationshipName}();
if ($relationship instanceof HasMany) {
$foreignKey = $relationship->getQualifiedForeignKeyName();
$foreignTable = explode('.', $foreignKey)[0];
$foreignColumn = explode('.', $foreignKey)[1];
$column = collect(Schema::getColumns($foreignTable))
->first(fn (array $column) => $column['name'] === $foreignColumn);
return Arr::get($column, 'nullable', false) ? 'unlink' : 'delete';
}
}
return 'unlink';
}
public function process($data)
{
if ($this->config('max_items') === 1 && ! $this->field->parent() instanceof Model) {
return Arr::first($data);
}
return parent::process($data);
}
public function getIndexItems($request)
{
$query = $this->getIndexQuery($request);
$this->applyOrderingToIndexQuery($query, $request);
$results = ($paginate = $request->boolean('paginate', true)) ? $query->paginate() : $query->get();
$items = $results->map(fn ($item) => $item instanceof Result ? $item->getSearchable()->model() : $item);
return $paginate ? $results->setCollection($items) : $items;
}
private function applyOrderingToIndexQuery(Builder|SearchQueryBuilder $query, FilteredRequest $request): void
{
$query->when(method_exists($query, 'getQuery') && $query->getQuery()->orders, function ($query) use ($request) {
if ($orderBy = $request->input('sort')) {
// The stack selector always uses `title` as the default sort column, but
// the "title field" for the model might be a different column, so we need to convert it.
$sortColumn = $orderBy === 'title' ? $this->resource()->titleField() : $orderBy;
$query->reorder($sortColumn, $request->input('order'));
}
}, fn ($query) => $query->orderBy($this->resource()->orderBy(), $this->resource()->orderByDirection()));
}
protected function getIndexQuery(FilteredRequest $request): Builder|SearchQueryBuilder
{
$query = $this->resource()->newEloquentQuery();
$query = $this->toSearchQuery($query, $request);
$query->when($query instanceof Builder && $query->hasNamedScope('runwayListing'), fn ($query) => $query->runwayListing());
$this->applyIndexQueryScopes($query, $request->all());
return $query;
}
private function toSearchQuery(Builder $query, FilteredRequest $request): Builder|SearchQueryBuilder
{
if (! $search = $request->search) {
return $query;
}
if ($index = $this->getSearchIndex()) {
return $index->search($search);
}
return $query->runwaySearch($search);
}
private function getSearchIndex(): ?Index
{
$index = $this->getExplicitSearchIndex() ?? $this->resource()->searchIndex();
return $index?->ensureExists();
}
private function getExplicitSearchIndex(): ?Index
{
return ($explicit = $this->config('search_index'))
? Search::in($explicit)
: null;
}
public function getResourceCollection($request, $items)
{
$resource = Runway::findResource($this->config('resource'));
return (new FieldtypeModels($items, $this))
->runwayResource($resource)
->blueprint($resource->blueprint())
->setColumnPreferenceKey("runway.{$resource->handle()}.columns");
}
public function preProcessIndex($data)
{
$resource = Runway::findResource($this->config('resource'));
if (! $data) {
return null;
}
if ($this->config('max_items') === 1) {
$data = [$data];
}
if ($data instanceof Model) {
$data = Arr::wrap($data);
}
return collect($data)->map(function ($item) use ($resource) {
$column = $resource->titleField();
$fieldtype = $resource->blueprint()->field($column)->fieldtype();
if (! $item instanceof Model) {
// In a Many to Many relationship, $item is an array.
if (is_array($item)) {
$item = $item['id'] ?? null;
}
// And sometimes, $item will be a Collection.
if ($item instanceof Collection) {
$item = $item->first()->{$resource->primaryKey()} ?? null;
}
$model = $resource->model()->firstWhere($resource->primaryKey(), $item);
} else {
$model = $item;
}
if (! $model) {
return null;
}
return [
'id' => $model->{$resource->primaryKey()},
'title' => $fieldtype->preProcessIndex($model->{$column}),
'edit_url' => $model->runwayEditUrl(),
];
});
}
public function augment($values)
{
$resource = Runway::findResource($this->config('resource'));
$results = $this->getAugmentableModels($resource, $values)
->map(function ($model) use ($resource) {
return Blink::once("Runway::FieldtypeAugment::{$resource->handle()}_{$model->{$resource->primaryKey()}}", function () use ($model) {
return $model->toAugmentedArray();
});
});
return $this->config('max_items') === 1
? $results->first()
: $results->toArray();
}
public function shallowAugment($values)
{
$resource = Runway::findResource($this->config('resource'));
$results = $this->getAugmentableModels($resource, $values)
->map(function ($model) use ($resource) {
return Blink::once("Runway::FieldtypeShallowAugment::{$resource->handle()}_{$model->{$resource->primaryKey()}}", function () use ($model) {
return $model->toShallowAugmentedArray();
});
});
return $this->config('max_items') === 1
? $results->first()
: $results->toArray();
}
protected function getAugmentableModels(Resource $resource, $values): Collection
{
return collect($values instanceof Collection ? $values : Arr::wrap($values))
->map(function ($model) use ($resource) {
if (! $model instanceof Model) {
$eagerLoadingRelationships = collect($this->config('with') ?? [])->join(',');
return Blink::once("Runway::Model::{$this->config('resource')}_{$model}}::{$eagerLoadingRelationships}", function () use ($resource, $model) {
return $resource->newEloquentQuery()
->when(
$this->config('with'),
fn ($query) => $query->with(Arr::wrap($this->config('with'))),
fn ($query) => $query->with($resource->eagerLoadingRelationships())
)
->firstWhere($resource->primaryKey(), $model);
});
}
return $model;
})
->when($resource->hasPublishStates(), fn ($collection) => $collection->filter(fn ($model) => $model?->published()))
->filter();
}
protected function getColumns()
{
$resource = Runway::findResource($this->config('resource'));
return $resource->blueprint()->columns()
->when($resource->hasPublishStates(), function ($collection) {
$collection->put('status', Column::make('status')
->listable(true)
->visible(true)
->defaultVisibility(true)
->sortable(false));
})
->setPreferred("runway.{$resource->handle()}.columns")
->rejectUnlisted()
->values();
}
protected function toItemArray($id)
{
$resource = Runway::findResource($this->config('resource'));
$model = $id instanceof Model ? $id : $resource->model()->runway()->firstWhere($resource->primaryKey(), $id);
if (! $model) {
return $this->invalidItemArray($id);
}
return (new FieldtypeModel($model, $this))->resolve()['data'];
}
protected function getCreatables()
{
$resource = Runway::findResource($this->config('resource'));
return [[
'title' => $resource->singular(),
'url' => cp_route('runway.create', [
'resource' => $resource->handle(),
]),
]];
}
public function filter()
{
return new Models($this);
}
protected function statusIcons()
{
$resource = Runway::findResource($this->config('resource'));
return $resource->hasPublishStates();
}
private function resource(): Resource
{
return Runway::findResource($this->config('resource'));
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Fieldtypes/BelongsToFieldtype.php | src/Fieldtypes/BelongsToFieldtype.php | <?php
namespace StatamicRadPack\Runway\Fieldtypes;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Database\Eloquent\Model;
use Statamic\Facades\GraphQL;
use StatamicRadPack\Runway\Runway;
class BelongsToFieldtype extends BaseFieldtype
{
protected function configFieldItems(): array
{
$config = [
'max_items' => [
'display' => __('Max Items'),
'type' => 'hidden',
'width' => 50,
'default' => 1,
'read_only' => true,
],
];
return array_merge($config, parent::configFieldItems());
}
public function toGqlType()
{
$resource = Runway::findResource($this->config('resource'));
return [
'type' => GraphQL::type("runway_graphql_types_{$resource->handle()}"),
'resolve' => function ($item, $args, $context, ResolveInfo $info) {
if (! $item instanceof Model) {
return $item->get($info->fieldName);
}
return $item->{$info->fieldName};
},
];
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Fieldtypes/HasManyFieldtype.php | src/Fieldtypes/HasManyFieldtype.php | <?php
namespace StatamicRadPack\Runway\Fieldtypes;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Statamic\Facades\GraphQL;
use StatamicRadPack\Runway\Runway;
class HasManyFieldtype extends BaseFieldtype
{
protected $indexComponent = 'relationship';
protected function configFieldItems(): array
{
$config = [
'max_items' => [
'display' => __('Max Items'),
'instructions' => __('statamic::messages.max_items_instructions'),
'type' => 'integer',
'width' => 50,
],
'reorderable' => [
'display' => __('Reorderable?'),
'instructions' => __('Can the models be reordered?'),
'type' => 'toggle',
'width' => 50,
],
'order_column' => [
'display' => __('Order Column'),
'instructions' => __('Which column should be used to keep track of the order?'),
'type' => 'text',
'width' => 50,
'placeholder' => 'sort_order',
'if' => [
'reorderable' => true,
],
],
];
return array_merge(parent::configFieldItems(), $config);
}
/**
* Pre-process the values before they get sent to the publish form.
*
* @return array
*/
public function preProcess($data)
{
$resource = Runway::findResource($this->config('resource'));
if (collect($data)->every(fn ($item) => $item instanceof Model)) {
return collect($data)->pluck($resource->primaryKey())->all();
}
return Arr::wrap($data);
}
public function preload()
{
return array_merge(parent::preload(), [
'actionUrl' => cp_route('runway.models.actions.run', [
'resource' => $this->config('resource'),
]),
]);
}
public function toGqlType()
{
$resource = Runway::findResource($this->config('resource'));
return [
'type' => GraphQL::listOf(GraphQL::type("runway_graphql_types_{$resource->handle()}")),
'resolve' => function ($item, $args, $context, ResolveInfo $info) {
if (! $item instanceof Model) {
return $item->get($info->fieldName);
}
return $item->{$info->fieldName};
},
];
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Console/Commands/ImportCollection.php | src/Console/Commands/ImportCollection.php | <?php
namespace StatamicRadPack\Runway\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Statamic\Console\RunsInPlease;
use Statamic\Contracts\Entries\Collection;
use Statamic\Facades;
use Statamic\Facades\YAML;
use Statamic\Fields\Field;
use StatamicRadPack\Runway\Runway;
use Stillat\Proteus\Support\Facades\ConfigWriter;
use function Laravel\Prompts\confirm;
use function Laravel\Prompts\progress;
use function Laravel\Prompts\select;
class ImportCollection extends Command
{
use RunsInPlease;
private $collection;
private $modelName;
private $modelClass;
private $blueprint;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'runway:import-collection
{ collection? : The handle of the collection to import. }
{ --force : Force overwrite if files already exist }';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Import a collection into the database.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$this->collection = $this->promptForCollection();
$this->modelName = Str::of($this->collection->handle())->singular()->title();
$this->modelClass = "App\Models\\{$this->modelName}";
if (class_exists($this->modelClass) && ! $this->option('force')) {
$this->components->error("A [{$this->modelName}] model already exists.");
return 1;
}
$this
->copyBlueprint()
->createEloquentModel()
->appendToRunwayConfig()
->createDatabaseMigration()
->importEntries();
$this->components->info("The {$this->collection->title()} collection has been imported.");
$this->line(' Next steps:');
$this->components->bulletList([
'Replace the {{ collection }} tag with the {{ runway }} tag in your templates.',
'If you have any Entry fields pointing to this collection, replace them with the Belong To or Has Many fieldtypes.',
"When you're ready, delete the {$this->collection->title()} collection.",
]);
}
private function promptForCollection(): Collection
{
$handle = $this->argument('collection') ?? select(
label: 'Which collection would you like to import?',
options: Facades\Collection::all()
->mapWithKeys(fn (Collection $collection) => [$collection->handle() => $collection->title()])
->all(),
);
$collection = Facades\Collection::find($handle);
if ($collection->entryBlueprints()->count() > 1) {
if (! confirm("Runway doesn't support multiple blueprints. Only the first blueprint will be imported. Are you sure you want to continue?")) {
exit;
}
}
if ($collection->sites()->count() > 1) {
if (! confirm("Runway doesn't support localization. Are you sure you want to continue?")) {
exit;
}
}
if ($collection->hasStructure()) {
if (! confirm("Runway doesn't support trees. Are you sure you want to continue?")) {
exit;
}
}
return $collection;
}
private function copyBlueprint(): self
{
$contents = Str::of(YAML::dump($this->collection->entryBlueprint()->contents()))
->replace("- 'new \Statamic\Rules\UniqueEntryValue({collection}, {id}, {site})'", '')
->__toString();
$this->blueprint = Facades\Blueprint::make("runway::{$this->collection->handle()}")
->setContents(YAML::parse($contents))
->removeField('parent');
if ($this->collection->dated()) {
$this->blueprint->ensureField('date', ['type' => 'date', 'display' => __('Date')], 'sidebar');
}
$this->blueprint->save();
return $this;
}
private function createEloquentModel(): self
{
// Casts are different in Laravel 10, so we need to use a different model stub.
$modelStub = version_compare(app()->version(), '11.0.0', '>')
? __DIR__.'/stubs/model.stub'
: __DIR__.'/stubs/model-l10.stub';
$modelContents = Str::of(File::get($modelStub))
->replace('{{ namespace }}', 'App\Models')
->replace('{{ class }}', $this->modelName)
->replace('{{ traits }}', $this->collection->routes()->isNotEmpty() ? 'HasRunwayResource, RunwayRoutes' : 'HasRunwayResource')
->replace('{{ fillable }}', collect($this->getDatabaseColumns())
->pluck('name')
->filter()
->map(fn ($column) => "'{$column}'")
->join(', '))
->replace('{{ casts }}', collect($this->getDatabaseColumns())
->filter(fn ($column) => in_array($column['type'], ['json', 'boolean', 'datetime', 'date', 'time', 'float', 'integer']))
->map(fn ($column) => " '{$column['name']}' => '{$column['type']}',")
->join(PHP_EOL))
->when($this->collection->requiresSlugs(), function ($str) {
return $str->replaceLast('}', <<<'PHP'
public function getRouteKeyName(): string
{
return 'slug';
}
}
PHP);
})
->__toString();
File::put(app_path("Models/{$this->modelName}.php"), $modelContents);
require_once app_path("Models/{$this->modelName}.php");
return $this;
}
private function appendToRunwayConfig(): self
{
ConfigWriter::write(
'runway.resources.'.str_replace('\\', '\\', $this->modelClass),
array_filter([
'handle' => $this->collection->handle(),
'name' => $this->collection->title(),
'published' => true,
'revisions' => $this->collection->revisionsEnabled(),
'route' => Str::of($this->collection->route(Facades\Site::default()->handle()))
->replace('{parent_uri}/', '')
->replace('{slug}', '{{ slug }}')
->__toString(),
'template' => $this->collection->template(),
'layout' => $this->collection->layout(),
'order_by' => $this->collection->sortField(),
'order_by_direction' => $this->collection->sortDirection(),
]),
);
// Ensure the array key is "ModelName::class", and not "'\App\Models\ModelName'".
$contents = File::get(config_path('runway.php'));
$contents = Str::of($contents)
->replace("'App\\Models\\{$this->modelName}' => [", "{$this->modelName}::class => [")
->when(! Str::contains($contents, "use App\Models\\{$this->modelName};"), fn ($contents) => $contents
->replace('return [', 'use App\Models\\'.$this->modelName.';'.PHP_EOL.PHP_EOL.'return [')
)
->__toString();
File::put(config_path('runway.php'), $contents);
Config::set('runway', require config_path('runway.php'));
Runway::discoverResources();
return $this;
}
private function createDatabaseMigration(): self
{
/** @var Model $model */
$model = new $this->modelClass;
if (Schema::hasTable($model->getTable())) {
$this->components->warn("The [{$model->getTable()}] table already exists. Skipping generation of migration.");
return $this;
}
$migrationContents = Str::of(File::get(__DIR__.'/stubs/migration.stub'))
->replace('{{ table }}', $model->getTable())
->replace('{{ columns }}', collect($this->getDatabaseColumns())->map(function (array $column) {
$type = $column['type'];
$string = "\$table->{$type}";
isset($column['name'])
? $string = "{$string}('{$column['name']}')"
: $string = "{$string}()";
if (isset($column['nullable'])) {
$string = "{$string}->nullable()";
}
if (isset($column['default'])) {
$default = $column['default'];
if (is_string($default)) {
$default = "'{$default}'";
}
if (is_bool($default)) {
$default = $default ? 'true' : 'false';
}
$string = "{$string}->default({$default})";
}
if (isset($column['primary'])) {
$string = "{$string}->primary()";
}
return " {$string};";
})->implode(PHP_EOL))
->__toString();
File::put(database_path('migrations/'.date('Y_m_d_His')."_create_{$model->getTable()}_table.php"), $migrationContents);
if (confirm('Would you like to run the migration?')) {
$this->call('migrate');
}
return $this;
}
private function importEntries(): self
{
/** @var Model $model */
$model = new $this->modelClass;
if (! Schema::hasTable($model->getTable())) {
return $this;
}
if (! confirm('Would you like to import existing entries')) {
return $this;
}
$this->newLine();
$progress = progress(label: 'Importing entries', steps: $this->collection->queryEntries()->count());
$progress->start();
$this->collection->queryEntries()->chunk(100, function ($entries) use ($model, $progress) {
$entries->each(function ($entry) use ($model, $progress) {
$attributes = $entry->data()
->only($this->blueprint->fields()->all()->map->handle())
->merge([
'uuid' => $entry->id(),
'slug' => $entry->slug(),
'published' => $entry->published(),
'updated_at' => $entry->get('updated_at') ?? now(),
])
->when($entry->hasDate(), fn ($attributes) => $attributes->merge([
'date' => $entry->date(),
]))
->all();
$model = $model::find($entry->id()) ?? (new $model);
$model->forceFill($attributes)->save();
$progress->advance();
});
});
$progress->finish();
return $this;
}
private function getDatabaseColumns(): array
{
return $this->blueprint->fields()->all()
->map(function (Field $field) {
return [
'type' => $this->getColumnTypeForField($field),
'name' => $field->handle(),
'nullable' => ! $field->isRequired(),
];
})
->prepend(['type' => 'string', 'name' => 'uuid', 'primary' => true])
->push(['type' => 'boolean', 'name' => 'published', 'default' => false])
->push(['type' => 'timestamps'])
->values()
->all();
}
private function getColumnTypeForField(Field $field): string
{
if (in_array($field->type(), ['array', 'checkboxes', 'grid', 'group', 'list', 'replicator', 'table'])) {
return 'json';
}
if (
$field->get('max_items') &&
in_array($field->type(), ['assets', 'asset_container', 'asset_folder', 'collections', 'dictionary', 'entries', 'navs', 'select', 'sites', 'structures', 'taggable', 'taxonomies', 'terms', 'user_groups', 'user_roles', 'users'])
) {
return 'json';
}
if (in_array($field->type(), ['html', 'markdown', 'textarea'])) {
return 'text';
}
if ($field->type() === 'bard') {
return $field->get('save_html')
? 'text'
: 'json';
}
if ($field->type() === 'code') {
return $field->get('mode_selectable')
? 'json'
: 'text';
}
if ($field->type() === 'date') {
return $field->get('time_enabled')
? 'datetime'
: 'date';
}
if ($field->type() === 'time') {
return 'time';
}
if ($field->type() === 'float') {
return 'float';
}
if ($field->type() === 'integer') {
return 'integer';
}
if ($field->type() === 'boolean') {
return 'boolean';
}
return 'string';
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Console/Commands/RebuildUriCache.php | src/Console/Commands/RebuildUriCache.php | <?php
namespace StatamicRadPack\Runway\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Statamic\Console\RunsInPlease;
use Statamic\Facades\Antlers;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Routing\RunwayUri;
use StatamicRadPack\Runway\Runway;
use function Laravel\Prompts\confirm;
use function Laravel\Prompts\progress;
class RebuildUriCache extends Command
{
use RunsInPlease;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'runway:rebuild-uris
{ --force : Force rebuilding of the URI cache. }';
/**
* The console command description.
*
* @var string
*/
protected $description = "Rebuild Runway's URI cache of resources.";
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
if (! $this->option('force')) {
$confirm = confirm(
'You are about to rebuild your entire URI cache. This may take part of your site down while running. Are you sure you want to continue?'
);
if (! $confirm) {
return;
}
}
RunwayUri::all()->each->delete();
Runway::allResources()
->each(function (Resource $resource) {
if (! $resource->hasRouting()) {
$this->components->warn("Skipping {$resource->name()}, routing not configured.");
return;
}
$query = $resource->newEloquentQuery()->withoutGlobalScopes();
$query->when($query->hasNamedScope('runwayRoutes'), fn ($query) => $query->runwayRoutes());
if (! $query->exists()) {
$this->components->warn("Skipping {$resource->name()}, no models to cache.");
return;
}
progress(
label: "Caching {$resource->name()} URIs",
steps: $query->get(),
callback: function ($model) use ($resource) {
$uri = Antlers::parser()
->parse($resource->route(), $model->toAugmentedArray())
->__toString();
$uri = Str::start($uri, '/');
$model->runwayUri()->create([
'uri' => $uri,
]);
}
);
});
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Console/Commands/ListResources.php | src/Console/Commands/ListResources.php | <?php
namespace StatamicRadPack\Runway\Console\Commands;
use Illuminate\Console\Command;
use Statamic\Console\RunsInPlease;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Runway;
class ListResources extends Command
{
use RunsInPlease;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'runway:resources';
/**
* The console command description.
*
* @var string
*/
protected $description = 'List all Runway resources.';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
if (! Runway::allResources()->count()) {
return $this->components->error("Your application doesn't have any resources.");
}
$this->table(
['Handle', 'Model', 'Route'],
Runway::allResources()->map(fn (Resource $resource) => [
$resource->handle(),
$resource->model()::class,
$resource->hasRouting() ? $resource->route() : 'N/A',
])->values()->toArray()
);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Search/Provider.php | src/Search/Provider.php | <?php
namespace StatamicRadPack\Runway\Search;
use Illuminate\Support\Collection;
use Statamic\Search\Searchables\Provider as BaseProvider;
use Statamic\Support\Str;
use StatamicRadPack\Runway\Runway;
class Provider extends BaseProvider
{
protected static $handle = 'runway';
protected static $referencePrefix = 'runway';
public function provide(): Collection
{
$resources = $this->usesWildcard() ? Runway::allResources()->keys() : $this->keys;
return collect($resources)->flatMap(function ($handle) {
return Runway::findResource($handle)
->newEloquentQuery()
->whereStatus('published')
->get()
->mapInto(Searchable::class);
})->filter($this->filter());
}
public function contains($searchable): bool
{
if (! $searchable instanceof Searchable) {
return false;
}
$resource = $searchable->resource();
if (! $this->usesWildcard() && ! in_array($resource->handle(), $this->keys)) {
return false;
}
return $this->filter()($searchable);
}
public function find(array $keys): Collection
{
return collect($keys)
->groupBy(fn ($key) => Str::before($key, '::'))
->flatMap(function ($items, $handle) {
$ids = $items->map(fn ($item) => Str::after($item, '::'));
return Runway::findResource($handle)->model()->whereStatus('published')->find($ids);
})
->mapInto(Searchable::class);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Search/Searchable.php | src/Search/Searchable.php | <?php
namespace StatamicRadPack\Runway\Search;
use Illuminate\Database\Eloquent\Model;
use Statamic\Contracts\Data\Augmentable;
use Statamic\Contracts\Data\Augmented;
use Statamic\Contracts\Query\ContainsQueryableValues;
use Statamic\Contracts\Search\Result;
use Statamic\Contracts\Search\Searchable as Contract;
use Statamic\Data\ContainsSupplementalData;
use Statamic\Data\HasAugmentedInstance;
use Statamic\Facades\Site;
use Statamic\Search\Result as ResultInstance;
use StatamicRadPack\Runway\Data\AugmentedModel;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Runway;
class Searchable implements Augmentable, ContainsQueryableValues, Contract
{
use ContainsSupplementalData, HasAugmentedInstance;
protected $model;
protected $resource;
public function __construct(Model $model)
{
$this->model = $model;
$this->resource = Runway::findResourceByModel($model);
$this->supplements = collect();
}
public function get($key, $fallback = null)
{
return $this->model->{$key} ?? $fallback;
}
public function model(): Model
{
return $this->model;
}
public function resource(): Resource
{
return $this->resource;
}
public function getQueryableValue(string $field)
{
if ($field === 'site') {
return Site::current()->handle();
}
return $this->model->{$field};
}
public function getSearchValue(string $field)
{
if (method_exists($this->model, $field)) {
return $this->model->$field();
}
return $this->model->{$field};
}
public function getSearchReference(): string
{
return vsprintf('runway::%s::%s', [
$this->resource->handle(),
$this->model->getKey(),
]);
}
public function toSearchResult(): Result
{
return new ResultInstance($this, 'runway:'.$this->resource->handle());
}
public function getCpSearchResultTitle(): string
{
return $this->model->{$this->resource->titleField()};
}
public function getCpSearchResultUrl(): string
{
return $this->model->runwayEditUrl();
}
public function getCpSearchResultBadge(): string
{
return $this->resource->name();
}
public function newAugmentedInstance(): Augmented
{
return (new AugmentedModel($this->model))
->supplement($this->supplements());
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Data/AugmentedModel.php | src/Data/AugmentedModel.php | <?php
namespace StatamicRadPack\Runway\Data;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Statamic\Data\AbstractAugmented;
use Statamic\Fields\Field;
use Statamic\Fields\Value;
use Statamic\Statamic;
use Statamic\Support\Arr;
use StatamicRadPack\Runway\Runway;
class AugmentedModel extends AbstractAugmented
{
protected $data;
protected $resource;
protected $supplements;
public function __construct($model)
{
$this->data = $model;
$this->resource = Runway::findResourceByModel($model);
$this->supplements = collect();
}
public function supplement(Collection $data)
{
$this->supplements = $data;
return $this;
}
public function keys()
{
return collect()
->merge($this->modelAttributes()->keys())
->merge($this->appendedAttributes()->values())
->merge($this->blueprintFields()->keys())
->merge($this->eloquentRelationships()->values())
->merge($this->commonKeys())
->unique()->sort()->values()->all();
}
private function commonKeys()
{
$commonKeys = [];
if ($this->resource->hasRouting()) {
$commonKeys[] = 'url';
}
return $commonKeys;
}
public function url(): ?string
{
return $this->resource->hasRouting()
? $this->data->uri()
: null;
}
public function apiUrl()
{
if (! $id = $this->data->{$this->resource->primaryKey()}) {
return null;
}
return Statamic::apiRoute('runway.show', [$this->resource->handle(), $id]);
}
protected function modelAttributes(): Collection
{
return collect($this->data->getAttributes());
}
protected function appendedAttributes(): Collection
{
return collect($this->data->getAppends());
}
public function blueprintFields(): Collection
{
return $this->resource->blueprint()->fields()->all();
}
protected function eloquentRelationships()
{
return $this->resource->eloquentRelationships()->reject(fn ($relationship) => $relationship === 'runwayUri');
}
protected function getFromData($handle)
{
return $this->supplements->get($handle) ?? data_get($this->data, $handle);
}
public function get($handle): Value
{
if ($this->resource->eloquentRelationships()->flip()->has($handle)) {
$value = $this->wrapEloquentRelationship($handle);
return $value->resolve();
}
if ($this->isNestedFieldPrefix($handle)) {
$value = $this->wrapNestedFields($handle);
return $value->resolve();
}
if ($this->isNestedField($handle)) {
$value = $this->wrapNestedField($handle);
return $value->resolve();
}
if ($this->hasModelAccessor($handle)) {
$value = $this->wrapModelAccessor($handle);
return $value->resolve();
}
return parent::get($handle);
}
private function wrapEloquentRelationship(string $handle): Value
{
$relatedField = $this->resource->eloquentRelationships()->flip()->get($handle);
return new Value(
fn () => $this->getFromData($handle),
$handle,
$this->fieldtype($relatedField),
$this->data
);
}
private function isNestedFieldPrefix(string $handle): bool
{
return $this->resource->nestedFieldPrefixes()->contains($handle);
}
private function wrapNestedFields(string $nestedFieldPrefix): Value
{
return new Value(
function () use ($nestedFieldPrefix) {
$values = $this->blueprintFields()
->filter(function (Field $field) use ($nestedFieldPrefix) {
return Str::startsWith($field->handle(), "{$nestedFieldPrefix}_");
})
->mapWithKeys(function (Field $field) use ($nestedFieldPrefix) {
$key = Str::after($field->handle(), "{$nestedFieldPrefix}_");
$value = data_get($this->data, "{$nestedFieldPrefix}.{$key}");
return [$key => $value];
});
return collect($values)->map(function ($value, $key) use ($nestedFieldPrefix) {
return new Value(
$value,
$key,
$this->fieldtype("{$nestedFieldPrefix}_{$key}"),
$this->data
);
})->all();
},
$nestedFieldPrefix,
null,
$this->data
);
}
private function isNestedField(string $handle): bool
{
foreach ($this->resource->nestedFieldPrefixes() as $nestedFieldPrefix) {
if (Str::startsWith($handle, "{$nestedFieldPrefix}_")) {
return $this->blueprintFields()->has($handle);
}
}
return false;
}
private function wrapNestedField(string $handle): Value
{
$nestedFieldPrefix = Str::before($handle, '_');
$key = Str::after($handle, "{$nestedFieldPrefix}_");
$value = data_get($this->data, "{$nestedFieldPrefix}.{$key}");
return new Value(
$value,
$handle,
$this->fieldtype($handle),
$this->data
);
}
private function hasModelAccessor(string $handle): bool
{
$method = Str::camel($handle);
return method_exists($this->data, $method)
&& (new \ReflectionMethod($this->data, $method))->getReturnType()?->getName() === Attribute::class;
}
private function wrapModelAccessor(string $handle): Value
{
return new Value(
function () use ($handle) {
$method = Str::camel($handle);
$attribute = invade($this->data)->$method();
if (! $attribute->get) {
return $this->data->getAttribute($handle);
}
$attributes = $this->data->getAttributes();
return ($attribute->get)(Arr::get($attributes, $handle), $attributes);
},
$handle,
$this->fieldtype($handle),
$this->data
);
}
private function fieldtype($handle)
{
return optional($this->blueprintFields()->get($handle))->fieldtype();
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Data/HasAugmentedInstance.php | src/Data/HasAugmentedInstance.php | <?php
namespace StatamicRadPack\Runway\Data;
use Statamic\Contracts\Data\Augmented;
use Statamic\Support\Traits\Hookable;
/**
* This trait is a copy of HasAugmentedInstance built into Statamic BUT
* without the __get, __set, __call methods which mess with Eloquent.
*/
trait HasAugmentedInstance
{
use Hookable;
public function augmentedValue($key)
{
return $this->augmented()->get($key);
}
private function toAugmentedCollectionWithFields($keys, $fields = null)
{
return $this->augmented()
->withRelations($this->defaultAugmentedRelations())
->withBlueprintFields($fields)
->select($keys ?? $this->defaultAugmentedArrayKeys());
}
public function toAugmentedCollection($keys = null)
{
return $this->toAugmentedCollectionWithFields($keys);
}
public function toAugmentedArray($keys = null)
{
return $this->toAugmentedCollection($keys)->all();
}
public function toDeferredAugmentedArray($keys = null)
{
return $this->toAugmentedCollectionWithFields($keys)->deferredAll();
}
public function toDeferredAugmentedArrayUsingFields($keys, $fields)
{
return $this->toAugmentedCollectionWithFields($keys, $fields)->deferredAll();
}
public function toShallowAugmentedCollection()
{
return $this->augmented()->select($this->shallowAugmentedArrayKeys())->withShallowNesting();
}
public function toShallowAugmentedArray()
{
return $this->toShallowAugmentedCollection()->all();
}
public function augmented(): Augmented
{
return $this->runHooks('augmented', $this->newAugmentedInstance());
}
abstract public function newAugmentedInstance(): Augmented;
protected function defaultAugmentedArrayKeys()
{
return null;
}
public function shallowAugmentedArrayKeys()
{
return ['id', 'title', 'api_url'];
}
protected function defaultAugmentedRelations()
{
return [];
}
public function toEvaluatedAugmentedArray($keys = null)
{
$collection = $this->toAugmentedCollection($keys);
// Can't just chain ->except() because it would return a new
// collection and the existing 'withRelations' would be lost.
if ($exceptions = $this->excludedEvaluatedAugmentedArrayKeys()) {
$collection = $collection
->except($exceptions)
->withRelations($collection->getRelations());
}
return $collection->withEvaluation()->toArray();
}
protected function excludedEvaluatedAugmentedArrayKeys()
{
return null;
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/GraphQL/ResourceShowQuery.php | src/GraphQL/ResourceShowQuery.php | <?php
namespace StatamicRadPack\Runway\GraphQL;
use GraphQL\Type\Definition\Type;
use Illuminate\Support\Str;
use Statamic\Facades\GraphQL;
use Statamic\GraphQL\Queries\Query;
use StatamicRadPack\Runway\Resource;
class ResourceShowQuery extends Query
{
public function __construct(protected Resource $resource)
{
$this->attributes['name'] = Str::lower($this->resource->singular());
}
public function type(): Type
{
return GraphQL::type("runway_graphql_types_{$this->resource->handle()}");
}
public function args(): array
{
return [
$this->resource->primaryKey() => GraphQL::nonNull(GraphQL::id()),
];
}
public function resolve($root, $args)
{
return $this->resource->model()->whereStatus('published')->find($args[$this->resource->primaryKey()]);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/GraphQL/ResourceIndexQuery.php | src/GraphQL/ResourceIndexQuery.php | <?php
namespace StatamicRadPack\Runway\GraphQL;
use GraphQL\Type\Definition\Type;
use Illuminate\Support\Str;
use Statamic\Facades\GraphQL;
use Statamic\GraphQL\Queries\Concerns\FiltersQuery;
use Statamic\GraphQL\Queries\Query;
use Statamic\GraphQL\Types\JsonArgument;
use StatamicRadPack\Runway\Resource;
class ResourceIndexQuery extends Query
{
use FiltersQuery {
filterQuery as traitFilterQuery;
}
public function __construct(protected Resource $resource)
{
$this->attributes['name'] = Str::lower($this->resource->plural());
}
public function type(): Type
{
return GraphQL::paginate(GraphQL::type("runway_graphql_types_{$this->resource->handle()}"));
}
public function args(): array
{
return [
'limit' => GraphQL::int(),
'page' => GraphQL::int(),
'filter' => GraphQL::type(JsonArgument::NAME),
'sort' => GraphQL::listOf(GraphQL::string()),
];
}
public function resolve($root, $args)
{
$query = $this->resource->newEloquentQuery()->with($this->resource->eagerLoadingRelationships());
$this->filterQuery($query, $args['filter'] ?? []);
$this->sortQuery($query, $args['sort'] ?? []);
return $query->paginate(
$args['limit'] ?? null,
['*'],
'page',
$args['page'] ?? null
);
}
private function filterQuery($query, $filters)
{
if (! isset($filters['status']) && ! isset($filters['published'])) {
$filters['status'] = 'published';
}
$this->traitFilterQuery($query, $filters);
}
protected function sortQuery($query, $sorts): void
{
if (empty($sorts)) {
$sorts = ['id'];
}
foreach ($sorts as $sort) {
$order = 'asc';
if (Str::contains($sort, ' ')) {
[$sort, $order] = explode(' ', (string) $sort);
}
$query = $query->orderBy($sort, $order);
}
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/GraphQL/ResourceType.php | src/GraphQL/ResourceType.php | <?php
namespace StatamicRadPack\Runway\GraphQL;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Rebing\GraphQL\Support\Type;
use Statamic\Facades\GraphQL;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Runway;
class ResourceType extends Type
{
public function __construct(protected Resource $resource)
{
$this->attributes['name'] = "runway_graphql_types_{$this->resource->handle()}";
}
public function fields(): array
{
return $this->resource->blueprint()->fields()->toGql()
->merge($this->nonBlueprintFields())
->merge($this->nestedFields())
->when($this->resource->hasPublishStates(), function ($collection) {
$collection->put('status', ['type' => GraphQL::nonNull(GraphQL::string())]);
$collection->put('published', ['type' => GraphQL::nonNull(GraphQL::boolean())]);
})
->reject(fn ($value, $key) => $this->resource->nestedFieldPrefix($key))
->mapWithKeys(fn ($value, $key) => [
Str::replace('_id', '', $key) => $value,
])
->map(function ($arr) {
if (is_array($arr)) {
$arr['resolve'] ??= $this->resolver();
}
return $arr;
})
->all();
}
protected function resolver()
{
return function ($model, $args, $context, ResolveInfo $info) {
if (! $model instanceof Model) {
$resource = Runway::findResource(Str::replace('runway_graphql_types_', '', $info->parentType->name));
$model = $resource->model()->firstWhere($resource->primaryKey(), $model);
}
return $model->resolveGqlValue($info->fieldName);
};
}
protected function nonBlueprintFields(): array
{
return collect(Schema::getColumns($this->resource->databaseTable()))
->reject(fn (array $column) => in_array(
$column['name'],
$this->resource->blueprint()->fields()->all()->keys()->toArray()
))
->mapWithKeys(function (array $column): array {
$type = null;
if ($column['type_name'] === 'bigint') {
$type = GraphQL::int();
}
if ($column['type_name'] === 'varchar' || $column['type_name'] === 'string') {
$type = GraphQL::string();
}
if ($column['type_name'] === 'timestamp' || $column['type_name'] === 'datetime') {
$type = GraphQL::string();
}
if ($column['nullable'] === false && ! is_null($type)) {
$type = GraphQL::nonNull($type);
}
return [$column['name'] => ['type' => $type]];
})
->reject(fn ($item): bool => is_null($item['type']))
->all();
}
protected function nestedFields(): array
{
return $this->resource->nestedFieldPrefixes()->mapWithKeys(fn (string $nestedFieldPrefix) => [
$nestedFieldPrefix => ['type' => GraphQL::type(NestedFieldsType::buildName($this->resource, $nestedFieldPrefix))],
])->all();
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/GraphQL/NestedFieldsType.php | src/GraphQL/NestedFieldsType.php | <?php
namespace StatamicRadPack\Runway\GraphQL;
use Statamic\Fields\Field;
use Statamic\Support\Str;
use StatamicRadPack\Runway\Resource;
class NestedFieldsType extends \Rebing\GraphQL\Support\Type
{
public function __construct(protected Resource $resource, protected string $nestedFieldPrefix)
{
$this->attributes['name'] = static::buildName($resource, $nestedFieldPrefix);
}
public static function buildName(Resource $resource, string $nestedFieldPrefix): string
{
return 'Runway_NestedFields_'.Str::studly($resource->handle()).'_'.Str::studly($nestedFieldPrefix);
}
public function fields(): array
{
return $this->resource->blueprint()->fields()->all()
->filter(fn (Field $field) => Str::startsWith($field->handle(), $this->nestedFieldPrefix))
->mapWithKeys(function (Field $field) {
$field = (clone $field);
$handle = Str::after($field->handle(), "{$this->nestedFieldPrefix}_");
return [$handle => $field->setHandle($handle)];
})
->map->toGql()
->all();
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/src/Policies/ResourcePolicy.php | src/Policies/ResourcePolicy.php | <?php
namespace StatamicRadPack\Runway\Policies;
use Statamic\Facades\User;
use StatamicRadPack\Runway\Resource;
class ResourcePolicy
{
public function view($user, Resource $resource, $model = null)
{
return User::fromUser($user)->hasPermission("view {$resource->handle()}");
}
public function create($user, Resource $resource)
{
return User::fromUser($user)->hasPermission("create {$resource->handle()}");
}
public function edit($user, Resource $resource, $model = null)
{
return User::fromUser($user)->hasPermission("edit {$resource->handle()}");
}
public function delete($user, Resource $resource, $model = null)
{
return User::fromUser($user)->hasPermission("delete {$resource->handle()}");
}
public function publish($user, Resource $resource, $model = null)
{
return User::fromUser($user)->hasPermission("publish {$resource->handle()}");
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/RelationshipsTest.php | tests/RelationshipsTest.php | <?php
namespace StatamicRadPack\Runway\Tests;
use Illuminate\Support\Facades\Schema;
use PHPUnit\Framework\Attributes\Test;
use Statamic\Facades\Blueprint;
use Statamic\Fields\Blueprint as FieldsBlueprint;
use StatamicRadPack\Runway\Relationships;
use StatamicRadPack\Runway\Tests\Fixtures\Models\Author;
use StatamicRadPack\Runway\Tests\Fixtures\Models\Post;
class RelationshipsTest extends TestCase
{
#[Test]
public function can_add_models_when_saving_has_many_relationship()
{
$author = Author::factory()->create();
$posts = Post::factory()->count(10)->create();
Blueprint::shouldReceive('find')->with('runway::post')->andReturn(new FieldsBlueprint);
Blueprint::shouldReceive('find')
->with('runway::author')
->andReturn((new FieldsBlueprint)->setContents([
'tabs' => [
'main' => [
'fields' => [
['handle' => 'posts', 'field' => ['type' => 'has_many', 'resource' => 'post']],
],
],
],
]));
Relationships::for($author)->with(['posts' => $posts->pluck('id')->all()])->save();
$this->assertTrue(
$posts->every(fn ($post) => $post->fresh()->author_id === $author->id)
);
}
#[Test]
public function can_unlink_models_when_saving_has_many_relationship_when_relationship_column_is_nullable()
{
$author = Author::factory()->create();
$posts = Post::factory()->count(3)->create(['author_id' => $author->id]);
Schema::shouldReceive('getColumns')->with('posts')->andReturn([
['name' => 'author_id', 'type' => 'integer', 'nullable' => true],
]);
// Without this, Schema::getColumnListing() will return null, even though shouldIgnoreMissing() is called. But whatever π€·ββοΈ
Schema::shouldReceive('getColumnListing')->with('posts')->andReturn(['published']);
Schema::shouldIgnoreMissing();
Blueprint::shouldReceive('find')->with('runway::post')->andReturn(new FieldsBlueprint);
Blueprint::shouldReceive('find')
->with('runway::author')
->andReturn((new FieldsBlueprint)->setContents([
'tabs' => [
'main' => [
'fields' => [
['handle' => 'posts', 'field' => ['type' => 'has_many', 'resource' => 'post']],
],
],
],
]));
Relationships::for($author)
->with(['posts' => [$posts[1]->id, $posts[2]->id]])
->save();
$this->assertDatabaseHas('posts', ['id' => $posts[0]->id, 'author_id' => null]);
$this->assertDatabaseHas('posts', ['id' => $posts[1]->id, 'author_id' => $author->id]);
$this->assertDatabaseHas('posts', ['id' => $posts[2]->id, 'author_id' => $author->id]);
}
#[Test]
public function can_delete_models_when_saving_has_many_relationship_when_relationship_column_is_not_nullable()
{
$author = Author::factory()->create();
$posts = Post::factory()->count(3)->create(['author_id' => $author->id]);
Schema::shouldReceive('getColumns')->with('posts')->andReturn([
['name' => 'author_id', 'type' => 'integer', 'nullable' => false],
]);
// Without this, Schema::getColumnListing() will return null, even though shouldIgnoreMissing() is called. But whatever π€·ββοΈ
Schema::shouldReceive('getColumnListing')->with('posts')->andReturn(['published']);
Schema::shouldIgnoreMissing();
Blueprint::shouldReceive('find')->with('runway::post')->andReturn(new FieldsBlueprint);
Blueprint::shouldReceive('find')
->with('runway::author')
->andReturn((new FieldsBlueprint)->setContents([
'tabs' => [
'main' => [
'fields' => [
['handle' => 'posts', 'field' => ['type' => 'has_many', 'resource' => 'post']],
],
],
],
]));
Relationships::for($author)
->with(['posts' => [$posts[1]->id, $posts[2]->id]])
->save();
$this->assertDatabaseMissing('posts', ['id' => $posts[0]->id]);
$this->assertDatabaseHas('posts', ['id' => $posts[1]->id, 'author_id' => $author->id]);
$this->assertDatabaseHas('posts', ['id' => $posts[2]->id, 'author_id' => $author->id]);
}
#[Test]
public function can_update_sort_orders_when_saving_has_many_relationship()
{
$author = Author::factory()->create();
$posts = Post::factory()->count(3)->create();
Blueprint::shouldReceive('find')->with('runway::post')->andReturn(new FieldsBlueprint);
Blueprint::shouldReceive('find')
->with('runway::author')
->andReturn((new FieldsBlueprint)->setContents([
'tabs' => [
'main' => [
'fields' => [
['handle' => 'posts', 'field' => ['type' => 'has_many', 'resource' => 'post', 'reorderable' => true, 'order_column' => 'sort_order']],
],
],
],
]));
Relationships::for($author)
->with(['posts' => [$posts[1]->id, $posts[2]->id, $posts[0]->id]])
->save();
$this->assertDatabaseHas('posts', ['id' => $posts[0]->id, 'author_id' => $author->id, 'sort_order' => 2]);
$this->assertDatabaseHas('posts', ['id' => $posts[1]->id, 'author_id' => $author->id, 'sort_order' => 0]);
$this->assertDatabaseHas('posts', ['id' => $posts[2]->id, 'author_id' => $author->id, 'sort_order' => 1]);
}
#[Test]
public function can_add_models_when_saving_belongs_to_many_relationship()
{
$author = Author::factory()->create();
$posts = Post::factory()->count(3)->create();
Blueprint::shouldReceive('find')
->with('runway::author')
->andReturn((new FieldsBlueprint)->setContents([
'tabs' => [
'main' => [
'fields' => [
['handle' => 'pivottedPosts', 'field' => ['type' => 'has_many', 'resource' => 'post']],
],
],
],
]));
Relationships::for($author)->with(['pivottedPosts' => $posts->pluck('id')->all()])->save();
$this->assertDatabaseHas('post_author', ['post_id' => $posts[0]->id, 'author_id' => $author->id]);
$this->assertDatabaseHas('post_author', ['post_id' => $posts[1]->id, 'author_id' => $author->id]);
$this->assertDatabaseHas('post_author', ['post_id' => $posts[2]->id, 'author_id' => $author->id]);
}
#[Test]
public function can_remove_models_when_saving_belongs_to_many_relationship()
{
$author = Author::factory()->create();
$posts = Post::factory()->count(3)->create();
Blueprint::shouldReceive('find')
->with('runway::author')
->andReturn((new FieldsBlueprint)->setContents([
'tabs' => [
'main' => [
'fields' => [
['handle' => 'pivottedPosts', 'field' => ['type' => 'has_many', 'resource' => 'post']],
],
],
],
]));
Relationships::for($author)
->with(['pivottedPosts' => [$posts[1]->id, $posts[2]->id]])
->save();
$this->assertDatabaseMissing('post_author', ['post_id' => $posts[0]->id, 'author_id' => $author->id]);
$this->assertDatabaseHas('post_author', ['post_id' => $posts[1]->id, 'author_id' => $author->id]);
$this->assertDatabaseHas('post_author', ['post_id' => $posts[2]->id, 'author_id' => $author->id]);
}
#[Test]
public function can_update_sort_orders_when_saving_belongs_to_many_relationship()
{
$author = Author::factory()->create();
$posts = Post::factory()->count(3)->create();
Blueprint::shouldReceive('find')
->with('runway::author')
->andReturn((new FieldsBlueprint)->setContents([
'tabs' => [
'main' => [
'fields' => [
['handle' => 'pivottedPosts', 'field' => ['type' => 'has_many', 'resource' => 'post', 'reorderable' => true, 'order_column' => 'pivot_sort_order']],
],
],
],
]));
Relationships::for($author)
->with(['pivottedPosts' => [$posts[0]->id, $posts[2]->id, $posts[1]->id]])
->save();
$this->assertDatabaseHas('post_author', ['post_id' => $posts[0]->id, 'author_id' => $author->id, 'pivot_sort_order' => 0]);
$this->assertDatabaseHas('post_author', ['post_id' => $posts[1]->id, 'author_id' => $author->id, 'pivot_sort_order' => 2]);
$this->assertDatabaseHas('post_author', ['post_id' => $posts[2]->id, 'author_id' => $author->id, 'pivot_sort_order' => 1]);
}
#[Test]
public function does_not_attempt_to_save_computed_fields()
{
$author = Author::factory()->create();
$posts = Post::factory()->count(10)->create();
Blueprint::shouldReceive('find')->with('runway::post')->andReturn(new FieldsBlueprint);
Blueprint::shouldReceive('find')
->with('runway::author')
->andReturn((new FieldsBlueprint)->setContents([
'tabs' => [
'main' => [
'fields' => [
['handle' => 'posts', 'field' => ['type' => 'has_many', 'resource' => 'post', 'visibility' => 'computed', 'save' => false]],
],
],
],
]));
Relationships::for($author)->with(['posts' => $posts->pluck('id')->all()])->save();
$this->assertFalse(
$posts->every(fn ($post) => $post->fresh()->author_id === $author->id)
);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/TestCase.php | tests/TestCase.php | <?php
namespace StatamicRadPack\Runway\Tests;
use Illuminate\Encryption\Encrypter;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Statamic\Facades\Blueprint;
use Statamic\Stache\Stores\UsersStore;
use Statamic\Statamic;
use Statamic\Testing\AddonTestCase;
use StatamicRadPack\Runway\Runway;
use StatamicRadPack\Runway\ServiceProvider;
abstract class TestCase extends AddonTestCase
{
use RefreshDatabase;
protected string $addonServiceProvider = ServiceProvider::class;
protected $shouldFakeVersion = true;
protected function setUp(): void
{
parent::setUp();
$this->loadMigrationsFrom(__DIR__.'/__fixtures__/database/migrations');
$this->runLaravelMigrations();
}
protected function resolveApplicationConfiguration($app)
{
parent::resolveApplicationConfiguration($app);
$app['config']->set('app.key', 'base64:'.base64_encode(
Encrypter::generateKey($app['config']['app.cipher'])
));
$app['config']->set('view.paths', [
__DIR__.'/__fixtures__/resources/views',
]);
$app['config']->set('statamic.api.enabled', true);
$app['config']->set('statamic.editions.pro', true);
$app['config']->set('statamic.users.repository', 'file');
$app['config']->set('statamic.stache.stores.users', [
'class' => UsersStore::class,
'directory' => __DIR__.'/__fixtures__/users',
]);
$app['config']->set('runway', require (__DIR__.'/__fixtures__/config/runway.php'));
Statamic::booted(function () {
Blueprint::setDirectory(__DIR__.'/__fixtures__/resources/blueprints');
});
Runway::clearRegisteredResources();
}
protected function getPackageProviders($app): array
{
return [
...parent::getPackageProviders($app),
\Spatie\LaravelRay\RayServiceProvider::class,
];
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/HasRunwayResourceTest.php | tests/HasRunwayResourceTest.php | <?php
namespace StatamicRadPack\Runway\Tests;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Schema;
use PHPUnit\Framework\Attributes\Test;
use StatamicRadPack\Runway\Runway;
use StatamicRadPack\Runway\Tests\Fixtures\Models\ExternalPost;
class HasRunwayResourceTest extends TestCase
{
#[Test]
public function scope_runway_search_works_with_custom_eloquent_connection()
{
Config::set('database.connections.external', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
Schema::connection('external')->create('external_posts', function ($table) {
$table->id();
$table->string('title');
$table->longText('body');
$table->timestamps();
});
Runway::registerResource(ExternalPost::class, []);
ExternalPost::create([
'title' => 'Test External Post',
'body' => 'This is the body of the test post.',
]);
ExternalPost::create([
'title' => 'Another Post',
'body' => 'This is different content.',
]);
ExternalPost::create([
'title' => 'Something Else',
'body' => 'No matching content here.',
]);
$results = ExternalPost::query()->runwaySearch('Test External')->get();
$this->assertCount(1, $results);
$this->assertEquals('Test External Post', $results->first()->title);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/ResourceTest.php | tests/ResourceTest.php | <?php
namespace StatamicRadPack\Runway\Tests;
use Illuminate\Support\Facades\Config;
use PHPUnit\Framework\Attributes\Test;
use Statamic\Facades\Blueprint;
use Statamic\Facades\Fieldset;
use StatamicRadPack\Runway\Runway;
class ResourceTest extends TestCase
{
#[Test]
public function can_get_eloquent_relationships_for_belongs_to_field()
{
Runway::discoverResources();
$resource = Runway::findResource('post');
$eloquentRelationships = $resource->eloquentRelationships();
$this->assertContains('author', $eloquentRelationships->toArray());
}
#[Test]
public function can_get_eloquent_relationships_for_has_many_field()
{
$blueprint = Blueprint::find('runway::author');
Blueprint::shouldReceive('find')
->with('runway::author')
->andReturn($blueprint->ensureField('posts', [
'type' => 'has_many',
'resource' => 'post',
'max_items' => 1,
'mode' => 'default',
]));
$resource = Runway::findResource('author');
$eloquentRelationships = $resource->eloquentRelationships();
$this->assertContains('posts', $eloquentRelationships->toArray());
}
#[Test]
public function can_get_eloquent_relationships_for_runway_uri_routing()
{
Runway::discoverResources();
$resource = Runway::findResource('post');
$eloquentRelationships = $resource->eloquentRelationships();
$this->assertContains('runwayUri', $eloquentRelationships->toArray());
}
#[Test]
public function can_get_eager_loading_relationships()
{
Runway::discoverResources();
$resource = Runway::findResource('post');
$eagerLoadingRelationships = $resource->eagerLoadingRelationships();
$this->assertEquals([
'author',
'runwayUri',
], $eagerLoadingRelationships);
}
#[Test]
public function can_get_eager_loading_relationships_from_config()
{
Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.with', [
'author',
]);
Runway::discoverResources();
$resource = Runway::findResource('post');
$eagerLoadingRelationships = $resource->eagerLoadingRelationships();
$this->assertEquals([
'author',
], $eagerLoadingRelationships);
}
#[Test]
public function can_get_generated_singular()
{
Runway::discoverResources();
$resource = Runway::findResource('post');
$singular = $resource->singular();
$this->assertEquals($singular, 'Post');
}
#[Test]
public function can_get_configured_singular()
{
Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.singular', 'Bibliothek');
Runway::discoverResources();
$resource = Runway::findResource('post');
$singular = $resource->singular();
$this->assertEquals($singular, 'Bibliothek');
}
#[Test]
public function can_get_generated_plural()
{
Runway::discoverResources();
$resource = Runway::findResource('post');
$plural = $resource->plural();
$this->assertEquals($plural, 'Posts');
}
#[Test]
public function can_get_configured_plural()
{
Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.plural', 'Bibliotheken');
Runway::discoverResources();
$resource = Runway::findResource('post');
$plural = $resource->plural();
$this->assertEquals($plural, 'Bibliotheken');
}
#[Test]
public function can_get_blueprint()
{
$resource = Runway::findResource('post');
$blueprint = $resource->blueprint();
$this->assertTrue($blueprint instanceof \Statamic\Fields\Blueprint);
$this->assertSame('runway', $blueprint->namespace());
$this->assertSame('post', $blueprint->handle());
}
#[Test]
public function can_create_blueprint_if_one_does_not_exist()
{
$resource = Runway::findResource('post');
Blueprint::shouldReceive('find')->with('runway::post')->andReturnNull()->once();
Blueprint::shouldReceive('find')->with('runway.post')->andReturnNull()->once();
Blueprint::shouldReceive('make')->with('post')->andReturn((new \Statamic\Fields\Blueprint)->setHandle('post'))->once();
Blueprint::shouldReceive('save')->andReturnSelf()->once();
$blueprint = $resource->blueprint();
$this->assertTrue($blueprint instanceof \Statamic\Fields\Blueprint);
$this->assertSame('runway', $blueprint->namespace());
$this->assertSame('post', $blueprint->handle());
}
#[Test]
public function can_get_listable_columns()
{
Fieldset::make('seo')->setContents([
'fields' => [
['handle' => 'seo_title', 'field' => ['type' => 'text', 'listable' => true]],
['handle' => 'seo_description', 'field' => ['type' => 'textarea', 'listable' => true]],
],
])->save();
$blueprint = Blueprint::make()->setContents([
'tabs' => [
'main' => [
'sections' => [
[
'fields' => [
['handle' => 'title', 'field' => ['type' => 'text', 'listable' => true]],
['handle' => 'summary', 'field' => ['type' => 'textarea', 'listable' => true]],
['handle' => 'body', 'field' => ['type' => 'markdown', 'listable' => 'hidden']],
['handle' => 'thumbnail', 'field' => ['type' => 'assets', 'listable' => false]],
['import' => 'seo'],
],
],
],
],
],
]);
Blueprint::shouldReceive('find')->with('runway::post')->andReturn($blueprint);
$resource = Runway::findResource('post');
$this->assertEquals([
'title',
'summary',
'body',
'seo_title',
'seo_description',
], $resource->listableColumns()->toArray());
}
#[Test]
public function can_get_title_field()
{
$blueprint = Blueprint::make()->setContents([
'tabs' => [
'main' => [
'sections' => [
[
'fields' => [
['handle' => 'values->listable_hidden_field', 'field' => ['type' => 'text', 'listable' => 'hidden']],
['handle' => 'values->listable_shown_field', 'field' => ['type' => 'text', 'listable' => true]],
['handle' => 'values->not_listable_field', 'field' => ['type' => 'text', 'listable' => false]],
],
],
],
],
],
]);
Blueprint::shouldReceive('find')->with('runway::post')->andReturn($blueprint);
Runway::discoverResources();
$resource = Runway::findResource('post');
$this->assertEquals('values->listable_hidden_field', $resource->titleField());
}
#[Test]
public function revisions_can_be_enabled()
{
Config::set('statamic.editions.pro', true);
Config::set('statamic.revisions.enabled', true);
Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.published', true);
Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.revisions', true);
Runway::discoverResources();
$resource = Runway::findResource('post');
$this->assertTrue($resource->revisionsEnabled());
}
#[Test]
public function revisions_cant_be_enabled_without_revisions_being_enabled_globally()
{
Config::set('statamic.editions.pro', true);
Config::set('statamic.revisions.enabled', false);
Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.published', true);
Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.revisions', true);
Runway::discoverResources();
$resource = Runway::findResource('post');
$this->assertFalse($resource->revisionsEnabled());
}
#[Test]
public function revisions_cant_be_enabled_without_statamic_pro()
{
Config::set('statamic.editions.pro', false);
Config::set('statamic.revisions.enabled', true);
Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.published', true);
Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.revisions', true);
Runway::discoverResources();
$resource = Runway::findResource('post');
$this->assertFalse($resource->revisionsEnabled());
}
#[Test]
public function revisions_cant_be_enabled_without_publish_states()
{
Config::set('statamic.editions.pro', true);
Config::set('statamic.revisions.enabled', true);
Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.published', false);
Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.revisions', true);
Runway::discoverResources();
$resource = Runway::findResource('post');
$this->assertFalse($resource->revisionsEnabled());
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/RunwayTest.php | tests/RunwayTest.php | <?php
namespace StatamicRadPack\Runway\Tests;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use PHPUnit\Framework\Attributes\Test;
use Statamic\Fields\Blueprint;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Runway;
use StatamicRadPack\Runway\Tests\Fixtures\Models\Author;
class RunwayTest extends TestCase
{
#[Test]
public function can_discover_and_get_all_resources()
{
Runway::discoverResources();
$all = Runway::allResources()->values();
$this->assertTrue($all instanceof Collection);
$this->assertCount(3, $all);
$this->assertTrue($all[0] instanceof Resource);
$this->assertEquals('author', $all[0]->handle());
$this->assertTrue($all[0]->model() instanceof Model);
$this->assertTrue($all[0]->blueprint() instanceof Blueprint);
$this->assertTrue($all[1] instanceof Resource);
$this->assertEquals('post', $all[1]->handle());
$this->assertTrue($all[1]->model() instanceof Model);
$this->assertTrue($all[1]->blueprint() instanceof Blueprint);
$this->assertTrue($all[2] instanceof Resource);
$this->assertEquals('user', $all[2]->handle());
$this->assertTrue($all[2]->model() instanceof Model);
$this->assertTrue($all[2]->blueprint() instanceof Blueprint);
}
#[Test]
public function can_find_resource()
{
Runway::discoverResources();
$find = Runway::findResource('author');
$this->assertTrue($find instanceof Resource);
$this->assertEquals('author', $find->handle());
$this->assertTrue($find->model() instanceof Model);
$this->assertTrue($find->blueprint() instanceof Blueprint);
}
#[Test]
public function can_register_resource()
{
config()->set('runway.resources', []);
Runway::discoverResources();
$this->assertFalse(Runway::allResources()->has('author'));
Runway::registerResource(Author::class, [
'name' => 'Authors',
]);
$this->assertTrue(Runway::allResources()->has('author'));
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Routing/RoutingModelTest.php | tests/Routing/RoutingModelTest.php | <?php
namespace StatamicRadPack\Runway\Tests\Routing;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Config;
use PHPUnit\Framework\Attributes\Test;
use StatamicRadPack\Runway\Data\AugmentedModel;
use StatamicRadPack\Runway\Resource;
use StatamicRadPack\Runway\Routing\RoutingModel;
use StatamicRadPack\Runway\Runway;
use StatamicRadPack\Runway\Tests\Fixtures\Models\Post;
use StatamicRadPack\Runway\Tests\TestCase;
class RoutingModelTest extends TestCase
{
#[Test]
public function can_get_route()
{
$post = Post::factory()->createQuietly();
$post->runwayUri()->create(['uri' => '/blog/post-slug']);
$routingModel = new RoutingModel($post);
$this->assertEquals('/blog/post-slug', $routingModel->route());
}
#[Test]
public function cant_get_route_without_runway_uri()
{
$post = Post::factory()->createQuietly();
$routingModel = new RoutingModel($post);
$this->assertNull($routingModel->route());
}
#[Test]
public function can_get_route_data()
{
$post = Post::factory()->createQuietly();
$post->runwayUri()->create(['uri' => '/blog/post-slug']);
$routingModel = new RoutingModel($post);
$this->assertEquals([
'id' => $post->id,
], $routingModel->routeData());
}
#[Test]
public function can_get_uri()
{
$post = Post::factory()->createQuietly();
$post->runwayUri()->create(['uri' => '/blog/post-slug']);
$routingModel = new RoutingModel($post);
$this->assertEquals('/blog/post-slug', $routingModel->uri());
}
#[Test]
public function can_get_url_without_redirect()
{
$post = Post::factory()->createQuietly();
$post->runwayUri()->create(['uri' => '/blog/post-slug']);
$routingModel = new RoutingModel($post);
$this->assertEquals('/blog/post-slug', $routingModel->urlWithoutRedirect());
}
#[Test]
public function can_get_response()
{
$post = Post::factory()->createQuietly();
$post->runwayUri()->create(['uri' => '/blog/post-slug']);
$routingModel = new RoutingModel($post);
$response = $routingModel->toResponse(new Request);
$this->assertInstanceOf(Response::class, $response);
$this->assertStringContainsString("<h1>{$post->title}</h1>", $response->getContent());
$this->assertStringContainsString("<article>{$post->body}</article>", $response->getContent());
}
#[Test]
public function can_get_resource()
{
Runway::discoverResources();
$post = Post::factory()->createQuietly();
$routingModel = new RoutingModel($post);
$this->assertInstanceOf(Resource::class, $routingModel->resource());
}
#[Test]
public function can_get_template()
{
Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.template', 'posts.show');
Runway::discoverResources();
$post = Post::factory()->createQuietly();
$post->runwayUri()->create(['uri' => '/blog/post-slug']);
$routingModel = new RoutingModel($post);
$this->assertEquals('posts.show', $routingModel->template());
}
#[Test]
public function can_get_layout()
{
Config::set('runway.resources.StatamicRadPack\Runway\Tests\Fixtures\Models\Post.layout', 'layouts.post');
Runway::discoverResources();
$post = Post::factory()->createQuietly();
$post->runwayUri()->create(['uri' => '/blog/post-slug']);
$routingModel = new RoutingModel($post);
$this->assertEquals('layouts.post', $routingModel->layout());
}
#[Test]
public function can_get_id()
{
$post = Post::factory()->createQuietly();
$post->runwayUri()->create(['uri' => '/blog/post-slug']);
$routingModel = new RoutingModel($post);
$this->assertEquals($post->id, $routingModel->id());
}
#[Test]
public function can_get_route_key()
{
$post = Post::factory()->createQuietly();
$post->runwayUri()->create(['uri' => '/blog/post-slug']);
$routingModel = new RoutingModel($post);
$this->assertEquals($post->id, $routingModel->getRouteKey());
}
#[Test]
public function can_get_augmented_instance()
{
$post = Post::factory()->createQuietly();
$post->runwayUri()->create(['uri' => '/blog/post-slug']);
$routingModel = new RoutingModel($post);
$this->assertInstanceOf(AugmentedModel::class, $routingModel->newAugmentedInstance());
}
#[Test]
public function can_get_something_from_model()
{
$post = Post::factory()->createQuietly();
$post->runwayUri()->create(['uri' => '/blog/post-slug']);
$routingModel = new RoutingModel($post);
$this->assertEquals($post->slug, $routingModel->slug);
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
statamic-rad-pack/runway | https://github.com/statamic-rad-pack/runway/blob/27defcba1673a204ded32122e413172dbc6aa186/tests/Routing/FrontendRoutingTest.php | tests/Routing/FrontendRoutingTest.php | <?php
namespace StatamicRadPack\Runway\Tests\Routing;
use Illuminate\Support\Facades\Config;
use PHPUnit\Framework\Attributes\Test;
use StatamicRadPack\Runway\Runway;
use StatamicRadPack\Runway\Tests\Fixtures\Models\Post;
use StatamicRadPack\Runway\Tests\TestCase;
class FrontendRoutingTest extends TestCase
{
#[Test]
public function returns_resource_response_for_resource()
{
$post = Post::factory()->create();
$runwayUri = $post->fresh()->runwayUri;
$this
->get($runwayUri->uri)
->assertOk()
->assertSee($post->title)
->assertSee('TEMPLATE: default')
->assertSee('LAYOUT: layout');
}
#[Test]
public function returns_resource_response_for_resource_with_nested_field()
{
$post = Post::factory()->create([
'values' => [
'alt_title' => 'Alternative Title...',
],
]);
$runwayUri = $post->fresh()->runwayUri;
$this
->get($runwayUri->uri)
->assertOk()
->assertSee('Alternative Title...')
->assertSee('TEMPLATE: default')
->assertSee('LAYOUT: layout');
}
#[Test]
public function returns_resource_response_for_resource_with_custom_template()
{
Config::set('runway.resources.'.Post::class.'.template', 'custom');
Runway::discoverResources();
$post = Post::factory()->create();
$runwayUri = $post->fresh()->runwayUri;
$this
->get($runwayUri->uri)
->assertOk()
->assertSee($post->title)
->assertSee('TEMPLATE: custom')
->assertSee('LAYOUT: layout');
}
#[Test]
public function returns_resource_response_for_resource_with_custom_layout()
{
Config::set('runway.resources.'.Post::class.'.layout', 'blog-layout');
Runway::discoverResources();
$post = Post::factory()->create();
$runwayUri = $post->fresh()->runwayUri;
$this
->get($runwayUri->uri)
->assertOk()
->assertSee($post->title)
->assertSee('TEMPLATE: default')
->assertSee('LAYOUT: blog-layout');
}
}
| php | MIT | 27defcba1673a204ded32122e413172dbc6aa186 | 2026-01-05T05:10:50.689341Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.