Procházet zdrojové kódy

string and array utils; db dataaccess

develop
Robin Thoni před 8 roky
rodič
revize
17e6d1946e

+ 3
- 1
composer.json Zobrazit soubor

@@ -8,10 +8,12 @@
8 8
         }
9 9
     ],
10 10
     "require": {
11
+        "php": "7.0.*",
11 12
         "guzzlehttp/guzzle": "^6.1",
12 13
         "nikic/fast-route": "^1.0",
13 14
         "nesbot/carbon": "^1.21",
14
-        "cboden/ratchet": "^0.3.5"
15
+        "cboden/ratchet": "^0.3.5",
16
+        "illuminate/database": "^5.2"
15 17
     },
16 18
     "require-dev": {
17 19
         "phpunit/phpunit": "5.3.*"

+ 64
- 0
src/Utils/Business/LuArrayUtils.php Zobrazit soubor

@@ -0,0 +1,64 @@
1
+<?php
2
+/**
3
+ * Created by PhpStorm.
4
+ * User: robin
5
+ * Date: 6/7/16
6
+ * Time: 5:04 PM
7
+ */
8
+
9
+namespace Luticate\Utils\Business;
10
+
11
+
12
+class LuArrayUtils
13
+{
14
+    public static function snakeToCamelCase($array)
15
+    {
16
+        if (!is_array($array))
17
+        {
18
+            return $array;
19
+        }
20
+        $camelCase = [];
21
+        foreach ($array as $key => $value)
22
+        {
23
+            $camelCase[LuStringUtils::snakeToCamelCase($key, true)] = self::snakeToCamelCase($value);
24
+        }
25
+        return $camelCase;
26
+    }
27
+    public static function camelCaseToSnake($array)
28
+    {
29
+        if (!is_array($array))
30
+        {
31
+            return $array;
32
+        }
33
+        $camelCase = [];
34
+        foreach ($array as $key => $value)
35
+        {
36
+            $camelCase[LuStringUtils::camelCaseToSnake($key, false)] = self::camelCaseToSnake($value);
37
+        }
38
+        return $camelCase;
39
+    }
40
+
41
+    public static function convertJsonString($json)
42
+    {
43
+        return LuStringUtils::convertJsonString($json);
44
+    }
45
+
46
+    public static function objectToArray($d)
47
+    {
48
+        if (is_object($d)) {
49
+            $d = get_object_vars($d);
50
+        }
51
+
52
+        if (is_array($d)) {
53
+            $data = [];
54
+            foreach ($d as $key => $value) {
55
+                $data[$key] = self::objectToArray($value);
56
+            }
57
+            return self::snakeToCamelCase($data);
58
+        }
59
+        else {
60
+            return $d;
61
+        }
62
+    }
63
+
64
+}

+ 13
- 13
src/Utils/Business/LuStringUtils.php Zobrazit soubor

@@ -12,34 +12,34 @@ use Carbon\Carbon;
12 12
 
13 13
 class LuStringUtils
14 14
 {
15
-    public static function stringSnakeToCamelCase($string, $capitalizeFirstCharacter) {
15
+    public static function snakeToCamelCase($string, $capitalizeFirstCharacter)
16
+    {
16 17
         $str = preg_replace_callback("/_[a-zA-Z]/", function($matches)
17 18
         {
18 19
             return strtoupper($matches[0][1]);
19 20
         }, $string);
20
-        if ($capitalizeFirstCharacter)
21
+        if ($capitalizeFirstCharacter && !empty($str)) {
21 22
             $str[0] = strtoupper($str[0]);
23
+        }
22 24
         return $str;
23 25
     }
24
-
25
-    public static function arraySnakeToCamelCase($array)
26
+    
27
+    public static function camelCaseToSnake($string, $underscoreFirstCharacter)
26 28
     {
27
-        if (!is_array($array))
29
+        $str = preg_replace_callback("/[A-Z]/", function($matches)
28 30
         {
29
-            return $array;
30
-        }
31
-        $camelCase = [];
32
-        foreach ($array as $key => $value)
33
-        {
34
-            $camelCase[self::stringSnakeToCamelCase($key, true)] = self::arraySnakeToCamelCase($value);
31
+            return strtolower("_" . $matches[0]);
32
+        }, $string);
33
+        if (!$underscoreFirstCharacter && !empty($str) && $str[0] == "_") {
34
+            $str = substr($str, 1, strlen($str) - 1);
35 35
         }
36
-        return $camelCase;
36
+        return $str;
37 37
     }
38 38
 
39 39
     public static function convertJsonString($json)
40 40
     {
41 41
         $array = json_decode($json, true);
42
-        return self::arraySnakeToCamelCase($array);
42
+        return LuArrayUtils::snakeToCamelCase($array);
43 43
     }
44 44
 
45 45
     public static function parseDate($str)

+ 22
- 0
src/Utils/Controller/LuticateApplication.php Zobrazit soubor

@@ -16,6 +16,7 @@ use Ratchet\MessageComponentInterface;
16 16
 use Ratchet\Http\HttpServer;
17 17
 use Ratchet\Server\IoServer;
18 18
 use Ratchet\WebSocket\WsServer;
19
+use Illuminate\Database\Capsule\Manager as Capsule;
19 20
 
20 21
 class LuticateApplication implements MessageComponentInterface
21 22
 {
@@ -83,6 +84,27 @@ class LuticateApplication implements MessageComponentInterface
83 84
         $this->_router->setup();
84 85
     }
85 86
     
87
+    public function setupDatabases()
88
+    {
89
+        $capsule = new Capsule;
90
+        foreach ($this->_config['databases'] as $database) {
91
+
92
+            $default = [
93
+                'name'      => 'mydb',
94
+                'driver'    => 'pgsql',
95
+                'host'      => '172.17.0.1',
96
+                'database'  => 'luticate2',
97
+                'username'  => 'dev',
98
+                'password'  => 'dev',
99
+                'charset'   => 'utf8',
100
+                'collation' => 'utf8_unicode_ci',
101
+                'prefix'    => ''
102
+            ];
103
+            $capsule->addConnection(array_merge($default, $database), $database['name']);
104
+        }
105
+        $capsule->setAsGlobal();
106
+    }
107
+    
86 108
     private function dispatch($httpMethod, $url, $parameters)
87 109
     {
88 110
         $r = new LuRequestDbo();

+ 116
- 86
src/Utils/DataAccess/LuDataAccess.php Zobrazit soubor

@@ -1,156 +1,186 @@
1 1
 <?php
2 2
 
3
-namespace Luticate\Utils;
3
+namespace Luticate\Utils\DataAccess;
4 4
 
5
-use DB;
5
+use Illuminate\Database\Capsule\Manager as Capsule;
6
+use Illuminate\Database\Connection;
7
+use Illuminate\Database\Query\Builder;
8
+use Luticate\Utils\Business\LuArrayUtils;
6 9
 use Luticate\Utils\Dbo\LuDbo;
7
-use Luticate\Utils\Dbo\LuMultipleDbo;
8 10
 
9 11
 abstract class LuDataAccess {
10 12
 
13
+    protected static $_connection = "mydb";
14
+    protected static $_table = "mydb_table";
15
+    protected static $_table_as = "__t__";
16
+    protected static $_dboClass = LuDbo::class;
17
+    protected static $_dboArrayClass = LuDbo::class;
18
+    protected static $_dboIgnoreList = [];
19
+
11 20
     public static function transact(\Closure $function)
12 21
     {
13
-        DB::transaction($function);
22
+        return static::getConnection()->transaction($function);
14 23
     }
15 24
 
16 25
     /**
17
-     * @param $data LuModel[]
18
-     * @return LuDbo[]
26
+     * @return Connection
19 27
      */
20
-    protected static function arrayToDbo($data)
28
+    public static function getConnection()
21 29
     {
22
-        $tab = [];
23
-        foreach ($data as $q) {
24
-            if (!is_null($q)) {
25
-                $tab[] = $q->toDbo();
26
-            }
27
-        }
28
-        return $tab;
30
+        return Capsule::connection(static::$_connection);
29 31
     }
30 32
 
31 33
     /**
32
-     * @param $id int
33
-     * @return LuModel
34
+     * @return Builder
34 35
      */
35
-    protected static function _getModelById($id)
36
+    public static function getTableAs()
36 37
     {
37
-        return static::getModel()->where('id', '=', $id)->first();
38
+        return static::getConnection()->table(static::$_table . " as " . static::$_table_as);
38 39
     }
39 40
 
40 41
     /**
41
-     * @param $id int
42
-     * @return LuDbo|null
42
+     * @return Builder
43 43
      */
44
-    public static function getById($id)
44
+    public static function getTable()
45 45
     {
46
-        $data = self::_getModelById($id);
47
-        if (is_null($data))
48
-            return null;
49
-        return $data->toDbo();
46
+        return static::getConnection()->table(static::$_table);
50 47
     }
51 48
 
52 49
     /**
53
-     * @param $id int
54
-     * @return bool
50
+     * @param $query Builder|callable
51
+     * @return Builder
55 52
      */
56
-    public static function deleteById($id)
53
+    public static function resolveQuery($query)
57 54
     {
58
-        $data = self::_getModelById($id);
59
-        if (is_null($data))
60
-            return false;
61
-        $data->delete();
62
-        return true;
55
+        if (is_callable($query)) {
56
+            $query = $query(static::getTableAs());
57
+        }
58
+        return $query;
63 59
     }
64 60
 
65 61
     /**
66
-     * @param $data LuDbo
67
-     * @return int
62
+     * @param $dbo LuDbo
63
+     * @param array $ignoreList
64
+     * @return array
68 65
      */
69
-    public static function addId($data)
66
+    public static function prepareDbo($dbo, $ignoreList = [])
70 67
     {
71
-        $data = static::getModel()->fromDbo($data);
72
-        unset($data->id);
73
-        $data->save();
74
-        return $data->id;
68
+        $json = $dbo->jsonSerialize();
69
+        foreach (array_merge(static::$_dboIgnoreList, $ignoreList) as $ignore) {
70
+            unset($json[$ignore]);
71
+        }
72
+        $json = LuArrayUtils::camelCaseToSnake($json);
73
+        return $json;
75 74
     }
76 75
 
77 76
     /**
78
-     * @param $data LuDbo
77
+     * @param $query Builder|callable
78
+     * @return LuDBo[]
79 79
      */
80
-    public static function add($data)
80
+    public static function getMultiple($query)
81 81
     {
82
-        $data = static::getModel()->fromDbo($data);
83
-        $data->save();
82
+        $query = static::resolveQuery($query);
83
+        $string = $query->aggregate("json_agg", [static::$_table_as]);
84
+        $json = json_decode($string, true);
85
+        $data = LuArrayUtils::snakeToCamelCase($json);
86
+        
87
+        return call_user_func([static::$_dboArrayClass, 'jsonDeserialize'], $data);
84 88
     }
85 89
 
86 90
     /**
87
-     * @param $id int
88
-     * @param $data LuDbo
89
-     * @return LuDbo|null
91
+     * @param $query Builder|callable
92
+     * @return LuDBo
90 93
      */
91
-    public static function editById($id, $data)
94
+    public static function getSingle($query)
92 95
     {
93
-        return static::getModel()->fromDbo($data, self::_getModelById($id))->save();
96
+        $query = static::resolveQuery($query);
97
+        $string = $query->take(1)->aggregate("json_agg", [static::$_table_as]);
98
+        if (is_null($string)) {
99
+            return null;
100
+        }
101
+        $json = json_decode($string, true);
102
+        $data = LuArrayUtils::snakeToCamelCase($json);
103
+        if (count($data) < 1) {
104
+            return null;
105
+        }
106
+
107
+        return call_user_func([static::$_dboClass, 'jsonDeserialize'], $data[0]);
94 108
     }
95 109
 
96 110
     /**
97
-     * @param $predicates array
98
-     * @param $orders array
99
-     * @param int $page
100
-     * @param int $perPage
101
-     * @return LuMultipleDbo
111
+     * @param $id
112
+     * @return LuDbo
102 113
      */
103
-    public static function getMultiple($predicates, $orders, $page = 0, $perPage = PHP_INT_MAX)
114
+    public static function getSingleById($id)
104 115
     {
105
-        /**
106
-         * @var $model LuModel
107
-         */
108
-        $model = static::getModel();
109
-        foreach($predicates as $predicate) {
110
-            $column = $predicate[0];
111
-            $operator = $predicate[1];
112
-            $value = $predicate[2];
113
-            $boolean = isset($predicate[3]) ? $predicate[3] : null;
114
-            $model = $model->where($column, $operator, $value, $boolean);
115
-        }
116
-        $count = $model->count();
117
-        foreach($orders as $order) {
118
-            $model = $model->orderBy($order[0], $order[1]);
119
-        }
120
-        $data = $model->take($perPage)->offset($page * $perPage)->get();
121
-        $dbo = self::arrayToDbo($data);
116
+        return static::getSingle(static::getTableAs()->where("id", "=", $id));
117
+    }
118
+
119
+    /**
120
+     * @param $id
121
+     * @return int
122
+     */
123
+    public static function deleteSingleById($id)
124
+    {
125
+        return static::getTableAs()->delete($id);
126
+    }
122 127
 
123
-        return new LuMultipleDbo($count, $dbo);
128
+    /**
129
+     * @param $query Builder|callable
130
+     * @return int
131
+     */
132
+    public static function deleteMultiple($query)
133
+    {
134
+        $query = static::resolveQuery($query);
135
+        return $query->delete();
124 136
     }
125 137
 
126 138
     /**
127
-     * @return LuModel
139
+     * @param $dbo LuDbo
140
+     * @param string[] $ignoreList
141
+     * @return bool
128 142
      */
129
-    protected static function getModel()
143
+    public static function addSingle($dbo, $ignoreList = [])
130 144
     {
131
-        return null;
145
+        $json = static::prepareDbo($dbo, $ignoreList);
146
+        return static::getTable()->insert($json);
132 147
     }
133 148
 
134 149
     /**
135
-     * @return array
150
+     * @param $dbo LuDbo
151
+     * @param string[] $ignoreList
152
+     * @return int
136 153
      */
137
-    protected static function getOrderBy()
154
+    public static function addSingleId($dbo, $ignoreList = [])
138 155
     {
139
-        return array();
156
+        $json = static::prepareDbo($dbo, $ignoreList);
157
+        unset($json['id']);
158
+        return static::getTable()->insertGetId($json);
140 159
     }
141 160
 
142 161
     /**
143
-     * @param $query
144
-     * @return array
162
+     * @param $dbo LuDbo
163
+     * @param string[] $ignoreList
164
+     * @return int
145 165
      */
146
-    protected static function getQueryPredicate($query)
166
+    public static function editSingleById($dbo, $ignoreList = [])
147 167
     {
148
-        return array();
168
+        $json = static::prepareDbo($dbo, $ignoreList);
169
+        $id = $json['id'];
170
+        unset($json['id']);
171
+        return static::getTable()->where("id", "=", $id)->update($json);
149 172
     }
150 173
 
151
-    public static function getAll($page = 0, $perPage = PHP_INT_MAX, $query = "")
174
+    /**
175
+     * @param $dbo LuDbo
176
+     * @param $query Builder|callable
177
+     * @param string[] $ignoreList
178
+     * @return int
179
+     */
180
+    public static function editMultiple($dbo, $query, $ignoreList = [])
152 181
     {
153
-        $predicates = (is_null($query) || $query == "") ? array() : static::getQueryPredicate($query);
154
-        return self::getMultiple($predicates, static::getOrderBy(), $page, $perPage);
182
+        $query = static::resolveQuery($query);
183
+        $json = static::prepareDbo($dbo, $ignoreList);
184
+        return $query->update($json);
155 185
     }
156 186
 }

+ 0
- 42
src/Utils/DataAccess/LuModel.php Zobrazit soubor

@@ -1,42 +0,0 @@
1
-<?php
2
-
3
-namespace Luticate\Utils;
4
-
5
-use Illuminate\Database\Eloquent\Collection;
6
-use Illuminate\Database\Eloquent\Model;
7
-use Luticate\Utils\Dbo\LuDbo;
8
-
9
-/**
10
- * LuModel
11
- *
12
- * @method static LuModel where($column, $operator = null, $value = null, $boolean = 'and')
13
- * @method static LuModel orWhere($column, $operator = null, $value = null)
14
- * @method static LuModel orderBy($column, $direction = 'asc')
15
- * @method static LuModel take($value)
16
- * @method static LuModel offset($value)
17
- * @method static LuModel rightJoin($table, $first, $operator = null, $second = null)
18
- * @method static LuModel leftJoin($table, $first, $operator = null, $second = null)
19
- * @method static LuModel join($table, $one, $operator = null, $two = null, $type = 'inner', $where = false)
20
- * @method static LuModel groupBy(...$columns)
21
- * @method static LuModel[] get($columns = ['*'])
22
- * @method static LuModel first($columns = ['*'])
23
- * @method static LuModel find($id, $columns = ['*'])
24
- * @method static LuModel select($columns = ['*'])
25
- * @method static int count($columns = '*')
26
- */
27
-abstract class LuModel extends Model
28
-{
29
-    /**
30
-     * Mapping from DBO model to business model.
31
-     * If this model has no DBO equivalent, do nothing in this function
32
-     * @return LuDbo
33
-     */
34
-    public abstract function toDbo();
35
-
36
-    /**
37
-     * @param $dbo LuDbo
38
-     * @param $dal LuModel|null
39
-     * @return LuModel
40
-     */
41
-    public abstract function fromDbo($dbo, $dal = null);
42
-}

+ 8
- 5
src/Utils/Dbo/LuDbo.php Zobrazit soubor

@@ -13,14 +13,17 @@ abstract class LuDbo implements \JsonSerializable {
13 13
     {
14 14
         return json_encode($this);
15 15
     }
16
-    
16
+
17
+    /**
18
+     * @return array
19
+     */
17 20
     public function jsonSerialize()
18 21
     {
19 22
         $json = [];
20 23
         $reflect = new \ReflectionClass(static::class);
21 24
         $properties = $reflect->getProperties();
22 25
         foreach ($properties as $property) {
23
-            $name = LuStringUtils::stringSnakeToCamelCase($property->getName(), true);
26
+            $name = LuStringUtils::snakeToCamelCase($property->getName(), true);
24 27
             $property->setAccessible(true);
25 28
             $value = $property->getValue($this);
26 29
             if (is_array($value)) {
@@ -77,7 +80,7 @@ abstract class LuDbo implements \JsonSerializable {
77 80
             $dbo->checkConstraints($constraints);
78 81
             return $dbo->getString();
79 82
         }
80
-        else if ($type == "int") {
83
+        else if ($type == "int" || $type == "integer") {
81 84
             $dbo = LuIntDbo::jsonDeserialize($value);
82 85
             $dbo->checkConstraints($constraints);
83 86
             return $dbo->getInt();
@@ -87,7 +90,7 @@ abstract class LuDbo implements \JsonSerializable {
87 90
             $dbo->checkConstraints($constraints);
88 91
             return $dbo->getFloat();
89 92
         }
90
-        else if ($type == "bool") {
93
+        else if ($type == "bool" || $type == "boolean") {
91 94
             $dbo = LuBoolDbo::jsonDeserialize($value);
92 95
             $dbo->checkConstraints($constraints);
93 96
             return $dbo->getBool();
@@ -131,7 +134,7 @@ abstract class LuDbo implements \JsonSerializable {
131 134
         $properties = $reflect->getProperties();
132 135
         foreach ($properties as $property) {
133 136
             $parser = new LuPropertyDocParser($property->getDocComment());
134
-            $name = LuStringUtils::stringSnakeToCamelCase($property->getName(), true);
137
+            $name = LuStringUtils::snakeToCamelCase($property->getName(), true);
135 138
             $doc = $parser->parse();
136 139
             $type = is_null($doc) ? null : $doc->getType();
137 140
 

+ 168
- 0
tests/DatabaseTest.php Zobrazit soubor

@@ -0,0 +1,168 @@
1
+<?php
2
+use Luticate\Utils\Controller\LuticateApplication;
3
+use Illuminate\Database\Capsule\Manager as Capsule;
4
+use Luticate\Utils\DataAccess\LuDataAccess;
5
+use Luticate\Utils\Dbo\LuDbo;
6
+use Luticate\Utils\Dbo\LuDboDeserializeException;
7
+
8
+/**
9
+ * Created by PhpStorm.
10
+ * User: robin
11
+ * Date: 6/7/16
12
+ * Time: 2:57 PM
13
+ */
14
+
15
+class TestTableDbo extends LuDbo
16
+{
17
+    /**
18
+     * @var $_id int
19
+     */
20
+    private $_id;
21
+
22
+    /**
23
+     * @var $_someText string
24
+     */
25
+    private $_someText;
26
+
27
+    /**
28
+     * @var $_someIntegerArray int[]
29
+     */
30
+    private $_someIntegerArray;
31
+
32
+    /**
33
+     * @return int
34
+     */
35
+    public function getId()
36
+    {
37
+        return $this->_id;
38
+    }
39
+
40
+    /**
41
+     * @param int $id
42
+     */
43
+    public function setId($id)
44
+    {
45
+        $this->_id = $id;
46
+    }
47
+
48
+    /**
49
+     * @return string
50
+     */
51
+    public function getSomeText()
52
+    {
53
+        return $this->_someText;
54
+    }
55
+
56
+    /**
57
+     * @param string $someText
58
+     */
59
+    public function setSomeText($someText)
60
+    {
61
+        $this->_someText = $someText;
62
+    }
63
+
64
+    /**
65
+     * @return int[]
66
+     */
67
+    public function getSomeIntegerArray()
68
+    {
69
+        return $this->_someIntegerArray;
70
+    }
71
+
72
+    /**
73
+     * @param int[] $someIntegerArray
74
+     */
75
+    public function setSomeIntegerArray($someIntegerArray)
76
+    {
77
+        $this->_someIntegerArray = $someIntegerArray;
78
+    }
79
+}
80
+
81
+class TestTableDboArray extends LuDbo
82
+{
83
+    /**
84
+     * @var TestTableDbo[]
85
+     */
86
+    protected $_array;
87
+    public function getArray()
88
+    {
89
+        return $this->_array;
90
+    }
91
+    public function setArray($value)
92
+    {
93
+        $this->_array = $value;
94
+    }
95
+
96
+    public function jsonSerialize()
97
+    {
98
+        return $this->_array;
99
+    }
100
+
101
+    public static function jsonDeserialize($json)
102
+    {
103
+        if (!is_array($json)) {
104
+            throw new LuDboDeserializeException("Invalid array value");
105
+        }
106
+        $dbo = new self();
107
+        $array = [];
108
+        foreach ($json as $data) {
109
+            $array[] = TestTableDbo::jsonDeserialize($data);
110
+        }
111
+        $dbo->setArray($array);
112
+        return $dbo;
113
+    }
114
+
115
+    public static function generateSample()
116
+    {
117
+        return [
118
+            TestTableDbo::generateSample(),
119
+            TestTableDbo::generateSample()
120
+        ];
121
+    }
122
+
123
+}
124
+
125
+class TestTableDataAccess extends LuDataAccess
126
+{
127
+    protected static $_connection = "mydb";
128
+    protected static $_table = "test_table";
129
+    protected static $_dboClass = TestTableDbo::class;
130
+    protected static $_dboArrayClass = TestTableDboArray::class;
131
+}
132
+
133
+class DatabaseTest extends \PHPUnit_Framework_TestCase
134
+{
135
+    public function testSetup()
136
+    {
137
+//        $config = ['databases' => [
138
+//            [
139
+//                'name'      => 'mydb',
140
+//                'driver'    => 'pgsql',
141
+//                'host'      => '172.17.0.1',
142
+//                'database'  => 'luticate2',
143
+//                'username'  => 'dev',
144
+//                'password'  => 'dev'
145
+//            ]
146
+//        ]];
147
+//        $app = new LuticateApplication($config);
148
+//        $app->setupDatabases();
149
+        
150
+//        $dbo = new TestTableDbo();
151
+//        $dbo->setId(11);
152
+//        $dbo->setSomeIntegerArray('{}');
153
+//        $dbo->setSomeText("lol2");
154
+
155
+//        var_dump(TestTableDataAccess::getSingleById(1));
156
+//        var_dump(TestTableDataAccess::deleteMultiple(function($q)
157
+//        {
158
+//            return $q->where("some_text", "=", "lol");
159
+//        }));
160
+//        var_dump(TestTableDataAccess::addSingleId($dbo));
161
+//        var_dump(TestTableDataAccess::addSingle($dbo, ['Id']));
162
+//        var_dump(TestTableDataAccess::editSingleById($dbo));
163
+//        var_dump(TestTableDataAccess::editMultiple($dbo, function($q)
164
+//        {
165
+//            return $q->where("some_text", "like", "lol%");
166
+//        }, ['Id']));
167
+    }
168
+}

Načítá se…
Zrušit
Uložit