UserController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. <?php
  2. /*
  3. * This file is part of the Sonata Project package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\UserBundle\Controller\Api;
  11. use FOS\RestBundle\Context\Context;
  12. use FOS\RestBundle\Controller\Annotations\QueryParam;
  13. use FOS\RestBundle\Controller\Annotations\View;
  14. use FOS\RestBundle\Request\ParamFetcherInterface;
  15. use FOS\RestBundle\View\View as FOSRestView;
  16. use FOS\UserBundle\Model\GroupInterface;
  17. use JMS\Serializer\SerializationContext;
  18. use Nelmio\ApiDocBundle\Annotation\ApiDoc;
  19. use Sonata\DatagridBundle\Pager\PagerInterface;
  20. use Sonata\UserBundle\Model\GroupManagerInterface;
  21. use Sonata\UserBundle\Model\UserInterface;
  22. use Sonata\UserBundle\Model\UserManagerInterface;
  23. use Symfony\Component\Form\FormFactoryInterface;
  24. use Symfony\Component\Form\FormInterface;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  27. /**
  28. * @author Hugo Briand <briand@ekino.com>
  29. */
  30. class UserController
  31. {
  32. /**
  33. * @var UserManagerInterface
  34. */
  35. protected $userManager;
  36. /**
  37. * @var GroupManagerInterface
  38. */
  39. protected $groupManager;
  40. /**
  41. * @var FormFactoryInterface
  42. */
  43. protected $formFactory;
  44. /**
  45. * @param UserManagerInterface $userManager
  46. * @param GroupManagerInterface $groupManager
  47. * @param FormFactoryInterface $formFactory
  48. */
  49. public function __construct(UserManagerInterface $userManager, GroupManagerInterface $groupManager, FormFactoryInterface $formFactory)
  50. {
  51. $this->userManager = $userManager;
  52. $this->groupManager = $groupManager;
  53. $this->formFactory = $formFactory;
  54. }
  55. /**
  56. * Returns a paginated list of users.
  57. *
  58. * @ApiDoc(
  59. * resource=true,
  60. * output={"class"="Sonata\DatagridBundle\Pager\PagerInterface", "groups"={"sonata_api_read"}}
  61. * )
  62. *
  63. * @QueryParam(name="page", requirements="\d+", default="1", description="Page for users list pagination (1-indexed)")
  64. * @QueryParam(name="count", requirements="\d+", default="10", description="Number of users by page")
  65. * @QueryParam(name="enabled", requirements="0|1", nullable=true, strict=true, description="Enabled/disabled users only?")
  66. * @QueryParam(name="locked", requirements="0|1", nullable=true, strict=true, description="Locked/Non-locked users only?")
  67. *
  68. * @View(serializerGroups={"sonata_api_read"}, serializerEnableMaxDepthChecks=true)
  69. *
  70. * @param ParamFetcherInterface $paramFetcher
  71. *
  72. * @return PagerInterface
  73. */
  74. public function getUsersAction(ParamFetcherInterface $paramFetcher)
  75. {
  76. $orderByQueryParam = new QueryParam();
  77. $orderByQueryParam->name = 'orderBy';
  78. $orderByQueryParam->requirements = 'ASC|DESC';
  79. $orderByQueryParam->nullable = true;
  80. $orderByQueryParam->strict = true;
  81. $orderByQueryParam->description = 'Query users order by clause (key is field, value is direction)';
  82. if (property_exists($orderByQueryParam, 'map')) {
  83. $orderByQueryParam->map = true;
  84. } else {
  85. $orderByQueryParam->array = true;
  86. }
  87. $paramFetcher->addParam($orderByQueryParam);
  88. $supporedCriteria = array(
  89. 'enabled' => '',
  90. 'locked' => '',
  91. );
  92. $page = $paramFetcher->get('page');
  93. $limit = $paramFetcher->get('count');
  94. $sort = $paramFetcher->get('orderBy');
  95. $criteria = array_intersect_key($paramFetcher->all(), $supporedCriteria);
  96. foreach ($criteria as $key => $value) {
  97. if (null === $value) {
  98. unset($criteria[$key]);
  99. }
  100. }
  101. if (!$sort) {
  102. $sort = array();
  103. } elseif (!is_array($sort)) {
  104. $sort = array($sort, 'asc');
  105. }
  106. return $this->userManager->getPager($criteria, $page, $limit, $sort);
  107. }
  108. /**
  109. * Retrieves a specific user.
  110. *
  111. * @ApiDoc(
  112. * requirements={
  113. * {"name"="id", "dataType"="integer", "requirement"="\d+", "description"="user id"}
  114. * },
  115. * output={"class"="Sonata\UserBundle\Model\UserInterface", "groups"={"sonata_api_read"}},
  116. * statusCodes={
  117. * 200="Returned when successful",
  118. * 404="Returned when user is not found"
  119. * }
  120. * )
  121. *
  122. * @View(serializerGroups={"sonata_api_read"}, serializerEnableMaxDepthChecks=true)
  123. *
  124. * @param $id
  125. *
  126. * @return UserInterface
  127. */
  128. public function getUserAction($id)
  129. {
  130. return $this->getUser($id);
  131. }
  132. /**
  133. * Adds an user.
  134. *
  135. * @ApiDoc(
  136. * input={"class"="sonata_user_api_form_user", "name"="", "groups"={"sonata_api_write"}},
  137. * output={"class"="Sonata\UserBundle\Model\User", "groups"={"sonata_api_read"}},
  138. * statusCodes={
  139. * 200="Returned when successful",
  140. * 400="Returned when an error has occurred while user creation",
  141. * }
  142. * )
  143. *
  144. * @param Request $request A Symfony request
  145. *
  146. * @return UserInterface
  147. *
  148. * @throws NotFoundHttpException
  149. */
  150. public function postUserAction(Request $request)
  151. {
  152. return $this->handleWriteUser($request);
  153. }
  154. /**
  155. * Updates an user.
  156. *
  157. * @ApiDoc(
  158. * requirements={
  159. * {"name"="id", "dataType"="integer", "requirement"="\d+", "description"="user identifier"}
  160. * },
  161. * input={"class"="sonata_user_api_form_user", "name"="", "groups"={"sonata_api_write"}},
  162. * output={"class"="Sonata\UserBundle\Model\User", "groups"={"sonata_api_read"}},
  163. * statusCodes={
  164. * 200="Returned when successful",
  165. * 400="Returned when an error has occurred while user creation",
  166. * 404="Returned when unable to find user"
  167. * }
  168. * )
  169. *
  170. * @param int $id User id
  171. * @param Request $request A Symfony request
  172. *
  173. * @return UserInterface
  174. *
  175. * @throws NotFoundHttpException
  176. */
  177. public function putUserAction($id, Request $request)
  178. {
  179. return $this->handleWriteUser($request, $id);
  180. }
  181. /**
  182. * Deletes an user.
  183. *
  184. * @ApiDoc(
  185. * requirements={
  186. * {"name"="id", "dataType"="integer", "requirement"="\d+", "description"="user identifier"}
  187. * },
  188. * statusCodes={
  189. * 200="Returned when user is successfully deleted",
  190. * 400="Returned when an error has occurred while user deletion",
  191. * 404="Returned when unable to find user"
  192. * }
  193. * )
  194. *
  195. * @param int $id An User identifier
  196. *
  197. * @return \FOS\RestBundle\View\View
  198. *
  199. * @throws NotFoundHttpException
  200. */
  201. public function deleteUserAction($id)
  202. {
  203. $user = $this->getUser($id);
  204. $this->userManager->deleteUser($user);
  205. return array('deleted' => true);
  206. }
  207. /**
  208. * Attach a group to a user.
  209. *
  210. * @ApiDoc(
  211. * requirements={
  212. * {"name"="userId", "dataType"="integer", "requirement"="\d+", "description"="user identifier"},
  213. * {"name"="groupId", "dataType"="integer", "requirement"="\d+", "description"="group identifier"}
  214. * },
  215. * output={"class"="Sonata\UserBundle\Model\User", "groups"={"sonata_api_read"}},
  216. * statusCodes={
  217. * 200="Returned when successful",
  218. * 400="Returned when an error has occurred while user/group attachment",
  219. * 404="Returned when unable to find user or group"
  220. * }
  221. * )
  222. *
  223. * @param int $userId A User identifier
  224. * @param int $groupId A Group identifier
  225. *
  226. * @return UserInterface
  227. *
  228. * @throws NotFoundHttpException
  229. * @throws \RuntimeException
  230. */
  231. public function postUserGroupAction($userId, $groupId)
  232. {
  233. $user = $this->getUser($userId);
  234. $group = $this->getGroup($groupId);
  235. if ($user->hasGroup($group)) {
  236. return FOSRestView::create(array(
  237. 'error' => sprintf('User "%s" already has group "%s"', $userId, $groupId),
  238. ), 400);
  239. }
  240. $user->addGroup($group);
  241. $this->userManager->updateUser($user);
  242. return array('added' => true);
  243. }
  244. /**
  245. * Detach a group to a user.
  246. *
  247. * @ApiDoc(
  248. * requirements={
  249. * {"name"="userId", "dataType"="integer", "requirement"="\d+", "description"="user identifier"},
  250. * {"name"="groupId", "dataType"="integer", "requirement"="\d+", "description"="group identifier"}
  251. * },
  252. * output={"class"="Sonata\UserBundle\Model\User", "groups"={"sonata_api_read"}},
  253. * statusCodes={
  254. * 200="Returned when successful",
  255. * 400="Returned when an error has occurred while user/group detachment",
  256. * 404="Returned when unable to find user or group"
  257. * }
  258. * )
  259. *
  260. * @param int $userId A User identifier
  261. * @param int $groupId A Group identifier
  262. *
  263. * @return UserInterface
  264. *
  265. * @throws NotFoundHttpException
  266. * @throws \RuntimeException
  267. */
  268. public function deleteUserGroupAction($userId, $groupId)
  269. {
  270. $user = $this->getUser($userId);
  271. $group = $this->getGroup($groupId);
  272. if (!$user->hasGroup($group)) {
  273. return FOSRestView::create(array(
  274. 'error' => sprintf('User "%s" has not group "%s"', $userId, $groupId),
  275. ), 400);
  276. }
  277. $user->removeGroup($group);
  278. $this->userManager->updateUser($user);
  279. return array('removed' => true);
  280. }
  281. /**
  282. * Retrieves user with id $id or throws an exception if it doesn't exist.
  283. *
  284. * @param $id
  285. *
  286. * @return UserInterface
  287. *
  288. * @throws NotFoundHttpException
  289. */
  290. protected function getUser($id)
  291. {
  292. $user = $this->userManager->findUserBy(array('id' => $id));
  293. if (null === $user) {
  294. throw new NotFoundHttpException(sprintf('User (%d) not found', $id));
  295. }
  296. return $user;
  297. }
  298. /**
  299. * Retrieves user with id $id or throws an exception if it doesn't exist.
  300. *
  301. * @param $id
  302. *
  303. * @return GroupInterface
  304. *
  305. * @throws NotFoundHttpException
  306. */
  307. protected function getGroup($id)
  308. {
  309. $group = $this->groupManager->findGroupBy(array('id' => $id));
  310. if (null === $group) {
  311. throw new NotFoundHttpException(sprintf('Group (%d) not found', $id));
  312. }
  313. return $group;
  314. }
  315. /**
  316. * Write an User, this method is used by both POST and PUT action methods.
  317. *
  318. * @param Request $request Symfony request
  319. * @param int|null $id An User identifier
  320. *
  321. * @return FormInterface
  322. */
  323. protected function handleWriteUser($request, $id = null)
  324. {
  325. $user = $id ? $this->getUser($id) : null;
  326. $form = $this->formFactory->createNamed(null, 'sonata_user_api_form_user', $user, array(
  327. 'csrf_protection' => false,
  328. ));
  329. $form->submit($request);
  330. if ($form->isValid()) {
  331. $user = $form->getData();
  332. $this->userManager->updateUser($user);
  333. $view = FOSRestView::create($user);
  334. if (class_exists('FOS\RestBundle\Context\Context')) {
  335. $context = new Context();
  336. $context->setGroups(array('sonata_api_read'));
  337. $view->setContext($context);
  338. } else {
  339. $serializationContext = SerializationContext::create();
  340. $serializationContext->setGroups(array('sonata_api_read'));
  341. $serializationContext->enableMaxDepthChecks();
  342. $view->setSerializationContext($serializationContext);
  343. }
  344. return $view;
  345. }
  346. return $form;
  347. }
  348. }