1
0
mirror of https://github.com/flarum/core.git synced 2025-10-14 08:24:28 +02:00

Major refactor and improvements

- Reorganised all namespaces and class names for consistency and structure. Following PSR bylaws (Abstract prefix, Interface/Trait suffix).
  - Move models into root of Core, because writing `use Flarum\Core\Discussion` is nice. Namespace the rest by type. (Namespacing by entity was too arbitrary.)
  - Moved some non-domain stuff out of Core: Database, Formatter, Settings.
  - Renamed config table and all references to "settings" for consistency.
  - Remove Core class and add url()/isInstalled()/inDebugMode() as instance methods of Foundation\Application.
  - Cleanup, docblocking, etc.

- Improvements to HTTP architecture
  - API and forum/admin Actions are now actually all the same thing (simple PSR-7 Request handlers), renamed to Controllers.
  - Upgrade to tobscure/json-api 0.2 branch.
  - Where possible, moved generic functionality to tobscure/json-api (e.g. pagination links). I'm quite happy with the backend balance now re: #262

- Improvements to other architecture
  - Use Illuminate's Auth\Access\Gate interface/implementation instead of our old Locked trait. We still use events to actually determine the permissions though. Our Policy classes are actually glorified event subscribers.
  - Extract model validation into Core\Validator classes.
  - Make post visibility permission stuff much more efficient and DRY.

- Renamed Flarum\Event classes for consistency. ref #246
  - `Configure` prefix for events dedicated to configuring an object.
  - `Get` prefix for events whose listeners should return something.
  - `Prepare` prefix when a variable is passed by reference so it can be modified.
  - `Scope` prefix when a query builder is passed.

- Miscellaneous improvements/bug-fixes. I'm easily distracted!
  - Increase default height of post composer.
  - Improve post stream redraw flickering in Safari by keying loading post placeholders with their IDs. ref #451
  - Use a PHP JavaScript minification library for minifying TextFormatter's JavaScript, instead of ClosureCompilerService (can't rely on external service!)
  - Use UrlGenerator properly in various places. closes #123
  - Make Api\Client return Response object. closes #128
  - Allow extensions to specify custom icon images.
  - Allow external API/admin URLs to be optionally specified in config.php. If the value or "url" is an array, we look for the corresponding path inside. Otherwise, we append the path to the base URL, using the corresponding value in "paths" if present. closes #244
This commit is contained in:
Toby Zerner
2015-10-08 14:28:02 +10:30
parent 8c7cdb184f
commit dd67291ce0
434 changed files with 8676 additions and 7997 deletions

View File

@@ -0,0 +1,203 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Api\Serializer;
use DateTime;
use Closure;
use Flarum\Core\User;
use Flarum\Event\PrepareApiAttributes;
use Flarum\Event\GetApiRelationship;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Events\Dispatcher;
use LogicException;
use Tobscure\JsonApi\AbstractSerializer as BaseAbstractSerializer;
use Flarum\Api\Relationship\HasOneBuilder;
use Flarum\Api\Relationship\HasManyBuilder;
use Tobscure\JsonApi\Relationship\BuilderInterface;
abstract class AbstractSerializer extends BaseAbstractSerializer
{
/**
* @var User
*/
protected $actor;
/**
* @var Dispatcher
*/
protected static $dispatcher;
/**
* @var Container
*/
protected static $container;
/**
* @return User
*/
public function getActor()
{
return $this->actor;
}
/**
* @param User $actor
*/
public function setActor(User $actor)
{
$this->actor = $actor;
}
/**
* {@inheritdoc}
*/
public function getAttributes($model, array $fields = null)
{
if (! is_object($model) && ! is_array($model)) {
return [];
}
$attributes = $this->getDefaultAttributes($model);
static::$dispatcher->fire(
new PrepareApiAttributes($this, $model, $attributes)
);
return $attributes;
}
/**
* Get the default set of serialized attributes for a model.
*
* @param object|array $model
* @return array
*/
abstract protected function getDefaultAttributes($model);
/**
* @param DateTime|null $date
* @return string|null
*/
protected function formatDate(DateTime $date = null)
{
if ($date) {
return $date->format(DateTime::RFC3339);
}
}
/**
* {@inheritdoc}
*/
public function getRelationshipBuilder($name)
{
if ($relationship = $this->getCustomRelationship($name)) {
return $relationship;
}
return parent::getRelationshipBuilder($name);
}
/**
* Get a custom relationship.
*
* @param string $name
* @return BuilderInterface|null
*/
protected function getCustomRelationship($name)
{
$builder = static::$dispatcher->until(
new GetApiRelationship($this, $name)
);
if ($builder && ! ($builder instanceof BuilderInterface)) {
throw new LogicException('GetApiRelationship handler must return an instance of '
. BuilderInterface::class);
}
return $builder;
}
/**
* Get a relationship builder for a has-one relationship.
*
* @param string|Closure|\Tobscure\JsonApi\SerializerInterface $serializer
* @param string|Closure|null $relation
* @return HasOneBuilder
*/
public function hasOne($serializer, $relation = null)
{
if (is_null($relation)) {
$relation = $this->getRelationCaller();
}
return new HasOneBuilder($serializer, $relation, $this->actor, static::$container);
}
/**
* Get a relationship builder for a has-many relationship.
*
* @param string|Closure|\Tobscure\JsonApi\SerializerInterface $serializer
* @param string|Closure|null $relation
* @return HasManyBuilder
*/
public function hasMany($serializer, $relation = null)
{
if (is_null($relation)) {
$relation = $this->getRelationCaller();
}
return new HasManyBuilder($serializer, $relation, $this->actor, static::$container);
}
/**
* Guess the name of a relation from the stack trace.
*
* @return string
*/
protected function getRelationCaller()
{
list(, , $caller) = debug_backtrace(false, 3);
return $caller['function'];
}
/**
* @return Dispatcher
*/
public static function getEventDispatcher()
{
return static::$dispatcher;
}
/**
* @param Dispatcher $dispatcher
*/
public static function setEventDispatcher(Dispatcher $dispatcher)
{
static::$dispatcher = $dispatcher;
}
/**
* @return Container
*/
public static function getContainer()
{
return static::$container;
}
/**
* @param Container $container
*/
public static function setContainer(Container $container)
{
static::$container = $container;
}
}

View File

@@ -0,0 +1,31 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Api\Serializer;
class CurrentUserSerializer extends UserSerializer
{
/**
* {@inheritdoc}
*/
protected function getDefaultAttributes($user)
{
$attributes = parent::getDefaultAttributes($user);
$attributes += [
'readTime' => $this->formatDate($user->read_time),
'unreadNotificationsCount' => (int) $user->getUnreadNotificationsCount(),
'newNotificationsCount' => (int) $user->getNewNotificationsCount(),
'preferences' => (array) $user->preferences
];
return $attributes;
}
}

View File

@@ -0,0 +1,88 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Api\Serializer;
use Flarum\Core\Discussion;
use InvalidArgumentException;
class DiscussionBasicSerializer extends AbstractSerializer
{
/**
* {@inheritdoc}
*/
protected $type = 'discussions';
/**
* {@inheritdoc}
*
* @param Discussion $discussion
* @throws InvalidArgumentException
*/
protected function getDefaultAttributes($discussion)
{
if (! ($discussion instanceof Discussion)) {
throw new InvalidArgumentException(get_class($this)
. ' can only serialize instances of ' . Discussion::class);
}
return [
'title' => $discussion->title
];
}
/**
* @return \Flarum\Api\Relationship\HasOneBuilder
*/
protected function startUser()
{
return $this->hasOne('Flarum\Api\Serializer\UserBasicSerializer');
}
/**
* @return \Flarum\Api\Relationship\HasOneBuilder
*/
protected function startPost()
{
return $this->hasOne('Flarum\Api\Serializer\PostBasicSerializer');
}
/**
* @return \Flarum\Api\Relationship\HasOneBuilder
*/
protected function lastUser()
{
return $this->hasOne('Flarum\Api\Serializer\UserBasicSerializer');
}
/**
* @return \Flarum\Api\Relationship\HasOneBuilder
*/
protected function lastPost()
{
return $this->hasOne('Flarum\Api\Serializer\PostBasicSerializer');
}
/**
* @return \Flarum\Api\Relationship\HasManyBuilder
*/
protected function posts()
{
return $this->hasMany('Flarum\Api\Serializer\PostSerializer');
}
/**
* @return \Flarum\Api\Relationship\HasManyBuilder
*/
protected function relevantPosts()
{
return $this->hasMany('Flarum\Api\Serializer\PostBasicSerializer');
}
}

View File

@@ -0,0 +1,74 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Api\Serializer;
use Flarum\Core\Discussion;
use Flarum\Core\Access\Gate;
class DiscussionSerializer extends DiscussionBasicSerializer
{
/**
* @var Gate
*/
protected $gate;
/**
* @param \Flarum\Core\Access\Gate $gate
*/
public function __construct(Gate $gate)
{
$this->gate = $gate;
}
/**
* {@inheritdoc}
*/
protected function getDefaultAttributes($discussion)
{
$gate = $this->gate->forUser($this->actor);
$attributes = parent::getDefaultAttributes($discussion) + [
'commentsCount' => (int) $discussion->comments_count,
'participantsCount' => (int) $discussion->participants_count,
'startTime' => $this->formatDate($discussion->start_time),
'lastTime' => $this->formatDate($discussion->last_time),
'lastPostNumber' => (int) $discussion->last_post_number,
'canReply' => $gate->allows('reply', $discussion),
'canRename' => $gate->allows('rename', $discussion),
'canDelete' => $gate->allows('delete', $discussion),
'canHide' => $gate->allows('hide', $discussion)
];
if ($discussion->hide_time) {
$attributes['isHidden'] = true;
$attributes['hideTime'] = $this->formatDate($discussion->hide_time);
}
Discussion::setStateUser($this->actor);
if ($state = $discussion->state) {
$attributes += [
'readTime' => $this->formatDate($state->read_time),
'readNumber' => (int) $state->read_number
];
}
return $attributes;
}
/**
* @return \Flarum\Api\Relationship\HasOneBuilder
*/
protected function hideUser()
{
return $this->hasOne('Flarum\Api\Serializer\UserSerializer');
}
}

View File

@@ -0,0 +1,98 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Api\Serializer;
use Flarum\Foundation\Application;
use Flarum\Core\Access\Gate;
use Flarum\Settings\SettingsRepository;
class ForumSerializer extends AbstractSerializer
{
/**
* {@inheritdoc}
*/
protected $type = 'forums';
/**
* @var Gate
*/
protected $gate;
/**
* @var Application
*/
protected $app;
/**
* @var SettingsRepository
*/
protected $settings;
/**
* @param Gate $gate
* @param Application $app
* @param SettingsRepository $settings
*/
public function __construct(Gate $gate, Application $app, SettingsRepository $settings)
{
$this->gate = $gate;
$this->app = $app;
$this->settings = $settings;
}
/**
* {@inheritdoc}
*/
public function getId($model)
{
return 1;
}
/**
* {@inheritdoc}
*/
protected function getDefaultAttributes($model)
{
$gate = $this->gate->forUser($this->actor);
$attributes = [
'title' => $this->settings->get('forum_title'),
'description' => $this->settings->get('forum_description'),
'baseUrl' => $url = $this->app->url(),
'basePath' => parse_url($url, PHP_URL_PATH) ?: '',
'debug' => $this->app->inDebugMode(),
'apiUrl' => $this->app->url('api'),
'welcomeTitle' => $this->settings->get('welcome_title'),
'welcomeMessage' => $this->settings->get('welcome_message'),
'themePrimaryColor' => $this->settings->get('theme_primary_color'),
'allowSignUp' => (bool) $this->settings->get('allow_sign_up'),
'defaultRoute' => $this->settings->get('default_route'),
'canViewDiscussions' => $gate->allows('viewDiscussions'),
'canViewUserList' => $gate->allows('viewUserList'),
'canStartDiscussion' => $gate->allows('startDiscussion')
];
if ($gate->allows('administrate')) {
$attributes['adminUrl'] = $this->app->url('admin');
$attributes['version'] = $this->app->version();
}
return $attributes;
}
/**
* @return \Flarum\Api\Relationship\HasManyBuilder
*/
protected function groups()
{
return $this->hasMany('Flarum\Api\Serializer\GroupSerializer');
}
}

View File

@@ -0,0 +1,52 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Api\Serializer;
use Flarum\Api\Serializer\AbstractSerializer;
use Flarum\Core\Group;
use InvalidArgumentException;
class GroupSerializer extends AbstractSerializer
{
/**
* {@inheritdoc}
*/
protected $type = 'groups';
/**
* {@inheritdoc}
*
* @param Group $group
* @throws InvalidArgumentException
*/
protected function getDefaultAttributes($group)
{
if (! ($group instanceof Group)) {
throw new InvalidArgumentException(get_class($this)
. ' can only serialize instances of ' . Group::class);
}
return [
'nameSingular' => $group->name_singular,
'namePlural' => $group->name_plural,
'color' => $group->color,
'icon' => $group->icon,
];
}
/**
* @return \Flarum\Api\Relationship\HasManyBuilder
*/
protected function permissions()
{
return $this->hasMany('Flarum\Api\Serializers\PermissionSerializer');
}
}

View File

@@ -0,0 +1,87 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Api\Serializer;
use Flarum\Core\Notification;
use InvalidArgumentException;
class NotificationSerializer extends AbstractSerializer
{
/**
* {@inheritdoc}
*/
protected $type = 'notifications';
/**
* A map of notification types (key) to the serializer that should be used
* to output the notification's subject (value).
*
* @var array
*/
protected static $subjectSerializers = [];
/**
* {@inheritdoc}
*
* @param \Flarum\Core\Notification $notification
* @throws InvalidArgumentException
*/
protected function getDefaultAttributes($notification)
{
if (! ($notification instanceof Notification)) {
throw new InvalidArgumentException(get_class($this)
. ' can only serialize instances of ' . Notification::class);
}
return [
'id' => (int) $notification->id,
'contentType' => $notification->type,
'content' => $notification->data,
'time' => $this->formatDate($notification->time),
'isRead' => (bool) $notification->is_read
];
}
/**
* @return \Flarum\Api\Relationship\HasOneBuilder
*/
protected function user()
{
return $this->hasOne('Flarum\Api\Serializer\UserBasicSerializer');
}
/**
* @return \Flarum\Api\Relationship\HasOneBuilder
*/
protected function sender()
{
return $this->hasOne('Flarum\Api\Serializer\UserBasicSerializer');
}
/**
* @return \Flarum\Api\Relationship\HasOneBuilder
*/
protected function subject()
{
return $this->hasOne(function ($notification) {
return static::$subjectSerializers[$notification->type];
});
}
/**
* @param $type
* @param $serializer
*/
public static function setSubjectSerializer($type, $serializer)
{
static::$subjectSerializers[$type] = $serializer;
}
}

View File

@@ -0,0 +1,68 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Api\Serializer;
use Flarum\Core\Post\CommentPost;
use Flarum\Core\Post;
use InvalidArgumentException;
class PostBasicSerializer extends AbstractSerializer
{
/**
* {@inheritdoc}
*/
protected $type = 'posts';
/**
* {@inheritdoc}
*
* @param \Flarum\Core\Post $post
* @throws InvalidArgumentException
*/
protected function getDefaultAttributes($post)
{
if (! ($post instanceof Post)) {
throw new InvalidArgumentException(get_class($this)
. ' can only serialize instances of ' . Post::class);
}
$attributes = [
'id' => (int) $post->id,
'number' => (int) $post->number,
'time' => $this->formatDate($post->time),
'contentType' => $post->type
];
if ($post instanceof CommentPost) {
$attributes['contentHtml'] = $post->content_html;
} else {
$attributes['content'] = $post->content;
}
return $attributes;
}
/**
* @return \Flarum\Api\Relationship\HasOneBuilder
*/
protected function user()
{
return $this->hasOne('Flarum\Api\Serializer\UserBasicSerializer');
}
/**
* @return \Flarum\Api\Relationship\HasOneBuilder
*/
protected function discussion()
{
return $this->hasOne('Flarum\Api\Serializer\DiscussionBasicSerializer');
}
}

View File

@@ -0,0 +1,102 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Api\Serializer;
use Flarum\Core\Access\Gate;
use Flarum\Core\Post\CommentPost;
class PostSerializer extends PostBasicSerializer
{
/**
* @var \Flarum\Core\Access\Gate
*/
protected $gate;
/**
* @param \Flarum\Core\Access\Gate $gate
*/
public function __construct(Gate $gate)
{
$this->gate = $gate;
}
/**
* {@inheritdoc}
*/
protected function getDefaultAttributes($post)
{
$attributes = parent::getDefaultAttributes($post);
unset($attributes['content']);
$gate = $this->gate->forUser($this->actor);
$canEdit = $gate->allows('edit', $post);
if ($post instanceof CommentPost) {
$attributes['contentHtml'] = $post->content_html;
if ($canEdit) {
$attributes['content'] = $post->content;
}
} else {
$attributes['content'] = $post->content;
}
if ($post->edit_time) {
$attributes['editTime'] = $this->formatDate($post->edit_time);
}
if ($post->hide_time) {
$attributes['isHidden'] = true;
$attributes['hideTime'] = $this->formatDate($post->hide_time);
}
$attributes += [
'canEdit' => $canEdit,
'canDelete' => $gate->allows('delete', $post)
];
return $attributes;
}
/**
* @return \Flarum\Api\Relationship\HasOneBuilder
*/
protected function user()
{
return $this->hasOne('Flarum\Api\Serializer\UserSerializer');
}
/**
* @return \Flarum\Api\Relationship\HasOneBuilder
*/
protected function discussion()
{
return $this->hasOne('Flarum\Api\Serializer\DiscussionSerializer');
}
/**
* @return \Flarum\Api\Relationship\HasOneBuilder
*/
protected function editUser()
{
return $this->hasOne('Flarum\Api\Serializer\UserSerializer');
}
/**
* @return \Flarum\Api\Relationship\HasOneBuilder
*/
protected function hideUser()
{
return $this->hasOne('Flarum\Api\Serializer\UserSerializer');
}
}

View File

@@ -0,0 +1,49 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Api\Serializer;
use Flarum\Core\User;
use InvalidArgumentException;
class UserBasicSerializer extends AbstractSerializer
{
/**
* {@inheritdoc}
*/
protected $type = 'users';
/**
* {@inheritdoc}
*
* @param User $user
* @throws InvalidArgumentException
*/
protected function getDefaultAttributes($user)
{
if (! ($user instanceof User)) {
throw new InvalidArgumentException(get_class($this)
. ' can only serialize instances of ' . User::class);
}
return [
'username' => $user->username,
'avatarUrl' => $user->avatar_url
];
}
/**
* @return \Flarum\Api\Relationship\HasManyBuilder
*/
protected function groups()
{
return $this->hasMany('Flarum\Api\Serializer\GroupSerializer');
}
}

View File

@@ -0,0 +1,65 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Api\Serializer;
use Flarum\Core\Access\Gate;
class UserSerializer extends UserBasicSerializer
{
/**
* @var Gate
*/
protected $gate;
/**
* @param Gate $gate
*/
public function __construct(Gate $gate)
{
$this->gate = $gate;
}
/**
* {@inheritdoc}
*/
protected function getDefaultAttributes($user)
{
$attributes = parent::getDefaultAttributes($user);
$gate = $this->gate->forUser($this->actor);
$canEdit = $gate->allows('edit', $user);
$attributes += [
'bio' => $user->bio,
'joinTime' => $this->formatDate($user->join_time),
'discussionsCount' => (int) $user->discussions_count,
'commentsCount' => (int) $user->comments_count,
'canEdit' => $canEdit,
'canDelete' => $gate->allows('delete', $user),
];
if ($user->getPreference('discloseOnline')) {
$attributes += [
'lastSeenTime' => $this->formatDate($user->last_seen_time)
];
}
if ($canEdit || $this->actor->id === $user->id) {
$attributes += [
'isActivated' => $user->is_activated,
'email' => $user->email
];
}
return $attributes;
}
}