Passed
Push — develop ( 6bc206...75605a )
by Carsten
10:11
created

PdoInsertNewUser::__construct()   B

Complexity

Conditions 3
Paths 1

Size

Total Lines 26
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 1
nop 3
dl 0
loc 26
ccs 7
cts 7
cp 1
crap 3
rs 8.8571
c 0
b 0
f 0
1
<?php
2
namespace Germania\UserProfiles;
3
4
use Germania\UserProfiles\Exceptions\InsertUserException;
5
6
use Psr\Log\LoggerInterface;
7
use Psr\Log\NullLogger;
8
9
/**
10
 * This Callable insert a new User and returns his new ID.
11
 *
12
 * Example:
13
 *
14
 *     <?php
15
 *     use Germania\UserProfiles\PdoInsertNewUser;
16
 *
17
 *     $pdo    = new PDO( ... );
18
 *     $logger = new Monolog();
19
 *     $table  = 'users';
20
 *
21
 *     $inserter = new PdoInsertNewUser( $pdo, $logger, $table);
22
 *     $new_id = $inserter([
23
 *         'first_name'   => 'John',
24
 *         'last_name'    => 'Doe',
25
 *         'display_name' => 'John Doe',
26
 *         'email'        => '[email protected]',
27
 *         'login'        => '[email protected]'
28
 *     ]);
29
 *     ?>
30
 *
31
 * @author  Carsten Witt <[email protected]>
32
 */
33
class PdoInsertNewUser
34
{
35
36
    /**
37
     * Database table
38
     * @var string
39
     */
40
    public $table = 'users';
41
42
    /**
43
     * @var PDO
44
     */
45
    public $pdo;
46
47
    /**
48
     * @var PDOStatement
0 ignored issues
show
Bug introduced by
The type Germania\UserProfiles\PDOStatement was not found. Did you mean PDOStatement? If so, make sure to prefix the type with \.
Loading history...
49
     */
50
    public $stmt;
51
52
    /**
53
     * @var LoggerInterface
54
     */
55
    public $logger;
56
57
58
    /**
59
     * @param PDO             $pdo         PDO instance
60
     * @param LoggerInterface $logger      Optional: PSR-3 Logger
61
     * @param string          $table       Optional: Database table name
62
     */
63 20
	public function __construct( \PDO $pdo, LoggerInterface $logger = null, $table = null )
64
    {
65
        // Setup
66 20
        $this->pdo    = $pdo;
0 ignored issues
show
Documentation Bug introduced by
It seems like $pdo of type PDO is incompatible with the declared type Germania\UserProfiles\PDO of property $pdo.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
67 20
		$this->logger = $logger ?: new NullLogger;
68 20
        $this->table  = $table  ?: $this->table;
69
70
        // Prepare business
71 20
        $sql = "INSERT INTO {$this->table} (
72
        user_login_name,
73
        user_display_name,
74
        user_email,
75
        user_last_name,
76
        user_first_name,
77
        created
78
        ) VALUES (
79
        :user_login_name,
80
        :user_display_name,
81
        :user_email,
82
        :user_last_name,
83
        :user_first_name,
84
        :created
85 5
        )";
86
87
        // Prepare
88 20
        $this->stmt = $this->pdo->prepare( $sql );
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->pdo->prepare($sql) of type PDOStatement is incompatible with the declared type Germania\UserProfiles\PDOStatement of property $stmt.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
89
90 20
	}
91
92
93
94
95
    /**
96
     * Inserts the user using the passed array. It must contain these elements:
97
     *
98
     * - first_name
99
     * - last_name
100
     * - display_name
101
     * - email
102
     * - login
103
     *
104
     * @param  array  $user_data User data
105
     *
106
     * @return int    New User ID
107
     *
108
     * @throws InsertUserException|UserProfileExceptionInterface if PDOStatement execution fails or missing required field.
109
     */
110 16
    public function __invoke( array $user_data )
111
    {
112
113
        // Setup
114
        $required_fields = [
115 16
            'first_name',
116 4
            'last_name',
117 4
            'display_name',
118 4
            'email',
119
            'login'
120 4
        ];
121
122
        // Check data
123 16
        foreach($required_fields as $rf):
124 16
            if (!array_key_exists($rf, $user_data)) :
125
126 4
                $message = "Missing field '$rf' in user data";
127 4
                $this->logger->error( $message );
128 13
                throw new InsertUserException( $message );
129
130
            endif;
131 4
        endforeach;
132
133
134
        // Perform
135 12
        $result = $this->stmt->execute([
136 12
            'user_login_name'   => $user_data[ "login" ],
137 12
            'user_display_name' => $user_data[ "display_name" ],
138 12
            'user_email'        => $user_data[ "email" ],
139 12
            'user_last_name'    => $user_data[ "last_name" ],
140 12
            'user_first_name'   => $user_data[ "first_name" ],
141 12
            'created' => date('Y-m-d H:i:s')
142 12
        ]) ? $this->pdo->lastInsertId() : null;
143
144
145
        // Evaluate
146
        $loginfo = [
147 12
            'new_user_id'       => $result,
148 12
            'user_display_name' => $user_data[ "display_name" ]
149 3
        ];
150 12
        if ($result):
151 8
            $this->logger->info("Successfully added new user.", $loginfo);
152 8
            return $result;
153
        endif;
154
155 4
        $this->logger->error("Could not add new user?!", $loginfo);
156 4
        throw new InsertUserException;
157
158
    }
159
160
161
}
162