This repository has been archived by the owner on Sep 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 96
/
RegisterController.php
83 lines (72 loc) · 2.43 KB
/
RegisterController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
namespace Conduit\Controllers\Auth;
use Conduit\Models\User;
use Conduit\Transformers\UserTransformer;
use Interop\Container\ContainerInterface;
use League\Fractal\Resource\Item;
use Slim\Http\Request;
use Slim\Http\Response;
use Respect\Validation\Validator as v;
class RegisterController
{
/** @var \Conduit\Validation\Validator */
protected $validator;
/** @var \Illuminate\Database\Capsule\Manager */
protected $db;
/** @var \League\Fractal\Manager */
protected $fractal;
/** @var \Conduit\Services\Auth\Auth */
private $auth;
/**
* RegisterController constructor.
*
* @param \Interop\Container\ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->auth = $container->get('auth');
$this->validator = $container->get('validator');
$this->db = $container->get('db');
$this->fractal = $container->get('fractal');
}
/**
* Register New Users from POST Requests to /api/users
*
* @param \Slim\Http\Request $request
* @param \Slim\Http\Response $response
*
* @return \Slim\Http\Response
*/
public function register(Request $request, Response $response)
{
$validation = $this->validateRegisterRequest($userParams = $request->getParam('user'));
if ($validation->failed()) {
return $response->withJson(['errors' => $validation->getErrors()], 422);
}
$user = new User($userParams);
$user->token = $this->auth->generateToken($user);
$user->password = password_hash($userParams['password'], PASSWORD_DEFAULT);
$user->save();
$resource = new Item($user, new UserTransformer());
$user = $this->fractal->createData($resource)->toArray();
return $response->withJson(
[
'user' => $user,
]);
}
/**
* @param array
*
* @return \Conduit\Validation\Validator
*/
protected function validateRegisterRequest($values)
{
return $this->validator->validateArray($values,
[
'email' => v::noWhitespace()->notEmpty()->email()->existsInTable($this->db->table('users'), 'email'),
'username' => v::noWhitespace()->notEmpty()->existsInTable($this->db->table('users'),
'username'),
'password' => v::noWhitespace()->notEmpty(),
]);
}
}