src/ApiV3Bundle/Controller/BaseController.php line 379

Open in your IDE?
  1. <?php
  2. namespace ApiV3Bundle\Controller;
  3. use ApiV3Bundle\Common\Paginator;
  4. use ApiV3Bundle\Util\AssetHelper;
  5. use AppBundle\Common\ArrayToolkit;
  6. use AppBundle\Twig\WebExtension;
  7. use Biz\Course\Service\CourseService;
  8. use Biz\Role\Util\PermissionBuilder;
  9. use Biz\System\Service\SettingService;
  10. use Biz\Testpaper\Service\TestpaperService;
  11. use Biz\User\CurrentUser;
  12. use Common\PrepareOrgTrait;
  13. use Common\ValidatorTrait;
  14. use CorporateTrainingBundle\Biz\ManagePermission\Service\ManagePermissionOrgService;
  15. use CorporateTrainingBundle\Biz\Org\Service\OrgService;
  16. use CorporateTrainingBundle\Biz\ResourceScope\Service\ResourceAccessScopeService;
  17. use CorporateTrainingBundle\Biz\ResourceScope\Service\ResourceVisibleScopeService;
  18. use CorporateTrainingBundle\Biz\User\Service\UserService;
  19. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use Symfony\Component\HttpFoundation\Response;
  23. class BaseController extends AbstractController
  24. {
  25.     use PrepareOrgTrait;
  26.     use ValidatorTrait;
  27.     public const APP_MODULE 'app';
  28.     public const TOKEN_TYPE 'mobile_login';
  29.     public const PREFIX_SORT_DESC '-';
  30.     public const NEW_TOKEN_HEADER 'Access-Token';
  31.     /**
  32.      * @return CurrentUser
  33.      */
  34.     protected function getCurrentUser()
  35.     {
  36.         return $this->getUser();
  37.     }
  38.     protected function getBiz()
  39.     {
  40.         return $this->get('biz');
  41.     }
  42.     /**
  43.      * @return CurrentUser
  44.      */
  45.     public function getUser()
  46.     {
  47.         return $this->getTokenStorage()->getToken()->getUser();
  48.     }
  49.     protected function getHeaderInfo($request)
  50.     {
  51.         if (null === $request->headers->get(self::NEW_TOKEN_HEADER)) {
  52.             return false;
  53.         }
  54.         return true;
  55.     }
  56.     public function setCurrentUser($userId$request)
  57.     {
  58.         $user $this->getUserService()->getUserWithOrgScopes($userId);
  59.         $currentUser = new CurrentUser();
  60.         if (empty($user)) {
  61.             $user = ['id' => 0];
  62.         }
  63.         $user['currentIp'] = $request->getClientIp();
  64.         $currentUser $currentUser->fromArray($user);
  65.         $permissions PermissionBuilder::instance()->findPermissionsByRoles($currentUser->getRoles());
  66.         $currentUser->setPermissions($permissions);
  67.         $biz $this->getBiz();
  68.         $biz['user'] = $currentUser;
  69.     }
  70.     protected function trans($id, array $parameters = [], $domain null$locale null)
  71.     {
  72.         return $this->container->get('translator')->trans($id$parameters$domain$locale);
  73.     }
  74.     protected function isPluginInstalled($pluginName)
  75.     {
  76.         return $this->get('kernel')->getPluginConfigurationManager()->isPluginInstalled($pluginName);
  77.     }
  78.     protected function createJsonResponse($data null$status Response::HTTP_OK$headers = [])
  79.     {
  80.         return new JsonResponse($data$status$headers);
  81.     }
  82.     protected function createSuccessJsonResponse($data null$code null)
  83.     {
  84.         $resultData = ['status' => true];
  85.         if (null !== $data) {
  86.             $resultData['data'] = $data;
  87.         }
  88.         if (null !== $code) {
  89.             $resultData['code'] = $code;
  90.         }
  91.         return $this->createJsonResponse($resultData);
  92.     }
  93.     protected function createViolationJsonResponse($message ''$arguments = [], $code 0$data null)
  94.     {
  95.         if (null === $data) {
  96.             return $this->createJsonResponse([
  97.                 'status' => false,
  98.                 'code' => $code,
  99.                 'message' => $this->trans($message$arguments),
  100.             ], Response::HTTP_BAD_REQUEST);
  101.         }
  102.         return $this->createJsonResponse([
  103.             'status' => false,
  104.             'code' => $code,
  105.             'data' => $data,
  106.             'message' => $this->trans($message$arguments),
  107.         ], Response::HTTP_BAD_REQUEST);
  108.     }
  109.     protected function createPaginationJsonResponse($dataPaginator $paginator)
  110.     {
  111.         return $this->createJsonResponse(['status' => true'data' => $data'paginator' => $paginator->__toArray()], Response::HTTP_OK);
  112.     }
  113.     protected function getLdapConfigParameter($name)
  114.     {
  115.         return $this->container->getParameter($name);
  116.     }
  117.     protected function log($action$message$data)
  118.     {
  119.         $this->getLogService()->info(
  120.             self::APP_MODULE,
  121.             $action,
  122.             $message,
  123.             $data
  124.         );
  125.     }
  126.     protected function getListSort(Request $request)
  127.     {
  128.         $sortStr $request->query->get('sort');
  129.         if ($sortStr) {
  130.             $explodeSort explode(','$sortStr);
  131.             $sort = [];
  132.             foreach ($explodeSort as $part) {
  133.                 $prefix substr($part01);
  134.                 $field str_replace(self::PREFIX_SORT_DESC''$part);
  135.                 if (self::PREFIX_SORT_DESC == $prefix) {
  136.                     $sort[$field] = 'DESC';
  137.                 } else {
  138.                     $sort[$field] = 'ASC';
  139.                 }
  140.             }
  141.             return $sort;
  142.         }
  143.         return [];
  144.     }
  145.     protected function getUsersInfo($userId)
  146.     {
  147.         $user $this->getUserService()->getUser($userId);
  148.         if ($user) {
  149.             $user['userGroup'] = $this->getUserGroupMemberService()->findUserGroupsByUserId($user['id']);
  150.             $user['permissionOrg'] = $this->getManagePermissionOrgService()->findUserManageOrgIdsByUserId($user['id']);
  151.             $profile $this->getUserService()->getUserProfile($user['id']);
  152.             $user array_merge($profile$user);
  153.             $relevantColumns = ['org''post''role''permissionOrg'];
  154.             $users $this->getUserService()->searchUserRelevantInfoByUsers([$user], $relevantColumns);
  155.             if (!empty($users[$user['id']]['orgIds'])) {
  156.                 $orgs $this->getOrgService()->findOrgsByIds($users[$user['id']]['orgIds']);
  157.                 $users[$user['id']]['orgNames'] = implode('|'array_column($orgs'name'));
  158.             }
  159.             return $users[$user['id']];
  160.         }
  161.         return $user;
  162.     }
  163.     protected function packageUserInfo($users)
  164.     {
  165.         $userInfo = [];
  166.         $userInfo['truename'] = $users['truename'];
  167.         $userInfo['nickname'] = $users['nickname'];
  168.         $userInfo['postName'] = !empty($users['post']['name']) ? $users['post']['name'] : '';
  169.         $userInfo['postId'] = !empty($users['post']['id']) ? $users['post']['id'] : '';
  170.         $userInfo['fullOrg'] = $users['fullOrg'];
  171.         $userInfo['fullOrgIds'] = implode('|'ArrayToolkit::column($users['org'], 'id'));
  172.         return $userInfo;
  173.     }
  174.     protected function getFilePath($uri$default ''$absolute false)
  175.     {
  176.         /**
  177.          * @var WebExtension $webExtension
  178.          */
  179.         $webExtension $this->container->get('web.twig.extension');
  180.         return $webExtension->getFilePath($uri$default$absolute);
  181.     }
  182.     protected function getFpath($path$defaultKey false$package 'content')
  183.     {
  184.         /**
  185.          * @var WebExtension $webExtension
  186.          */
  187.         $webExtension $this->container->get('web.twig.extension');
  188.         return $webExtension->getFpath($path$defaultKey$package);
  189.     }
  190.     public function filterHtml($text)
  191.     {
  192.         if (empty($text)) {
  193.             return '';
  194.         }
  195.         preg_match_all('/\<img.*?src\s*=\s*[\'\"](.*?)[\'\"]/i'$text$matches);
  196.         if (empty($matches)) {
  197.             return $text;
  198.         }
  199.         $path trim($this->container->getParameter('topxia.upload.public_url_path'), '/');
  200.         foreach ($matches[1] as $url) {
  201.             $uri preg_replace("/^\/{$path}\//"''$url); // getFurl方法会默认加上 $path
  202.             $text str_replace($urlAssetHelper::getFurl($uri'content'), $text);
  203.         }
  204.         return $text;
  205.     }
  206.     protected function formatUserInfo($ownerId)
  207.     {
  208.         $userInfo current($this->getUserService()->searchUsers([
  209.             'id' => $ownerId ?? -1,
  210.             'noNeedLocked' => 1,
  211.         ], [], 01, ['id''truename''nickname''smallAvatar''mediumAvatar''largeAvatar']));
  212.         $userInfo['smallAvatar'] = AssetHelper::getFurl($userInfo['smallAvatar'] ?? '''avatar.png');
  213.         $userInfo['mediumAvatar'] = AssetHelper::getFurl($userInfo['mediumAvatar'] ?? '''avatar.png');
  214.         $userInfo['largeAvatar'] = AssetHelper::getFurl($userInfo['largeAvatar'] ?? '''avatar.png');
  215.         return $userInfo;
  216.     }
  217.     protected function formatOrgInfos(array $orgIds)
  218.     {
  219.         $orgs $this->getOrgService()->findOrgsByIds($orgIds ?? -1);
  220.         $orgInfos array_map(function ($org) {
  221.             return $org ? [
  222.                 'id' => $org['id'],
  223.                 'name' => $org['name'],
  224.                 'orgCode' => $org['orgCode'],
  225.             ] : null;
  226.         }, $orgs);
  227.         return ArrayToolkit::index($orgInfos'id');
  228.     }
  229.     protected function formatUserInfos(array $userIds, ?string $type null)
  230.     {
  231.         $conditions = [
  232.             'userIds' => $userIds ?: '-1',
  233.             'noNeedLocked' => 1,
  234.         ];
  235.         if ('all' === $type) {
  236.             $conditions['type'] = 'all';
  237.             $conditions['isExcludeTypes'] = true;
  238.         }
  239.         $userInfos $this->getUserService()->searchUsers($conditions, [], 0PHP_INT_MAX, ['id''truename''nickname''smallAvatar''mediumAvatar''largeAvatar''locked']);
  240.         $userInfos ArrayToolkit::index($userInfos'id');
  241.         foreach ($userInfos as $key => $userInfo) {
  242.             $userInfos[$key]['smallAvatar'] = AssetHelper::getFurl($userInfo['smallAvatar'] ?? '''avatar.png');
  243.             $userInfos[$key]['mediumAvatar'] = AssetHelper::getFurl($userInfo['mediumAvatar'] ?? '''avatar.png');
  244.             $userInfos[$key]['largeAvatar'] = AssetHelper::getFurl($userInfo['largeAvatar'] ?? '''avatar.png');
  245.         }
  246.         return $userInfos;
  247.     }
  248.     protected function getOrgIdStringByCodeString($orgCodeString)
  249.     {
  250.         $orgCodes explode(','$orgCodeString);
  251.         $orgs $this->getOrgService()->findOrgsByOrgCodes($orgCodes);
  252.         return implode(','array_column($orgs'id'));
  253.     }
  254.     /**
  255.      * @return SettingService
  256.      */
  257.     protected function getSettingService()
  258.     {
  259.         return $this->createService('System:SettingService');
  260.     }
  261.     /**
  262.      * @return UserService
  263.      */
  264.     protected function getUserService()
  265.     {
  266.         return $this->createService('User:UserService');
  267.     }
  268.     public function getLogService()
  269.     {
  270.         return $this->createService('System:LogService');
  271.     }
  272.     /**
  273.      * @return CourseService
  274.      */
  275.     protected function getCourseService()
  276.     {
  277.         return $this->createService('Course:CourseService');
  278.     }
  279.     /**
  280.      * @return \Biz\Course\Service\Impl\CourseSetServiceImpl
  281.      */
  282.     protected function getCourseSetService()
  283.     {
  284.         return $this->createService('Course:CourseSetService');
  285.     }
  286.     protected function getTaskService()
  287.     {
  288.         return $this->createService('Task:TaskService');
  289.     }
  290.     protected function getActivityService()
  291.     {
  292.         return $this->createService('Activity:ActivityService');
  293.     }
  294.     /**
  295.      * @return TestpaperService
  296.      */
  297.     protected function getTestpaperService()
  298.     {
  299.         return $this->createService('Testpaper:TestpaperService');
  300.     }
  301.     protected function getUserGroupMemberService()
  302.     {
  303.         return $this->createService('CorporateTrainingBundle:UserGroup:MemberService');
  304.     }
  305.     /**
  306.      * @return ManagePermissionOrgService
  307.      */
  308.     protected function getManagePermissionOrgService()
  309.     {
  310.         return $this->createService('CorporateTrainingBundle:ManagePermission:ManagePermissionOrgService');
  311.     }
  312.     protected function createService($alias)
  313.     {
  314.         $biz $this->getBiz();
  315.         return $biz->service($alias);
  316.     }
  317.     protected function getTokenStorage()
  318.     {
  319.         return $this->container->get('security.token_storage');
  320.     }
  321.     /**
  322.      * @return OrgService
  323.      */
  324.     protected function getOrgService()
  325.     {
  326.         return $this->getBiz()->service('Org:OrgService');
  327.     }
  328.     /**
  329.      * @return ResourceAccessScopeService
  330.      */
  331.     protected function getResourceAccessService()
  332.     {
  333.         return $this->createService('CorporateTrainingBundle:ResourceScope:ResourceAccessScopeService');
  334.     }
  335.     /**
  336.      * @return ResourceVisibleScopeService
  337.      */
  338.     protected function getResourceVisibleScopeService()
  339.     {
  340.         return $this->getBiz()->service('ResourceScope:ResourceVisibleScopeService');
  341.     }
  342. }