User
last analyzed

Complexity

Total Complexity 0

Size/Duplication

Total Lines 1
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 0
lcom 0
cbo 1
dl 0
loc 1
c 0
b 0
f 0
1
<?php
2
3
use ORM\EntityManager;
4
5
require __DIR__ . '/vendor/autoload.php';
6
7
$username = 'user_a'; // $_POST['username']
8
$password = 'password_a'; // $_POST['password']
9
10
/**************************
11
 * SETUP EXAMPLE DATABASE *
12
 **************************/
13
$em = new EntityManager([
14
    EntityManager::OPT_CONNECTION => new \ORM\DbConfig('sqlite', '/tmp/example.sqlite')
15
]);
16
17
$em->getConnection()->query("DROP TABLE IF EXISTS user");
18
19
$em->getConnection()->query("CREATE TABLE user (
20
  id INTEGER NOT NULL PRIMARY KEY,
21
  username VARCHAR (20) NOT NULL,
22
  password VARCHAR (32) NOT NULL
23
)");
24
25
$em->getConnection()->query("CREATE UNIQUE INDEX user_username ON user (username)");
26
27
$em->getConnection()->query("INSERT INTO user (username, password) VALUES
28
  ('user_a', '" . md5('password_a') . "'),
29
  ('user_b', '" . md5('password_b') . "'),
30
  ('user_c', '" . md5('password_c') . "')
31
");
32
33
/*********************
34
 * DEFINE THE ENTITY *
35
 *********************/
36
37
/**
38
 * Class User
39
 *
40
 * The following annotations are optional
41
 * @property int id
42
 * @property string username
43
 * @property string password
44
 */
45
class User extends ORM\Entity {}
46
47
/*******************************
48
 * Fetch entity with own query *
49
 *******************************/
50
$user = $em->fetch(User::class)
0 ignored issues
show
Bug introduced by
The method setQuery does only exist in ORM\EntityFetcher, but not in ORM\Entity.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
51
    ->setQuery("SELECT * FROM user WHERE username = ? AND password = ?", [$username, md5($password)])
52
    ->one();
53
54
var_dump($user);
55
56
57
/*******************************
58
 * Fetch with where conditions *
59
 *******************************/
60
$user = $em->fetch(User::class)
0 ignored issues
show
Bug introduced by
The method where does only exist in ORM\EntityFetcher, but not in ORM\Entity.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
61
    ->where('username', 'LIKE', $username)
62
    ->andWhere('password', '=', md5($password))
63
    ->one();
64
65
var_dump($user);
66
67
/*******************************************
68
 * Fetch with parenthesis, group and order *
69
 *******************************************/
70
try {
71
    $fetcher = $em->fetch(User::class)
72
                  ->where(User::class . '::username LIKE ?', 'USER_A')
73
                  ->andWhere('password', '=', md5('password_a'))
74
                  ->orParenthesis()
75
                      ->where(User::class . '::username = ' . $em->getConnection()->quote('user_b'))
76
                      ->andWhere('t0.password = \'' . md5('password_b') . '\'')
77
                      ->close()
78
                  ->groupBy('id')
79
                  ->orderBy(
80
                      'CASE WHEN username = ? THEN 1 WHEN username = ? THEN 2 ELSE 3 END',
81
                      'ASC',
82
                      ['user_a', 'user_b']
83
                  );
84
    $users = $fetcher->all();
85
86
    var_dump($users);
87
} catch (\PDOException $exception) {
88
    file_put_contents('php://stderr', $exception->getMessage() . "\nSQL:" . $fetcher->getQuery());
89
}
90
91
/*******************
92
 * Cache an entity *
93
 *******************/
94
$cachedUser = serialize($user);
95
var_dump($cachedUser);
96
97
/******************************
98
 * Get previously cached User *
99
 ******************************/
100
// lets say we cached user3 with password from user1 - so modify the $cachedUser
101
$cachedUser = str_replace([
102
    's:1:"1"',
103
    's:6:"user_a"'
104
], [
105
    's:1:"3"',
106
    's:6:"user_c"'
107
], $cachedUser);
108
/** @var User $user */
109
$user = $em->map(unserialize($cachedUser));
110
$user = $em->fetch(User::class, 3);
111
var_dump($user, $user->isDirty(), $user->isDirty('username'));
0 ignored issues
show
Bug introduced by
The method isDirty does only exist in ORM\Entity, but not in ORM\EntityFetcher.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
112
113
/*********************************
114
 * Get a previously fetched user *
115
 *********************************/
116
// sqlite returns strings and currently we do not convert to int
117
$user1 = $em->fetch(User::class, 1); // queries the database again
118
$user2 = $em->map(new User(['id' => 1]));
119
$user3 = $em->fetch(User::class, 1); // returns $user2
120
$user4 = $em->map(new User(['id' => '1']));
121
var_dump($user1->username, $user2->username, $user3 === $user2, $user1 === $user4);
0 ignored issues
show
Documentation introduced by
The property username does not exist on object<ORM\Entity>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
122
123
/********************************
124
 * Validate data for a new user *
125
 ********************************/
126
$data = [
127
    'username' => 'This username is way to long for a username',
128
    'password' => null // null is not allowed
129
];
130
$result = User::validateArray($data);
131
echo $result['username']->getMessage() . "\n" . $result['password']->getMessage() . "\n";
132