diff --git a/README.md b/README.md index 239ca67..737f158 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,17 @@ Every time you call `Yard\Data\PostData::from($post)` you receive an instance of If you choose to create a new data class for your custom post type, you can have this class be returned for all instances of that post type. -Just use the config file and map all custom posts and it's classes: +To do this, you need to add the Fully Qualified Class Name (FQCN) of your custom data class to the `supports` array when registering your custom post type: + +```php +register_post_type('vacancy', [ + 'supports' => [ + 'data-class' => ['classFQN' => App\Data\KnowledgebaseData::class], + ], +]); +```` + +Another option is to create a mapping in the `config/yard-data.php` file. The mapping in the project config takes precedence over the register_post_type `supports` args. ```php 'post_types' => [ diff --git a/src/PostData.php b/src/PostData.php index c508f18..8f6efc1 100644 --- a/src/PostData.php +++ b/src/PostData.php @@ -8,6 +8,7 @@ use Corcel\Model\Post; use ReflectionClass; use ReflectionNamedType; +use RuntimeException; use Spatie\LaravelData\Attributes\MapInputName; use Spatie\LaravelData\Attributes\WithCastable; use Spatie\LaravelData\Data; @@ -86,7 +87,7 @@ public static function fromCorcel(Post $post): PostData } /** - * @return class-string + * @return class-string */ private static function dataClass(string $postType): string { @@ -96,7 +97,21 @@ private static function dataClass(string $postType): string return $classes[$postType]; } - return static::class; + $classFQN = get_all_post_type_supports($postType)['data-class'][0]['classFQN'] ?? null; + + if (null === $classFQN) { + return static::class; + } + + if (! class_exists($classFQN)) { + throw new RuntimeException(sprintf('The class "%s" does not exist or is not autoloaded.', $classFQN)); + } + + if (! is_a($classFQN, PostData::class, true)) { + throw new RuntimeException(sprintf('The class "%s" must extend %s.', $classFQN, PostData::class)); + } + + return $classFQN; } private function metaPrefix(): string