/** * Insert the batch of records as one MySql query. * * @param bool $onDupeUpdate used to do on duplicate key update */ public function insert($onDupeUpdate = true) { $master = $this->connection->master(); $records = (array) $this; $master->insertMultiple($this->tableWithDBPrefix(), $records); $result = $this->connection->master()->autoSelect("SELECT LAST_INSERT_ID() as lastId"); if ($result->lastId !== "0") { $primary = $this->getPrimaryKey(); if (count($primary) === 1) { $start = $result->lastId; foreach ($this->inputRecords as $index => $record) { $member = Introspection::modelizeName($primary[0]); $record->{$member} = $start + $index; } } } }
/** * Determine the column that we should write to * * @param string * @return string */ public function determineColumn($column) { if (empty($this->columnList)) { $this->loadColumns(); } // if the column is exactly the same just return it if (isset($this->columnList[$column])) { return $column; } // check to see if the injected mapper function can solve our column lookup problem if (is_callable($this->mapper)) { $mapped = call_user_func_array($this->mapper, array($column)); if ($mapped) { return $mapped; } } // tabelize the column and see if we have a match and if so return the tabelized version $tablized = Introspection::tabelizeName($column); if (isset($this->columnList[$tablized])) { return $tablized; } // check to see if the column has a specific abbreviation in which case we uppercase the entire word ex SSN, DOB, CC $upperColumn = strtoupper($column); if (isset($this->columnList[$upperColumn])) { return $upperColumn; } // if we have a map array look it up there if (isset($this->mapArray[$column])) { return $this->mapArray[$column]; } }
/** * Validate a model being operated on fits the context settings of the class so we do not get into any * undesirable states. * * @param $model * return boolean */ public function validateModel($model) { $modelName = $this->getConfig()->modelName; if (Introspection::getClassName($model) !== $modelName) { return false; } $modelFactory = $this->getConfig()->getModelFactory(); return $modelFactory->willCreate($model); }
/** * Populate the configuration from an array of settings * * @param array $settings * @throws \InvalidArgumentException */ public function populate($settings = array()) { $publicVars = Introspection::getPublicVars($this); foreach ($settings as $name => $value) { if ($name === 'adapters') { if (!is_array($value)) { throw new \InvalidArgumentException("adapter value must be an array " . print_r($value, true) . " given."); } foreach ($value as $adapterType) { if (!$this->validAdapter($adapterType)) { throw new \InvalidArgumentException("{$adapterType} is not a support adapter type. Supported Adapters " . implode("|", $this->supportedAdapters)); } } } if ($name === 'namespaces') { $this->setNamespaces($value); } elseif ($name === 'adapterFactory') { $this->setAdapterFactory($value); } elseif (array_key_exists($name, $publicVars)) { $this->{$name} = $value; } else { $this->settings[$name] = $value; } } }
/** * Updates the table with data from the data model. * * @param $table * @param $update * @param $where * @return \Common\Storage\PDOStatement * @throws \InvalidArgumentException */ public function autoUpdate($table, $update, $where) { if (empty($table)) { throw new \InvalidArgumentException("Table being referenced must be set when using autoUpdate"); } if (empty($update)) { throw new \InvalidArgumentException("variables to be inserted must be set when using autoUpdate"); } if (empty($where)) { throw new \InvalidArgumentException('a where clause is expected to be set when using autoUpdate'); } if (is_object($update)) { $update = Introspection::flattenToArray($update); } $skipValues = array(); foreach ($update as $columnName => $value) { if ($value === "NOW()" || $value === "CURDATE()" || $value === "NULL") { $set[] = "{$columnName} = {$value}"; $skipValues[] = $columnName; } else { $set[] = '`' . $columnName . '` = ?'; } } // need remove and null values from the update param s foreach ($skipValues as $skipValue) { unset($update[$skipValue]); } $params = array_merge(array_values($update), array_values($where)); $query = 'UPDATE ' . $table . ' SET ' . implode(", ", $set) . ' WHERE ' . implode(' = ? AND ', array_keys($where)) . ' = ? '; try { $Stmt = $this->prepare($query); } catch (\Exception $e) { throw QueryException::create("Update Query Prepare failed: " . $e->getMessage())->setQuery($this->getLastQuery()); } try { $Stmt->execute(array_values($params)); } catch (\PDOException $e) { switch ($e->getCode()) { case '23000': return $Stmt; case '40001': $Stmt->execute(array_values($params)); break; default: throw $e; } } return $Stmt; }
/** * Turn the search criteria on a model to the respective db search columns * * @param array * @return array */ protected function tablizeCriteria($criteria) { return $criteria; // deprecating this to see what breaks // remap the criteria to the correct DB format $mappedCriteria = array(); if (!empty($criteria) || count($criteria) > 0) { foreach ($criteria as $key => $value) { $colName = Introspection::tabelizeName($key); $mappedCriteria[$colName] = $value; } } return $mappedCriteria; }
$cmd->option('group')->describedAs('group to use in db configs `default`'); $cmd->option('db')->describedAs('database name')->require(); $cmd->option('t')->aka('table')->describeAs("table to generate a model for")->require(); $cmd->option('e')->aka('environment')->describeAs("Environment to run mysql connection against")->require(); $cmd->option('d')->aka('directory')->describeAs("Directory to store the results")->require(); $cmd->option('n')->aka('namespace')->describeAs("Namespace for models")->require(); $mysql = new \Common\Storage\Connection\Mysql(array("environment" => $cmd['e'], "configPath" => $cmd['configPath'], "database" => $cmd['db'], "group" => $cmd['group'])); $columns = $mysql->getColumnList($cmd['db'], $cmd['t']); $namespace = $cmd['n']; $class = $cmd['table']; $props = array(); foreach ($columns as $col => $details) { if (in_array($col, array('DateAdded', 'DateTimeAdded', 'LastUpdated'))) { continue; } $props[] = "\tpublic \$" . \Common\Tool\Introspection::modelizeName($col) . ";"; } $props = implode(PHP_EOL . PHP_EOL, $props); $output = <<<eot <?php namespace {$namespace}; use Common\\Model\\BaseModel; class {$class} extends BaseModel { {$props} } eot; $file = $cmd['d'] . $cmd['t'] . ".php"; echo "writing: " . $file . PHP_EOL; file_put_contents($file, $output);
/** * Function tests if the passed in object can be created by this instance creator based on current configuration * settings on the class * @param object * @return boolean */ public function willCreate($object) { $class = Introspection::getClassName($object); $namespaceClass = get_class($object); try { $createdName = $this->getFullClass($class); } catch (ClassNotFoundException $e) { return false; } if ($createdName[0] === "\\") { $namespaceClass = "\\{$namespaceClass}"; } return $namespaceClass === $createdName; }
/** * Convert out object to a standard array. * * @return array */ public function toArray() { return Introspection::getPublicVars($this); }