CommentTransformer.php 2.0 KB
<?php
/**
+-----------------------------------------------------------------------------------------------------------------------
 * 数据转换层: 评论转换类
+-----------------------------------------------------------------------------------------------------------------------
 *
 * @copyright   Copyright
 * @author      Richer
 * @package     App\Transformers\System
 * @version     2019年10月15日,16:03:49
 * @link
 */
namespace App\Transformers\System;

use App\Models\System\Comment;
use App\Transformers\BaseTransformer;

class CommentTransformer extends BaseTransformer
{
    public function transform(Comment $model)
    {
        return [

            'id'                => (int) $model->id,

            /* place your other model properties here */
            'commentable_type'  => (string)$model->commentable_type,
            'commentable_id'    => (int) $model->commentable_id,
            'comment'           => (string)$model->comment,
            'favorites_count'   => (int)$model->favorites_count,
            'votes_count'       => (int)$model->votes_count,
            'comments_count'    => (int)$model->comments_count,
            'voted'             => (int) !auth('api')->user() ? 0 : auth('api')->user()->hasUpvoted($model) === true ? 1 : 0,
            'created_at'        => format_date($model->created_at),
            'created_by'        => (int)$model->created_by,
            'created_at_month'  => format_date($model->created_at, 'm'),
            'created_at_day'    => format_date($model->created_at, 'd'),
            'author'            => $this->transformAuthor($model->commentator),
            'comments'          => $this->transformComments($model->comments),
        ];
    }

    /**
     *
     * @param $items
     * @return array
     */
    public function transformComments($items)
    {
        $array = [];
        foreach ($items as $item) {
            $array[count($array)] = $this-> transform($item);
        }
        return $array;
    }
}