1
0
mirror of https://gitee.com/koogua/course-tencent-cloud.git synced 2025-06-29 22:01:38 +08:00

清理代码

This commit is contained in:
xiaochong0302 2020-04-03 19:20:46 +08:00
parent f565e68e43
commit fd723e7e03
167 changed files with 1162 additions and 1300 deletions

View File

@ -9,9 +9,7 @@ class Builder extends Component
public function arrayToObject($array) public function arrayToObject($array)
{ {
$result = kg_array_object($array); return kg_array_object($array);
return $result;
} }
} }

View File

@ -56,7 +56,7 @@ class ChapterTreeList extends Builder
unset($attrs['file_id'], $attrs['file_status']); unset($attrs['file_id'], $attrs['file_status']);
} }
$result = [ return [
'id' => $chapter['id'], 'id' => $chapter['id'],
'title' => $chapter['title'], 'title' => $chapter['title'],
'summary' => $chapter['summary'], 'summary' => $chapter['summary'],
@ -64,8 +64,6 @@ class ChapterTreeList extends Builder
'free' => $chapter['free'], 'free' => $chapter['free'],
'attrs' => $attrs, 'attrs' => $attrs,
]; ];
return $result;
} }
} }

View File

@ -7,7 +7,6 @@ use App\Models\Course as CourseModel;
class CourseChapterUser extends Builder class CourseChapterUser extends Builder
{ {
/** /**
* 处理课时进度 * 处理课时进度
* *
@ -69,8 +68,7 @@ class CourseChapterUser extends Builder
} }
} }
return [
$result = [
'id' => $chapter['id'], 'id' => $chapter['id'],
'title' => $chapter['title'], 'title' => $chapter['title'],
'summary' => $chapter['summary'], 'summary' => $chapter['summary'],
@ -79,8 +77,6 @@ class CourseChapterUser extends Builder
'attrs' => $attrs, 'attrs' => $attrs,
'me' => $me, 'me' => $me,
]; ];
return $result;
} }
} }

View File

@ -60,7 +60,7 @@ class UserList extends Builder
protected function getEduRoles() protected function getEduRoles()
{ {
$result = [ return [
UserModel::EDU_ROLE_STUDENT => [ UserModel::EDU_ROLE_STUDENT => [
'id' => UserModel::EDU_ROLE_STUDENT, 'id' => UserModel::EDU_ROLE_STUDENT,
'name' => '学员', 'name' => '学员',
@ -70,8 +70,6 @@ class UserList extends Builder
'name' => '讲师', 'name' => '讲师',
], ],
]; ];
return $result;
} }
} }

View File

@ -0,0 +1,33 @@
<?php
namespace App\Caches;
class AccessToken extends Cache
{
protected $lifetime = 2 * 3600;
public function getLifetime()
{
return $this->lifetime;
}
public function getKey($id = null)
{
return "access_token:{$id}";
}
public function getContent($id = null)
{
$categoryRepo = new CategoryRepo();
$category = $categoryRepo->findById($id);
if (!$category) {
return new \stdClass();
}
return $category;
}
}

View File

@ -47,9 +47,7 @@ class CategoryTreeList extends Cache
$builder = new CategoryTreeListBuilder(); $builder = new CategoryTreeListBuilder();
$content = $builder->handleTreeList($items); return $builder->handleTreeList($items);
return $content;
} }
} }

View File

@ -47,9 +47,7 @@ class ChapterTreeList extends Cache
$builder = new ChapterTreeListBuilder(); $builder = new ChapterTreeListBuilder();
$content = $builder->handleTreeList($items); return $builder->handleTreeList($items);
return $content;
} }
} }

View File

@ -1,72 +0,0 @@
<?php
namespace App\Caches;
use App\Repos\Config as ConfigRepo;
class Config extends Cache
{
protected $lifetime = 365 * 86400;
/**
* 获取某组配置项
*
* @param string $section
* @return array
*/
public function getSectionConfig($section)
{
$items = $this->get();
$result = [];
if (!$items) {
return $result;
}
foreach ($items as $item) {
if ($item['section'] == $section) {
$result[$item['item_key']] = $item['item_value'];
}
}
return $result;
}
/**
* 获取某个配置项的值
*
* @param string $section
* @param string $key
* @return string|null
*/
public function getItemValue($section, $key)
{
$config = $this->getSectionConfig($section);
$result = $config[$key] ?? null;
return $result;
}
public function getLifetime()
{
return $this->lifetime;
}
public function getKey($id = null)
{
return 'config';
}
public function getContent($id = null)
{
$configRepo = new ConfigRepo();
$items = $configRepo->findAll();
return $items->toArray();
}
}

View File

@ -83,18 +83,14 @@ abstract class Counter extends Component
$this->get($id); $this->get($id);
} }
$value = $this->redis->hGet($key, $hashKey); return $this->redis->hGet($key, $hashKey);
return $value;
} }
public function hDel($id, $hashKey) public function hDel($id, $hashKey)
{ {
$key = $this->getKey($id); $key = $this->getKey($id);
$value = $this->redis->hDel($key, $hashKey); return $this->redis->hDel($key, $hashKey);
return $value;
} }
public function hIncrBy($id, $hashKey, $value = 1) public function hIncrBy($id, $hashKey, $value = 1)

View File

@ -2,8 +2,8 @@
namespace App\Caches; namespace App\Caches;
use App\Models\Category as CategoryModel;
use App\Repos\Course as CourseRepo; use App\Repos\Course as CourseRepo;
use Phalcon\Mvc\Model\Resultset;
class CourseCategoryList extends Cache class CourseCategoryList extends Cache
{ {
@ -24,9 +24,6 @@ class CourseCategoryList extends Cache
{ {
$courseRepo = new CourseRepo(); $courseRepo = new CourseRepo();
/**
* @var Resultset $categories
*/
$categories = $courseRepo->findCategories($id); $categories = $courseRepo->findCategories($id);
if ($categories->count() == 0) { if ($categories->count() == 0) {
@ -37,7 +34,7 @@ class CourseCategoryList extends Cache
} }
/** /**
* @param Resultset $categories * @param CategoryModel[] $categories
* @return array * @return array
*/ */
public function handleContent($categories) public function handleContent($categories)

View File

@ -5,7 +5,6 @@ namespace App\Caches;
use App\Models\Package as PackageModel; use App\Models\Package as PackageModel;
use App\Repos\Course as CourseRepo; use App\Repos\Course as CourseRepo;
use App\Repos\Package as PackageRepo; use App\Repos\Package as PackageRepo;
use Phalcon\Mvc\Model\Resultset;
class CoursePackageList extends Cache class CoursePackageList extends Cache
{ {
@ -26,9 +25,6 @@ class CoursePackageList extends Cache
{ {
$courseRepo = new CourseRepo(); $courseRepo = new CourseRepo();
/**
* @var Resultset $packages
*/
$packages = $courseRepo->findPackages($id); $packages = $courseRepo->findPackages($id);
if ($packages->count() == 0) { if ($packages->count() == 0) {

View File

@ -4,7 +4,6 @@ namespace App\Caches;
use App\Models\Course as CourseModel; use App\Models\Course as CourseModel;
use App\Repos\Course as CourseRepo; use App\Repos\Course as CourseRepo;
use Phalcon\Mvc\Model\Resultset;
class CourseRelatedList extends Cache class CourseRelatedList extends Cache
{ {
@ -25,9 +24,6 @@ class CourseRelatedList extends Cache
{ {
$courseRepo = new CourseRepo(); $courseRepo = new CourseRepo();
/**
* @var Resultset $courses
*/
$courses = $courseRepo->findRelatedCourses($id); $courses = $courseRepo->findRelatedCourses($id);
if ($courses->count() == 0) { if ($courses->count() == 0) {
@ -37,7 +33,6 @@ class CourseRelatedList extends Cache
return $this->handleContent($courses); return $this->handleContent($courses);
} }
/** /**
* @param CourseModel[] $courses * @param CourseModel[] $courses
* @return array * @return array

View File

@ -4,7 +4,6 @@ namespace App\Caches;
use App\Models\User as UserModel; use App\Models\User as UserModel;
use App\Repos\Course as CourseRepo; use App\Repos\Course as CourseRepo;
use Phalcon\Mvc\Model\Resultset;
class CourseTeacherList extends Cache class CourseTeacherList extends Cache
{ {
@ -25,9 +24,6 @@ class CourseTeacherList extends Cache
{ {
$courseRepo = new CourseRepo(); $courseRepo = new CourseRepo();
/**
* @var Resultset $users
*/
$users = $courseRepo->findTeachers($id); $users = $courseRepo->findTeachers($id);
if ($users->count() == 0) { if ($users->count() == 0) {

View File

@ -3,8 +3,8 @@
namespace App\Caches; namespace App\Caches;
use App\Models\Course as CourseModel; use App\Models\Course as CourseModel;
use App\Repos\Course as CourseRepo;
use Phalcon\Mvc\Model\Resultset; use Phalcon\Mvc\Model\Resultset;
use Phalcon\Mvc\Model\ResultsetInterface;
class HotCourseList extends Cache class HotCourseList extends Cache
{ {
@ -23,12 +23,7 @@ class HotCourseList extends Cache
public function getContent($id = null) public function getContent($id = null)
{ {
$courseRepo = new CourseRepo(); $courses = $this->findHotCourses($id);
/**
* @var Resultset $courses
*/
$courses = $courseRepo->findRelatedCourses($id);
if ($courses->count() == 0) { if ($courses->count() == 0) {
return []; return [];
@ -61,4 +56,17 @@ class HotCourseList extends Cache
return $result; return $result;
} }
/**
* @param int $limit
* @return ResultsetInterface|Resultset|CourseModel[]
*/
protected function findHotCourses($limit = 10)
{
return CourseModel::query()
->where('deleted = 0')
->orderBy('score DESC')
->limit($limit)
->execute();
}
} }

View File

@ -3,8 +3,8 @@
namespace App\Caches; namespace App\Caches;
use App\Models\Course as CourseModel; use App\Models\Course as CourseModel;
use App\Repos\Course as CourseRepo;
use Phalcon\Mvc\Model\Resultset; use Phalcon\Mvc\Model\Resultset;
use Phalcon\Mvc\Model\ResultsetInterface;
class LatestCourseList extends Cache class LatestCourseList extends Cache
{ {
@ -23,12 +23,7 @@ class LatestCourseList extends Cache
public function getContent($id = null) public function getContent($id = null)
{ {
$courseRepo = new CourseRepo(); $courses = $this->findLatestCourses(5);
/**
* @var Resultset $courses
*/
$courses = $courseRepo->findRelatedCourses($id);
if ($courses->count() == 0) { if ($courses->count() == 0) {
return []; return [];
@ -37,7 +32,6 @@ class LatestCourseList extends Cache
return $this->handleContent($courses); return $this->handleContent($courses);
} }
/** /**
* @param CourseModel[] $courses * @param CourseModel[] $courses
* @return array * @return array
@ -67,4 +61,17 @@ class LatestCourseList extends Cache
return $result; return $result;
} }
/**
* @param int $limit
* @return ResultsetInterface|Resultset|CourseModel[]
*/
protected function findLatestCourses($limit = 10)
{
return CourseModel::query()
->where('deleted = 0')
->orderBy('created_at DESC')
->limit($limit)
->execute();
}
} }

View File

@ -59,12 +59,10 @@ class NavTreeList extends Cache
$builder = new NavTreeListBuilder(); $builder = new NavTreeListBuilder();
$content = [ return [
'top' => $builder->handleTreeList($list['top']), 'top' => $builder->handleTreeList($list['top']),
'bottom' => $builder->handleTreeList($list['bottom']), 'bottom' => $builder->handleTreeList($list['bottom']),
]; ];
return $content;
} }
} }

View File

@ -23,7 +23,7 @@ class SlideList extends Cache
public function getContent($id = null) public function getContent($id = null)
{ {
/** /**
* @var Resultset $slides * @var Resultset|SlideModel[] $slides
*/ */
$slides = SlideModel::query() $slides = SlideModel::query()
->columns(['id', 'title', 'cover', 'summary', 'target', 'content']) ->columns(['id', 'title', 'cover', 'summary', 'target', 'content'])

View File

@ -11,9 +11,7 @@ class UserDailyCounter extends Counter
{ {
$tomorrow = strtotime('tomorrow'); $tomorrow = strtotime('tomorrow');
$lifetime = $tomorrow - time(); return $tomorrow - time();
return $lifetime;
} }
public function getKey($id = null) public function getKey($id = null)
@ -23,7 +21,7 @@ class UserDailyCounter extends Counter
public function getContent($id = null) public function getContent($id = null)
{ {
$content = [ return [
'favorite_count' => 0, 'favorite_count' => 0,
'comment_count' => 0, 'comment_count' => 0,
'consult_count' => 0, 'consult_count' => 0,
@ -33,8 +31,6 @@ class UserDailyCounter extends Counter
'consult_vote_count' => 0, 'consult_vote_count' => 0,
'review_vote_count' => 0, 'review_vote_count' => 0,
]; ];
return $content;
} }
} }

View File

@ -36,13 +36,11 @@ class CloseOrderTask extends Task
$createdAt = time() - 12 * 3600; $createdAt = time() - 12 * 3600;
$orders = OrderModel::query() return OrderModel::query()
->where('status = :status:', ['status' => $status]) ->where('status = :status:', ['status' => $status])
->andWhere('created_at < :created_at:', ['created_at' => $createdAt]) ->andWhere('created_at < :created_at:', ['created_at' => $createdAt])
->limit($limit) ->limit($limit)
->execute(); ->execute();
return $orders;
} }
} }

View File

@ -75,13 +75,11 @@ class CloseTradeTask extends Task
$createdAt = time() - 15 * 60; $createdAt = time() - 15 * 60;
$trades = TradeModel::query() return TradeModel::query()
->where('status = :status:', ['status' => $status]) ->where('status = :status:', ['status' => $status])
->andWhere('created_at < :created_at:', ['created_at' => $createdAt]) ->andWhere('created_at < :created_at:', ['created_at' => $createdAt])
->limit($limit) ->limit($limit)
->execute(); ->execute();
return $trades;
} }
} }

View File

@ -2,7 +2,6 @@
namespace App\Console\Tasks; namespace App\Console\Tasks;
use App\Models\Category as CategoryModel;
use App\Repos\Category as CategoryRepo; use App\Repos\Category as CategoryRepo;
use Phalcon\Cli\Task; use Phalcon\Cli\Task;
@ -15,9 +14,6 @@ class CountCourseTask extends Task
$mapping = []; $mapping = [];
/**
* @var CategoryModel[] $subCategories
*/
$subCategories = $categoryRepo->findAll(['level' => 2, 'deleted' => 0]); $subCategories = $categoryRepo->findAll(['level' => 2, 'deleted' => 0]);
foreach ($subCategories as $category) { foreach ($subCategories as $category) {
@ -35,9 +31,6 @@ class CountCourseTask extends Task
} }
} }
/**
* @var CategoryModel[] $topCategories
*/
$topCategories = $categoryRepo->findAll(['level' => 1, 'deleted' => 0]); $topCategories = $categoryRepo->findAll(['level' => 1, 'deleted' => 0]);
foreach ($topCategories as $category) { foreach ($topCategories as $category) {

View File

@ -68,24 +68,20 @@ class LiveNoticeProviderTask extends Task
CourseUserModel::SOURCE_IMPORT, CourseUserModel::SOURCE_IMPORT,
]; ];
$rows = $this->modelsManager->createBuilder() return $this->modelsManager->createBuilder()
->columns(['cu.course_id', 'cu.user_id', 'cl.chapter_id', 'cl.start_time']) ->columns(['cu.course_id', 'cu.user_id', 'cl.chapter_id', 'cl.start_time'])
->addFrom(ChapterLiveModel::class, 'cl') ->addFrom(ChapterLiveModel::class, 'cl')
->join(CourseUserModel::class, 'cl.course_id = cu.course_id', 'cu') ->join(CourseUserModel::class, 'cl.course_id = cu.course_id', 'cu')
->inWhere('cu.source_type', $sourceTypes) ->inWhere('cu.source_type', $sourceTypes)
->betweenWhere('start_time', $beginTime, $endTime) ->betweenWhere('start_time', $beginTime, $endTime)
->getQuery()->execute(); ->getQuery()->execute();
return $rows;
} }
public function getLifetime() public function getLifetime()
{ {
$tomorrow = strtotime('tomorrow'); $tomorrow = strtotime('tomorrow');
$lifetime = $tomorrow - time(); return $tomorrow - time();
return $lifetime;
} }
public function getCacheKey() public function getCacheKey()

View File

@ -110,23 +110,19 @@ class ManageCourseIndexTask extends Task
{ {
$searcher = new CourseSearch(); $searcher = new CourseSearch();
$result = $searcher->search($query); return $searcher->search($query);
return $result;
} }
/** /**
* 查找课程 * 查找课程
* *
* @return Resultset|ResultsetInterface * @return ResultsetInterface|Resultset|CourseModel[]
*/ */
protected function findCourses() protected function findCourses()
{ {
$courses = CourseModel::query() return CourseModel::query()
->where('published = 1') ->where('published = 1')
->execute(); ->execute();
return $courses;
} }
} }

View File

@ -225,13 +225,11 @@ class OrderTask extends Task
{ {
$status = TradeModel::STATUS_FINISHED; $status = TradeModel::STATUS_FINISHED;
$result = TradeModel::findFirst([ return TradeModel::findFirst([
'conditions' => ['order_id = :order_id: AND status = :status:'], 'conditions' => ['order_id = :order_id: AND status = :status:'],
'bind' => ['order_id' => $orderId, 'status' => $status], 'bind' => ['order_id' => $orderId, 'status' => $status],
'order' => 'id DESC', 'order' => 'id DESC',
]); ]);
return $result;
} }
/** /**
@ -244,15 +242,13 @@ class OrderTask extends Task
$status = TaskModel::STATUS_PENDING; $status = TaskModel::STATUS_PENDING;
$tryCount = self::TRY_COUNT; $tryCount = self::TRY_COUNT;
$tasks = TaskModel::query() return TaskModel::query()
->where('item_type = :item_type:', ['item_type' => $itemType]) ->where('item_type = :item_type:', ['item_type' => $itemType])
->andWhere('status = :status:', ['status' => $status]) ->andWhere('status = :status:', ['status' => $status])
->andWhere('try_count < :try_count:', ['try_count' => $tryCount]) ->andWhere('try_count < :try_count:', ['try_count' => $tryCount])
->orderBy('priority ASC') ->orderBy('priority ASC')
->limit($limit) ->limit($limit)
->execute(); ->execute();
return $tasks;
} }
} }

View File

@ -4,6 +4,7 @@ namespace App\Console\Tasks;
use App\Caches\Chapter as ChapterCache; use App\Caches\Chapter as ChapterCache;
use App\Caches\ChapterCounter as ChapterCounterCache; use App\Caches\ChapterCounter as ChapterCounterCache;
use App\Library\Cache\Backend\Redis as RedisCache;
use App\Repos\Chapter as ChapterRepo; use App\Repos\Chapter as ChapterRepo;
use App\Services\ChapterCacheSyncer; use App\Services\ChapterCacheSyncer;
use Phalcon\Mvc\Model\Resultset; use Phalcon\Mvc\Model\Resultset;
@ -12,7 +13,7 @@ class RebuildChapterCacheTask extends Task
{ {
/** /**
* @var \App\Library\Cache\Backend\Redis * @var RedisCache
*/ */
protected $cache; protected $cache;

View File

@ -277,15 +277,13 @@ class RefundTask extends Task
$status = TaskModel::STATUS_PENDING; $status = TaskModel::STATUS_PENDING;
$tryCount = self::TRY_COUNT; $tryCount = self::TRY_COUNT;
$tasks = TaskModel::query() return TaskModel::query()
->where('item_type = :item_type:', ['item_type' => $itemType]) ->where('item_type = :item_type:', ['item_type' => $itemType])
->andWhere('status = :status:', ['status' => $status]) ->andWhere('status = :status:', ['status' => $status])
->andWhere('try_count < :try_count:', ['try_count' => $tryCount]) ->andWhere('try_count < :try_count:', ['try_count' => $tryCount])
->orderBy('priority ASC') ->orderBy('priority ASC')
->limit($limit) ->limit($limit)
->execute(); ->execute();
return $tasks;
} }
} }

View File

@ -34,13 +34,11 @@ class RevokeVipTask extends Task
{ {
$time = time(); $time = time();
$users = UserModel::query() return UserModel::query()
->where('vip = 1') ->where('vip = 1')
->andWhere('vip_expiry < :time:', ['time' => $time]) ->andWhere('vip_expiry_time < :time:', ['time' => $time])
->limit($limit) ->limit($limit)
->execute(); ->execute();
return $users;
} }
} }

View File

@ -28,19 +28,17 @@ class UnlockUserTask extends Task
* 查找待解锁用户 * 查找待解锁用户
* *
* @param int $limit * @param int $limit
* @return UserModel[]|Resultset|ResultsetInterface * @return ResultsetInterface|Resultset|UserModel[]
*/ */
protected function findUsers($limit = 1000) protected function findUsers($limit = 1000)
{ {
$time = time() - 6 * 3600; $time = time() - 6 * 3600;
$users = UserModel::query() return UserModel::query()
->where('locked = 1') ->where('locked = 1')
->andWhere('lock_expiry < :time:', ['time' => $time]) ->andWhere('lock_expiry_time < :time:', ['time' => $time])
->limit($limit) ->limit($limit)
->execute(); ->execute();
return $users;
} }
} }

View File

@ -127,27 +127,21 @@ class VodEventTask extends Task
{ {
$vodService = new VodService(); $vodService = new VodService();
$result = $vodService->pullEvents(); return $vodService->pullEvents();
return $result;
} }
protected function confirmEvents($handles) protected function confirmEvents($handles)
{ {
$vodService = new VodService(); $vodService = new VodService();
$result = $vodService->confirmEvents($handles); return $vodService->confirmEvents($handles);
return $result;
} }
protected function isAudioFile($format) protected function isAudioFile($format)
{ {
$formats = ['mp3', 'm4a', 'wav', 'flac', 'ogg']; $formats = ['mp3', 'm4a', 'wav', 'flac', 'ogg'];
$result = in_array(strtolower($format), $formats); return in_array(strtolower($format), $formats);
return $result;
} }
protected function updateVodAttrs($courseId) protected function updateVodAttrs($courseId)

View File

@ -61,7 +61,7 @@ class TestController extends Controller
$pushUrl = $liveService->getPushUrl('test'); $pushUrl = $liveService->getPushUrl('test');
$codeUrl = $this->url->get( $codeUrl = $this->url->get(
['for' => 'home.qr.img'], ['for' => 'web.qr.img'],
['text' => urlencode($pushUrl)] ['text' => urlencode($pushUrl)]
); );
@ -178,7 +178,7 @@ class TestController extends Controller
if ($code) { if ($code) {
$codeUrl = $this->url->get( $codeUrl = $this->url->get(
['for' => 'home.qr.img'], ['for' => 'web.qr.img'],
['text' => urlencode($code)] ['text' => urlencode($code)]
); );
} }

View File

@ -27,8 +27,7 @@ class Module implements ModuleDefinitionInterface
}); });
$di->setShared('auth', function () { $di->setShared('auth', function () {
$authUser = new AdminAuthUser(); return new AdminAuthUser();
return $authUser;
}); });
} }

View File

@ -43,6 +43,7 @@
<tr> <tr>
<th>课程</th> <th>课程</th>
<th>课时数</th> <th>课时数</th>
<th>用户数</th>
<th>价格</th> <th>价格</th>
<th>发布</th> <th>发布</th>
<th>操作</th> <th>操作</th>
@ -60,6 +61,11 @@
<span class="layui-badge layui-bg-green">{{ item.lesson_count }}</span> <span class="layui-badge layui-bg-green">{{ item.lesson_count }}</span>
</a> </a>
</td> </td>
<td>
<a href="{{ url({'for':'admin.student.list'},{'course_id':item.id}) }}">
<span class="layui-badge layui-bg-green">{{ item.user_count }}</span>
</a>
</td>
<td> <td>
<p>市场:¥{{ item.market_price }}</p> <p>市场:¥{{ item.market_price }}</p>
<p>会员:¥{{ item.vip_price }}</p> <p>会员:¥{{ item.vip_price }}</p>

View File

@ -37,7 +37,7 @@
</dl> </dl>
</li> </li>
<li class="layui-nav-item"> <li class="layui-nav-item">
<a href="{{ url({'for':'home.index'}) }}" target="_blank">前台</a> <a href="{{ url({'for':'web.index'}) }}" target="_blank">前台</a>
</li> </li>
</ul> </ul>
</div> </div>

View File

@ -34,7 +34,7 @@ class IndexController extends Controller
} }
} }
dd($definitions); return $this->jsonSuccess(['routes' => $definitions]);
} }
} }

View File

@ -2,7 +2,7 @@
namespace App\Http\Api; namespace App\Http\Api;
use App\Services\AuthUser\Home as ApiAuthUser; use App\Services\AuthUser\Web as ApiAuthUser;
use Phalcon\DiInterface; use Phalcon\DiInterface;
use Phalcon\Mvc\ModuleDefinitionInterface; use Phalcon\Mvc\ModuleDefinitionInterface;
use Phalcon\Mvc\View; use Phalcon\Mvc\View;
@ -24,8 +24,8 @@ class Module implements ModuleDefinitionInterface
}); });
$di->setShared('auth', function () { $di->setShared('auth', function () {
$authUser = new ApiAuthUser(); return new ApiAuthUser();
return $authUser;
}); });
} }
} }

View File

@ -1,10 +1,9 @@
<?php <?php
namespace App\Services\Frontend\Account; namespace App\Http\Api\Services;
use App\Services\Frontend\Service; use App\Services\Frontend\Service;
use App\Validators\Account as AccountValidator; use App\Validators\Account as AccountValidator;
use App\Validators\Security as SecurityValidator;
class Login extends Service class Login extends Service
{ {
@ -14,15 +13,18 @@ class Login extends Service
$validator = new AccountValidator(); $validator = new AccountValidator();
$user = $validator->checkUserLogin($account, $password); $user = $validator->checkUserLogin($account, $password);
return $user;
} }
public function loginByVerify($account, $code) public function loginByVerify($account, $code)
{ {
$validator = new SecurityValidator(); $validator = new AccountValidator();
$user = $validator->checkVerifyLogin($account, $code);
}
protected function grantAuthToken()
{
$validator->checkVerifyCode($account, $code);
} }
} }

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Html5\Controllers;
use App\Traits\Response as ResponseTrait;
class Controller extends \Phalcon\Mvc\Controller
{
use ResponseTrait;
public function initialize()
{
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace App\Http\Html5\Controllers;
/**
* @RoutePrefix("/mobile")
*/
class IndexController extends Controller
{
/**
* @Get("/", name="mobile.index")
*/
public function indexAction()
{
}
/**
* @Get("/routes", name="mobile.routes")
*/
public function routesAction()
{
$definitions = [];
$routes = $this->router->getRoutes();
foreach ($routes as $route) {
if (strpos($route->getPattern(), '/api') !== false) {
$definitions[] = [
'pattern' => $route->getPattern(),
'methods' => $route->getHttpMethods(),
];
}
}
return $this->jsonSuccess(['routes' => $definitions]);
}
}

31
app/Http/Html5/Module.php Normal file
View File

@ -0,0 +1,31 @@
<?php
namespace App\Http\Html5;
use App\Services\AuthUser\Html5 as Html5AuthUser;
use Phalcon\DiInterface;
use Phalcon\Mvc\ModuleDefinitionInterface;
use Phalcon\Mvc\View;
class Module implements ModuleDefinitionInterface
{
public function registerAutoLoaders(DiInterface $di = null)
{
}
public function registerServices(DiInterface $di)
{
$di->setShared('view', function () {
$view = new View();
$view->disable();
return $view;
});
$di->setShared('auth', function () {
return new Html5AuthUser();
});
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace App\Http\Html5\Services;
use App\Validators\Account as AccountValidator;
class Login extends Service
{
public function loginByPassword($account, $password)
{
$validator = new AccountValidator();
$user = $validator->checkUserLogin($account, $password);
}
public function loginByVerify($account, $code)
{
$validator = new AccountValidator();
$user = $validator->checkVerifyLogin($account, $code);
}
protected function grantAuthToken()
{
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace App\Http\Html5\Services;
class Logout extends Service
{
public function logoutBySession()
{
}
public function logoutByToken()
{
}
}

View File

@ -1,6 +1,6 @@
<?php <?php
namespace App\Http\Home\Services; namespace App\Http\Html5\Services;
use App\Traits\Auth as AuthTrait; use App\Traits\Auth as AuthTrait;
use Phalcon\Mvc\User\Component; use Phalcon\Mvc\User\Component;
@ -9,5 +9,4 @@ class Service extends Component
{ {
use AuthTrait; use AuthTrait;
} }

View File

@ -1,8 +1,8 @@
<?php <?php
namespace App\Http\Home\Controllers; namespace App\Http\Web\Controllers;
use App\Http\Home\Services\Account as AccountService; use App\Http\Web\Services\Account as AccountService;
/** /**
* @RoutePrefix("/account") * @RoutePrefix("/account")
@ -11,7 +11,7 @@ class AccountController extends Controller
{ {
/** /**
* @Post("/signup", name="home.account.signup") * @Post("/signup", name="web.account.signup")
*/ */
public function signupAction() public function signupAction()
{ {
@ -25,7 +25,7 @@ class AccountController extends Controller
} }
/** /**
* @Route("/login", name="home.account.login") * @Route("/login", name="web.account.login")
*/ */
public function loginAction() public function loginAction()
{ {
@ -39,7 +39,7 @@ class AccountController extends Controller
} }
/** /**
* @Get("/logout", name="home.account.logout") * @Get("/logout", name="web.account.logout")
*/ */
public function logoutAction() public function logoutAction()
{ {
@ -47,11 +47,11 @@ class AccountController extends Controller
$service->logout(); $service->logout();
$this->response->redirect(['for' => 'home.index']); $this->response->redirect(['for' => 'web.index']);
} }
/** /**
* @Route("/password/reset", name="home.account.reset_password") * @Route("/password/reset", name="web.account.reset_password")
*/ */
public function resetPasswordAction() public function resetPasswordAction()
{ {
@ -63,7 +63,7 @@ class AccountController extends Controller
} }
/** /**
* @Post("/mobile/update", name="home.account.update_mobile") * @Post("/mobile/update", name="web.account.update_mobile")
*/ */
public function updateMobileAction() public function updateMobileAction()
{ {
@ -75,7 +75,7 @@ class AccountController extends Controller
} }
/** /**
* @Post("/password/update", name="home.account.update_password") * @Post("/password/update", name="web.account.update_password")
*/ */
public function updatePasswordAction() public function updatePasswordAction()
{ {
@ -87,7 +87,7 @@ class AccountController extends Controller
} }
/** /**
* @Post("/captcha/send", name="home.account.send_captcha") * @Post("/captcha/send", name="web.account.send_captcha")
*/ */
public function sendCaptchaAction() public function sendCaptchaAction()
{ {

View File

@ -1,8 +1,8 @@
<?php <?php
namespace App\Http\Home\Controllers; namespace App\Http\Web\Controllers;
use App\Http\Home\Services\Chapter as ChapterService; use App\Http\Web\Services\Chapter as ChapterService;
/** /**
* @RoutePrefix("/chapter") * @RoutePrefix("/chapter")
@ -11,7 +11,7 @@ class ChapterController extends Controller
{ {
/** /**
* @Get("/{id:[0-9]+}", name="home.chapter.show") * @Get("/{id:[0-9]+}", name="web.chapter.show")
*/ */
public function showAction($id) public function showAction($id)
{ {
@ -23,7 +23,7 @@ class ChapterController extends Controller
} }
/** /**
* @Get("/{id:[0-9]+}/comments", name="home.chapter.comments") * @Get("/{id:[0-9]+}/comments", name="web.chapter.comments")
*/ */
public function commentsAction($id) public function commentsAction($id)
{ {
@ -35,7 +35,7 @@ class ChapterController extends Controller
} }
/** /**
* @Post("/{id:[0-9]+}/agree", name="home.chapter.agree") * @Post("/{id:[0-9]+}/agree", name="web.chapter.agree")
*/ */
public function agreeAction($id) public function agreeAction($id)
{ {
@ -47,7 +47,7 @@ class ChapterController extends Controller
} }
/** /**
* @Post("/{id:[0-9]+}/oppose", name="home.chapter.oppose") * @Post("/{id:[0-9]+}/oppose", name="web.chapter.oppose")
*/ */
public function opposeAction($id) public function opposeAction($id)
{ {
@ -59,7 +59,7 @@ class ChapterController extends Controller
} }
/** /**
* @Post("/{id:[0-9]+}/position", name="home.chapter.position") * @Post("/{id:[0-9]+}/position", name="web.chapter.position")
*/ */
public function positionAction($id) public function positionAction($id)
{ {
@ -71,7 +71,7 @@ class ChapterController extends Controller
} }
/** /**
* @Post("/{id:[0-9]+}/finish", name="home.chapter.finish") * @Post("/{id:[0-9]+}/finish", name="web.chapter.finish")
*/ */
public function finishAction($id) public function finishAction($id)
{ {

View File

@ -1,6 +1,6 @@
<?php <?php
namespace App\Http\Home\Controllers; namespace App\Http\Web\Controllers;
use App\Caches\Config as ConfigCache; use App\Caches\Config as ConfigCache;
use App\Caches\NavTreeList as NavTreeListCache; use App\Caches\NavTreeList as NavTreeListCache;

View File

@ -1,6 +1,6 @@
<?php <?php
namespace App\Http\Home\Controllers; namespace App\Http\Web\Controllers;
use App\Services\Frontend\Course as CourseService; use App\Services\Frontend\Course as CourseService;
use App\Services\Frontend\CourseList as CourseListService; use App\Services\Frontend\CourseList as CourseListService;
@ -15,7 +15,7 @@ class CourseController extends Controller
{ {
/** /**
* @Get("/list", name="home.course.list") * @Get("/list", name="web.course.list")
*/ */
public function listAction() public function listAction()
{ {
@ -29,7 +29,7 @@ class CourseController extends Controller
} }
/** /**
* @Get("/{id:[0-9]+}", name="home.course.show") * @Get("/{id:[0-9]+}", name="web.course.show")
*/ */
public function showAction($id) public function showAction($id)
{ {
@ -43,7 +43,7 @@ class CourseController extends Controller
} }
/** /**
* @Get("/{id:[0-9]+}/related", name="home.course.related") * @Get("/{id:[0-9]+}/related", name="web.course.related")
*/ */
public function relatedAction($id) public function relatedAction($id)
{ {
@ -57,7 +57,7 @@ class CourseController extends Controller
} }
/** /**
* @Get("/{id:[0-9]+}/reviews", name="home.course.reviews") * @Get("/{id:[0-9]+}/reviews", name="web.course.reviews")
*/ */
public function reviewsAction($id) public function reviewsAction($id)
{ {
@ -71,7 +71,7 @@ class CourseController extends Controller
} }
/** /**
* @Post("/{id:[0-9]+}/favorite", name="home.course.favorite") * @Post("/{id:[0-9]+}/favorite", name="web.course.favorite")
*/ */
public function favoriteAction($id) public function favoriteAction($id)
{ {

View File

@ -1,6 +1,6 @@
<?php <?php
namespace App\Http\Home\Controllers; namespace App\Http\Web\Controllers;
use App\Traits\Response as ResponseTrait; use App\Traits\Response as ResponseTrait;
use Phalcon\Mvc\View; use Phalcon\Mvc\View;
@ -19,7 +19,7 @@ class ErrorController extends \Phalcon\Mvc\Controller
} }
/** /**
* @Get("/400", name="home.error.400") * @Get("/400", name="web.error.400")
*/ */
public function show400Action() public function show400Action()
{ {
@ -27,7 +27,7 @@ class ErrorController extends \Phalcon\Mvc\Controller
} }
/** /**
* @Get("/401", name="home.error.401") * @Get("/401", name="web.error.401")
*/ */
public function show401Action() public function show401Action()
{ {
@ -35,7 +35,7 @@ class ErrorController extends \Phalcon\Mvc\Controller
} }
/** /**
* @Get("/403", name="home.error.403") * @Get("/403", name="web.error.403")
*/ */
public function show403Action() public function show403Action()
{ {
@ -43,7 +43,7 @@ class ErrorController extends \Phalcon\Mvc\Controller
} }
/** /**
* @Get("/404", name="home.error.404") * @Get("/404", name="web.error.404")
*/ */
public function show404Action() public function show404Action()
{ {
@ -55,7 +55,7 @@ class ErrorController extends \Phalcon\Mvc\Controller
} }
/** /**
* @Get("/500", name="home.error.500") * @Get("/500", name="web.error.500")
*/ */
public function show500Action() public function show500Action()
{ {

View File

@ -1,12 +1,12 @@
<?php <?php
namespace App\Http\Home\Controllers; namespace App\Http\Web\Controllers;
class IndexController extends Controller class IndexController extends Controller
{ {
/** /**
* @Get("/", name="home.index") * @Get("/", name="web.index")
*/ */
public function indexAction() public function indexAction()
{ {

View File

@ -1,8 +1,8 @@
<?php <?php
namespace App\Http\Home\Controllers; namespace App\Http\Web\Controllers;
use App\Http\Home\Services\My as MyService; use App\Http\Web\Services\My as MyService;
/** /**
* @RoutePrefix("/my") * @RoutePrefix("/my")
@ -11,7 +11,7 @@ class MyController extends Controller
{ {
/** /**
* @Get("/courses", name="home.my.courses") * @Get("/courses", name="web.my.courses")
*/ */
public function coursesAction() public function coursesAction()
{ {
@ -25,7 +25,7 @@ class MyController extends Controller
} }
/** /**
* @Get("/consults", name="home.my.consults") * @Get("/consults", name="web.my.consults")
*/ */
public function consultsAction() public function consultsAction()
{ {
@ -37,7 +37,7 @@ class MyController extends Controller
} }
/** /**
* @Get("/reviews", name="home.my.reviews") * @Get("/reviews", name="web.my.reviews")
*/ */
public function reviewsAction() public function reviewsAction()
{ {
@ -49,7 +49,7 @@ class MyController extends Controller
} }
/** /**
* @Get("/orders", name="home.my.orders") * @Get("/orders", name="web.my.orders")
*/ */
public function ordersAction() public function ordersAction()
{ {
@ -63,7 +63,7 @@ class MyController extends Controller
} }
/** /**
* @Get("/coupons", name="home.my.coupons") * @Get("/coupons", name="web.my.coupons")
*/ */
public function couponsAction() public function couponsAction()
{ {
@ -75,7 +75,7 @@ class MyController extends Controller
} }
/** /**
* @Get("/balance", name="home.my.balance") * @Get("/balance", name="web.my.balance")
*/ */
public function balanceAction() public function balanceAction()
{ {

View File

@ -1,6 +1,6 @@
<?php <?php
namespace App\Http\Home\Controllers; namespace App\Http\Web\Controllers;
use App\Models\Order as OrderModel; use App\Models\Order as OrderModel;
use Home\Services\Order as OrderService; use Home\Services\Order as OrderService;
@ -12,7 +12,7 @@ class OrderController extends Controller
{ {
/** /**
* @Post("/confirm", name="home.order.confirm") * @Post("/confirm", name="web.order.confirm")
*/ */
public function confirmAction() public function confirmAction()
{ {
@ -52,7 +52,7 @@ class OrderController extends Controller
} }
/** /**
* @Post("/create", name="home.order.create") * @Post("/create", name="web.order.create")
*/ */
public function createAction() public function createAction()
{ {
@ -64,7 +64,7 @@ class OrderController extends Controller
} }
/** /**
* @Get("/cashier", name="home.order.cashier") * @Get("/cashier", name="web.order.cashier")
*/ */
public function cashierAction() public function cashierAction()
{ {
@ -82,7 +82,7 @@ class OrderController extends Controller
} }
/** /**
* @Post("/pay", name="home.order.pay") * @Post("/pay", name="web.order.pay")
*/ */
public function payAction() public function payAction()
{ {
@ -102,7 +102,7 @@ class OrderController extends Controller
} }
/** /**
* @Post("/notify/{channel}", name="home.order.notify") * @Post("/notify/{channel}", name="web.order.notify")
*/ */
public function notifyAction($channel) public function notifyAction($channel)
{ {
@ -112,7 +112,7 @@ class OrderController extends Controller
} }
/** /**
* @Post("/status", name="home.order.status") * @Post("/status", name="web.order.status")
*/ */
public function statusAction() public function statusAction()
{ {
@ -128,7 +128,7 @@ class OrderController extends Controller
} }
/** /**
* @Post("/cancel", name="home.order.cancel") * @Post("/cancel", name="web.order.cancel")
*/ */
public function cancelAction() public function cancelAction()
{ {

View File

@ -1,6 +1,6 @@
<?php <?php
namespace App\Http\Home\Controllers; namespace App\Http\Web\Controllers;
use App\Services\Payment\Alipay as AlipayService; use App\Services\Payment\Alipay as AlipayService;
use App\Services\Payment\Wxpay as WxpayService; use App\Services\Payment\Wxpay as WxpayService;
@ -12,7 +12,7 @@ class PaymentController extends \Phalcon\Mvc\Controller
use ResponseTrait; use ResponseTrait;
/** /**
* @Post("/alipay/notify", name="home.alipay.notify") * @Post("/alipay/notify", name="web.alipay.notify")
*/ */
public function alipayNotifyAction() public function alipayNotifyAction()
{ {
@ -28,7 +28,7 @@ class PaymentController extends \Phalcon\Mvc\Controller
} }
/** /**
* @Post("/wxpay/notify", name="home.wxpay.notify") * @Post("/wxpay/notify", name="web.wxpay.notify")
*/ */
public function wxpayNotifyAction() public function wxpayNotifyAction()
{ {
@ -44,7 +44,7 @@ class PaymentController extends \Phalcon\Mvc\Controller
} }
/** /**
* @Post("/alipay/status", name="home.alipay.status") * @Post("/alipay/status", name="web.alipay.status")
*/ */
public function alipayStatusAction() public function alipayStatusAction()
{ {
@ -58,7 +58,7 @@ class PaymentController extends \Phalcon\Mvc\Controller
} }
/** /**
* @Post("/wxpay/status", name="home.wxpay.status") * @Post("/wxpay/status", name="web.wxpay.status")
*/ */
public function wxpayStatusAction() public function wxpayStatusAction()
{ {

View File

@ -1,6 +1,6 @@
<?php <?php
namespace App\Http\Home\Controllers; namespace App\Http\Web\Controllers;
use App\Models\ContentImage as ContentImageModel; use App\Models\ContentImage as ContentImageModel;
use App\Services\Storage as StorageService; use App\Services\Storage as StorageService;
@ -13,7 +13,7 @@ class PublicController extends \Phalcon\Mvc\Controller
use ResponseTrait; use ResponseTrait;
/** /**
* @Route("/auth", name="home.auth") * @Route("/auth", name="web.auth")
*/ */
public function authAction() public function authAction()
{ {
@ -21,11 +21,11 @@ class PublicController extends \Phalcon\Mvc\Controller
return $this->jsonError(['msg' => '会话已过期,请重新登录']); return $this->jsonError(['msg' => '会话已过期,请重新登录']);
} }
$this->response->redirect(['for' => 'home.login']); $this->response->redirect(['for' => 'web.login']);
} }
/** /**
* @Route("/robot", name="home.robot") * @Route("/robot", name="web.robot")
*/ */
public function robotAction() public function robotAction()
{ {
@ -35,7 +35,7 @@ class PublicController extends \Phalcon\Mvc\Controller
} }
/** /**
* @Route("/forbidden", name="home.forbidden") * @Route("/forbidden", name="web.forbidden")
*/ */
public function forbiddenAction() public function forbiddenAction()
{ {
@ -45,7 +45,7 @@ class PublicController extends \Phalcon\Mvc\Controller
} }
/** /**
* @Get("/content/img/{id:[0-9]+}", name="home.content.img") * @Get("/content/img/{id:[0-9]+}", name="web.content.img")
*/ */
public function contentImageAction($id) public function contentImageAction($id)
{ {
@ -66,7 +66,7 @@ class PublicController extends \Phalcon\Mvc\Controller
} }
/** /**
* @Get("/qr/img", name="home.qr.img") * @Get("/qr/img", name="web.qr.img")
*/ */
public function qrImageAction() public function qrImageAction()
{ {

View File

@ -1,8 +1,8 @@
<?php <?php
namespace App\Http\Home\Controllers; namespace App\Http\Web\Controllers;
use App\Http\Home\Services\Review as ReviewService; use App\Http\Web\Services\Review as ReviewService;
/** /**
* @RoutePrefix("/review") * @RoutePrefix("/review")
@ -11,7 +11,7 @@ class ReviewController extends Controller
{ {
/** /**
* @Post("/create", name="home.review.create") * @Post("/create", name="web.review.create")
*/ */
public function createAction() public function createAction()
{ {
@ -25,7 +25,7 @@ class ReviewController extends Controller
} }
/** /**
* @Get("/{id:[0-9]+}", name="home.review.show") * @Get("/{id:[0-9]+}", name="web.review.show")
*/ */
public function showAction($id) public function showAction($id)
{ {
@ -37,7 +37,7 @@ class ReviewController extends Controller
} }
/** /**
* @Post("/{id:[0-9]+}/update", name="home.review.update") * @Post("/{id:[0-9]+}/update", name="web.review.update")
*/ */
public function updateAction($id) public function updateAction($id)
{ {
@ -51,7 +51,7 @@ class ReviewController extends Controller
} }
/** /**
* @Post("/{id:[0-9]+}/delete", name="home.review.delete") * @Post("/{id:[0-9]+}/delete", name="web.review.delete")
*/ */
public function deleteAction($id) public function deleteAction($id)
{ {
@ -63,7 +63,7 @@ class ReviewController extends Controller
} }
/** /**
* @Post("/{id:[0-9]+}/agree", name="home.review.agree") * @Post("/{id:[0-9]+}/agree", name="web.review.agree")
*/ */
public function agreeAction($id) public function agreeAction($id)
{ {
@ -75,7 +75,7 @@ class ReviewController extends Controller
} }
/** /**
* @Post("/{id:[0-9]+}/oppose", name="home.review.oppose") * @Post("/{id:[0-9]+}/oppose", name="web.review.oppose")
*/ */
public function opposeAction($id) public function opposeAction($id)
{ {
@ -87,7 +87,7 @@ class ReviewController extends Controller
} }
/** /**
* @Post("/{id:[0-9]+}/reply", name="home.review.reply") * @Post("/{id:[0-9]+}/reply", name="web.review.reply")
*/ */
public function replyAction($id) public function replyAction($id)
{ {

View File

@ -1,6 +1,6 @@
<?php <?php
namespace App\Http\Home\Controllers; namespace App\Http\Web\Controllers;
/** /**
* @RoutePrefix("/search") * @RoutePrefix("/search")
@ -9,7 +9,7 @@ class SearchController extends Controller
{ {
/** /**
* @Get("/courses", name="home.search.courses") * @Get("/courses", name="web.search.courses")
*/ */
public function coursesAction() public function coursesAction()
{ {
@ -33,7 +33,7 @@ class SearchController extends Controller
} }
/** /**
* @Get("/course/update", name="home.search.update_course") * @Get("/course/update", name="web.search.update_course")
*/ */
public function updateCourseAction() public function updateCourseAction()
{ {
@ -51,7 +51,7 @@ class SearchController extends Controller
} }
/** /**
* @Get("/course/create", name="home.search.create_course") * @Get("/course/create", name="web.search.create_course")
*/ */
public function createCourseAction() public function createCourseAction()
{ {
@ -69,7 +69,7 @@ class SearchController extends Controller
} }
/** /**
* @Get("/course/delete", name="home.search.delete_course") * @Get("/course/delete", name="web.search.delete_course")
*/ */
public function deleteCourseAction() public function deleteCourseAction()
{ {

View File

@ -1,6 +1,6 @@
<?php <?php
namespace App\Http\Home\Controllers; namespace App\Http\Web\Controllers;
/** /**
* @RoutePrefix("/user") * @RoutePrefix("/user")
@ -9,7 +9,7 @@ class UserController extends Controller
{ {
/** /**
* @Get("/{id:[0-9]+}", name="home.user.show") * @Get("/{id:[0-9]+}", name="web.user.show")
*/ */
public function showAction($id) public function showAction($id)
{ {
@ -17,7 +17,7 @@ class UserController extends Controller
} }
/** /**
* @Get("/{id:[0-9]+}/courses", name="home.user.courses") * @Get("/{id:[0-9]+}/courses", name="web.user.courses")
*/ */
public function coursesAction($id) public function coursesAction($id)
{ {
@ -25,7 +25,7 @@ class UserController extends Controller
} }
/** /**
* @Post("/{id:[0-9]+}/message", name="home.user.message") * @Post("/{id:[0-9]+}/message", name="web.user.message")
*/ */
public function messageAction($id) public function messageAction($id)
{ {

View File

@ -1,8 +1,8 @@
<?php <?php
namespace App\Http\Home; namespace App\Http\Web;
use App\Services\AuthUser\Home as HomeAuthUser; use App\Services\AuthUser\Web as WebAuthUser;
use Phalcon\DiInterface; use Phalcon\DiInterface;
use Phalcon\Mvc\ModuleDefinitionInterface; use Phalcon\Mvc\ModuleDefinitionInterface;
use Phalcon\Mvc\View; use Phalcon\Mvc\View;
@ -27,8 +27,8 @@ class Module implements ModuleDefinitionInterface
}); });
$di->setShared('auth', function () { $di->setShared('auth', function () {
$authUser = new HomeAuthUser(); return new WebAuthUser();
return $authUser;
}); });
} }
} }

View File

@ -0,0 +1,12 @@
<?php
namespace App\Http\Web\Services;
use App\Traits\Auth as AuthTrait;
use Phalcon\Mvc\User\Component;
class Service extends Component
{
use AuthTrait;
}

View File

@ -100,9 +100,7 @@ function kg_array_whitelist($params, $whitelist)
*/ */
function kg_array_object($array) function kg_array_object($array)
{ {
$result = json_decode(json_encode($array)); return json_decode(json_encode($array));
return $result;
} }
/** /**
@ -113,9 +111,7 @@ function kg_array_object($array)
*/ */
function kg_object_array($object) function kg_object_array($object)
{ {
$result = json_decode(json_encode($object), true); return json_decode(json_encode($object), true);
return $result;
} }
/** /**
@ -149,9 +145,7 @@ function kg_site_base_url()
$host = filter_input(INPUT_SERVER, 'HTTP_HOST'); $host = filter_input(INPUT_SERVER, 'HTTP_HOST');
$path = filter_input(INPUT_SERVER, 'SCRIPT_NAME'); $path = filter_input(INPUT_SERVER, 'SCRIPT_NAME');
$baseUrl = "{$scheme}://{$host}" . rtrim(dirname($path), '/'); return "{$scheme}://{$host}" . rtrim(dirname($path), '/');
return $baseUrl;
} }
/** /**

View File

@ -2,7 +2,9 @@
namespace App\Library\OAuth; namespace App\Library\OAuth;
class QQ extends \App\Library\OAuth use App\Library\OAuth;
class QQ extends OAuth
{ {
const AUTHORIZE_URL = 'https://graph.qq.com/oauth2.0/authorize'; const AUTHORIZE_URL = 'https://graph.qq.com/oauth2.0/authorize';

View File

@ -2,7 +2,9 @@
namespace App\Library\OAuth; namespace App\Library\OAuth;
class WeiBo extends \App\Library\OAuth use App\Library\OAuth;
class WeiBo extends OAuth
{ {
const AUTHORIZE_URL = 'https://api.weibo.com/oauth2/authorize'; const AUTHORIZE_URL = 'https://api.weibo.com/oauth2/authorize';

View File

@ -2,7 +2,9 @@
namespace App\Library\OAuth; namespace App\Library\OAuth;
class WeiXin extends \App\Library\OAuth use App\Library\OAuth;
class WeiXin extends OAuth
{ {
const AUTHORIZE_URL = 'https://open.weixin.qq.com/connect/qrconnect'; const AUTHORIZE_URL = 'https://open.weixin.qq.com/connect/qrconnect';

View File

@ -53,9 +53,7 @@ class QueryBuilder extends BaseQueryBuilder
{ {
$this->params['page'] = $page; $this->params['page'] = $page;
$queryUrl = $this->url . '?' . http_build_query($this->params); return $this->url . '?' . http_build_query($this->params);
return $queryUrl;
} }
} }

View File

@ -11,39 +11,29 @@ class Query extends Component
{ {
$page = $this->request->get('page', 'int', 1); $page = $this->request->get('page', 'int', 1);
$result = $page > 1000 ? 1000 : $page; return $page > 1000 ? 1000 : $page;
return $result;
} }
public function getLimit() public function getLimit()
{ {
$limit = $this->request->get('limit', 'int', 15); $limit = $this->request->get('limit', 'int', 15);
$result = $limit > 100 ? 100 : $limit; return $limit > 100 ? 100 : $limit;
return $result;
} }
public function getSort() public function getSort()
{ {
$sort = $this->request->get('sort', 'trim', ''); return $this->request->get('sort', 'trim', '');
return $sort;
} }
public function getUrl() public function getUrl()
{ {
$url = $this->request->get('_url', 'trim', ''); return $this->request->get('_url', 'trim', '');
return $url;
} }
public function getParams() public function getParams()
{ {
$params = $this->request->get(); return $this->request->get();
return $params;
} }
} }

View File

@ -31,6 +31,7 @@ class Security
$this->options['lifetime'] = $options['lifetime'] ?? 3600; $this->options['lifetime'] = $options['lifetime'] ?? 3600;
$this->cache = Di::getDefault()->get('cache'); $this->cache = Di::getDefault()->get('cache');
$this->session = Di::getDefault()->get('session'); $this->session = Di::getDefault()->get('session');
$this->generateToken(); $this->generateToken();

View File

@ -51,9 +51,7 @@ class Word
public static function filterChineseWords($str) public static function filterChineseWords($str)
{ {
$result = preg_replace(self::CHINESE_PATTERN, '', $str); return preg_replace(self::CHINESE_PATTERN, '', $str);
return $result;
} }
public static function filterChineseSymbols($str) public static function filterChineseSymbols($str)
@ -65,9 +63,7 @@ class Word
'', '', '', '', '“ ', '”', '', '', '', '', '', '', '“ ', '”', '', '',
]; ];
$result = str_replace($search, '', $str); return str_replace($search, '', $str);
return $result;
} }
} }

View File

@ -2,7 +2,7 @@
namespace App\Listeners; namespace App\Listeners;
use App\Caches\Config as ConfigCache; use App\Caches\SectionConfig as SectionConfigCache;
use App\Library\Logger as AppLogger; use App\Library\Logger as AppLogger;
use Phalcon\Logger\Adapter\File as FileLogger; use Phalcon\Logger\Adapter\File as FileLogger;
use Phalcon\Mvc\User\Plugin as UserPlugin; use Phalcon\Mvc\User\Plugin as UserPlugin;
@ -33,11 +33,9 @@ class Listener extends UserPlugin
*/ */
public function getSectionConfig($section) public function getSectionConfig($section)
{ {
$configCache = new ConfigCache(); $cache = new SectionConfigCache();
$result = $configCache->getSectionConfig($section); return $cache->get($section);
return $result;
} }
} }

View File

@ -0,0 +1,95 @@
<?php
namespace App\Models;
use Phalcon\Mvc\Model\Behavior\SoftDelete;
class AccessToken extends Model
{
/**
* 主键编号
*
* @var string
*/
public $id;
/**
* 用户编号
*
* @var int
*/
public $user_id;
/**
* 删除标识
*
* @var int
*/
public $deleted;
/**
* 过期时间
*
* @var int
*/
public $expired_at;
/**
* 创建时间
*
* @var int
*/
public $created_at;
/**
* 更新时间
*
* @var int
*/
public $updated_at;
public function getSource()
{
return 'kg_access_token';
}
public function initialize()
{
parent::initialize();
$this->addBehavior(
new SoftDelete([
'field' => 'deleted',
'value' => 1,
])
);
}
public function beforeCreate()
{
$this->id = $this->getRandId($this->user_id);
$this->expired_at = strtotime('+2 hours');
}
public function beforeUpdate()
{
$this->updated_at = time();
}
public function afterCreate()
{
$refreshToken = new RefreshToken();
$refreshToken->user_id = $this->user_id;
$refreshToken->create();
}
protected function getRandId($userId, $prefix = 'AT')
{
return md5("{$prefix}-{$userId}" . time() . rand(1000, 9999));
}
}

View File

@ -133,23 +133,19 @@ class CourseUser extends Model
public static function roleTypes() public static function roleTypes()
{ {
$list = [ return [
self::ROLE_STUDENT => '学员', self::ROLE_STUDENT => '学员',
self::ROLE_TEACHER => '讲师', self::ROLE_TEACHER => '讲师',
]; ];
return $list;
} }
public static function sourceTypes() public static function sourceTypes()
{ {
$list = [ return [
self::SOURCE_FREE => '免费', self::SOURCE_FREE => '免费',
self::SOURCE_CHARGE => '付费', self::SOURCE_CHARGE => '付费',
self::SOURCE_IMPORT => '导入', self::SOURCE_IMPORT => '导入',
]; ];
return $list;
} }
} }

View File

@ -164,22 +164,18 @@ class Nav extends Model
public static function positionTypes() public static function positionTypes()
{ {
$list = [ return [
self::POSITION_TOP => '顶部', self::POSITION_TOP => '顶部',
self::POSITION_BOTTOM => '底部', self::POSITION_BOTTOM => '底部',
]; ];
return $list;
} }
public static function targetTypes() public static function targetTypes()
{ {
$list = [ return [
self::TARGET_BLANK => '新窗口', self::TARGET_BLANK => '新窗口',
self::TARGET_SELF => '原窗口', self::TARGET_SELF => '原窗口',
]; ];
return $list;
} }
} }

View File

@ -181,38 +181,32 @@ class Order extends Model
public static function itemTypes() public static function itemTypes()
{ {
$list = [ return [
self::ITEM_COURSE => '课程', self::ITEM_COURSE => '课程',
self::ITEM_PACKAGE => '套餐', self::ITEM_PACKAGE => '套餐',
self::ITEM_REWARD => '赞赏', self::ITEM_REWARD => '赞赏',
self::ITEM_VIP => '会员', self::ITEM_VIP => '会员',
self::ITEM_TEST => '测试', self::ITEM_TEST => '测试',
]; ];
return $list;
} }
public static function sourceTypes() public static function sourceTypes()
{ {
$list = [ return [
self::SOURCE_DESKTOP => 'desktop', self::SOURCE_DESKTOP => 'desktop',
self::SOURCE_ANDROID => 'android', self::SOURCE_ANDROID => 'android',
self::SOURCE_IOS => 'ios', self::SOURCE_IOS => 'ios',
]; ];
return $list;
} }
public static function statusTypes() public static function statusTypes()
{ {
$list = [ return [
self::STATUS_PENDING => '待支付', self::STATUS_PENDING => '待支付',
self::STATUS_FINISHED => '已完成', self::STATUS_FINISHED => '已完成',
self::STATUS_CLOSED => '已关闭', self::STATUS_CLOSED => '已关闭',
self::STATUS_REFUNDED => '已退款', self::STATUS_REFUNDED => '已退款',
]; ];
return $list;
} }
} }

View File

@ -0,0 +1,87 @@
<?php
namespace App\Models;
use Phalcon\Mvc\Model\Behavior\SoftDelete;
class RefreshToken extends Model
{
/**
* 主键编号
*
* @var string
*/
public $id;
/**
* 用户编号
*
* @var int
*/
public $user_id;
/**
* 删除标识
*
* @var int
*/
public $deleted;
/**
* 过期时间
*
* @var int
*/
public $expired_at;
/**
* 创建时间
*
* @var int
*/
public $created_at;
/**
* 更新时间
*
* @var int
*/
public $updated_at;
public function getSource()
{
return 'kg_refresh_token';
}
public function initialize()
{
parent::initialize();
$this->addBehavior(
new SoftDelete([
'field' => 'deleted',
'value' => 1,
])
);
}
public function beforeCreate()
{
$this->id = $this->getRandId($this->user_id);
$this->expired_at = strtotime('+30 days');
$this->created_at = time();
}
public function beforeUpdate()
{
$this->updated_at = time();
}
protected function getRandId($userId, $prefix = 'RT')
{
return md5("{$prefix}-{$userId}" . time() . rand(1000, 9999));
}
}

View File

@ -146,7 +146,7 @@ class Refund extends Model
public static function statusTypes() public static function statusTypes()
{ {
$list = [ return [
self::STATUS_PENDING => '待处理', self::STATUS_PENDING => '待处理',
self::STATUS_CANCELED => '已取消', self::STATUS_CANCELED => '已取消',
self::STATUS_APPROVED => '已审核', self::STATUS_APPROVED => '已审核',
@ -154,8 +154,6 @@ class Refund extends Model
self::STATUS_FINISHED => '已完成', self::STATUS_FINISHED => '已完成',
self::STATUS_FAILED => '已失败', self::STATUS_FAILED => '已失败',
]; ];
return $list;
} }
} }

View File

@ -128,24 +128,20 @@ class Role extends Model
public static function types() public static function types()
{ {
$list = [ return [
self::TYPE_SYSTEM => '内置', self::TYPE_SYSTEM => '内置',
self::TYPE_CUSTOM => '自定', self::TYPE_CUSTOM => '自定',
]; ];
return $list;
} }
public static function sysRoleTypes() public static function sysRoleTypes()
{ {
$list = [ return [
self::ROLE_ROOT => '管理人员', self::ROLE_ROOT => '管理人员',
self::ROLE_OPERATOR => '运营人员', self::ROLE_OPERATOR => '运营人员',
self::ROLE_EDITOR => '编辑人员', self::ROLE_EDITOR => '编辑人员',
self::ROLE_FINANCE => '财务人员', self::ROLE_FINANCE => '财务人员',
]; ];
return $list;
} }
} }

View File

@ -137,13 +137,11 @@ class Slide extends Model
public static function targetTypes() public static function targetTypes()
{ {
$list = [ return [
self::TARGET_COURSE => '课程', self::TARGET_COURSE => '课程',
self::TARGET_PAGE => '单页', self::TARGET_PAGE => '单页',
self::TARGET_LINK => '链接', self::TARGET_LINK => '链接',
]; ];
return $list;
} }
} }

View File

@ -143,24 +143,20 @@ class Trade extends Model
public static function channelTypes() public static function channelTypes()
{ {
$list = [ return [
self::CHANNEL_ALIPAY => '支付宝', self::CHANNEL_ALIPAY => '支付宝',
self::CHANNEL_WXPAY => '微信', self::CHANNEL_WXPAY => '微信',
]; ];
return $list;
} }
public static function statusTypes() public static function statusTypes()
{ {
$list = [ return [
self::STATUS_PENDING => '待支付', self::STATUS_PENDING => '待支付',
self::STATUS_FINISHED => '已完成', self::STATUS_FINISHED => '已完成',
self::STATUS_CLOSED => '已关闭', self::STATUS_CLOSED => '已关闭',
self::STATUS_REFUNDED => '已退款', self::STATUS_REFUNDED => '已退款',
]; ];
return $list;
} }
} }

View File

@ -183,23 +183,19 @@ class User extends Model
public static function genderTypes() public static function genderTypes()
{ {
$list = [ return [
self::GENDER_MALE => '男', self::GENDER_MALE => '男',
self::GENDER_FEMALE => '女', self::GENDER_FEMALE => '女',
self::GENDER_NONE => '保密', self::GENDER_NONE => '保密',
]; ];
return $list;
} }
public static function eduRoleTypes() public static function eduRoleTypes()
{ {
$list = [ return [
self::EDU_ROLE_STUDENT => '学员', self::EDU_ROLE_STUDENT => '学员',
self::EDU_ROLE_TEACHER => '讲师', self::EDU_ROLE_TEACHER => '讲师',
]; ];
return $list;
} }
} }

View File

@ -20,7 +20,7 @@ class Cache extends Provider
'lifetime' => $config->redis->lifetime, 'lifetime' => $config->redis->lifetime,
]); ]);
$backend = new RedisBackend($frontend, [ return new RedisBackend($frontend, [
'host' => $config->redis->host, 'host' => $config->redis->host,
'port' => $config->redis->port, 'port' => $config->redis->port,
'auth' => $config->redis->auth, 'auth' => $config->redis->auth,
@ -28,8 +28,6 @@ class Cache extends Provider
'prefix' => $config->redis->prefix, 'prefix' => $config->redis->prefix,
'persistent' => $config->redis->persistent, 'persistent' => $config->redis->persistent,
]); ]);
return $backend;
}); });
} }

View File

@ -15,9 +15,7 @@ class Config extends Provider
$options = require config_path() . '/config.php'; $options = require config_path() . '/config.php';
$config = new PhalconConfig($options); return new PhalconConfig($options);
return $config;
}); });
} }

View File

@ -5,13 +5,9 @@ namespace App\Providers;
use Phalcon\DiInterface; use Phalcon\DiInterface;
use Phalcon\Mvc\User\Component; use Phalcon\Mvc\User\Component;
/**
* \App\Providers\Provider
*
* @package App\Providers
*/
abstract class Provider extends Component implements ProviderInterface abstract class Provider extends Component implements ProviderInterface
{ {
/** /**
* Service name * Service name
* *
@ -38,4 +34,5 @@ abstract class Provider extends Component implements ProviderInterface
{ {
return $this->serviceName; return $this->serviceName;
} }
} }

View File

@ -4,13 +4,9 @@ namespace App\Providers;
use Phalcon\Di\InjectionAwareInterface; use Phalcon\Di\InjectionAwareInterface;
/**
* \App\Providers\ServiceProviderInterface
*
* @package App\Providers
*/
interface ProviderInterface extends InjectionAwareInterface interface ProviderInterface extends InjectionAwareInterface
{ {
/** /**
* Register application service. * Register application service.
* *
@ -24,4 +20,5 @@ interface ProviderInterface extends InjectionAwareInterface
* @return string * @return string
*/ */
public function getName(); public function getName();
} }

View File

@ -16,28 +16,28 @@ class Router extends Provider
$router = new AnnotationsRouter(false); $router = new AnnotationsRouter(false);
$router->removeExtraSlashes(true); $router->removeExtraSlashes(true);
$router->setDefaultNamespace('App\Http\Home\Controllers'); $router->setDefaultNamespace('App\Http\Web\Controllers');
$router->notFound([ $router->notFound([
'module' => 'home', 'module' => 'web',
'controller' => 'error', 'controller' => 'error',
'action' => 'show404', 'action' => 'show404',
]); ]);
$homeFiles = scandir(app_path('Http/Home/Controllers')); $webFiles = scandir(app_path('Http/Web/Controllers'));
foreach ($homeFiles as $file) { foreach ($webFiles as $file) {
if (strpos($file, 'Controller.php')) { if (strpos($file, 'Controller.php')) {
$className = str_replace('Controller.php', '', $file); $className = str_replace('Controller.php', '', $file);
$router->addModuleResource('home', 'App\Http\Home\Controllers\\' . $className); $router->addModuleResource('home', 'App\Http\Web\Controllers\\' . $className);
} }
} }
$adminFiles = scandir(app_path('Http/Admin/Controllers')); $html5Files = scandir(app_path('Http/Html5/Controllers'));
foreach ($adminFiles as $file) { foreach ($html5Files as $file) {
if (strpos($file, 'Controller.php')) { if (strpos($file, 'Controller.php')) {
$className = str_replace('Controller.php', '', $file); $className = str_replace('Controller.php', '', $file);
$router->addModuleResource('admin', 'App\Http\Admin\Controllers\\' . $className); $router->addModuleResource('html5', 'App\Http\Html5\Controllers\\' . $className);
} }
} }
@ -50,6 +50,15 @@ class Router extends Provider
} }
} }
$adminFiles = scandir(app_path('Http/Admin/Controllers'));
foreach ($adminFiles as $file) {
if (strpos($file, 'Controller.php')) {
$className = str_replace('Controller.php', '', $file);
$router->addModuleResource('admin', 'App\Http\Admin\Controllers\\' . $className);
}
}
return $router; return $router;
}); });
} }

View File

@ -12,10 +12,7 @@ class Security extends Provider
public function register() public function register()
{ {
$this->di->setShared($this->serviceName, function () { $this->di->setShared($this->serviceName, function () {
return new AppSecurity();
$security = new AppSecurity();
return $security;
}); });
} }

42
app/Repos/AccessToken.php Normal file
View File

@ -0,0 +1,42 @@
<?php
namespace App\Repos;
use App\Models\AccessToken as AccessTokenModel;
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Resultset;
use Phalcon\Mvc\Model\ResultsetInterface;
class AccessToken extends Repository
{
/**
* @param int $id
* @return AccessTokenModel|Model|bool
*/
public function findById($id)
{
return AccessTokenModel::findFirst($id);
}
/**
* @param int $userId
* @return ResultsetInterface|Resultset|AccessTokenModel[]
*/
public function findByUserId($userId)
{
return AccessTokenModel::query()
->where('user_id = :user_id:', ['user_id' => $userId])
->andWhere('deleted = 0')
->execute();
}
public function countByUserId($userId)
{
return AccessTokenModel::count([
'conditions' => 'user_id = :user_id: AND deleted = 0',
'bind' => ['user_id' => $userId],
]);
}
}

View File

@ -16,9 +16,7 @@ class Account extends Repository
*/ */
public function findById($id) public function findById($id)
{ {
$result = AccountModel::findFirst($id); return AccountModel::findFirst($id);
return $result;
} }
/** /**
@ -27,12 +25,10 @@ class Account extends Repository
*/ */
public function findByPhone($phone) public function findByPhone($phone)
{ {
$result = AccountModel::findFirst([ return AccountModel::findFirst([
'conditions' => 'phone = :phone:', 'conditions' => 'phone = :phone:',
'bind' => ['phone' => $phone], 'bind' => ['phone' => $phone],
]); ]);
return $result;
} }
/** /**
@ -41,12 +37,10 @@ class Account extends Repository
*/ */
public function findByEmail($email) public function findByEmail($email)
{ {
$result = AccountModel::findFirst([ return AccountModel::findFirst([
'conditions' => 'email = :email:', 'conditions' => 'email = :email:',
'bind' => ['email' => $email], 'bind' => ['email' => $email],
]); ]);
return $result;
} }
/** /**
@ -56,12 +50,10 @@ class Account extends Repository
*/ */
public function findByIds($ids, $columns = '*') public function findByIds($ids, $columns = '*')
{ {
$result = AccountModel::query() return AccountModel::query()
->columns($columns) ->columns($columns)
->inWhere('id', $ids) ->inWhere('id', $ids)
->execute(); ->execute();
return $result;
} }
} }

View File

@ -11,13 +11,6 @@ use Phalcon\Mvc\Model\ResultsetInterface;
class Audit extends Repository class Audit extends Repository
{ {
/**
* @param array $where
* @param string $sort
* @param int $page
* @param int $limit
* @return object
*/
public function paginate($where = [], $sort = 'latest', $page = 1, $limit = 15) public function paginate($where = [], $sort = 'latest', $page = 1, $limit = 15)
{ {
$builder = $this->modelsManager->createBuilder(); $builder = $this->modelsManager->createBuilder();
@ -71,9 +64,7 @@ class Audit extends Repository
*/ */
public function findById($id) public function findById($id)
{ {
$result = AuditModel::findFirst($id); return AuditModel::findFirst($id);
return $result;
} }
/** /**
@ -83,13 +74,10 @@ class Audit extends Repository
*/ */
public function findByIds($ids, $columns = '*') public function findByIds($ids, $columns = '*')
{ {
$result = AuditModel::query() return AuditModel::query()
->columns($columns) ->columns($columns)
->inWhere('id', $ids) ->inWhere('id', $ids)
->execute(); ->execute();
return $result;
} }
} }

View File

@ -12,32 +12,6 @@ use Phalcon\Mvc\Model\ResultsetInterface;
class Category extends Repository class Category extends Repository
{ {
/**
* @param int $id
* @return CategoryModel|Model|bool
*/
public function findById($id)
{
$result = CategoryModel::findFirst($id);
return $result;
}
/**
* @param array $ids
* @param array|string $columns
* @return ResultsetInterface|Resultset|CategoryModel[]
*/
public function findByIds($ids, $columns = '*')
{
$result = CategoryModel::query()
->columns($columns)
->inWhere('id', $ids)
->execute();
return $result;
}
/** /**
* @param array $where * @param array $where
* @return ResultsetInterface|Resultset|CategoryModel[] * @return ResultsetInterface|Resultset|CategoryModel[]
@ -66,9 +40,29 @@ class Category extends Repository
$query->orderBy('priority ASC'); $query->orderBy('priority ASC');
$result = $query->execute(); return $query->execute();
}
return $result; /**
* @param int $id
* @return CategoryModel|Model|bool
*/
public function findById($id)
{
return CategoryModel::findFirst($id);
}
/**
* @param array $ids
* @param array|string $columns
* @return ResultsetInterface|Resultset|CategoryModel[]
*/
public function findByIds($ids, $columns = '*')
{
return CategoryModel::query()
->columns($columns)
->inWhere('id', $ids)
->execute();
} }
/** /**
@ -76,13 +70,11 @@ class Category extends Repository
*/ */
public function findTopCategories() public function findTopCategories()
{ {
$result = CategoryModel::query() return CategoryModel::query()
->where('parent_id = 0') ->where('parent_id = 0')
->andWhere('deleted = 0') ->andWhere('deleted = 0')
->andWhere('published = 1') ->andWhere('published = 1')
->execute(); ->execute();
return $result;
} }
/** /**
@ -91,29 +83,25 @@ class Category extends Repository
*/ */
public function findChildCategories($categoryId) public function findChildCategories($categoryId)
{ {
$result = CategoryModel::query() return CategoryModel::query()
->where('parent_id = :parent_id:', ['parent_id' => $categoryId]) ->where('parent_id = :parent_id:', ['parent_id' => $categoryId])
->andWhere('deleted = 0') ->andWhere('deleted = 0')
->andWhere('published = 1') ->andWhere('published = 1')
->execute(); ->execute();
return $result;
} }
public function countChildCategories($categoryId) public function countChildCategories($categoryId)
{ {
$count = CategoryModel::count([ return CategoryModel::count([
'conditions' => 'parent_id = :parent_id: AND deleted = 0 AND published = 1', 'conditions' => 'parent_id = :parent_id: AND deleted = 0 AND published = 1',
'bind' => ['parent_id' => $categoryId], 'bind' => ['parent_id' => $categoryId],
]); ]);
return $count;
} }
public function countCourses($categoryId) public function countCourses($categoryId)
{ {
$phql = "SELECT COUNT(*) AS total FROM %s cc JOIN %s c ON cc.course_id = c.id $phql = 'SELECT COUNT(*) AS total FROM %s cc JOIN %s c ON cc.course_id = c.id
WHERE cc.category_id = :category_id: AND c.published = 1 AND c.deleted = 0"; WHERE cc.category_id = :category_id: AND c.published = 1 AND c.deleted = 0';
$phql = sprintf($phql, CourseCategoryModel::class, CourseModel::class); $phql = sprintf($phql, CourseCategoryModel::class, CourseModel::class);

View File

@ -17,32 +17,6 @@ use Phalcon\Mvc\Model\ResultsetInterface;
class Chapter extends Repository class Chapter extends Repository
{ {
/**
* @param int $id
* @return ChapterModel|Model|bool
*/
public function findById($id)
{
$result = ChapterModel::findFirst($id);
return $result;
}
/**
* @param array $ids
* @param string|array $columns
* @return ResultsetInterface|Resultset|ChapterModel[]
*/
public function findByIds($ids, $columns = '*')
{
$result = ChapterModel::query()
->columns($columns)
->inWhere('id', $ids)
->execute();
return $result;
}
/** /**
* @param array $where * @param array $where
* @return ResultsetInterface|Resultset|ChapterModel[] * @return ResultsetInterface|Resultset|ChapterModel[]
@ -69,9 +43,29 @@ class Chapter extends Repository
$query->andWhere('deleted = :deleted:', ['deleted' => $where['deleted']]); $query->andWhere('deleted = :deleted:', ['deleted' => $where['deleted']]);
} }
$result = $query->execute(); return $query->execute();
}
return $result; /**
* @param int $id
* @return ChapterModel|Model|bool
*/
public function findById($id)
{
return ChapterModel::findFirst($id);
}
/**
* @param array $ids
* @param string|array $columns
* @return ResultsetInterface|Resultset|ChapterModel[]
*/
public function findByIds($ids, $columns = '*')
{
return ChapterModel::query()
->columns($columns)
->inWhere('id', $ids)
->execute();
} }
/** /**
@ -87,9 +81,7 @@ class Chapter extends Repository
if (!$vod) return false; if (!$vod) return false;
$result = ChapterModel::findFirst($vod->chapter_id); return ChapterModel::findFirst($vod->chapter_id);
return $result;
} }
/** /**
@ -98,12 +90,10 @@ class Chapter extends Repository
*/ */
public function findChapterVod($chapterId) public function findChapterVod($chapterId)
{ {
$result = ChapterVodModel::findFirst([ return ChapterVodModel::findFirst([
'conditions' => 'chapter_id = :chapter_id:', 'conditions' => 'chapter_id = :chapter_id:',
'bind' => ['chapter_id' => $chapterId], 'bind' => ['chapter_id' => $chapterId],
]); ]);
return $result;
} }
/** /**
@ -112,12 +102,10 @@ class Chapter extends Repository
*/ */
public function findChapterLive($chapterId) public function findChapterLive($chapterId)
{ {
$result = ChapterLiveModel::findFirst([ return ChapterLiveModel::findFirst([
'conditions' => 'chapter_id = :chapter_id:', 'conditions' => 'chapter_id = :chapter_id:',
'bind' => ['chapter_id' => $chapterId], 'bind' => ['chapter_id' => $chapterId],
]); ]);
return $result;
} }
/** /**
@ -126,12 +114,10 @@ class Chapter extends Repository
*/ */
public function findChapterRead($chapterId) public function findChapterRead($chapterId)
{ {
$result = ChapterReadModel::findFirst([ return ChapterReadModel::findFirst([
'conditions' => 'chapter_id = :chapter_id:', 'conditions' => 'chapter_id = :chapter_id:',
'bind' => ['chapter_id' => $chapterId], 'bind' => ['chapter_id' => $chapterId],
]); ]);
return $result;
} }
/** /**
@ -141,101 +127,83 @@ class Chapter extends Repository
*/ */
public function findUserCommentVotes($chapterId, $userId) public function findUserCommentVotes($chapterId, $userId)
{ {
$result = $this->modelsManager->createBuilder() return $this->modelsManager->createBuilder()
->columns('cv.*') ->columns('cv.*')
->addFrom(CommentModel::class, 'c') ->addFrom(CommentModel::class, 'c')
->join(CommentVoteModel::class, 'c.id = cv.comment_id', 'cv') ->join(CommentVoteModel::class, 'c.id = cv.comment_id', 'cv')
->where('c.chapter_id = :chapter_id:', ['chapter_id' => $chapterId]) ->where('c.chapter_id = :chapter_id:', ['chapter_id' => $chapterId])
->andWhere('cv.user_id = :user_id:', ['user_id' => $userId]) ->andWhere('cv.user_id = :user_id:', ['user_id' => $userId])
->getQuery()->execute(); ->getQuery()->execute();
return $result;
} }
public function maxChapterPriority($courseId) public function maxChapterPriority($courseId)
{ {
$result = ChapterModel::maximum([ return ChapterModel::maximum([
'column' => 'priority', 'column' => 'priority',
'conditions' => 'course_id = :course_id: AND parent_id = 0', 'conditions' => 'course_id = :course_id: AND parent_id = 0',
'bind' => ['course_id' => $courseId], 'bind' => ['course_id' => $courseId],
]); ]);
return $result;
} }
public function maxLessonPriority($chapterId) public function maxLessonPriority($chapterId)
{ {
$result = ChapterModel::maximum([ return ChapterModel::maximum([
'column' => 'priority', 'column' => 'priority',
'conditions' => 'parent_id = :parent_id:', 'conditions' => 'parent_id = :parent_id:',
'bind' => ['parent_id' => $chapterId], 'bind' => ['parent_id' => $chapterId],
]); ]);
return $result;
} }
public function countLessons($chapterId) public function countLessons($chapterId)
{ {
$result = ChapterModel::count([ return ChapterModel::count([
'conditions' => 'parent_id = :chapter_id: AND deleted = 0', 'conditions' => 'parent_id = :chapter_id: AND deleted = 0',
'bind' => ['chapter_id' => $chapterId], 'bind' => ['chapter_id' => $chapterId],
]); ]);
return $result;
} }
public function countUsers($chapterId) public function countUsers($chapterId)
{ {
$count = ChapterUserModel::count([ return ChapterUserModel::count([
'conditions' => 'chapter_id = :chapter_id: AND deleted = 0', 'conditions' => 'chapter_id = :chapter_id: AND deleted = 0',
'bind' => ['chapter_id' => $chapterId], 'bind' => ['chapter_id' => $chapterId],
]); ]);
return $count;
} }
public function countComments($chapterId) public function countComments($chapterId)
{ {
$count = CommentModel::count([ return CommentModel::count([
'conditions' => 'chapter_id = :chapter_id: AND deleted = 0', 'conditions' => 'chapter_id = :chapter_id: AND deleted = 0',
'bind' => ['chapter_id' => $chapterId], 'bind' => ['chapter_id' => $chapterId],
]); ]);
return $count;
} }
public function countAgrees($chapterId) public function countAgrees($chapterId)
{ {
$type = ChapterVoteModel::TYPE_AGREE; $type = ChapterVoteModel::TYPE_AGREE;
$count = ChapterVoteModel::count([ return ChapterVoteModel::count([
'conditions' => 'chapter_id = :chapter_id: AND type = :type: AND deleted = 0', 'conditions' => 'chapter_id = :chapter_id: AND type = :type: AND deleted = 0',
'bind' => ['chapter_id' => $chapterId, 'type' => $type], 'bind' => ['chapter_id' => $chapterId, 'type' => $type],
]); ]);
return $count;
} }
public function countOpposes($chapterId) public function countOpposes($chapterId)
{ {
$type = ChapterVoteModel::TYPE_OPPOSE; $type = ChapterVoteModel::TYPE_OPPOSE;
$count = ChapterVoteModel::count([ return ChapterVoteModel::count([
'conditions' => 'chapter_id = :chapter_id: AND type = :type: AND deleted = 0', 'conditions' => 'chapter_id = :chapter_id: AND type = :type: AND deleted = 0',
'bind' => ['chapter_id' => $chapterId, 'type' => $type], 'bind' => ['chapter_id' => $chapterId, 'type' => $type],
]); ]);
return $count;
} }
public function countUserComments($chapterId, $userId) public function countUserComments($chapterId, $userId)
{ {
$count = CommentModel::count([ return CommentModel::count([
'conditions' => 'chapter_id = :chapter_id: AND user_id = :user_id:', 'conditions' => 'chapter_id = :chapter_id: AND user_id = :user_id:',
'bind' => ['chapter_id' => $chapterId, 'user_id' => $userId], 'bind' => ['chapter_id' => $chapterId, 'user_id' => $userId],
]); ]);
return $count;
} }
} }

View File

@ -10,21 +10,6 @@ use Phalcon\Mvc\Model\ResultsetInterface;
class ChapterUser extends Repository class ChapterUser extends Repository
{ {
/**
* @param int $chapterId
* @param int $userId
* @return ChapterUserModel|Model|bool
*/
public function findChapterUser($chapterId, $userId)
{
$result = ChapterUserModel::findFirst([
'conditions' => 'chapter_id = ?1 AND user_id = ?2 AND deleted = 0',
'bind' => [1 => $chapterId, 2 => $userId],
]);
return $result;
}
/** /**
* @param array $where * @param array $where
* @return ResultsetInterface|Resultset|ChapterUserModel[] * @return ResultsetInterface|Resultset|ChapterUserModel[]
@ -47,9 +32,20 @@ class ChapterUser extends Repository
$query->andWhere('user_id = :user_id:', ['user_id' => $where['user_id']]); $query->andWhere('user_id = :user_id:', ['user_id' => $where['user_id']]);
} }
$result = $query->execute(); return $query->execute();
}
return $result; /**
* @param int $chapterId
* @param int $userId
* @return ChapterUserModel|Model|bool
*/
public function findChapterUser($chapterId, $userId)
{
return ChapterUserModel::findFirst([
'conditions' => 'chapter_id = ?1 AND user_id = ?2 AND deleted = 0',
'bind' => [1 => $chapterId, 2 => $userId],
]);
} }
} }

View File

@ -15,12 +15,10 @@ class ChapterVote extends Repository
*/ */
public function findChapterVote($chapterId, $userId) public function findChapterVote($chapterId, $userId)
{ {
$result = ChapterVoteModel::findFirst([ return ChapterVoteModel::findFirst([
'conditions' => 'chapter_id = :chapter_id: AND user_id = :user_id:', 'conditions' => 'chapter_id = :chapter_id: AND user_id = :user_id:',
'bind' => ['chapter_id' => $chapterId, 'user_id' => $userId], 'bind' => ['chapter_id' => $chapterId, 'user_id' => $userId],
]); ]);
return $result;
} }
} }

View File

@ -12,13 +12,6 @@ use Phalcon\Mvc\Model\ResultsetInterface;
class Comment extends Repository class Comment extends Repository
{ {
/**
* @param array $where
* @param string $sort
* @param int $page
* @param int $limit
* @return \stdClass
*/
public function paginate($where = [], $sort = 'latest', $page = 1, $limit = 15) public function paginate($where = [], $sort = 'latest', $page = 1, $limit = 15)
{ {
$builder = $this->modelsManager->createBuilder(); $builder = $this->modelsManager->createBuilder();
@ -78,9 +71,7 @@ class Comment extends Repository
*/ */
public function findById($id) public function findById($id)
{ {
$result = CommentModel::findFirst($id); return CommentModel::findFirst($id);
return $result;
} }
/** /**
@ -90,46 +81,38 @@ class Comment extends Repository
*/ */
public function findByIds($ids, $columns = '*') public function findByIds($ids, $columns = '*')
{ {
$result = CommentModel::query() return CommentModel::query()
->columns($columns) ->columns($columns)
->inWhere('id', $ids) ->inWhere('id', $ids)
->execute(); ->execute();
return $result;
} }
public function countReplies($commentId) public function countReplies($commentId)
{ {
$count = CommentModel::count([ return CommentModel::count([
'conditions' => 'parent_id = :parent_id: AND deleted = 0', 'conditions' => 'parent_id = :parent_id: AND deleted = 0',
'bind' => ['parent_id' => $commentId], 'bind' => ['parent_id' => $commentId],
]); ]);
return $count;
} }
public function countAgrees($commentId) public function countAgrees($commentId)
{ {
$type = CommentVoteModel::TYPE_AGREE; $type = CommentVoteModel::TYPE_AGREE;
$count = CommentVoteModel::count([ return CommentVoteModel::count([
'conditions' => 'comment_id = :comment_id: AND type = :type: AND deleted = 0', 'conditions' => 'comment_id = :comment_id: AND type = :type: AND deleted = 0',
'bind' => ['comment_id' => $commentId, 'type' => $type], 'bind' => ['comment_id' => $commentId, 'type' => $type],
]); ]);
return $count;
} }
public function countOpposes($commentId) public function countOpposes($commentId)
{ {
$type = CommentVoteModel::TYPE_OPPOSE; $type = CommentVoteModel::TYPE_OPPOSE;
$count = CommentVoteModel::count([ return CommentVoteModel::count([
'conditions' => 'comment_id = :comment_id: AND type = :type: AND deleted = 0', 'conditions' => 'comment_id = :comment_id: AND type = :type: AND deleted = 0',
'bind' => ['comment_id' => $commentId, 'type' => $type], 'bind' => ['comment_id' => $commentId, 'type' => $type],
]); ]);
return $count;
} }
} }

Some files were not shown because too many files have changed in this diff Show More