public function create_column($column) { $c = new Column(); $c->inflected_name = Inflector::instance()->variablize($column['name']); $c->name = $column['name']; $c->nullable = $column['notnull'] ? false : true; $c->pk = $column['pk'] ? true : false; $c->auto_increment = $column['type'] == 'INTEGER' && $c->pk; $column['type'] = preg_replace('/ +/', ' ', $column['type']); $column['type'] = str_replace(array('(', ')'), ' ', $column['type']); $column['type'] = Utils::squeeze(' ', $column['type']); $matches = explode(' ', $column['type']); if (!empty($matches)) { $c->raw_type = strtolower($matches[0]); if (count($matches) > 1) { $c->length = intval($matches[1]); } } $c->map_raw_type(); if ($c->type == Column::DATETIME) { $c->length = 19; } elseif ($c->type == Column::DATE) { $c->length = 10; } // From SQLite3 docs: The value is a signed integer, stored in 1, 2, 3, 4, 6, // or 8 bytes depending on the magnitude of the value. // so is it ok to assume it's possible an int can always go up to 8 bytes? if ($c->type == Column::INTEGER && !$c->length) { $c->length = 8; } $c->default = $c->cast($column['dflt_value'], $this); return $c; }
function classify($class_name, $singularize = false) { if ($singularize) { $class_name = Utils::singularize($class_name); } $class_name = Inflector::instance()->camelize($class_name); return ucfirst($class_name); }
public function test_singularize() { $this->assert_equals('order_status', AR\Utils::singularize('order_status')); $this->assert_equals('order_status', AR\Utils::singularize('order_statuses')); $this->assert_equals('os_type', AR\Utils::singularize('os_type')); $this->assert_equals('os_type', AR\Utils::singularize('os_types')); $this->assert_equals('photo', AR\Utils::singularize('photos')); $this->assert_equals('pass', AR\Utils::singularize('pass')); $this->assert_equals('pass', AR\Utils::singularize('passes')); }
function classify($class_name, $singularize = false) { if ($singularize) { $parts = explode('_', Inflector::instance()->uncamelize($class_name)); $class_name = ''; foreach ($parts as $name) { $class_name .= '_' . Utils::singularize($name); } $class_name = ltrim($class_name, '_'); } $class_name = Inflector::instance()->camelize($class_name); return ucfirst($class_name); }
public function error_messages_for($obj, $obj_name = "", $obj_prefix = "") { if ($obj->errors && $obj->errors->size()) { if ($obj_name == "") { $obj_name = \ActiveRecord\Utils::singularize(strtolower(get_class($obj))); } if ($obj_prefix == "") { if (\ActiveRecord\Utils::pluralize_if(2, $obj_name) == "2 " . $obj_name) { $obj_prefix = "these"; } else { $obj_prefix = "this"; } } $html = "<p>" . "<div class=\"flash-error\">" . "<strong>" . $obj->errors->size() . " " . h(\ActiveRecord\Utils::pluralize_if($obj->errors->size(), "error")) . " prohibited " . raw_or_h($obj_prefix) . " " . raw_or_h($obj_name) . " from being " . ($obj->is_new_record() ? "created" : "saved") . ":</strong><br />\n"; foreach ($obj->errors as $err) { $html .= raw_or_h($err) . "<br />"; } $html .= "</div>" . "</p>"; return $html; } }
private function getPurchases($wantedid, $wantedtype, $whowantsid, $whowantstype){ $isperm = false; $conditions = array(); if($wantedid > 0){ $tmpcondition = array('id=?',$wantedid); \ActiveRecord\Utils::add_condition($conditions, $tmpcondition); } if($wantedtype !== ''){ $tmpcondition = array('purchase_number=?',$wantedtype); \ActiveRecord\Utils::add_condition($conditions, $tmpcondition); } if(($whowantstype !== Menu::ppl_type_admin && !$isperm)){ //whatever id, status been asked give if they are their related orders only $tmpcondition = array('person_id=?', $whowantsid); \ActiveRecord\Utils::add_condition($conditions, $tmpcondition); } $result = \Purchase::find('all', array('conditions' => $conditions, 'order' => 'purchase_at desc')); $except = array(); $include = array('purchaseproducts' => array('include' => array('product'))); foreach ($result as &$rec) { $rec = $rec->to_array(array('include' => $include, 'except' => $except)); } return $result; }
protected function createConditionsFromKeys(Model $model, $condition_keys = [], $value_keys = []) { $condition_string = \implode('_and_', $condition_keys); $condition_values = \array_values($model->getValuesFor($value_keys)); // return null if all the foreign key values are null so that we don't try to do a query like "id is null" if (all(null, $condition_values)) { return null; } $conditions = SQLBuilder::createConditionsFromUnderscoredString(Table::load(\get_class($model))->conn, $condition_string, $condition_values); # DO NOT CHANGE THE NEXT TWO LINES. add_condition operates on a reference and will screw options array up if (isset($this->options['conditions'])) { $options_conditions = $this->options['conditions']; } else { $options_conditions = []; } return Utils::addCondition($options_conditions, $conditions); }
private function is_blank_with_option($var, &$options) { return Utils::is_blank($var) && (isset($options['allow_blank']) && $options['allow_blank']); }
private function limit($offset, $limit) { $ret = []; $sql = 'SELECT * FROM authors ORDER BY name ASC'; $this->conn->queryAndFetch($this->conn->limit($sql, $offset, $limit), function ($row) use(&$ret) { $ret[] = $row; }); $return = new Utils(); return $return->collect($ret, 'author_id'); }
protected function _translate_error($attribute, $error) { if ($this->gettext_available) { $attribute = gettext(Utils::human_attribute($attribute)); $error = gettext($error); } else { $attribute = Utils::human_attribute($attribute); } return sprintf($error, $attribute); }
public function tableize($s) { return Utils::pluralize(\strtolower($this->underscorify($s))); }
/** * Returns all the error messages as an array, including error key. * * <code> * $model->errors->errors(); * * # array( * # "name" => array("Name can't be blank"), * # "state" => array("State is the wrong length (should be 2 chars)") * # ) * </code> * * @param array $closure Closure to fetch the errors in some other format (optional) * This closure has the signature function($attribute, $message) * and is called for each available error message. * @return array */ public function to_array($closure = null) { $errors = array(); if ($this->errors) { foreach ($this->errors as $attribute => $messages) { foreach ($messages as $msg) { if (is_null($msg)) { continue; } $errors[$attribute][] = $message = preg_match("/^\\^/", $msg) ? preg_replace("/^\\^/", "", $msg) : Utils::human_attribute($attribute) . ' ' . $msg; if ($closure) { $closure($attribute, $message); } } } } return $errors; }
/** * Returns all the error messages as an array. * * <code> * $model->errors->full_messages(); * * # array( * # "Name can't be blank", * # "State is the wrong length (should be 2 chars)" * # ) * </code> * * @param array $options Options for messages * @return array */ public function full_messages() { $full_messages = array(); if ($this->errors) { foreach ($this->errors as $attribute => $messages) { foreach ($messages as $msg) { if (is_null($msg)) { continue; } $full_messages[] = Utils::human_attribute($attribute) . ' ' . $msg; } } } return $full_messages; }
/** * Determines if the specified array is a valid Activerecord options array. * * @param array $array An options array * @param bool $throw True to throw an Exceptions if not valid * @return boolean True if valid otherwise valse * @throws {@link Activerecord} if the array contained any invalid options */ public static function isOptionsHash($array, $throw = true) { $utils = new Utils(); if ($utils->isHash($array)) { $keys = \array_keys($array); $diff = \array_diff($keys, self::$valid_options); if (!empty($diff) && $throw) { throw new ExceptionActiverecord("Unknown key(s): " . \join(', ', $diff)); } $intersect = \array_intersect($keys, self::$valid_options); if (!empty($intersect)) { return true; } } return false; }
public function keyify($class_name) { return \strtolower($this->underscorify(Utils::denamespace($class_name))) . '_id'; }
/** * Get the name of the model that fits AR relational convention * * @param Table $table Optionally injected Table instance * @param boolean $quoted Whether or not to quote escape the string with SQL-style quotes * @static * @access public * @return string */ public static function getConventionalRelationName(Table $table = null, $quoted = false) { $table = $table ?: static::table(); $table_name = $table->get_fully_qualified_table_name($quoted); return ARUtils::singularize($table_name); }
public function render($template, $vars = array()) { /* render(array("partial" => "somedir/file"), array("v" => $v)) */ if (!is_array($template)) { $template = array("action" => $template); } if (isset($template["status"])) { Request::send_status_header($template["status"]); } $collection = array(); if (isset($template["collection"]) && is_array($template["collection"])) { if (isset($template["as"])) { $collection = array($template["as"] => $template["collection"]); } else { /* figure out the type of things in the collection */ $cl = strtolower(get_class($template["collection"][0])); if ($cl != "") { $cl = \ActiveRecord\Utils::singularize($cl); } if ($cl == "") { throw new HalfMoonException("could not figure out type of " . "collection"); } $collection = array($cl => $template["collection"]); } } /* just render text with no layout */ if (is_array($template) && array_key_exists("text", $template)) { if (!$this->content_type_set()) { $this->content_type = "text/plain"; } if (Config::log_level_at_least("full")) { Log::info("Rendering text"); } print $template["text"]; } elseif (is_array($template) && array_key_exists("html", $template)) { if (!$this->content_type_set()) { $this->content_type = "text/html"; } if (Config::log_level_at_least("full")) { Log::info("Rendering HTML"); } print $template["html"]; } elseif (is_array($template) && array_key_exists("json", $template)) { if (!$this->content_type_set()) { $this->content_type = "application/json"; } if (Config::log_level_at_least("full")) { Log::info("Rendering json"); } /* there's no way to know if we were passed a json-encoded string, * or a string that needs to be encoded, so just encode everything * and hope the user figures it out */ print json_encode($template["json"]); } elseif (is_array($template) && array_key_exists("js", $template)) { if (!$this->content_type_set()) { $this->content_type = "text/javascript"; } if (Config::log_level_at_least("full")) { Log::info("Rendering javascript"); } print $template["js"]; } else { $tf = ""; /* render a partial template */ if (is_array($template) && isset($template["partial"])) { $tf = $template["partial"]; } elseif (is_array($template) && isset($template["action"])) { $tf = $template["action"]; } elseif (is_array($template)) { $tf = join("", array_values($template)); } else { $tf = $template; } if (substr($tf, 0, 1) == "/") { /* full path, just use it */ } elseif (strpos($tf, "/") !== false) { /* path relative to base view path */ $tf = HALFMOON_ROOT . "/views/" . $tf; } else { /* just a file in this controller's directory * (AdminSomethingController -> admin_something) */ $tf = $this->view_template_path() . $tf; } /* partial template files start with _ */ if (is_array($template) && isset($template["partial"])) { $tf = dirname($tf) . "/_" . basename($tf); } /* do the actual renders */ $filename = null; /* regular php/html */ if (file_exists($filename = $tf . ".phtml")) { if (!$this->content_type_set()) { $this->content_type = "text/html"; } } elseif (file_exists($filename = $tf . ".pxml")) { if (!$this->content_type_set()) { $this->content_type = "application/xml"; } } elseif (file_exists($filename = $tf . ".pjs")) { if (!$this->content_type_set()) { $this->content_type = "text/javascript"; } } else { throw new MissingTemplate("no template file " . $tf . ".p{html,xml,js}"); } if (count($collection)) { $ck = Utils::A(array_keys($collection), 0); /* it would be nice to be able to just read the template * into a string and eval() it each time to save on i/o, * but php won't let us catch parse errors properly and * there may be some other fallout */ foreach ($collection[$ck] as $cobj) { $vars[$ck] = $cobj; $this->_really_render_file($filename, $vars); } } else { $this->_really_render_file($filename, $vars); } } if (!$this->in_view) { if (is_array($template) && array_key_exists("layout", $template)) { $this::$layout = $template["layout"]; } elseif ($this->content_type_set() && $this->content_type != static::$DEFAULT_CONTENT_TYPE) { /* if we were called from the controller, we're not outputting * html, and no layout was explicitly specified, we probably * don't want a layout */ $this::$layout = false; } } $this->did_render = true; }
public function testWrapStringsInArrays() { $utils = new Utils(); $x = ['1', ['2']]; $this->assertEquals([['1'], ['2']], $utils->wrapStringsInArrays($x)); $x = '1'; $this->assertEquals([['1']], $utils->wrapStringsInArrays($x)); }
private function setAssociations() { require_once __DIR__ . '/Relations/InterfaceRelations.php'; require_once __DIR__ . '/Relations/AbstractRelations.php'; $namespace = $this->class->getNamespaceName(); foreach ($this->class->getStaticProperties() as $name => $definitions) { if (!$definitions) { continue; } foreach (Utils::wrapStringsInArrays($definitions) as $definition) { $relationship = null; $definition += ['namespace' => $namespace]; switch ($name) { case 'has_many': $relationship = new HasMany($definition); break; case 'has_one': $relationship = new HasOne($definition); break; case 'belongs_to': $relationship = new BelongsTo($definition); break; case 'has_and_belongs_to_many': $relationship = new HasAndBelongsToMany($definition); break; } if ($relationship) { $this->addRelationship($relationship); } } } }
/** * Add an error message. * * @param string $attribute Name of an attribute on the model * @param string $msg The error message */ public function add($attribute, $msg) { $model = $this->modelName; if (is_null($msg)) { $msg = self::$DEFAULT_ERROR_MESSAGES['invalid']; } if (isset($model::$attr_names[$attribute])) { $msg = $model::$attr_names[$attribute] . ' ' . $msg; } else { $msg = Utils::human_attribute($attribute) . ' ' . $msg; } if (!isset($this->errors[$attribute])) { $this->errors[$attribute] = array($msg); } else { $this->errors[$attribute][] = $msg; } }
/** * Returns all the error messages as an array, including error key. * * <code> * $model->errors->errors(); * * # array( * # "name" => array("Name can't be blank"), * # "state" => array("State is the wrong length (should be 2 chars)") * # ) * </code> * * @param array $closure Closure to fetch the errors in some other format (optional) * This closure has the signature function($attribute, $message) * and is called for each available error message. * @return array */ public function toArray($closure = null) { $errors = array(); if ($this->errors) { foreach ($this->errors as $attribute => $messages) { foreach ($messages as $msg) { if (is_null($msg)) { continue; } $errors[$attribute][] = $message = Utils::humanAttribute($attribute) . ' ' . $msg; if ($closure) { $closure($attribute, $message); } } } } return $errors; }
private function applyWhereConditions($args) { require_once 'Expressions.php'; $num_args = \count($args); if ($num_args == 1 && Utils::isHash($args[0])) { $hash = \is_null($this->joins) ? $args[0] : $this->prependTableNameToFields($args[0]); $e = new Expressions($this->connection, $hash); $this->where = $e->toString(); $this->where_values = Utils::arrayFlatten($e->values()); } elseif ($num_args > 0) { // if the values has a nested array then we'll need to use Expressions to expand the bind marker for us $values = \array_slice($args, 1); // foreach ($values as $name => &$value) oiginal foreach ($values as &$value) { if (\is_array($value)) { $e = new Expressions($this->connection, $args[0]); $e->bindValues($values); $this->where = $e->toString(); $this->where_values = Utils::arrayFlatten($e->values()); return; } } // no nested array so nothing special to do $this->where = $args[0]; $this->where_values =& $values; } }