Created
December 10, 2015 08:32
-
-
Save hiromi2424/9e50bd03d9d64da54878 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
App::uses('AppModel', 'Model'); | |
class ArrayModel extends AppModel { | |
public $useDbConfig = 'array'; | |
public $useTable = false; | |
public $records = []; | |
public function __construct($id = false, $table = null, $ds = null) { | |
// disable overriding datasource | |
if (is_array($id) && isset($id['ds'])) { | |
unset($id['ds']); | |
} | |
$this->_processConstructRecords(); | |
if (!$this->displayField) { | |
$this->displayField = $this->hasField(array('title', 'name', $this->primaryKey)); | |
} | |
parent::__construct($id, $table); | |
} | |
protected function _processConstructRecords() { | |
if (method_exists($this, '_constructRecords')) { | |
$result = $this->_constructRecords(); | |
if (!empty($result) && is_array($result)) { | |
$this->records = $result; | |
} | |
} | |
} | |
protected function _simpleConstructRecords($list, $split = "/\n/") { | |
$lines = preg_split($split, $list, -1, PREG_SPLIT_NO_EMPTY); | |
$countLines = count($lines); | |
for ($i = 0; $i < $countLines; $i++) { | |
$id = $i + 1; | |
$name = $lines[$i]; | |
$this->records[] = compact('id', 'name'); | |
} | |
} | |
protected function _constructRecordsFromAssocArray(array $array) { | |
$current = current($array); | |
$count = count($current); | |
for ($i = 0; $i < $count; $i++) { | |
$id = $i + 1; | |
$record = compact('id'); | |
foreach ($array as $name => $values) { | |
$record[$name] = $values[$i]; | |
} | |
$this->records[] = $record; | |
} | |
} | |
public function schema($field = false) { | |
if (empty($this->_schema) || $field = true) { | |
$keys = []; | |
foreach ($this->records as $record) { | |
$keys = array_merge($keys, array_keys($record)); | |
} | |
$this->_schema = []; | |
$default = [ | |
'type' => 'string', | |
'length' => null, | |
'null' => false, | |
'default' => null, | |
]; | |
foreach ($keys as $key) { | |
$this->_schema[$key] = $default; | |
$values = Hash::extract($this->records, "{n}.$key"); | |
if (Hash::numeric($values)) { | |
$this->_schema[$key]['type'] = 'int'; | |
} | |
} | |
} | |
if (!is_string($field)) { | |
return $this->_schema; | |
} | |
if (isset($this->_schema[$field])) { | |
return $this->_schema[$field]; | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment