From c3dfa3560af1ccc08a477d2c32aa48c1828e94a9 Mon Sep 17 00:00:00 2001 From: Toby Zerner Date: Sat, 28 May 2016 09:37:43 +0930 Subject: [PATCH] Allow extensions to add default model attributes Extensions can add default column values in their migrations, but Eloquent doesn't know about this when it first saves a model to the database. This is useful in flarum-ext-approval where the default value for is_approved on the posts table is true. --- src/Database/AbstractModel.php | 17 +++++++ src/Event/ConfigureModelDefaultAttributes.php | 45 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 src/Event/ConfigureModelDefaultAttributes.php diff --git a/src/Database/AbstractModel.php b/src/Database/AbstractModel.php index daa964532..7da4f5712 100755 --- a/src/Database/AbstractModel.php +++ b/src/Database/AbstractModel.php @@ -11,6 +11,7 @@ namespace Flarum\Database; use Flarum\Event\ConfigureModelDates; +use Flarum\Event\ConfigureModelDefaultAttributes; use Flarum\Event\GetModelRelationship; use Illuminate\Database\Eloquent\Model as Eloquent; use Illuminate\Database\Eloquent\Relations\Relation; @@ -66,6 +67,22 @@ abstract class AbstractModel extends Eloquent }); } + /** + * {@inheritdoc} + */ + public function __construct(array $attributes = []) + { + $defaults = []; + + static::$dispatcher->fire( + new ConfigureModelDefaultAttributes($this, $defaults) + ); + + $this->attributes = $defaults; + + parent::__construct($attributes); + } + /** * Get the attributes that should be converted to dates. * diff --git a/src/Event/ConfigureModelDefaultAttributes.php b/src/Event/ConfigureModelDefaultAttributes.php new file mode 100644 index 000000000..1eecba56b --- /dev/null +++ b/src/Event/ConfigureModelDefaultAttributes.php @@ -0,0 +1,45 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Flarum\Event; + +use Flarum\Database\AbstractModel; + +class ConfigureModelDefaultAttributes +{ + /** + * @var AbstractModel + */ + public $model; + + /** + * @var array + */ + public $attributes; + + /** + * @param AbstractModel $model + * @param array $attributes + */ + public function __construct(AbstractModel $model, array &$attributes) + { + $this->model = $model; + $this->attributes = &$attributes; + } + + /** + * @param string $model + * @return bool + */ + public function isModel($model) + { + return $this->model instanceof $model; + } +}