Skip to content

Instantly share code, notes, and snippets.

@edgrosvenor
Created April 6, 2026 05:39
Show Gist options
  • Select an option

  • Save edgrosvenor/fbce7d420d9bb4c2f37eb1275c4ac8f9 to your computer and use it in GitHub Desktop.

Select an option

Save edgrosvenor/fbce7d420d9bb4c2f37eb1275c4ac8f9 to your computer and use it in GitHub Desktop.
Fat Enums: WithData exceptions and ShouldThrow sentinel
<?php
// What happens when data is missing?
// 1. Missing the attribute entirely throws MissingDataAttributeException
#[WithData(['label' => 'Active'])]
case Active = 'active';
case Inactive = 'inactive'; // No attribute!
Status::Inactive->data('label');
// MissingDataAttributeException: "Status::Inactive has no WithData attribute"
// 2. Missing a key throws MissingDataKeyException
Status::Active->data('icon');
// MissingDataKeyException: "Key 'icon' not found in WithData for Status::Active"
// 3. Use defaults to suppress exceptions
Status::Active->data('icon', default: null); // null
Status::Active->data('icon', default: 'star'); // 'star'
// How does it know null is a default vs "no default given"?
// The ShouldThrow sentinel pattern:
class ShouldThrow
{
private function __construct() {}
}
public function data(string $key, mixed $default = new ShouldThrow): mixed
{
// If $default is still ShouldThrow, no default was passed
if ($default instanceof ShouldThrow) {
throw new MissingDataKeyException(...);
}
return $default;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment