Explicit mapping of post type to class

This commit is contained in:
Toby Zerner 2015-02-13 10:30:32 +10:30
parent 5ebd0a0e93
commit edfd053fc2
2 changed files with 20 additions and 6 deletions

View File

@ -5,6 +5,7 @@ use Config;
use Event;
use Flarum\Core\Formatter\FormatterManager;
use Flarum\Core\Posts\Post;
class CoreServiceProvider extends ServiceProvider
{
@ -31,6 +32,9 @@ class CoreServiceProvider extends ServiceProvider
Event::listen('Flarum.Core.*', 'Flarum\Core\Listeners\DiscussionMetadataUpdater');
Event::listen('Flarum.Core.*', 'Flarum\Core\Listeners\UserMetadataUpdater');
Event::listen('Flarum.Core.*', 'Flarum\Core\Listeners\RenamedPostCreator');
Post::addType('comment', 'Flarum\Core\Posts\CommentPost');
Post::addType('renamed', 'Flarum\Core\Posts\RenamedPost');
}
/**

View File

@ -27,6 +27,8 @@ class Post extends Entity
'hide_user_id' => 'integer',
];
protected static $types = [];
public static function boot()
{
parent::boot();
@ -111,15 +113,23 @@ class Post extends Entity
}
}
public static function addType($type, $class)
{
static::$types[$type] = $class;
}
public function newFromBuilder($attributes = [])
{
if (!empty($attributes->type)) {
$class = 'Flarum\Core\Posts\\'.ucfirst($attributes->type).'Post';
if (class_exists($class)) {
$instance = new $class;
$instance->exists = true;
$instance->setRawAttributes((array) $attributes, true);
return $instance;
$type = $attributes->type;
if (isset(static::$types[$type])) {
$class = static::$types[$type];
if (class_exists($class)) {
$instance = new $class;
$instance->exists = true;
$instance->setRawAttributes((array) $attributes, true);
return $instance;
}
}
}