Test Failed
Push — trunk ( db071f...8d464a )
by SuperNova.WS
06:33
created

classPersistent   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 130
Duplicated Lines 5.38 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 7
loc 130
rs 10
c 0
b 0
f 0
wmc 26
lcom 1
cbo 1

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 2
A getInstance() 7 7 2
A db_loadItem() 0 12 4
A db_loadAll() 0 10 2
A loadDefaults() 0 5 2
A db_saveAll() 0 9 1
C db_saveItem() 0 25 8
A pass() 0 4 1
A __get() 0 8 2
A __set() 0 8 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * Created by Gorlum 29.10.2016 10:16
4
 */
5
6
/**
7
 *
8
 * Persistent is extension of class cacher and can save itself to DB
9
 * It's most usefull to hold basic structures as configuration, variables etc
10
 * Persistent pretty smart to handle one-level tables structures a-la "variable_name"+"variable_value"
11
 * Look supernova.sql to learn more
12
 * Also this class can holds default values for variables
13
 *
14
 * @package supernova
15
 *
16
 */
17
class classPersistent extends classCache {
18
  protected $table_name;
19
  protected $sql_index_field;
20
  protected $sql_value_field;
21
22
  protected $defaults = array();
23
24
  /**
25
   * @var bool $force
26
   */
27
  protected $force = false;
28
29
  public function __construct($gamePrefix = 'sn_', $table_name = 'table') {
30
    parent::__construct("{$gamePrefix}{$table_name}_");
31
    $this->table_name = $table_name;
32
33
    $this->sql_index_field = "{$table_name}_name";
34
    $this->sql_value_field = "{$table_name}_value";
35
36
    if(!$this->_DB_LOADED) {
0 ignored issues
show
Documentation introduced by
The property _DB_LOADED does not exist on object<classPersistent>. 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...
37
      $this->db_loadAll();
38
    }
39
  }
40
41 View Code Duplication
  public static function getInstance($gamePrefix = 'sn_', $table_name = '') {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
42
    if (!isset(self::$cacheObject)) {
43
      $className = get_class();
44
      self::$cacheObject = new $className($gamePrefix, $table_name);
45
    }
46
    return self::$cacheObject;
47
  }
48
49
  /**
50
   * @param string $index
51
   *
52
   * @return string|null
53
   */
54
  public function db_loadItem($index) {
55
    $result = null;
56
    if($index) {
57
      $index_safe = db_escape($index);
58
      $queryResult = doquery("SELECT `{$this->sql_value_field}` FROM `{{{$this->table_name}}}` WHERE `{$this->sql_index_field}` = '{$index_safe}' FOR UPDATE", true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
59
      if(is_array($queryResult) && !empty($queryResult)) {
60
        $this->$index = $result = $queryResult[$this->sql_value_field];
61
      }
62
    }
63
64
    return $result;
65
  }
66
67
  public function db_loadAll() {
68
    $this->loadDefaults();
69
70
    $query = doquery("SELECT * FROM {{{$this->table_name}}} FOR UPDATE;");
71
    while($row = db_fetch($query)) {
72
      $this->$row[$this->sql_index_field] = $row[$this->sql_value_field];
73
    }
74
75
    $this->_DB_LOADED = true;
0 ignored issues
show
Documentation introduced by
The property _DB_LOADED does not exist on object<classPersistent>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
76
  }
77
78
  public function loadDefaults() {
79
    foreach($this->defaults as $defName => $defValue) {
80
      $this->$defName = $defValue;
81
    }
82
  }
83
84
  public function db_saveAll() {
85
//    $toSave = array();
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% 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...
86
//    foreach($this->defaults as $field => $value) {
87
//      $toSave[$field] = NULL;
88
//    }
89
//    $this->db_saveItem($toSave);
90
    // Для того, что бы не лезть в кэш за каждым айтемом, а сразу все известные переменные сохранить
91
    $this->db_saveItem(array_combine(array_keys($this->defaults), array_fill(0, count($this->defaults), null)));
92
  }
93
94
  public function db_saveItem($item_list, $value = NULL) {
95
    if(empty($item_list)) {
96
      return;
97
    }
98
99
    !is_array($item_list) ? $item_list = array($item_list => $value) : false;
100
101
    // Сначала записываем данные в базу - что бы поймать все блокировки
102
    $qry = array();
103
    foreach($item_list as $item_name => $item_value) {
104
      if($item_name) {
105
        $item_value = db_escape($item_value === NULL ? $this->$item_name : $item_value);
106
        $item_name = db_escape($item_name);
107
        $qry[] = "('{$item_name}', '{$item_value}')";
108
      }
109
    }
110
    doquery("REPLACE INTO `{{" . $this->table_name . "}}` (`{$this->sql_index_field}`, `{$this->sql_value_field}`) VALUES " . implode(',', $qry) . ";");
111
112
    // И только после взятия блокировок - меняем значения в кэше
113
    foreach($item_list as $item_name => $item_value) {
114
      if($item_name) {
115
        $this->__set($item_name, $item_value);
116
      }
117
    }
118
  }
119
120
  /**
121
   * Makes cache to pass next operation to DB - whether it read or write
122
   */
123
  public function pass() {
124
    $this->force = true;
125
    return $this;
126
  }
127
128
  public function __get($name) {
129
    if($this->force) {
130
      $this->force = false;
131
      $this->db_loadItem($name);
132
    }
133
134
    return parent::__get($name);
135
  }
136
137
  public function __set($name, $value) {
138
    if($this->force) {
139
      $this->force = false;
140
      $this->db_saveItem($name, $value);
141
    }
142
143
    parent::__set($name, $value);
144
  }
145
146
}
147