Example #1
0
 /**
  * Constructeur
  * @param array $config
  */
 function __construct(array $config = array())
 {
     // Initialise la configuration, si elle existe
     if (isset($config['orm'])) {
         self::$config = array_merge(self::$config, $config['orm']);
     }
     // Premier chargement de L'ORM
     if (self::$CI === NULL) {
         // Charge l'instance de CodeIgniter
         self::$CI =& get_instance();
         // Charge le fichier langue
         self::$CI->load->language('orm');
         // Si la clé de cryptage est vide, on désactive le cryptage
         if (self::$config['encryption_enable'] && empty(self::$config['encryption_key'])) {
             self::$config['encryption_enable'] = FALSE;
         }
         // Charge l'autoloader de L'ORM
         if (self::$config['autoloadmodel']) {
             self::$CI->load->helper('orm');
         }
         // Si le cryptage est actif charge les éléments indispensable au cryptage
         if (self::$config['encryption_enable']) {
             self::$CI->load->helper('string');
         }
     }
 }
Example #2
0
 /**
  * Returns one object from collection
  *
  * @return mixed|null
  */
 public function findOne()
 {
     if (!$this->hasStatement('select')) {
         $this->select('*');
     }
     $this->limit(1);
     $result = null;
     $sql = $this->compile();
     $tbl = $this->getStatement('table');
     $cache_key = OrmCache::genKey($sql, $this->values_accum);
     if (($result_cached = OrmCache::getCachedQuery($cache_key)) !== false && $this->use_cache) {
         return $result_cached;
     }
     if (($result_cached = OrmCache::getFromInternalCache($cache_key)) !== false) {
         return $result_cached;
     }
     if ($row = Db::getRow($sql, $this->values_accum)) {
         $result = Orm::collection($this->entity_name)->create($row);
     }
     if ($this->use_cache) {
         OrmCache::cacheQuery($cache_key, $tbl['sql'], $result);
         return $result;
     }
     OrmCache::storeInternal($cache_key, $tbl['sql'], $result);
     return $result;
 }
Example #3
0
 public function __construct($options)
 {
     $this->options = array_merge($this->options, $options);
     $this->Session = Session::getInstance();
     $this->db = Orm::loadModel('Users');
     $this->options['salt'] = Configure::get('globals.salt');
 }
Example #4
0
File: Orm.php Project: LeoPelan/ORM
 public static function count($tableName)
 {
     $query = "SELECT COUNT(*) FROM " . $tableName;
     $req = self::$connexion->prepare($query);
     $res = $req->execute();
     Orm::writeLog($req, $res, $query);
     $res = $req->fetch();
     return $res[0];
 }
Example #5
0
 public function campaigns($limit = 20)
 {
     $this->info['description'] = 'Spicer\'s Campaigns';
     $this->info['lastBuildDate'] = date(DATE_RFC2822, Orm::factory('campaign')->where('status', 'approved')->find()->created);
     $campaigns = Orm::factory('campaign')->where('status', 'approved')->find_all($limit);
     foreach ($campaigns as $campaign) {
         $items[] = array('title' => $campaign->name, 'link' => 'campaigns/view/' . $campaign->name, 'guid' => 'campaigns/view/' . $campaign->name, 'description' => $campaign->description, 'author' => 'admin@spicers.com.au (Spicers)', 'pubDate' => date(DATE_RFC2822, $campaign->created));
     }
     echo feed::create($this->info, $items);
 }
Example #6
0
 public static function getFuncName($hash, $name = NULL)
 {
     if (Orm::validName(self::default_name)) {
         throw new OrmException(sprintf('The Orm name "%s" is valid and must absolutely NOT be!', self::default_name));
     }
     if (is_null($name)) {
         $name = self::default_name;
     }
     return sprintf('%s_%s', $name, $hash);
 }
Example #7
0
 public function before()
 {
     // This codeblock is very useful in development sites:
     // What it does is get rid of invalid sessions which cause exceptions, which may happen
     // 1) when you make errors in your code.
     // 2) when the session expires!
     try {
         $this->session = Session::instance();
     } catch (ErrorException $e) {
         session_destroy();
     }
     // Execute parent::before first
     parent::before();
     // Open session
     $this->session = Session::instance();
     // First make sure we have at least one admin user
     // This code can safely be deleted after the first login
     // DELETE AFTER FIRST LOGIN -- BLOCK START
     $user = Orm::Factory('user');
     if ($user->count_all() == 0) {
         $login_role = ORM::factory('role', array('name' => 'login'));
         $admin_role = ORM::factory('role', array('name' => 'admin'));
         $data = array('username' => 'administrator', 'email' => '*****@*****.**', 'password' => 'admin12345', 'password_confirm' => 'admin12345');
         $user->create_user($data, array('username', 'password', 'email'));
         $user->add('roles', $login_role)->add('roles', $admin_role);
         $user->save();
     }
     $user = NULL;
     // DELETE AFTER FIRST LOGIN -- BLOCK END
     // Handle the unlikely situation where a logged-in user was recently deleted
     // by an admin, but is now making a request.  In this case, we want to log the user out
     // before trying to process the request.
     $auth = Auth::instance();
     $user = $auth->get_user();
     // In this situation, we will still have a user in the session,
     // and the auth instance will still see its original role(s),
     // but the ORM will fetch NULL for the user ID
     if (!empty($user) and $user->id === NULL) {
         $auth->logout(TRUE, TRUE);
     }
     // Check user auth and role
     $action_name = Request::current()->action();
     if ($this->auth_required !== FALSE && $auth->logged_in($this->auth_required) === FALSE || is_array($this->secure_actions) && array_key_exists($action_name, $this->secure_actions) && $auth->logged_in($this->secure_actions[$action_name]) === FALSE) {
         if ($auth->logged_in()) {
             // user is logged in but not on the secure_actions list
             $this->access_required();
         } else {
             $this->login_required();
         }
     }
 }
Example #8
0
 /**
  * @param $model
  */
 public function loadModel($model)
 {
     if (is_array($model)) {
         foreach ($model as $k => $v) {
             if (Orm::modelExist($v)) {
                 $this->{$v} = Orm::loadModel($v);
             }
         }
     } else {
         if (Orm::modelExist($model)) {
             $this->{$model} = Orm::loadModel($model);
         }
     }
 }
Example #9
0
 /**
  * Return some dummy data
  */
 public function fetch($fetch_style = PDO::FETCH_BOTH, $cursor_orientation = PDO::FETCH_ORI_NEXT, $cursor_offset = 0)
 {
     // Hack to get searched for values and if searching for id = 9999
     // return false, as if it doesn't exist.
     //
     $mostRecent = array_pop(Orm::getQueryLog());
     if (stripos($mostRecent, "`id` = '9999'") !== false) {
         return false;
     }
     if ($this->current_row == 5) {
         return false;
     } else {
         $this->current_row++;
         return array('name' => 'Fred', 'age' => 10, 'id' => '1');
     }
 }
Example #10
0
function rowMatch($orm_name, $class, $property)
{
    $actual_datatypes = getActualDatatypes($orm_name);
    $db_type = getDbType($orm_name);
    if (!isset($_POST[$idx = sprintf('type_%s_%s', $class, $property)])) {
        throw new OrmInputException(sprintf('Must specify a type for %s->%s', $class, $property));
    }
    $datatype = $actual_datatypes[$_POST[$idx]];
    $type = $datatype->type;
    $length = isset($_POST[$idx = sprintf('length_%s_%s', $class, $property)]) && !empty($_POST[$idx]) ? $_POST[$idx] : $datatype->length;
    $default = isset($_POST[$idx = sprintf('default_%s_%s', $class, $property)]) ? $_POST[$idx] : $datatype->default;
    $autoinc = isset($_POST[$idx = sprintf('autoinc_%s_%s', $class, $property)]) && $_POST[$idx] == 'on';
    $allownull = isset($_POST[$idx = sprintf('allownull_%s_%s', $class, $property)]) && $_POST[$idx] == 'on';
    $length = empty($length) ? '' : sprintf(' (%s)', $length);
    $default = empty($default) ? '' : sprintf(' DEFAULT %s', Orm::sqlVar($orm_name, $default, $datatype->cast));
    if ($autoinc) {
        switch ($db_type) {
            case 'Dummy':
            case 'MySQL':
            case 'MySQLi':
                $autoinc = ' AUTO_INCREMENT';
                break;
            case 'SQLite':
                # this page left blank ;) -- SQLite automatically treats integer primary keys as auto_inc
                break;
        }
    } else {
        $autoinc = '';
    }
    if (!$allownull) {
        $allownull = ' NOT NULL';
    } else {
        $allownull = '';
    }
    return (object) array('name' => Orm::propertyToDbName($property), 'type' => $type, 'length' => $length, 'default' => $default, 'allownull' => $allownull, 'autoinc' => $autoinc);
}
Example #11
0
 protected function loadAll()
 {
     if (is_null($this->items)) {
         $this->items = Orm::collection($this->source)->order('sort')->findAll();
     }
 }
Example #12
0
<?php

/**
 * Created by PhpStorm.
 * User: leopelan
 * Date: 09/12/15
 * Time: 12:11
 */
require_once 'orm/Orm.php';
Orm::init('localhost', 'orm', 'root', 'root');
// var_dump(Orm::getAll('user'));
// var_dump(Orm::count('user'));
// Orm::deleteById('user','2');
Example #13
0
 public function getAnonUser()
 {
     return Orm::collection('User')->where('username = ?', array($this->anon_name))->findOne();
 }
Example #14
0
<?php

require_once 'orm/Orm.php';
$Host = $argv[1];
$User = $argv[2];
$Password = $argv[3];
$dbName = $argv[4];
$tableName = $argv[5];
$className = ucfirst($argv[6]);
Orm::init($Host, $dbName, $User, $Password);
$fields = Orm::getColSql($tableName);
$tabs = 4;
function do_tabs($tabs)
{
    $ret = '';
    for ($i = 0; $i < $tabs; $i++) {
        $ret .= ' ';
    }
    return $ret;
}
$code = "<?php\n\n";
$code .= "class {$className}\n{\n";
$code .= do_tabs($tabs) . 'protected $tableNameBdd' . ";\n";
foreach ($fields as $field) {
    $code .= do_tabs($tabs) . 'protected $' . $field . ";\n";
}
$code .= "\n";
$code .= do_tabs($tabs) . 'public function set_tableNameBdd' . '($tableNameBdd' . ")\n";
$code .= do_tabs($tabs) . "{\n";
$code .= do_tabs($tabs + 2) . 'return $this->tableNameBdd' . ' = $tableNameBdd' . ";\n";
$code .= do_tabs($tabs) . "}\n";
Example #15
0
 public function testUnderscoreToCamelCase()
 {
     $this->assertEquals('detect', Orm::underscoredToCamelCase('detect'));
     $this->assertEquals('detectMission', Orm::underscoredToCamelCase('detect_mission'));
     $this->assertEquals('detectMissionDirectives', Orm::underscoredToCamelCase('detect_mission_directives'));
     $this->assertEquals('forTable', Orm::underscoredToCamelCase('for_table'));
     $this->assertEquals('findMany', Orm::underscoredToCamelCase('find_many'));
     $this->assertEquals('_findMany', Orm::underscoredToCamelCase('_find_many'));
     $this->assertEquals('findMany', Orm::underscoredToCamelCase('FIND_Many'));
     $this->assertEquals('find', Orm::underscoredToCamelCase('Find'));
     $this->assertEquals('_find', Orm::underscoredToCamelCase('_Find'));
     $this->assertEquals('_findOne', Orm::underscoredToCamelCase('_FIND_ONE'));
 }
Example #16
0
File: test.php Project: ahri/orm
    print_r($habitation = $o->getRelsByClasses('Home', 'LivesIn', 'Person -> (LivesIn) -> Home'));
    print_r($habitation->classHome[0]);
    print_r($habitation->classLivesIn[0]);
}
#OrmSqlCache::save();
# suggested tests
# 1. Orm::load
# 2. OrmClass->getRelsByClasses() for direct relation
# 3. OrmClass->getRelsByClasses() for indirect relation
# 4. OrmClass->getRelsByClasses() for multiple relations
# 5. OrmClass->getRelsByClasses() with chain
# 6. OrmClass->getRelsByClasses() with chains
# 7. OrmClass->getRelsByClass() without and with chain
# TODO
# consider adding an incrementing integer to alias so that multiple passes of the same rule are ok
# this would allow the system more flexibility for a person (keep the routing part crippled though)
# would need to update the SQL generation stage, and the Object creation stage
# after more thought; could result in output of objects that are the same as already constructed ones
# to mitigate this we could scan previously constructed objects of the same class type for equal keys (as they've just been constructed anyway)
# and merely point to the same object -- use Orm->equals() to establish this
# started coding this and stopped... see $seen_results
# -- stopped cos i'll have to have numbers in all aliases and i'm not so sure i want that!
if (sizeof($history = SSql::getQueryHistory()) > 0) {
    printf("Number of SQL queries: %d, SQL Query History\n%s", sizeof($history), print_r($history, true));
}
if (function_exists('xdebug_peak_memory_usage')) {
    printf("Peak memory usage: %.3fMB\n", xdebug_peak_memory_usage() / pow(2, 20));
}
#Test::summary('OrmClass');
Orm::routeFromChain(NULL, 'Person -> (LivesIn) -> Home -> (Neighbours) -> Home -> (Neighbours) -> Home', array((object) array('class' => 'LivesIn')));
Example #17
0
 /**
  * @param $key
  * @param $value
  * @return mixed
  */
 public function __set($key, $value)
 {
     if (isset($this->_has_one[$key]) && isset($this->_has_one[$key]['entity']) && is_object($value) && is_a($value, Orm::ENTITY_BASE_CLASS)) {
         $entity_info = $value->info();
         // creating field name
         $field = isset($this->_has_one[$key]['foreign_key']) ? $this->_has_one[$key]['foreign_key'] : $this->_table . '_id';
         if ($entity_info['entity'] == $this->_has_one[$key]['entity']) {
             /* @todo remove this \|/ condition! 
              */
             //only update the field if it's different from $value
             //if(!$value->fieldExists($field) || $value[$field] != $this->getId()) {
             $this->addJob(self::QUEUE_POST_STORE, self::QUEUE_TYPE_SET_VAL, array('object_left' => $value, 'field_left' => $field, 'object_right' => $this, 'field_right' => $this->_primary_key));
             $this->addJob(self::QUEUE_POST_STORE, self::QUEUE_TYPE_EXEC, array('object' => $value, 'method' => 'store'));
             //}
         }
     } elseif (isset($this->_belongs_to[$key]) && isset($this->_belongs_to[$key]['entity'])) {
         // getting entity info
         $entity_info = Orm::entityInfo($this->_belongs_to[$key]['entity']);
         // creating field name
         $field = isset($this->_belongs_to[$key]['foreign_key']) ? $this->_belongs_to[$key]['foreign_key'] : $entity_info['table'] . '_id';
         // going on if the value is an object based on Entity class
         if ($entity_info['entity'] == $this->_belongs_to[$key]['entity'] && is_object($value) && is_a($value, Orm::ENTITY_BASE_CLASS)) {
             // just setting the id if the object is already loaded
             if ($value->loaded()) {
                 $this->setFieldValue($field, $value->getId());
             } else {
                 // we got a new object - adding the job to save it and set the realtion after
                 $this->addJob(self::QUEUE_PRE_STORE, self::QUEUE_TYPE_EXEC, array('object' => $value, 'method' => 'store'));
                 $this->addJob(self::QUEUE_PRE_STORE, self::QUEUE_TYPE_SET_VAL, array('object_left' => $this, 'field_left' => $field, 'object_right' => $value, 'field_right' => $entity_info['primary_key']));
             }
         } else {
             // we got a numeric ID, just setting it
             $this->setFieldValue($field, $value);
         }
     } elseif (isset($this->_has_many[$key]) && isset($this->_has_many[$key]['entity'])) {
         if (!is_array($value)) {
             return;
         }
         // creating field name
         $field = isset($this->_has_many[$key]['foreign_key']) ? $this->_has_many[$key]['foreign_key'] : $this->_table . '_id';
         foreach ($value as $num => $object) {
             $entity_info = null;
             // create fake object if we got array of IDs as $value
             if (is_numeric($object)) {
                 $entity_info = Orm::entityInfo($this->_has_many[$key]['entity']);
                 $object = Orm::collection($this->_has_many[$key]['entity'])->create(array($entity_info['primary_key'] => $object));
             }
             if ($entity_info['entity'] == $this->_has_many[$key]['entity']) {
                 //only update the field if it's different from $value
                 if (!isset($object[$field]) || $object[$field] != $this->getId()) {
                     $this->addJob(self::QUEUE_POST_STORE, self::QUEUE_TYPE_SET_VAL, array('object_left' => $object, 'field_left' => $field, 'object_right' => $this, 'field_right' => $this->_primary_key));
                     $this->addJob(self::QUEUE_POST_STORE, self::QUEUE_TYPE_EXEC, array('object' => $object, 'method' => 'store'));
                 }
             }
         }
     } elseif (isset($this->_has_many_through[$key]) && isset($this->_has_many_through[$key]['entity'])) {
         $join_table = isset($this->_has_many_through[$key]['join_table']) ? $this->_has_many_through[$key]['join_table'] : null;
         $base_table_key = isset($this->_has_many_through[$key]['base_table_key']) ? $this->_has_many_through[$key]['base_table_key'] : null;
         $associated_table_key = isset($this->_has_many_through[$key]['associated_table_key']) ? $this->_has_many_through[$key]['associated_table_key'] : null;
         $join_table_fields = isset($this->_has_many_through[$key]['join_table_fields']) ? $this->_has_many_through[$key]['join_table_fields'] : null;
         // assume we have an array of objects (or just IDs)
         if (is_array($value)) {
             $related_objects = array();
             $entity_info = null;
             foreach ($value as $object) {
                 // create fake object if we got array of IDs as $value
                 if (is_numeric($object)) {
                     $entity_info = Orm::entityInfo($this->_has_many_through[$key]['entity']);
                     $object = Orm::collection($this->_has_many_through[$key]['entity'])->create(array($entity_info['primary_key'] => $object));
                 }
                 // can't go on if it's not an Entity
                 if (!is_a($object, Orm::ENTITY_BASE_CLASS)) {
                     continue;
                 }
                 // getting entity info
                 if (!$entity_info) {
                     $entity_info = $object->info();
                 }
                 // and finally, if entity name is the same as defined in class, setting the relation
                 if ($entity_info['entity'] == $this->_has_many_through[$key]['entity']) {
                     $this->addJob(self::QUEUE_POST_STORE, self::QUEUE_TYPE_EXEC, array('object' => $this, 'method' => 'attachThrough', 'params' => array($object, $join_table, $base_table_key, $associated_table_key, $join_table_fields)));
                     $related_objects[] = $object;
                 }
             }
             // removing old relations
             $this->addJob(self::QUEUE_POST_STORE, self::QUEUE_TYPE_EXEC, array('object' => $this, 'method' => 'clearUnrelated', 'params' => array($this->_has_many_through[$key]['entity'], $related_objects, $join_table, $base_table_key, $associated_table_key)));
         } elseif (empty($value)) {
             // clear all relationships
             $this->addJob(self::QUEUE_PRE_STORE, self::QUEUE_TYPE_EXEC, array('object' => $this, 'method' => 'clearRelations', 'params' => array($this->_has_many_through[$key]['entity'], $join_table, $base_table_key)));
         }
     } else {
         $this->setFieldValue($key, $value);
     }
 }
Example #18
0
 public static function getDbObjects($name = null)
 {
     $objs = array();
     $o = (object) array('is_class' => false, 'is_irelationship' => false, 'keys' => array(), 'properties' => array(), 'parent' => NULL, 'relationships' => array());
     foreach (Orm::getRules($name) as $rule) {
         foreach ($rule as $name => $class) {
             if (!is_string($class)) {
                 continue;
             }
             if (!class_exists($class)) {
                 if (!isset($objs[$class])) {
                     $objs[$class] = clone $o;
                 }
                 continue;
             }
             $class_reflection = new ReflectionClass($class);
             do {
                 if (!$class_reflection->isInstantiable()) {
                     continue;
                 }
                 if (!isset($objs[$class_reflection->getName()])) {
                     $objs[$class_reflection->getName()] = clone $o;
                 }
             } while (($class_reflection = $class_reflection->getParentClass()) && $class_reflection->getName() != Orm::ORM_CLASS_CLASS && $class_reflection->getName() != Orm::ORM_CLASS_RELATIONSHIP);
             # check that we're not hitting the top
         }
         $objs[$rule->input]->relationships[$rule->relationship] = $rule->output;
     }
     foreach ($objs as $class => $o) {
         if ($o->is_class = class_exists($class) && is_subclass_of($class, Orm::ORM_CLASS_CLASS)) {
             $o->keys = Orm::getKeys($class);
             $o->properties = Orm::getProperties($class);
             $class_reflection = new ReflectionClass($class);
             while (($class_reflection = $class_reflection->getParentClass()) && $class_reflection->getName() != Orm::ORM_CLASS_CLASS && $class_reflection->getName() != Orm::ORM_CLASS_RELATIONSHIP) {
                 if (!$class_reflection->isInstantiable()) {
                     continue;
                 }
                 $o->parent = $class_reflection->getName();
                 break;
             }
         }
         if ($o->is_irelationship = class_exists($class) && is_subclass_of($class, Orm::ORM_CLASS_RELATIONSHIP)) {
             $o->properties = Orm::getProperties($class, true);
         }
         if ($o->keys == array(Orm::AUTO_PROPERTY_ID)) {
             array_unshift($o->properties, Orm::AUTO_PROPERTY_ID);
         }
     }
     return $objs;
 }
Example #19
0
 /**
  * Creates new collection that holds entities of $entity_name class
  *
  * @param string $entity_name name of the entity
  */
 public function __construct($entity_name)
 {
     $this->entity_name = ucfirst($entity_name);
     $this->entity_info = Orm::entityInfo($entity_name);
     $this->reset();
 }
Example #20
0
<?php

/**
 * Copyright Skinit, Inc.
 */
require_once 'autoload.inc';
// read config
$configFile = file_get_contents('orm_config.json');
$config = json_decode($configFile, true);
// register the data store and get its instance
Orm::registerDataStore("Example", "sqlite", array("test/example.db"));
$dataStore = Orm::getDataStore("Example");
// create model files
Orm::generateModels($dataStore, $config);
Example #21
0
 function deleteLinks($id)
 {
     foreach ($this->hasAndBelongsToMany as $assoc => $data) {
         $object = null;
         $model = null;
         $object = ucfirst(singular($data['joinTable']));
         $model = new Orm($object, $data['joinTable'], $data['foreignKey']);
         $conditions = array($model->alias . '.' . $model->primaryKey => $id);
         $records = $model->findAll($conditions, array($model->alias . '.' . $model->primaryKey));
         if (!empty($records)) {
             foreach ($records as $record) {
                 $model->del($record[$model->alias][$model->primaryKey]);
             }
         }
     }
 }
Example #22
0
    const Employer_keys = 'name';
    public $name;
}
abstract class Recorded extends OrmClass
{
    public $created;
    public $altered;
}
class Building extends Recorded
{
    public $address;
}
class Office extends Building
{
}
class Home extends Building
{
}
class LivesIn extends OrmRelationship
{
    public $since;
}
Orm::setup(<<<EOF
Person   to Person   as Partner
Person   to Employer as EmployedBy
Job      to Employer as Employs
Job      to Person   as EmployeeOf
Employer to Office   as Owns
Person   to Home     as LivesIn
EOF
);