Completed
Push — work-fleets ( e155c0...addb18 )
by SuperNova.WS
06:08
created

Entity::bindFieldImport()   C

Complexity

Conditions 8
Paths 2

Size

Total Lines 44
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 8
eloc 22
nc 2
nop 2
dl 0
loc 44
rs 5.3846
c 1
b 0
f 1
ccs 0
cts 26
cp 0
crap 72
1
<?php
2
3
/**
4
 * Class Entity
5
 *
6
 * @property int|float $dbId Buddy record DB ID
7
 */
8
class Entity implements \Common\IMagicProperties {
9
  /**
10
   * Name of table for this entity
11
   *
12
   * @var string $tableName
13
   */
14
  protected static $tableName = '_table';
15
  /**
16
   * Name of key field field in this table
17
   *
18
   * @var string $idField
19
   */
20
  protected static $idField = 'id';
21
  /**
22
   * Container for property values
23
   *
24
   * @var PropertyHider $_container
25
   */
26
  protected $_container;
27
  protected static $_containerName = 'PropertyHiderInArray';
28
29
  /**
30
   * Property list
31
   *
32
   * @var array
33
   */
34
  protected static $_properties = array();
35
36
  /**
37
   * @var array
38
   */
39
  protected static $_propertyToField = array();
40
41
  /**
42
   * @var db_mysql|null $dbStatic
43
   */
44
  public static $dbStatic = null;
45
46
  protected function bindFieldExport($propertyData, $propertyName) {
47
    $fieldName = $propertyData[P_DB_FIELD];
48
49
    // Last resort - binding export function to DB field name
50
    // Property is mapped 1-to-1 to field
51
    if (!empty($propertyData[P_DB_FIELD]) && empty($propertyData[P_DB_ROW_EXPORT])) {
52
      /**
53
       * @param static $that
54
       */
55
      // Alas! No bindTo() method in 5.3 closures! So we should use what we have
56
      $propertyData[P_DB_ROW_EXPORT] = function ($that, &$row) use ($propertyName, $fieldName, $propertyData) {
57
        $row[$fieldName] = $that->$propertyName;
58
      };
59
    }
60
  }
61
62
  protected function bindFieldImport($propertyData, $propertyName) {
63
    $fieldName = $propertyData[P_DB_FIELD];
64
65
    // Last resort - binding import function to DB field name
66
    // Property is mapped 1-to-1 to field
67
    if (!empty($propertyData[P_DB_FIELD]) && empty($propertyData[P_DB_ROW_IMPORT])) {
68
      /**
69
       * @param static $that
70
       */
71
      // Alas! No bindTo() method in 5.3 closures! So we should use what we have
72
      $propertyData[P_DB_ROW_IMPORT] = function ($that, &$row) use ($propertyName, $fieldName, $propertyData) {
73
        $type = !empty($propertyData[P_DB_TYPE]) ? $propertyData[P_DB_TYPE] : '';
74
75
        // "array"
76
77
        // TODO: Here should be some conversions to property type
78
        switch ($type) {
79
          case TYPE_INTEGER:
80
            $value = intval($row[$fieldName]);
81
          break;
82
83
          case TYPE_DOUBLE:
84
            $value = floatval($row[$fieldName]);
85
          break;
86
87
          case TYPE_BOOLEAN:
88
            $value = boolval($row[$fieldName]);
89
          break;
90
91
          case TYPE_NULL:
92
            $value = null;
93
          break;
94
95
          // No-type defaults to string
96
          default:
97
            $value = (string)$row[$fieldName];
98
          break;
99
        }
100
101
//        $that->$propertyName = $row[$fieldName];
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
102
        $that->$propertyName = $value;
103
      };
104
    }
105
  }
106
107
  /**
108
   * Fills property-to-field table which used to generate result array
109
   */
110
  protected function fillPropertyToField() {
111
    if (!empty(static::$_propertyToField)) {
112
      return;
113
    }
114
115
    // Filling property-to-field relation array
116
    foreach (static::$_properties as $propertyName => &$propertyData) {
117
      $this->bindFieldExport($propertyData, $propertyName);
0 ignored issues
show
Unused Code introduced by
The call to the method Entity::bindFieldExport() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
118
      $this->bindFieldImport($propertyData, $propertyName);
0 ignored issues
show
Unused Code introduced by
The call to the method Entity::bindFieldImport() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
119
    }
120
  }
121
122
  /**
123
   * Entity constructor.
124
   *
125
   * @param \Pimple\GlobalContainer $gc
126
   */
127
  public function __construct($gc) {
128
    empty(static::$dbStatic) && !empty($gc->db) ? static::$dbStatic = $gc->db : false;
0 ignored issues
show
Documentation Bug introduced by
It seems like $gc->db can also be of type object<Closure>. However, the property $dbStatic is declared as type object<db_mysql>|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
129
130
    $this->_container = new static::$_containerName();
131
    $this->_container->setProperties(static::$_properties);
132
133
    $this->fillPropertyToField();
0 ignored issues
show
Unused Code introduced by
The call to the method Entity::fillPropertyToField() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
134
  }
135
136
137
  public function getTableName() {
138
    return static::$tableName;
139
  }
140
141
  public function getIdFieldName() {
142
    return static::$idField;
143
  }
144
145
  public function load($recordId) {
146
    classSupernova::$gc->dbRowOperator->getById($this, $recordId);
0 ignored issues
show
Bug introduced by
The method getById does only exist in DbRowSimple, but not in Closure.

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...
147
  }
148
149
  // TODO - move to reader ????????
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
150
  public function delete() {
151
    return classSupernova::$gc->dbRowOperator->deleteById($this);
0 ignored issues
show
Bug introduced by
The method deleteById does only exist in DbRowSimple, but not in Closure.

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...
152
  }
153
154
  /**
155
   * @return int|string
156
   */
157
  // TODO - move to reader ????????
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
158
  public function insert() {
159
    return classSupernova::$gc->dbRowOperator->insert($this);
0 ignored issues
show
Bug introduced by
The method insert does only exist in DbRowSimple, but not in Closure.

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...
160
  }
161
162
  public function isContainerEmpty() {
163
    return $this->_container->isContainerEmpty();
164
  }
165
166
  public function isNew() {
167
    return $this->getIdFieldName() != 0;
168
  }
169
170
  /**
171
   * Invoke row transformation operation on object
172
   *
173
   * Uses in to save/load data from DB row into/from object
174
   *
175
   * @param array  $row
176
   * @param string $operation
177
   * @param string $desc
178
   *
179
   * @throws Exception
180
   */
181
  protected function rowInvokeOperation(&$row, $operation, $desc) {
182
    foreach (static::$_properties as $propertyName => $propertyData) {
183
      if (is_callable($propertyData[$operation])) {
184
        // Some black magic here
185
        // Closure is a class - so have __invoke() magic method
186
        // It means we can invoke it by directly call __invoke()
187
        $propertyData[$operation]->__invoke($this, $row);
188
        // TODO - however for a sake of uniformity may be we should consider use call_user_func
189
//      call_user_func($propertyData[P_DB_ROW_EXPORT], $this);
190
      } else {
191
        throw new \Exception('There is no valid DB row ' . $desc . ' for ' . get_called_class() . '::' . $propertyName);
192
      }
193
    }
194
  }
195
196
  /**
197
   * Import DB row state into object properties
198
   *
199
   * @param array $row
200
   */
201
  public function importDbRow($row) {
202
    $this->rowInvokeOperation($row, P_DB_ROW_IMPORT, 'IMPORTER');
203
  }
204
205
  /**
206
   * Export data from object properties into DB row for further use
207
   *
208
   * @param bool $withDbId - Should dbId too be returned. Useful for INSERT statements
209
   *
210
   * @return array
211
   */
212
  public function exportDbRow($withDbId = true) {
213
    $row = array();
214
215
    $this->rowInvokeOperation($row, P_DB_ROW_EXPORT, 'EXPORTER');
216
217
    if (!$withDbId) {
218
      unset($row[$this->getIdFieldName()]);
219
    }
220
221
    return $row;
222
  }
223
224
225
  public function __get($name) {
226
    return $this->_container->$name;
227
  }
228
229
  public function __set($name, $value) {
230
    $this->_container->$name = $value;
231
  }
232
233
  public function __isset($name) {
234
    return isset($this->_container->$name);
235
  }
236
237
  public function __unset($name) {
238
    unset($this->_container->$name);
239
  }
240
241
}
242