Exemplo n.º 1
0
 public function createColumn(&$column)
 {
     $c = new Column();
     $c->inflected_name = Inflector::instance()->variablize($column['field']);
     $c->name = $column['field'];
     $c->nullable = $column['null'] === 'YES' ? true : false;
     $c->pk = $column['key'] === 'PRI' ? true : false;
     $c->auto_increment = $column['extra'] === 'auto_increment' ? true : false;
     if ($column['type'] == 'timestamp' || $column['type'] == 'datetime') {
         $c->raw_type = 'datetime';
         $c->length = 19;
     } elseif ($column['type'] == 'date') {
         $c->raw_type = 'date';
         $c->length = 10;
     } elseif ($column['type'] == 'time') {
         $c->raw_type = 'time';
         $c->length = 8;
     } else {
         \preg_match('/^([A-Za-z0-9_]+)(\\(([0-9]+(,[0-9]+)?)\\))?/', $column['type'], $matches);
         $c->raw_type = \count($matches) > 0 ? $matches[1] : $column['type'];
         if (\count($matches) >= 4) {
             $c->length = \intval($matches[3]);
         }
     }
     $c->mapRawType();
     $c->default = $c->cast($column['default'], $this);
     return $c;
 }
Exemplo n.º 2
0
 public function create_column($column)
 {
     $column['column_name'] = strtolower($column['column_name']);
     $column['data_type'] = strtolower(preg_replace('/\\(.*?\\)/', '', $column['data_type']));
     if ($column['data_default'] !== null) {
         $column['data_default'] = trim($column['data_default'], "' ");
     }
     if ($column['data_type'] == 'number') {
         if ($column['data_scale'] > 0) {
             $column['data_type'] = 'decimal';
         } elseif ($column['data_scale'] == 0) {
             $column['data_type'] = 'int';
         }
     }
     $c = new Column();
     $c->inflected_name = Inflector::instance()->variablize($column['column_name']);
     $c->name = $column['column_name'];
     $c->nullable = $column['nullable'] == 'Y' ? true : false;
     $c->pk = $column['pk'] == 'P' ? true : false;
     $c->length = $column['data_length'];
     if ($column['data_type'] == 'timestamp') {
         $c->raw_type = 'datetime';
     } else {
         $c->raw_type = $column['data_type'];
     }
     $c->map_raw_type();
     $c->default = $c->cast($column['data_default']);
     return $c;
 }
 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;
 }
Exemplo n.º 4
0
 public function createColumn(&$column)
 {
     $c = new Column();
     $c->inflected_name = Inflector::instance()->variablize($column['field']);
     $c->name = $column['field'];
     $c->nullable = $column['not_nullable'] ? false : true;
     $c->pk = $column['pk'] ? true : false;
     $c->auto_increment = false;
     if (\substr($column['type'], 0, 9) == 'timestamp') {
         $c->raw_type = 'datetime';
         $c->length = 19;
     } elseif ($column['type'] == 'date') {
         $c->raw_type = 'date';
         $c->length = 10;
     } else {
         \preg_match('/^([A-Za-z0-9_]+)(\\(([0-9]+(,[0-9]+)?)\\))?/', $column['type'], $matches);
         $c->raw_type = \count($matches) > 0 ? $matches[1] : $column['type'];
         $c->length = \count($matches) >= 4 ? \intval($matches[3]) : \intval($column['attlen']);
         if ($c->length < 0) {
             $c->length = null;
         }
     }
     $c->mapRawType();
     if ($column['default']) {
         \preg_match("/^nextval\\('(.*)'\\)\$/", $column['default'], $matches);
         if (\count($matches) == 2) {
             $c->sequence = $matches[1];
         } else {
             $c->default = $c->cast($column['default'], $this);
         }
     }
     return $c;
 }
Exemplo n.º 5
0
	public function __construct($source, $dest, $options = null)
	{
		$this->source_class = get_class($source);

		if (isset($options['class_name']))
		{
			$this->dest_class = $options['class_name'];
		}
		else
		{
			$this->dest_class = \Inflector::classify($dest);
		}

		if (isset($options['foreign_key']))
		{
			$this->foreign_key = $options['foreign_key'];
		}
		else
		{
			$this->foreign_key = \Inflector::foreign_key($this->source_class);
		}

		if ( ! class_exists($this->dest_class))
		{
			$this->dest_class = '\\Model\\'.$this->dest_class;
		}

		if ( ! class_exists($this->source_class))
		{
			$this->source_class = '\\Model\\'.$this->source_class;
		}

		$this->options = $options;
	}
Exemplo n.º 6
0
 public function join()
 {
     $dest_table = \Inflector::tableize($this->dest_class);
     $source_table = \Inflector::tableize($this->source_class);
     $dest_inst = new $this->dest_class();
     $columns = $dest_inst->get_columns();
     $join = array('table' => $dest_table, 'type' => 'LEFT OUTER', 'on' => array($source_table . '.' . $this->foreign_key, '=', $dest_table . '.' . $dest_inst->get_primary_key()));
     return array(array($dest_table => $columns), $join);
 }
Exemplo n.º 7
0
 /**
  * Initializes the cache.
  *
  * With the $options array it's possible to define:
  * - expiration of the key, (time in seconds)
  * - a namespace for the key
  *
  * this last one is useful in the case two applications use
  * a shared key/store (for instance a shared Memcached db)
  *
  * Ex:
  * $cfg_ar = ActiveRecord\Config::instance();
  * $cfg_ar->set_cache('memcache://localhost:11211',array('namespace' => 'my_cool_app',
  *																											 'expire'		 => 120
  *																											 ));
  *
  * In the example above all the keys expire after 120 seconds, and the
  * all get a postfix 'my_cool_app'.
  *
  * (Note: expiring needs to be implemented in your cache store.)
  *
  * @param string $url URL to your cache server
  * @param array $options Specify additional options
  */
 public static function initialize($url, $options = array())
 {
     if ($url) {
         $url = parse_url($url);
         $file = ucwords(Inflector::instance()->camelize($url['scheme']));
         $class = "ActiveRecord\\{$file}";
         require_once __DIR__ . "/cache/{$file}.php";
         static::$adapter = new $class($url);
     } else {
         static::$adapter = null;
     }
     static::$options = array_merge(array('expire' => 30, 'namespace' => ''), $options);
 }
Exemplo n.º 8
0
 /**
  * Runs the validators.
  * @return Errors the validation errors if any
  */
 public function validate()
 {
     $reflection = Reflections::instance()->get(get_class($this->model));
     // create array of validators to use from valid functions merged with the static properties
     $this->validators = array_intersect(array_keys($reflection->getStaticProperties()), self::$VALIDATION_FUNCTIONS);
     if (empty($this->validators)) {
         return $this->record;
     }
     $inflector = Inflector::instance();
     foreach ($this->validators as $validate) {
         $func = $inflector->variablize($validate);
         $this->{$func}($reflection->getStaticPropertyValue($validate));
     }
     return $this->record;
 }
Exemplo n.º 9
0
 public function load(Model $model)
 {
     $keys = [];
     $inflector = Inflector::instance();
     foreach ($this->foreign_key as $key) {
         $keys[] = $inflector->variablize($key);
     }
     if (!($conditions = $this->createConditionsFromKeys($model, $this->primary_key, $keys))) {
         return null;
     }
     $options = $this->unsetNonFinderOptions($this->options);
     $options['conditions'] = $conditions;
     $class = $this->class_name;
     return $class::first($options);
 }
Exemplo n.º 10
0
 public function create_column(&$column)
 {
     $c = new Column();
     $c->inflected_name = Inflector::instance()->variablize($column['field']);
     $c->name = $column['field'];
     $c->nullable = $column['nullable'] === 'YES' ? true : false;
     $c->auto_increment = $column['extra'] === '1' ? true : false;
     $c->pk = $column['pk'] === 'PRIMARY KEY' ? true : false;
     $c->raw_type = $column['data_type'];
     $c->length = $column['length'] ? $column['length'] : $column['radix'];
     if ($c->raw_type == 'text') {
         $c->length = null;
     }
     if ($c->raw_type == 'datetime') {
         $c->length = 19;
     }
     $c->map_raw_type();
     $c->default = $c->cast(preg_replace("#\\(+'?(.*?)'?\\)+#", '$1', $column['data_default']), $this);
     return $c;
 }
Exemplo n.º 11
0
 public function __construct($source, $dest, $options = null)
 {
     $this->source_class = get_class($source);
     if (isset($options['class_name'])) {
         $this->dest_class = $options['class_name'];
     } else {
         $this->dest_class = \Inflector::classify($dest);
     }
     if (isset($options['foreign_key'])) {
         $this->foreign_key = $options['foreign_key'];
     } else {
         $this->foreign_key = \Inflector::foreign_key($this->source_class);
     }
     $namespace = (\Request::active() ? ucfirst(\Request::active()->module) : '') . '\\';
     if (class_exists($dest = $namespace . 'Model_' . $this->dest_class)) {
         $this->dest_class = $dest;
     }
     if (!class_exists($this->source_class)) {
         $this->source_class = 'Model_' . $this->source_class;
     }
     $this->options = $options;
 }
Exemplo n.º 12
0
 /**
  * Get an array containing the key and value of the foreign key for the association
  *
  * @param Model $model
  * @access private
  * @return array
  */
 private function getForeignKeyForNewAssociation(Model $model)
 {
     $this->setKeys($model);
     $primary_key = Inflector::instance()->variablize($this->foreign_key[0]);
     return [$primary_key => $model->id];
 }
Exemplo n.º 13
0
 /**
  * Issue an INSERT sql statement for this model's attribute.
  *
  * @see save
  * @param boolean $validate Set to true or false depending on if you want the validators to run or not
  * @return boolean True if the model was saved to the database otherwise false
  */
 private function insert($validate = true)
 {
     $this->verify_not_readonly('insert');
     if ($validate && !$this->_validate()) {
         return false;
     }
     $table = static::table();
     $this->invoke_callback('before_create', false);
     if ($dirty = $this->dirty_attributes()) {
         $table->insert($dirty);
     } else {
         $table->insert($this->attributes);
     }
     $this->invoke_callback('after_create', false);
     $pk = $this->get_primary_key(false);
     // if we've got an autoincrementing pk set it
     if (count($pk) == 1 && $table->columns[$pk[0]]->auto_increment) {
         $inflector = Inflector::instance();
         $this->attributes[$inflector->variablize($pk[0])] = $table->conn->insert_id($table->sequence);
     }
     $this->__new_record = false;
     return true;
 }
Exemplo n.º 14
0
 public static function human_attribute($attr)
 {
     $inflector = Inflector::instance();
     $inflected = $inflector->variablize($attr);
     $normal = $inflector->uncamelize($inflected);
     return ucfirst(str_replace('_', ' ', $normal));
 }
Exemplo n.º 15
0
 public 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);
 }
 /**
  * Generate a "slug" from the given string
  *
  * @param string $string The string to generate a slug from
  * @access public
  * @return string
  */
 public function generateSlug($string)
 {
     $slug = Inflector::instance()->underscorify($string);
     return strtoupper($slug);
 }
Exemplo n.º 17
0
 private function set_table_name()
 {
     if (($table = $this->class->getStaticPropertyValue('table', null)) || ($table = $this->class->getStaticPropertyValue('table_name', null))) {
         $this->table = $table;
     } else {
         // infer table name from the class name
         $this->table = Inflector::instance()->tableize($this->class->getName());
         // strip namespaces from the table name if any
         $parts = explode('\\', $this->table);
         $this->table = $parts[count($parts) - 1];
     }
     if (($db = $this->class->getStaticPropertyValue('db', null)) || ($db = $this->class->getStaticPropertyValue('db_name', null))) {
         $this->db_name = $db;
     }
 }
Exemplo n.º 18
0
 public function join()
 {
     $dest_table = \Inflector::tableize($this->dest_class);
     $source_table = \Inflector::tableize($this->source_class);
     $source_inst = new $this->source_class();
     $dest_inst = new $this->dest_class();
     $columns = $dest_inst->get_columns();
     if (isset($dest_inst->table_name)) {
         $dest_table = $dest_inst->table_name;
     }
     if (!isset($this->options['through']) || !$this->options['through']) {
         $join = array('table' => $dest_table, 'type' => 'LEFT OUTER', 'on' => array($dest_table . '.' . $this->foreign_key, '=', $source_table . '.' . $source_inst->get_primary_key()));
     } else {
         $through_foreign_key = array_key_exists('through_foreign_key', $this->options) ? $this->options['through_foreign_key'] : \Inflector::foreign_key($this->dest_class);
         $join = array(array('table' => $this->options['through'], 'type' => 'LEFT OUTER', 'on' => array($this->options['through'] . '.' . $this->foreign_key, '=', $source_table . '.' . $source_inst->get_primary_key())), array('table' => $dest_table, 'type' => 'LEFT OUTER', 'on' => array($dest_table . '.' . $dest_inst->get_primary_key(), '=', $this->options['through'] . '.' . $through_foreign_key)));
     }
     return array(array($dest_table => $columns), $join);
 }
Exemplo n.º 19
0
 /**
  * Eagerly loads relationships for $models.
  *
  * This method takes an array of models, collects PK or FK (whichever is needed for relationship), then queries
  * the related table by PK/FK and attaches the array of returned relationships to the appropriately named relationship on
  * $models.
  *
  * @param Table $table
  * @param $models array of model objects
  * @param $attributes array of attributes from $models
  * @param $includes array of eager load directives
  * @param $query_keys -> key(s) to be queried for on included/related table
  * @param $model_values_keys -> key(s)/value(s) to be used in query from model which is including
  * @return void
  */
 protected function queryAndAttachRelatedModelsEagerly(Table $table, $models, $attributes, $includes = [], $query_keys = [], $model_values_keys = [])
 {
     $values = [];
     $options = $this->options;
     $inflector = Inflector::instance();
     $query_key = $query_keys[0];
     $model_values_key = $model_values_keys[0];
     // foreach ($attributes as $column => $value) original
     foreach ($attributes as $value) {
         $values[] = $value[$inflector->variablize($model_values_key)];
     }
     $values = [$values];
     $conditions = SQLBuilder::createConditionsFromUnderscoredString($table->conn, $query_key, $values);
     if (isset($options['conditions']) && \strlen($options['conditions'][0]) > 1) {
         $utils->addCondition($options['conditions'], $conditions);
     } else {
         $options['conditions'] = $conditions;
     }
     if (!empty($includes)) {
         $options['include'] = $includes;
     }
     if (!empty($options['through'])) {
         // save old keys as we will be reseting them below for inner join convenience
         $pk = $this->primary_key;
         $fk = $this->foreign_key;
         $this->setKeys($this->getTable()->class->getName(), true);
         if (!isset($options['class_name'])) {
             $class = classify($options['through'], true);
             if (isset($this->options['namespace']) && !\class_exists($class)) {
                 $class = $this->options['namespace'] . '\\' . $class;
             }
             $through_table = $class::table();
         } else {
             $class = $options['class_name'];
             $relation = $class::table()->getRelationship($options['through']);
             $through_table = $relation->getTable();
         }
         $options['joins'] = $this->constructInnerJoinSql($through_table, true);
         $query_key = $this->primary_key[0];
         // reset keys
         $this->primary_key = $pk;
         $this->foreign_key = $fk;
     }
     $options = $this->unsetNonFinderOptions($options);
     $class = $this->class_name;
     $related_models = $class::find('all', $options);
     $used_models = [];
     $model_values_key = $inflector->variablize($model_values_key);
     $query_key = $inflector->variablize($query_key);
     foreach ($models as $model) {
         $matches = 0;
         $key_to_match = $model->{$model_values_key};
         foreach ($related_models as $related) {
             if ($related->{$query_key} == $key_to_match) {
                 $hash = \spl_object_hash($related);
                 if (\in_array($hash, $used_models)) {
                     $model->setRelationshipFromEagerLoad(clone $related, $this->attribute_name);
                 } else {
                     $model->setRelationshipFromEagerLoad($related, $this->attribute_name);
                 }
                 $used_models[] = $hash;
                 $matches++;
             }
         }
         if (0 === $matches) {
             $model->setRelationshipFromEagerLoad(null, $this->attribute_name);
         }
     }
 }
 /**
  * Set an attribute of the object
  *
  * @see \ActiveRecord\Model::__set()
  * @param string $name
  * @param mixed $value The value of the field
  * @return mixed
  */
 public function __set($name, $value)
 {
     // Camelize the name
     $camelized_name = Inflector::instance()->camelize($name);
     // Check for setter
     if (method_exists($this, "set_{$name}")) {
         $name = "set_{$name}";
         return $this->{$name}($value);
     } elseif (method_exists($this, "set{$camelized_name}")) {
         $name = "set{$camelized_name}";
         return $this->{$name}($value);
     }
     // Otherwise, just use our parent's magic setter
     return parent::__set($name, $value);
 }
Exemplo n.º 21
0
 public function setUp()
 {
     $this->inflector = Inflector::instance();
 }
Exemplo n.º 22
0
 private function set_table_name()
 {
     if (($table = $this->class->getStaticPropertyValue('table', null)) || ($table = $this->class->getStaticPropertyValue('table_name', null))) {
         $this->table = $table;
     } else {
         // infer table name from the class name
         $this->table = Inflector::instance()->tableize($this->class->getName());
     }
     if (($db = $this->class->getStaticPropertyValue('db', null)) || ($db = $this->class->getStaticPropertyValue('db_name', null))) {
         $this->db_name = $db;
     }
 }