|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Laravel 4 - Persistant Settings |
| 4 | + * |
| 5 | + * @author Andreas Lutro <[email protected]> |
| 6 | + * @license http://opensource.org/MIT |
| 7 | + * @package l4-settings |
| 8 | + */ |
| 9 | + |
| 10 | +namespace anlutro\LaravelSettings; |
| 11 | + |
| 12 | +use Illuminate\Database\Connection; |
| 13 | + |
| 14 | +class DatabaseSettingStore extends SettingStore |
| 15 | +{ |
| 16 | + protected $connection; |
| 17 | + protected $table; |
| 18 | + |
| 19 | + public function __construct(Connection $connection, $table = null) |
| 20 | + { |
| 21 | + $this->connection = $connection; |
| 22 | + $this->table = $table ?: 'persistant_settings'; |
| 23 | + } |
| 24 | + |
| 25 | + protected function write(array $data) |
| 26 | + { |
| 27 | + $this->newQuery()->truncate(); |
| 28 | + $dbData = $this->prepareWriteData($this->data); |
| 29 | + $this->newQuery()->insert($dbData); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Transforms settings data into an array ready to be insterted into the |
| 34 | + * database. |
| 35 | + * |
| 36 | + * ['foo' => ['bar' => 1, 'baz', => 2]] is first transformed into |
| 37 | + * ['foo.bar' => 1, 'foo.baz' => 2] which is then transformed into |
| 38 | + * [['key' => 'foo.bar', 'value' => 1], ...] |
| 39 | + * |
| 40 | + * ['foo' => ['bar', 'baz']] is transformed into |
| 41 | + * ['foo.0' => 'bar', 'foo.1' => 'baz'] and so on. |
| 42 | + * |
| 43 | + * @param array $data |
| 44 | + * |
| 45 | + * @return array |
| 46 | + */ |
| 47 | + protected function prepareWriteData($data) |
| 48 | + { |
| 49 | + $data = array_dot($data); |
| 50 | + return array_map(function($key, $value) { |
| 51 | + return array('key' => $key, 'value' => $value); |
| 52 | + }, array_keys($data), array_values($data)); |
| 53 | + } |
| 54 | + |
| 55 | + protected function read() |
| 56 | + { |
| 57 | + return $this->parseReadData($this->newQuery()->get()); |
| 58 | + } |
| 59 | + |
| 60 | + public function parseReadData($data) |
| 61 | + { |
| 62 | + $results = array(); |
| 63 | + |
| 64 | + foreach ($data as $row) { |
| 65 | + if (is_array($row)) { |
| 66 | + $key = $row['key']; |
| 67 | + $value = $row['value']; |
| 68 | + } elseif (is_object($row)) { |
| 69 | + $key = $row->key; |
| 70 | + $value = $row->value; |
| 71 | + } |
| 72 | + |
| 73 | + array_set($results, $key, $value); |
| 74 | + } |
| 75 | + |
| 76 | + return $results; |
| 77 | + } |
| 78 | + |
| 79 | + protected function newQuery() |
| 80 | + { |
| 81 | + return $this->connection->table($this->table); |
| 82 | + } |
| 83 | +} |
0 commit comments