/** * Assign default forein_model to singular association name * @param Jam_Meta $meta * @param string $name */ public function initialize(Jam_Meta $meta, $name) { if (!$this->foreign_model) { $this->foreign_model = Inflector::singular($name); } parent::initialize($meta, $name); }
public function before() { parent::before(); // Save the old action so it can be brought back on after $this->_action = $this->request->action; // Set the current action $current_action = $this->request->action; $id = $this->request->param('id', NULL); // Let's guess the action based on the params if (!in_array($this->request->action, array('edit', 'add', 'delete')) and (!is_null($id) or !empty($id))) { $current_action = 'read'; } if (!method_exists($this, 'action_' . $this->request->action)) { $model = Jelly::select(Inflector::singular($this->request->controller)); foreach ($model->get_state() as $key => $value) { $param = $this->request->param($key, NULL); if (!is_null($param)) { $model->set_state($key, $param); } } $this->request->response = Kostache::factory($this->request->controller . '/' . $current_action)->set_model($model); // Since the magic has been executed, just execute an empty action $this->request->action = 'default'; } }
/** * Convert an array to XML string * * @static * @param array $array * @param string $root * @param SimpleXMLElement $xml * @return string */ public static function xml(array $array, $root = 'data', SimpleXMLElement &$xml = null) { // Initialize if (is_null($xml)) { $xml = simplexml_load_string('<?xml version="1.0" encoding="' . Kohana::$charset . '"?><' . $root . ' />'); } foreach ($array as $key => $value) { // No numeric keys in our xml please! $numeric = false; if (is_numeric($key)) { $numeric = true; $key = Inflector::singular($root); } // Valid XML name $key = preg_replace('/[^a-z0-9\\-\\_\\.\\:]/i', '', $key); // Recursive call required for array values if (is_array($value)) { $node = true || Arr::is_assoc($value) || $numeric ? $xml->addChild($key) : $xml; self::xml($value, $key, $node); } else { $xml->addChild($key, htmlspecialchars($value)); } } return $xml->asXML(); }
/** * Get field validation messages * * @return string */ public function get_error() { $errors = $this->_get_view_var('errors'); if ($errors) { if ($this->_field instanceof Jelly_Field_ManyToMany) { if (array_key_exists(Inflector::singular($this->_field->name), $errors)) { return $errors[Inflector::singular($this->_field->name)]; //extra validation from controller } elseif (isset($errors['_external'])) { if (array_key_exists(Inflector::singular($this->_field->name), $errors['_external'])) { return $errors['_external'][Inflector::singular($this->_field->name)]; } } } else { if (array_key_exists($this->_field->name, $errors)) { return $errors[$this->_field->name]; //extra validation from controller } elseif (isset($errors['_external'])) { if (array_key_exists($this->_field->name, $errors['_external'])) { return $errors['_external'][$this->_field->name]; } } } } }
/** * Constructs a new CDM model * * @param key record key to load */ public function __construct($key = NULL) { if (!CDM::$_connected) { foreach (Kohana::config('cdm')->connection['hosts'] as $host) { // Connect to cassandra nodes CassandraConn::add_node($host['hostname'], $host['port']); } CDM::$_connected = TRUE; } if (!isset($this->_keyspace)) { // Find the application keyspace if not already set $this->_keyspace = Kohana::config('cdm')->keyspace; } if (!isset($this->_column_family)) { // Use singular version of model name for the column family $this->_column_family = Inflector::singular(strtolower(substr(get_class($this), 10))); } if (!isset(CDM::$_managers[$this->_keyspace][$this->_column_family])) { // Create column manager CDM::$_managers[$this->_keyspace][$this->_column_family] = new CassandraCF($this->_keyspace, $this->_column_family, $this->_is_super); } $this->_manager = CDM::$_managers[$this->_keyspace][$this->_column_family]; if ($key !== NULL) { // Load initial record $this->find($key); } }
/** * Initialize object (for relations) * @param orm $object */ public function initialize(&$object) { $models[0] = Inflector::plural(strtolower(str_replace('Model_', '', get_class($object)))); $models[1] = $this->item['name']; sort($models); $object->create_relation('hasMany', $this->item['name'], array('model' => Inflector::singular($this->item['name']), 'through' => $models[0] . '_' . $models[1])); }
public function config($group, $type, $model_name = NULL) { $model_name = $model_name ? $model_name : $this->model_name; $config = self::$_config === NULL ? self::$_config = Kohana::$config->load('huia/api') : self::$_config; $custom = $config->get('custom_' . $group); $regexp = Arr::path($custom, strtolower(Inflector::singular($model_name)) . '.' . $type); return $regexp !== NULL ? $regexp : Arr::get($config->get($group), $type); }
public function title() { $name = str_replace('Controller_Tart_', '', get_class($this)); $name = ucwords(Inflector::humanize($name)); if ($this->request->param('id')) { return ucwords(Inflector::singular($name)) . ' - ' . Inflector::humanize($this->request->action()); } else { return $name . ' - ' . Inflector::humanize($this->request->action()); } }
/** * Prepare controller and model for crud actions */ public function before() { parent::before(); $this->controller_name = $this->request->controller(); if ($this->model == null) { $this->model = $this->request->controller(); } if (is_string($this->model)) { $this->model = ORM::factory(Inflector::singular($this->model)); } }
/** * Add a validator item * * @access public * @param mixed $type * @param mixed $rule * @return object */ public function add_validator($type, $rule) { $type = Inflector::plural($rule->type); if (in_array($type, array('filters', 'display_filters'))) { return $this->add_filter(Inflector::singular($type), $rule); } $next = count($this->_validators[$type]); // Resolve the context $this->make_context($rule); $this->_validators[$type][$next] = $rule; return $this; }
/** * Try to load Flatfile Model, based on url segment * Throw 404 error page if markdown file cant found **/ public function __construct() { try { $model_name = Inflector::singular(strtolower(Request::current()->controller())); $model = 'Model_' . ucfirst($model_name); /** * Assign model to a variable named as the controller name **/ $this->{$model_name} = new $model(Request::initial()->param('slug')); } catch (Kohana_Exception $e) { if ($slug = Request::initial()->param('slug')) { throw HTTP_Exception::factory(404, __("Unable to find page :slug"), array(':slug' => $slug)); } throw HTTP_Exception::factory(404, __("Unable to find URI :uri"), array(':uri' => Request::initial()->uri())); } }
/** * Input for edit item * @return string Form::input */ public function input_edit($value) { if (is_object($value)) { $id = $value->id; } else { $id = $value; $value = ORM::factory(Inflector::singular($this->item['name']), $id); } $field = isset($this->item['field']) ? $this->item['field'] : 'name'; $values_model = $value->clear()->find_all()->as_array($field); $values = array(); foreach ($values_model as $value) { $values[$value->id] = $value->{$field}; } if (!$this->item['notnull']) { Arr::unshift($values, 0, ''); } return Form::select($this->item['name'], $values, $id); }
/** * Returns age in human readable format with only the largest span * * @param int|string $time1 * @param int|string $time2 * @param string $output * @return string */ public static function age($time1, $time2 = null) { if (!is_numeric($time1)) { $time1 = strtotime($time1); } if (!is_null($time2) && !is_int($time2)) { $time2 = strtotime($time2); } if ($difference = Date::span($time1, $time2) and is_array($difference)) { foreach ($difference as $span => $amount) { if ($amount > 0) { return $amount . ' ' . __(Inflector::singular($span, $amount)); } } } if (empty($difference)) { return '0 ' . __('seconds'); } return __('some time'); }
/** * Count the number of records in the table. * @param bool $reset Pass FALSE to avoid resetting on the next call * @return int */ public function count_all($reset = true) { $is_distinct = false; $selects = []; foreach ($this->_db_pending as $key => $method) { if ($method['name'] == 'distinct') { $is_distinct = true; // Ignore any selected columns for now $selects[] = $method; unset($this->_db_pending[$key]); } if ($method['name'] == 'select') { // Ignore any selected columns for now $selects[] = $method; unset($this->_db_pending[$key]); } } if (!empty($this->_load_with)) { foreach ($this->_load_with as $alias) { // Bind relationship $this->with($alias); } } $this->_build(Database::SELECT); $records = $this->_db_builder->from([$this->_table_name, $this->_object_name]); if ($is_distinct) { $records->select([DB::expr('COUNT(DISTINCT(`' . Inflector::singular($this->_table_name) . '`.`' . $this->_primary_key . '`))'), 'records_found']); } else { $records->select([DB::expr('COUNT(*)'), 'records_found']); } $records = $records->execute($this->_db)->get('records_found'); // Add back in selected columns $this->_db_pending += $selects; $this->reset($reset); // Return the total number of records in a table return $records; }
/** * Initialize the fields and add validation rules based on field properties. * * @return void */ protected function __construct() { if ($this->_init) { if ($this->state() === 'loading') { // Object loading via mysql_fetch_object or similar has finished $this->state('loaded'); } // Can only be called once return; } // Initialization has been started $this->_init = TRUE; // Set up the fields $this->_init(); if (!$this->_model) { // Set the model name based on the class name $this->_model = strtolower(substr(get_class($this), 6)); } if (!$this->_table) { // Set the table name to the plural model name $this->_table = inflector::plural($this->_model); } foreach ($this->_fields as $name => $field) { if ($field->primary === TRUE) { if (!$this->_primary_key) { // This is the primary key $this->_primary_key = $name; } else { if (is_string($this->_primary_key)) { // More than one primary key found, create a list of keys $this->_primary_key = array($this->_primary_key); } // Add this key to the list $this->_primary_key[] = $name; } } } foreach ($this->_fields as $name => $field) { if ($field instanceof Sprig_Field_ForeignKey and !$field->model) { if ($field instanceof Sprig_Field_HasMany) { $field->model = Inflector::singular($name); } else { $field->model = $name; } } if ($field instanceof Sprig_Field_ManyToMany) { if (!$field->through) { // Get the model names for the relation pair $pair = array(strtolower($this->_model), strtolower($field->model)); // Sort the model names alphabetically sort($pair); // Join the model names to get the relation name $pair = implode('_', $pair); if (!isset(Sprig::$_relations[$pair])) { // Must set the pair key before loading the related model // or we will fall into an infinite recursion loop Sprig::$_relations[$pair] = TRUE; $tables = array($this->table(), Sprig::factory($field->model)->table()); // Sort the table names alphabetically sort($tables); // Join the table names to get the table name Sprig::$_relations[$pair] = implode('_', $tables); } // Assign by reference so that changes to the pivot table // will carry over to all models $field->through =& Sprig::$_relations[$pair]; } } if (!$field->column) { // Create the key based on the field name if ($field instanceof Sprig_Field_BelongsTo) { if (isset($field->foreign_key) and $field->foreign_key) { $fk = $field->foreign_key; } else { $fk = Sprig::factory($field->model)->fk(); } $field->column = $fk; } elseif ($field instanceof Sprig_Field_HasOne) { $field->column = $this->fk(); } elseif ($field instanceof Sprig_Field_ForeignKey) { // This field is probably a Many and does not need a column } else { $field->column = $name; } } if (!$field->label) { $field->label = Inflector::humanize($name); } if ($field->null) { // Fields that allow NULL values must accept empty values $field->empty = TRUE; } if ($field->editable) { if (!$field->empty and !isset($field->rules['not_empty'])) { // This field must not be empty $field->rules['not_empty'] = NULL; } if ($field->unique) { // Field must be a unique value $field->callbacks[] = array($this, '_unique_field'); } if ($field->choices and !isset($field->rules['in_array'])) { // Field must be one of the available choices $field->rules['in_array'] = array(array_keys($field->choices)); } if (!empty($field->min_length)) { $field->rules['min_length'] = array($field->min_length); } if (!empty($field->max_length)) { $field->rules['max_length'] = array($field->max_length); } } if ($field instanceof Sprig_Field_BelongsTo or !$field instanceof Sprig_Field_ForeignKey) { // Set the default value for any field that is stored in the database $this->_original[$name] = $field->value($field->default); } } }
/** * Initialize the fields and add validation rules based on field properties. * * @return void */ protected function init() { if ($this->_init) { // Can only be called once return; } // Set up fields $this->set_model_definition(); if (!$this->_model) { // Set the model name based on the class name $this->_model = strtolower(substr(get_class($this), 6)); } foreach ($this->_fields as $name => &$field) { if ($field['type'] === 'has_one' && !isset($field['model'])) { $field['model'] = $name; } elseif ($field['type'] === 'has_many' && !isset($field['model'])) { $field['model'] = Inflector::singular($name); } } if (!$this->_embedded) { if (!$this->_collection) { // Set the collection name to the plural model name $this->_collection = Inflector::plural($this->_model); } if (!isset($this->_fields['_id'])) { // default _id field $this->_fields['_id'] = array('type' => 'MongoId'); } // Normalize relations foreach ($this->_relations as $name => &$relation) { if ($relation['type'] === 'has_and_belongs_to_many') { $relation['model'] = isset($relation['model']) ? $relation['model'] : Inflector::singular($name); $relation['related_relation'] = isset($relation['related_relation']) ? $relation['related_relation'] : Inflector::plural($this->_model); } elseif (!isset($relation['model'])) { if ($relation['type'] === 'belongs_to' || $relation['type'] === 'has_one') { $relation['model'] = $name; } else { $relation['model'] = Inflector::singular($name); } } switch ($relation['type']) { case 'belongs_to': $this->_fields[$name . '_id'] = array('type' => 'MongoId', 'required' => !Arr::get($relation, 'sparse', FALSE)); break; case 'has_and_belongs_to_many': $this->_fields[$name . '_ids'] = array('type' => 'set', 'duplicates' => FALSE); break; } } } $this->_init = TRUE; }
/** * Builds "degenerated" words if the word does not exist in the database. * * @access protected * @param string word to degenerate * @return array array of degenerated words of the word */ protected function _degenerate_word($word) { // Check if word has been processed already if (isset($this->degenerates[$word]) === TRUE) { return $this->degenerates[$word]; } $degenerates = array(); // Add word with upper, lower and ucfirst casing $degenerates[] = strtolower($word); $degenerates[] = strtoupper($word); $degenerates[] = ucfirst($word); // Temporarily remove ! or ? or . from end of word for inflections $w = preg_replace('/([!?\\.])+$/', '', $word); // Add inflections $singular = Inflector::singular($w); $plural = Inflector::plural($w); $degenerates[] = $singular; $degenerates[] = strtoupper($singular); $degenerates[] = ucfirst($singular); $degenerates[] = $plural; $degenerates[] = strtoupper($plural); $degenerates[] = ucfirst($plural); // Remove duplicates $degenerates = array_unique($degenerates); // Degenerate each casing versions foreach ($degenerates as $degenerate) { // Check for ! or ? at end of word if (preg_match('/[!?]$/', $degenerate)) { // Reduce to single ! or ? at end of word, if multiple were found if (preg_match('/[!?]{2,}$/', $degenerate) > 0) { $degenerates[] = preg_replace('/([!?])+$/', '$1', $degenerate); } // Remove ! or ? from end of word $degenerates[] = preg_replace('/([!?])+$/', '', $degenerate); } else { // Add ! and ? to end of word $degenerates[] = $degenerate . '!'; $degenerates[] = $degenerate . '?'; } // Remove . from end of word if (preg_match('/[\\.]$/', $degenerate)) { while (preg_match('/[\\.]$/', $degenerate)) { $degenerates[] = $degenerate = substr($degenerate, 0, strlen($degenerate) - 1); } } else { // Add . to end of word $degenerates[] = $degenerate . '.'; } } // Remove duplicates $degenerates = array_unique($degenerates); // Remove degenerate word that matches the original word if (in_array($word, $degenerates)) { foreach ($degenerates as $key => $degenerate) { if ($degenerate == $word) { unset($degenerates[$key]); break; } } } // Store the list of degenerates for the word $this->degenerates[$word] = $degenerates; return $degenerates; }
/** * Prepares the model database connection, determines the table name, * and loads column information. * * @return void */ protected function _initialize() { if (!is_object($this->_db)) { // Get database instance $this->_db = Database::instance($this->_db); } if (empty($this->_table_name)) { // Table name is the same as the object name $this->_table_name = $this->_object_name; if ($this->_table_names_plural === TRUE) { // Make the table name plural $this->_table_name = Inflector::plural($this->_table_name); } } foreach ($this->_belongs_to as $alias => $details) { $defaults['model'] = $alias; $defaults['foreign_key'] = $alias . $this->_foreign_key_suffix; $this->_belongs_to[$alias] = array_merge($defaults, $details); } foreach ($this->_has_one as $alias => $details) { $defaults['model'] = $alias; $defaults['foreign_key'] = $this->_object_name . $this->_foreign_key_suffix; $this->_has_one[$alias] = array_merge($defaults, $details); } foreach ($this->_has_many as $alias => $details) { $defaults['model'] = Inflector::singular($alias); $defaults['foreign_key'] = $this->_object_name . $this->_foreign_key_suffix; $defaults['through'] = NULL; $defaults['far_key'] = Inflector::singular($alias) . $this->_foreign_key_suffix; $this->_has_many[$alias] = array_merge($defaults, $details); } // Load column information $this->reload_columns(); }
/** * Recursive helper for writing XML element(s) * * @param XMLWriter $xml XMLWriter instance * @param array|string $data element(s) to write * @param string $root root tag for nested elements */ private static function __from_array(XMLWriter &$xml, $data, $root = '') { if (is_array($data)) { foreach ($data as $index => $element) { if (is_int($index)) { $root = $root ? Inflector::singular($root) : 'element_' . $index; } else { $root = $index; } $xml->startElement($root); if (is_array($element)) { self::__from_array($xml, $element, $root); } else { if (ctype_alnum($element) or ctype_graph($element) or strpos($element, ' ') > -1) { $xml->writeCdata($element); } else { $xml->writeRaw($element); } } $xml->endElement(); } } }
public function proxy_load_relationship($object, $relationship) { // Build query : $query = glue::qselect($this->name, $set); foreach ($this->object_pk($object) as $f => $val) { $query->where($f, '=', $val); $query->fields($f); } $query->with($set, Inflector::singular($relationship)); // Execute query : $query->execute(); }
/** * Tests Inflector::singular * * @test * @dataProvider provider_singular * @param boolean $input Input for File::mime * @param boolean $expected Output for File::mime */ public function test_singular($input, $count, $expected) { $this->assertSame($expected, Inflector::singular($input, $count)); }
/** * Setting namespace item for a log section * * @param string $item * @param string $section */ public function _set_namespace_item($item, $section) { $item = Sprig::factory(Inflector::singular($section) . '_sprig', array('name' => $item)); $item->create(); Logapp::${$section}[$item] = $_item->id; }
/** * Setting namespace item for a log section * * @param string $item * @param string $section */ public function _set_namespace_item($item, $section) { $_item = Jelly::factory(Inflector::singular($section) . '_jelly')->set(array('name' => $item))->save(); Logapp::${$section}[$item] = $_item->id; }
/** * Safe Tag * * Pass individual tag phrases along with object and object ID's in order to * set a tag on an object. If the tag in its raw form does not yet exist, * this function will create it. * * @param integer $user_id The user_id unique ID of the person who tagged the object with this tag * @param Model $object The Model Object * @param string $tag A raw string from a web form containing tags * @return boolean * * @uses Inflector::singular */ public function safe_tag($user_id = 0, Model $object, $tag = '') { $object_id = $object->id; if (!($user_id = intval($user_id)) or !($object_id = intval($object_id)) or empty($tag)) { return FALSE; } if (!empty($this->config['append_to_integer']) and is_numeric($tag) and intval($tag) == $tag) { // Converts numeric tag "123" to "123_" to facilitate // alphanumeric sorting (otherwise, PHP converts string to // true integer). $tag = preg_replace('/^([0-9]+)$/', "\$1" . $this->config['append_to_integer'], $tag); } $normalized_tag = $this->normalize_tag(strtolower($tag)); //this is required to avoid duplicate tags, ex: 'demo, demo, test' $result = ORM::factory(Inflector::singular($this->config['tagging_model']))->join($this->config['tag_table'], 'INNER')->on('tag_id', '=', $this->config['tag_table'] . '.id')->where($this->config['object_foreign_key'], '=', $object_id)->where($this->config['tag_table'] . '.type', '=', $object->type)->where('name', '=', $normalized_tag); if ($result->reset(FALSE)->count_all() > 0) { return TRUE; } // Then see if a tag in this form exists. $result = ORM::factory(Inflector::singular($this->config['tag_table']))->where('name', '=', $tag)->where('type', '=', $object->type); if ($result->reset(FALSE)->count_all() > 0) { $result = $result->find(); $tag_id = $result->id; } else { // Add new tag! $new_tag = ORM::factory(Inflector::singular($this->config['tag_table'])); $new_tag->name = $normalized_tag; $new_tag->type = $object->type; $new_tag->save(); $tag_id = $new_tag->id; } if (!($tag_id > 0)) { return FALSE; } $new_tagging = ORM::factory(Inflector::singular($this->config['tagging_model'])); $new_tagging->tag_id = $tag_id; $new_tagging->author = $user_id; $new_tagging->type = $object->type; $new_tagging->{$this->config['object_foreign_key']} = $object_id; $new_tagging->save(); return TRUE; }
<div id="chart" class="yui-u"> <canvas id="perfchart" width="600" height="250">Performance chart here.</canvas> </div> </div> <ul> <?php echo '<li>server ', html::anchor($bot->server->uri(), $bot->server->name), '</li>'; ?> </ul> <?php if (isset($stats)) { ?> <h3>Last <?php echo count($stats), ' ', ucfirst(Inflector::singular('games', count($stats))); ?> of <?php echo $game_count; ?> </h3> <ol class="stats"> <?php foreach ($stats as $game) { echo '<li>', $game->DatePlayed, ' ', html::anchor($game->bot1->uri(), $game->bot1->name), ', ', html::anchor($game->bot2->uri(), $game->bot2->name), ', ', html::anchor($game->bot3->uri(), $game->bot3->name), ', ', html::anchor($game->bot4->uri(), $game->bot4->name), ' Winner: ', html::anchor($game->winner->uri(), $game->winner->name), ' ', '<span>Show History</span>', '<div class="history">', '<pre>', $game->GameHistory, '</pre>', '</div>', '</li>'; } ?> </ol> <?php } ?>
/** * Clears all inflection rules. * * @param string|boolean $lang The language name to reset or `true` to reset all even defaults. */ public static function reset($lang = null) { if (is_string($lang)) { unset(static::$_singular[$lang]); unset(static::$_plural[$lang]); return; } static::$_singular = []; static::$_plural = []; if ($lang === true) { return; } /** * Initilalize the class with english inflector rules. */ Inflector::singular('/([^s])s$/i', '\\1', 'default'); Inflector::plural('/([^s])$/i', '\\1s', 'default'); Inflector::singular('/(x|z|s|ss|ch|sh)es$/i', '\\1', 'default'); Inflector::plural('/(x|z|ss|ch|sh)$/i', '\\1es', 'default'); Inflector::singular('/ies$/i', 'y', 'default'); Inflector::plural('/([^aeiouy]|qu)y$/i', '\\1ies', 'default'); Inflector::plural('/(meta|data)$/i', '\\1', 'default'); Inflector::irregular('child', 'children', 'default'); Inflector::irregular('equipment', 'equipment', 'default'); Inflector::irregular('information', 'information', 'default'); Inflector::irregular('man', 'men', 'default'); Inflector::irregular('news', 'news', 'default'); Inflector::irregular('person', 'people', 'default'); Inflector::irregular('woman', 'women', 'default'); /** * Warning, using an "exhastive" list of rules will slow * down all singularizations/pluralizations generations. * So it may be preferable to only add the ones you are actually needed. * * Anyhow bellow a list english exceptions which are not covered by the above rules. */ // Inflector::irregular('advice', 'advice', 'default'); // Inflector::irregular('aircraft', 'aircraft', 'default'); // Inflector::irregular('alias', 'aliases', 'default'); // Inflector::irregular('alga', 'algae', 'default'); // Inflector::irregular('alumna', 'alumnae', 'default'); // Inflector::irregular('alumnus', 'alumni', 'default'); // Inflector::irregular('analysis', 'analyses', 'default'); // Inflector::irregular('antenna', 'antennae', 'default'); // Inflector::irregular('automaton', 'automata', 'default'); // Inflector::irregular('axis', 'axes', 'default'); // Inflector::irregular('bacillus', 'bacilli', 'default'); // Inflector::irregular('bacterium', 'bacteria', 'default'); // Inflector::irregular('barracks', 'barracks', 'default'); // Inflector::irregular('basis', 'bases', 'default'); // Inflector::irregular('bellows', 'bellows', 'default'); // Inflector::irregular('buffalo', 'buffaloes', 'default'); // Inflector::irregular('bus', 'buses', 'default'); // Inflector::irregular('bison', 'bison', 'default'); // Inflector::irregular('cactus', 'cacti', 'default'); // Inflector::irregular('cafe', 'cafes', 'default'); // Inflector::irregular('calf', 'calves', 'default'); // Inflector::irregular('cargo', 'cargoes', 'default'); // Inflector::irregular('cattle', 'cattle', 'default'); // Inflector::irregular('child', 'children', 'default'); // Inflector::irregular('congratulations', 'congratulations', 'default'); // Inflector::irregular('corn', 'corn', 'default'); // Inflector::irregular('crisis', 'crises', 'default'); // Inflector::irregular('criteria', 'criterion', 'default'); // Inflector::irregular('curriculum', 'curricula', 'default'); // Inflector::irregular('datum', 'data', 'default'); // Inflector::irregular('deer', 'deer', 'default'); // Inflector::irregular('die', 'dice', 'default'); // Inflector::irregular('dregs', 'dregs', 'default'); // Inflector::irregular('duck', 'duck', 'default'); // Inflector::irregular('echo', 'echos', 'default'); // Inflector::irregular('elf', 'elves', 'default'); // Inflector::irregular('ellipsis', 'ellipses', 'default'); // Inflector::irregular('embargo', 'embargoes', 'default'); // Inflector::irregular('equipment', 'equipment', 'default'); // Inflector::irregular('erratum', 'errata', 'default'); // Inflector::irregular('evidence', 'evidence', 'default'); // Inflector::irregular('eyeglasses', 'eyeglasses', 'default'); // Inflector::irregular('fish', 'fish', 'default'); // Inflector::irregular('focus', 'foci', 'default'); // Inflector::irregular('foot', 'feet', 'default'); // Inflector::irregular('fungus', 'fungi', 'default'); // Inflector::irregular('gallows', 'gallows', 'default'); // Inflector::irregular('genus', 'genera', 'default'); // Inflector::irregular('goose', 'geese', 'default'); // Inflector::irregular('gold', 'gold', 'default'); // Inflector::irregular('grotto', 'grottoes', 'default'); // Inflector::irregular('gymnasium', 'gymnasia', 'default'); // Inflector::irregular('half', 'halves', 'default'); // Inflector::irregular('headquarters', 'headquarters', 'default'); // Inflector::irregular('hoof', 'hooves', 'default'); // Inflector::irregular('hypothesis', 'hypotheses', 'default'); // Inflector::irregular('information', 'information', 'default'); // Inflector::irregular('graffito', 'graffiti', 'default'); // Inflector::irregular('half', 'halves', 'default'); // Inflector::irregular('hero', 'heroes', 'default'); // Inflector::irregular('jewelry', 'jewelry', 'default'); // Inflector::irregular('kin', 'kin', 'default'); // Inflector::irregular('knife', 'knives', 'default'); // Inflector::irregular('larva', 'larvae', 'default'); // Inflector::irregular('leaf', 'leaves', 'default'); // Inflector::irregular('legislation', 'legislation', 'default'); // Inflector::irregular('life', 'lives', 'default'); // Inflector::irregular('loaf', 'loaves', 'default'); // Inflector::irregular('locus', 'loci', 'default'); // Inflector::irregular('louse', 'lice', 'default'); // Inflector::irregular('luck', 'luck', 'default'); // Inflector::irregular('luggage', 'luggage', 'default'); // Inflector::irregular('man', 'men', 'default'); // Inflector::irregular('mathematics', 'mathematics', 'default'); // Inflector::irregular('matrix', 'matrices', 'default'); // Inflector::irregular('means', 'means', 'default'); // Inflector::irregular('measles', 'measles', 'default'); // Inflector::irregular('medium', 'media', 'default'); // Inflector::irregular('memorandum', 'memoranda', 'default'); // Inflector::irregular('money', 'monies', 'default'); // Inflector::irregular('moose', 'moose', 'default'); // Inflector::irregular('mosquito', 'mosquitoes', 'default'); // Inflector::irregular('motto', 'mottoes', 'default'); // Inflector::irregular('mouse', 'mice', 'default'); // Inflector::irregular('mumps', 'mumps', 'default'); // Inflector::irregular('music', 'music', 'default'); // Inflector::irregular('mythos', 'mythoi', 'default'); // Inflector::irregular('nebula', 'nebulae', 'default'); // Inflector::irregular('neurosis', 'neuroses', 'default'); // Inflector::irregular('news', 'news', 'default'); // Inflector::irregular('nucleus', 'nuclei', 'default'); // Inflector::irregular('numen', 'numina', 'default'); // Inflector::irregular('oasis', 'oases', 'default'); // Inflector::irregular('oats', 'oats', 'default'); // Inflector::irregular('octopus', 'octopuses', 'default'); // Inflector::irregular('offspring', 'offspring', 'default'); // Inflector::irregular('ovum', 'ova', 'default'); // Inflector::irregular('ox', 'oxen', 'default'); // Inflector::irregular('pajamas', 'pajamas', 'default'); // Inflector::irregular('pants', 'pants', 'default'); // Inflector::irregular('paralysis', 'paralyses', 'default'); // Inflector::irregular('parenthesis', 'parentheses', 'default'); // Inflector::irregular('person', 'people', 'default'); // Inflector::irregular('phenomenon', 'phenomena', 'default'); // Inflector::irregular('pike', 'pike', 'default'); // Inflector::irregular('plankton', 'plankton', 'default'); // Inflector::irregular('pliers', 'pliers', 'default'); // Inflector::irregular('polyhedron', 'polyhedra', 'default'); // Inflector::irregular('potato', 'potatoes', 'default'); // Inflector::irregular('quiz', 'quizzes', 'default'); // Inflector::irregular('radius', 'radii', 'default'); // Inflector::irregular('roof', 'roofs', 'default'); // Inflector::irregular('salmon', 'salmon', 'default'); // Inflector::irregular('scarf', 'scarves', 'default'); // Inflector::irregular('scissors', 'scissors', 'default'); // Inflector::irregular('self', 'selves', 'default'); // Inflector::irregular('series', 'series', 'default'); // Inflector::irregular('shears', 'shears', 'default'); // Inflector::irregular('sheep', 'sheep', 'default'); // Inflector::irregular('shelf', 'shelves', 'default'); // Inflector::irregular('shorts', 'shorts', 'default'); // Inflector::irregular('silver', 'silver', 'default'); // Inflector::irregular('species', 'species', 'default'); // Inflector::irregular('squid', 'squid', 'default'); // Inflector::irregular('stimulus', 'stimuli', 'default'); // Inflector::irregular('stratum', 'strata', 'default'); // Inflector::irregular('swine', 'swine', 'default'); // Inflector::irregular('syllabus', 'syllabi', 'default'); // Inflector::irregular('synopsis', 'synopses', 'default'); // Inflector::irregular('synthesis', 'syntheses', 'default'); // Inflector::irregular('tax', 'taxes', 'default'); // Inflector::irregular('terminus', 'termini', 'default'); // Inflector::irregular('thesis', 'theses', 'default'); // Inflector::irregular('thief', 'thieves', 'default'); // Inflector::irregular('tomato', 'tomatoes', 'default'); // Inflector::irregular('tongs', 'tongs', 'default'); // Inflector::irregular('tooth', 'teeth', 'default'); // Inflector::irregular('torpedo', 'torpedoes', 'default'); // Inflector::irregular('torus', 'tori', 'default'); // Inflector::irregular('trousers', 'trousers', 'default'); // Inflector::irregular('trout', 'trout', 'default'); // Inflector::irregular('tweezers', 'tweezers', 'default'); // Inflector::irregular('vertebra', 'vertebrae', 'default'); // Inflector::irregular('vertex', 'vertices', 'default'); // Inflector::irregular('vespers', 'vespers', 'default'); // Inflector::irregular('veto', 'vetoes', 'default'); // Inflector::irregular('volcano', 'volcanoes', 'default'); // Inflector::irregular('vortex', 'vortices', 'default'); // Inflector::irregular('vita', 'vitae', 'default'); // Inflector::irregular('virus', 'viri', 'default'); // Inflector::irregular('wheat', 'wheat', 'default'); // Inflector::irregular('wife', 'wives', 'default'); // Inflector::irregular('wolf', 'wolves', 'default'); // Inflector::irregular('woman', 'women', 'default'); // Inflector::irregular('zero', 'zeros', 'default'); }
/** * Gets the database columns associated with the field. * * @param Sprig_Field The sprig field. * @param Database_Table The parent database table. * @return array */ private function _columns(Sprig_Field $field, Database_Table $table) { // Foreign keys are represented as BelongTo relationships if ($field instanceof Sprig_Field_BelongsTo) { // Get the model the field references $references = $this->_model($field->model); // Get all the primary keys in the referenced model as an array $pks = is_array($references->pk()) ? $references->pk() : array($references->pk()); // Prepare a column array $columns = array(); // Loop through each primary key foreach ($pks as $pk) { // Get the foreign primary key field $foreign_field = $references->field($pk); // Generates a table column for that foreign field $column = current($this->_columns($foreign_field, $table)); // Renames the column to the standard foreign key format $column->name = Inflector::singular($references->table()) . '_' . $pk; // If the column is an integer if ($column instanceof Database_Column_Int) { // We must disable auto_increment $column->auto_increment = FALSE; } // Add the column to the column array $columns[] = $column; } // No further processing is needed, so return the columns. return $columns; } elseif ($field instanceof Sprig_Field_Char) { // If the character field is a text field if ($field instanceof Sprig_Field_Text) { // Set the column to have a text datatype $column = Database_Column::factory('text'); // TODO: Ugly hack, fix it. (Text datatypes dont take parameters). unset($column->max_length); } else { // Create a new database column $column = Database_Column::factory('varchar'); // Set the varchar's max length to a default of 45 $column->max_length = isset($field->max_length) ? $field->max_length : 64; } } elseif ($field instanceof Sprig_Field_Integer) { // Use the int datatype and create the column $column = Database_Column::factory('int'); // If the field is Sprig_Field_Auto then auto_increment is set to true. $column->auto_increment = $field instanceof Sprig_Field_Auto; } elseif ($field instanceof Sprig_Field_Boolean) { // Very simply, a tinyint is a 0 or a 1 $column = Database_Column::factory('tinyint'); } // Set the value of the column's name $column->name = $field->column; // Set the column's default value $column->default = $field->default; // The column is nullable if the field is not empty $column->nullable = !$field->empty; // Return the column as an array return array($column); }
?> <?php $hide = ($type === 'skipped' or $type === 'incomplete'); ?> <div class="<?php echo $type; ?> -list"> <h2 onclick="toggle('<?php echo $type; ?> ');"><?php echo count($tests); ?> <?php echo __(ucfirst(Inflector::singular($type, count($tests)))); ?> <span id="<?php echo $type; ?> -show" class="show">[<?php echo $hide ? __('show') : __('hide'); ?> ]</span></h2> <ol id="<?php echo $type; ?> -ol" class="<?php echo $hide ? 'hidden' : ''; ?> ">
/** * Prepares the model database connection, determines the table name, * and loads column information. * * @return void */ protected function _initialize() { // Set the object name and plural name $this->_object_name = strtolower(substr(get_class($this), 6)); // Check if this model has already been initialized if (!($init = Arr::get(ORM::$_init_cache, $this->_object_name, FALSE))) { $init = array('_belongs_to' => array(), '_has_one' => array(), '_has_many' => array(), '_has_many_keys' => array()); // Set the object plural name if none predefined if (!isset($this->_object_plural)) { $init['_object_plural'] = Inflector::plural($this->_object_name); } if (!$this->_errors_filename) { $init['_errors_filename'] = $this->_object_name; } if (!is_object($this->_db)) { // Get database instance $init['_db'] = Database::instance($this->_db_group); } if (empty($this->_table_name)) { // Table name is the same as the object name $init['_table_name'] = $this->_object_name; if ($this->_table_names_plural === TRUE) { // Make the table name plural $init['_table_name'] = Arr::get($init, '_object_plural', $this->_object_plural); } } if (!empty($this->_ignored_columns)) { // Optimize for performance $init['_ignored_columns'] = array_combine($this->_ignored_columns, $this->_ignored_columns); } $defaults = array(); foreach ($this->_belongs_to as $alias => $details) { $defaults['model'] = $alias; $defaults['foreign_key'] = $alias . $this->_foreign_key_suffix; $init['_belongs_to'][$alias] = array_merge($defaults, $details); } foreach ($this->_has_one as $alias => $details) { $defaults['model'] = $alias; $defaults['foreign_key'] = $this->_object_name . $this->_foreign_key_suffix; $init['_has_one'][$alias] = array_merge($defaults, $details); } foreach ($this->_has_many as $alias => $details) { $defaults['model'] = Inflector::singular($alias); $defaults['foreign_key'] = $this->_object_name . $this->_foreign_key_suffix; $defaults['through'] = NULL; $defaults['far_key'] = Inflector::singular($alias) . $this->_foreign_key_suffix; $init['_has_many'][$alias] = array_merge($defaults, $details); } foreach ($this->_has_many_keys as $alias => $details) { $defaults['model'] = Inflector::singular($alias); $defaults['foreign_key'] = array($this->_object_name . $this->_foreign_key_suffix); $defaults['far_key'] = array(Inflector::singular($alias) . $this->_foreign_key_suffix); $init['_has_many_keys'][$alias] = array_merge($defaults, $details); } ORM::$_init_cache[$this->_object_name] = $init; } // Assign initialized properties to the current object foreach ($init as $property => $value) { $this->{$property} = $value; } // Load column information $this->reload_columns(); // Clear initial model state $this->clear(); }
public static function generate_model($model, $force = FALSE) { $class_name = 'Model_' . $model; $file = str_replace('_', DIRECTORY_SEPARATOR, $model); $base_dir = 'Base'; $model_dir = APPPATH . 'classes' . DIRECTORY_SEPARATOR . 'Model' . DIRECTORY_SEPARATOR; $model_base = $model_dir . $base_dir . DIRECTORY_SEPARATOR; $file_name = Kohana::find_file('classes/model', $file); $file_base_name = Kohana::find_file('classes/model/base', $file); $table_name = strtolower(Inflector::plural($model)); $table_id = strtolower($model) . '_id'; $rules = array(); $labels = array(); $has_many = array(); $belongs_to = array(); $columns = Database::instance()->list_columns($table_name); foreach ($columns as $field) { $name = Arr::get($field, 'column_name'); $key = Arr::get($field, 'key'); $type = Arr::get($field, 'type'); $low_name = str_replace('_id', '', $name); $maximum_length = Arr::get($field, 'character_maximum_length', Arr::get($field, 'display')); $title = ucfirst($name); // ignore id and _at$ if ($name === 'id' or preg_match('@_at$@', $name)) { continue; } $field_rules = array(); // unique if ($key === 'UNI') { $field_rules[] = "array(array(\$this, 'unique'), array(':field', ':value')),"; } // unique if ($type === 'int') { $field_rules[] = "array('numeric'),"; } // not null if (Arr::get($field, 'is_nullable') === FALSE) { $field_rules[] = "array('not_empty'),"; } // max length if ($maximum_length) { $field_rules[] = "array('max_length', array(':value', {$maximum_length})),"; } // cpf if ($name === 'cpf') { $field_rules[] = "array('cpf', array(':value')),"; } // email if (preg_match('@email@', $name)) { $field_rules[] = "array('email', array(':value')),"; } // rules if (!empty($field_rules)) { $rules[$name] = $field_rules; } // labels if (!preg_match('@_id$@', $name)) { $labels[$name] = $title; } // belongs to if (preg_match('@_id$@', $name)) { $model_name = ORM::get_model_name($low_name); $belongs_to[$low_name] = "array(" . "'model' => '" . $model_name . "'" . "),"; $labels[$low_name] = ucfirst($low_name); } } foreach (Database::instance()->list_tables() as $name) { $_columns = array_keys(Database::instance()->list_columns($name)); // has many through if (preg_match('/(^' . $table_name . '_(.*)|(.*)_' . $table_name . '$)/', $name, $matchs)) { $related = $matchs[count($matchs) - 1]; $has_many[$related] = "array(" . "'model' => '" . ORM::get_model_name($related) . "', " . "'through' => '" . $name . "'" . "),"; $labels[$related] = ucfirst($related); } // has many if (in_array('id', $_columns) and in_array($table_id, $_columns)) { $related = Inflector::singular($name); $field_name = Inflector::singular($table_name); $model_name = ORM::get_model_name($related); $has_many[str_replace($field_name . '_', '', $name)] = "array(" . "'model' => '" . $model_name . "'" . "),"; } } $class_extends = 'Model_App'; $columns = self::format_columns($columns); $full_class_name = 'Model_' . $base_dir . '_' . $model; $view = View::factory('huia/orm/base'); $view->set('class_name', $full_class_name); $view->set('class_extends', $class_extends); $view->set('table_name', $class_name); $view->set('rules', $rules); $view->set('labels', $labels); $view->set('has_many', $has_many); $view->set('belongs_to', $belongs_to); $view->set('columns', $columns); $render_view = $view->render(); $hash_current = $file_base_name ? preg_replace("/[^A-Za-z0-9]/", "", @file_get_contents($file_base_name)) : NULL; $hash_new = preg_replace("/[^A-Za-z0-9]/", "", $render_view); if ($hash_current !== $hash_new) { $file_base_name = $model_base . $file . EXT; create_dir(dirname($file_base_name)); file_put_contents($file_base_name, $view->render()); } // Create if dont exists if (!$file_name) { $view = View::factory('huia/orm'); $view->set('class_name', $class_name); $view->set('class_extends', 'Model_' . $base_dir . '_' . $model); $file_name = $model_dir . $file . EXT; create_dir(dirname($file_name)); file_put_contents($file_name, $view->render()); } }