|
8 | 8 | namespace Mantle\Database\Model; |
9 | 9 |
|
10 | 10 | use Carbon\Carbon; |
11 | | -use DateTime; |
12 | 11 | use DateTimeInterface; |
13 | 12 | use Mantle\Contracts; |
14 | 13 | use Mantle\Database\Model\Relations\Belongs_To; |
15 | | -use Mantle\Database\Model\Relations\Has_One; |
16 | 14 | use Mantle\Database\Query\Builder; |
17 | 15 | use Mantle\Database\Query\Post_Query_Builder; |
18 | 16 | use Mantle\Support\Helpers; |
19 | 17 |
|
| 18 | +use function Mantle\Support\Helpers\stringable; |
| 19 | + |
20 | 20 | /** |
21 | 21 | * Post Model |
22 | 22 | * |
@@ -182,43 +182,28 @@ public static function find( $object ) { |
182 | 182 | * |
183 | 183 | * @param string $post_type Post type to create the model for. |
184 | 184 | */ |
185 | | - public static function for( string $post_type ): self { |
186 | | - $instance = new class() extends Post { |
187 | | - /** |
188 | | - * Constructor. |
189 | | - */ |
190 | | - public function __construct() {} |
191 | | - |
192 | | - /** |
193 | | - * Post type for the model. |
194 | | - */ |
195 | | - public static string $for_object_name = ''; |
196 | | - |
197 | | - /** |
198 | | - * Retrieve the object name. |
199 | | - */ |
200 | | - public static function get_object_name(): string { |
201 | | - return self::$for_object_name; |
202 | | - } |
203 | | - |
204 | | - /** |
205 | | - * Boot the model if it has not been booted. |
206 | | - * |
207 | | - * Prevent booting the model unless the object name is set. |
208 | | - */ |
209 | | - public static function boot_if_not_booted(): void { |
210 | | - if ( empty( self::$for_object_name ) ) { |
211 | | - return; |
212 | | - } |
213 | | - |
214 | | - parent::boot_if_not_booted(); |
215 | | - } |
216 | | - }; |
| 185 | + public static function for( string $post_type ): Post { |
| 186 | + $post_type = sanitize_key( $post_type ); |
| 187 | + $class_name = 'Post_' . stringable( $post_type )->studly()->replace( '-', '_' )->__toString(); |
| 188 | + $namespace = __NAMESPACE__; |
| 189 | + |
| 190 | + if ( ! class_exists( "{$namespace}\\{$class_name}" ) ) { |
| 191 | + // Similar to how Mockery creates classes on the fly for testing. No other |
| 192 | + // solution was found to create a class on the fly. |
| 193 | + eval( // phpcs:ignore Squiz.PHP.Eval.Discouraged |
| 194 | + <<<PHP |
| 195 | +namespace {$namespace} { |
| 196 | + class {$class_name} extends Post { |
| 197 | + public static \$object_name = '{$post_type}'; |
| 198 | + } |
| 199 | +} |
| 200 | +PHP |
| 201 | + ); |
| 202 | + } |
217 | 203 |
|
218 | | - $instance::$for_object_name = $post_type; |
219 | | - $instance::boot_if_not_booted(); |
| 204 | + $full_class_name = "{$namespace}\\{$class_name}"; |
220 | 205 |
|
221 | | - return $instance; |
| 206 | + return new $full_class_name(); |
222 | 207 | } |
223 | 208 |
|
224 | 209 | /** |
|
0 commit comments