function testEntity()
 {
     global $_PA;
     // Dal::register_query_callback("explain_query");
     // see if our test entity already exists
     $entity = Entity::load("PHPUnit", "TestEntity", "#1");
     $this->assertNull($entity, "we shouldn't have any Entites in the service PHPUnit at this point.");
     $myEntity = new TestEntity('#1');
     echo "sync #1\n";
     Entity::sync($myEntity);
     // create a second
     $myEntity2 = new TestEntity('#2');
     echo "sync #2\n";
     Entity::sync($myEntity2);
     // modify #1
     $myEntity->attributes['ThreeAttribute'] = array('value' => "Baz");
     Entity::sync($myEntity);
     // remove an attribute from #2
     unset($myEntity2->attributes['OneAttribute']);
     Entity::sync($myEntity2);
     $myEntity3 = new TestEntity('#3');
     Entity::sync($myEntity3);
     $myEntity4 = new TestEntity('#4');
     $myEntity4->attributes['ThreeAttribute'] = array('value' => "Baz");
     $myEntity4->attributes['fourAttribute'] = array('value' => "4");
     Entity::sync($myEntity4);
     // test attribute search
     // Dal::register_query_callback("explain_query");
     $foundEntities = Entity::search(array('entity_service' => 'PHPUnit', 'entity_type' => 'TestEntity'), array('OneAttribute' => 'F', 'TwoAttribute' => 'b', 'ThreeAttribute' => 'b', 'FourAttribute' => '4'));
     // Dal::unregister_query_callback("explain_query");
     echo "\nfound " . count($foundEntities) . " entities by attribute search:\n";
     foreach ($foundEntities as $i => $e) {
         echo "entity: '{$e['entity_service']}:{$e['entity_type']}:{$e['entity_id']}\n";
     }
     // Dal::register_query_callback("explain_query");
     $foundEntities = Entity::search(array(), array('FourAttribute' => '4'));
     // Dal::unregister_query_callback("explain_query");
     echo "\nfound " . count($foundEntities) . " entities by attribute search:\n";
     foreach ($foundEntities as $i => $e) {
         echo "entity: '{$e['entity_service']}:{$e['entity_type']}:{$e['entity_id']}\n";
     }
     $testEntities = Entity::search(array('entity_service' => 'PHPUnit', 'entity_type' => 'TestEntity'));
     echo "\nfound " . count($testEntities) . " test entities:\n";
     // load test entities
     foreach ($testEntities as $i => $e) {
         echo "entity: '{$e['entity_service']}:{$e['entity_type']}:{$e['entity_id']}\n";
         // print_r(Entity::load($e['entity_service'], $e['entity_type'], $e['entity_id'])); echo "\n";
     }
     // clean up test entities
     foreach ($testEntities as $i => $e) {
         Entity::delete($e['entity_service'], $e['entity_type'], $e['entity_id']);
     }
     // test again
     $testEntities = Entity::search(array('entity_service' => 'PHPUnit'));
     $this->assertEquals(count($testEntities), 0, "There should no longer be any Entities in the PHPUnit service.");
 }
 public static function sync($entity)
 {
     $_ent = Entity::load($entity->entity_service, $entity->entity_type, $entity->entity_id);
     if (empty($_ent)) {
         self::update_user_points($entity->attributes);
     } else {
         self::update_user_points($entity->attributes, $_ent->attributes);
     }
     parent::sync($entity);
 }
Exemple #3
0
 public static function sync($e)
 {
     $entity = Entity::load($e->entity_service, $e->entity_type, $e->entity_id);
     if (empty($entity)) {
         // create
         echo "CREATE {$e->entity_service}, {$e->entity_type}, {$e->entity_id}\n";
         Entity::create($e);
     } else {
         echo "UPDATE {$e->entity_service}, {$e->entity_type}, {$e->entity_id}\n";
         // sync
         $entity->update($e);
     }
 }
 public function testEntity()
 {
     $entity = new Entity($this->user_model);
     $CI =& get_instance();
     $entity->addMixin($CI->load->mixin('user_basic_info'));
     $this->test_data->addUser();
     $this->test_data->addUserBasicInfo();
     $this->assertNotNull($this->entity);
     $entity->load($this->test_data->the_user_id);
     $entity->status = 'jack';
     $entity->apply();
     $user = $this->user_model->load($entity->id);
     $this->assertEquals($entity->status, $user->status);
     $this->assertEquals($entity->username, 'jack');
     $entity->password = '******';
     $entity->apply();
     $user = $this->user_basic_info_model->getByUid($entity->id);
     $this->assertEquals($entity->password, $user->password);
 }
 public static function load_for_group($group_id, $load_entity = true)
 {
     $result = Entity::search(array('entity_service' => 'typedGroup', 'entity_id' => $group_id));
     $entity = NULL;
     if (!empty($result)) {
         $entity_result = $result[0];
         if (empty($load_entity)) {
             return $entity_result;
         }
         $entity = Entity::load($entity_result['entity_service'], $entity_result['entity_type'], $entity_result['entity_id']);
         // load extra group info for logo and sloagan
         try {
             $group = ContentCollection::load_collection((int) $entity_result['entity_id']);
             $entity->attributes['name']['value'] = $group->title;
             $entity->attributes['logo']['value'] = $group->picture;
             $entity->attributes['slogan']['value'] = $group->description;
         } catch (PAException $e) {
             return NULL;
         }
     }
     return $entity;
 }
Exemple #6
0
require_once $ROOT_DIR . '/include/entity.php';
require_once $ROOT_DIR . '/include/markdown.php';
require_once $ROOT_DIR . '/include/view_helpers.php';
$tasks_dir = realpath($_CONFIG['tasks_dir']);
$dir_iterator = new RecursiveDirectoryIterator($tasks_dir);
$files = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
$tasks = array();
foreach ($files as $file) {
    // Skip everything that is not a check script
    if ($file->getBasename() != 'check') {
        continue;
    }
    $check_script = $file->getRealpath();
    $task_dir = dirname($check_script);
    $id = substr($task_dir, strlen($tasks_dir) + 1);
    $infos = Entity::load($task_dir . '/task.txt');
    if ($infos) {
        $title = $infos->title;
        $description = Markdown($infos->content);
        $points = intval($infos->points);
    } else {
        $title = basename($id);
        $description = null;
        $points = 0;
    }
    $tasks[] = array('id' => $id, 'check_script' => $check_script, 'title' => $title, 'description' => $description, 'points' => $points);
}
// Sort tasks ascending by their id (directory and exercise name)
uasort($tasks, function ($a, $b) {
    if ($a['id'] == $b['id']) {
        return 0;
 public function saveEntity(Entity $entity)
 {
     if ($entity->repository !== $this && $entity instanceof ActiveEntity) {
         $entity->load();
     }
     $idFields = $entity->metadata->getIdFields();
     $fields = $entity->metadata->getFields();
     $autoField = null;
     // Pokud jsou na zaznam vazany relace, ktere je treba ulozit
     $needToSaveEvenWithoutData = $entity->repository !== $this;
     $this->db->begin();
     try {
         // Provedu upravy pred ulozenim (zaregistrovane Behaviors, etc.)
         if ($entity instanceof ActiveEntity) {
             $entity->onPreSave($entity);
         }
         // Kontrola, jestli mam definovane sloupce s PK indexem
         foreach ($idFields as $name) {
             if (!$entity->metadata->isFieldGenerated($name)) {
                 if (!isset($entity->data->{$name})) {
                     throw new EntityException("Cannot save '" . get_class($entity) . "' with missing value for field '{$name}' which is mandatory because of ID index", EntityException::ID_NOT_DEFINED);
                 }
             } elseif ($autoField === null) {
                 $autoField = $name;
             } else {
                 throw new \LogicException('More than one generated ID field are not supported');
             }
         }
         // Nactu si vsechny zmenene polozky do pole: sloupec => hodnota
         $updateData = $entity->data->getChangedData(true);
         // Pole se vsemi virtualnimi sloupci, ktere jsou ve skutecnosti vazany v jine tabulce
         // Musime je na konci odebrat z tech, co se ukladaji do teto entity
         $externalFields = array();
         // Projdu vsechny registrovane polozky a overim pripadne externi vazby
         foreach ($fields as $curr) {
             $type = $entity->metadata->getFieldType($curr);
             // Pokud je polozka OneToOne relaci (z moji strany -> mappedBy moje entita)
             // musim ji ulozit PRED samotnou entitou (potrebuje jeji ID)
             // Po ulozeni svazane entity si musim vzit jeji ID a pridat ho do dat k ulozeni.
             if ($type == 'OneToOne') {
                 if ($entity->metadata->getFieldMappedBy($curr) === null || get_class($entity) != $entity->metadata->getFieldMappedBy($curr) && !is_subclass_of(get_class($entity), $entity->metadata->getFieldMappedBy($curr))) {
                     // Ukladam jen non-NULL sloupce
                     if (isset($entity->data->{$curr})) {
                         // Bacha na to, ze to nesmim brat z dat (kvuli tomu, ze tam muze bejt
                         // pri nacteni z DB pouze ID)
                         $targetEntity = $entity->{$curr};
                         if ($targetEntity !== null) {
                             if (!$targetEntity instanceof ActiveEntity) {
                                 throw new \LogicException("Can't save OneToMany entity for field '{$curr}'. Data object is not instance of ActiveEntity. " . get_class($targetEntity) . ' given.');
                             }
                             $this->save($targetEntity);
                             $joinPairs = $entity->metadata->getFieldJoinPairs($curr);
                             if (count($joinPairs) == 0) {
                                 throw new \LogicException("Missing join pairs for " . get_class($entity) . "::{$curr}, forgot to set joinOn/joinUsing?");
                             } elseif (count($joinPairs) > 1) {
                                 throw new \LogicException("Joining entity on more keys is currently not supported (" . get_class($entity) . "::{$curr})");
                             }
                             list($localIdField, $targetIdField) = reset($joinPairs);
                             if ($entity->data->{$localIdField} !== $targetEntity->{$targetIdField}) {
                                 $updateData[$entity->metadata->getFieldColumn($localIdField)] = $targetEntity->{$targetIdField};
                             }
                         }
                     }
                     // Pokud polozka je pouze mapovana na nasi entitu, klic je na druhe strane
                     // => Ukladam ji az po ulozeni sama sebe
                 } else {
                     $externalFields[] = $curr;
                     unset($updateData[$curr]);
                 }
             } elseif ($type == 'OneToMany') {
                 if ($entity->{$curr} instanceof Collection && $entity->{$curr}->mightNeedSave()) {
                     $needToSaveEvenWithoutData = true;
                 }
                 $externalFields[] = $curr;
                 unset($updateData[$curr]);
             }
         }
         // Vsechny data k ulozeni do tabulky (vcetne tech nezmenenych, ale bez virtualnich sloupcu - vazeb)
         $allTableFields = array_diff_key(array_merge($entity->data->getAllData(true), $updateData), array_flip($externalFields));
         // ULOZENI SAMOTNE ENTITY ---------------------------------------------
         // Pokud jsou k ulozeni nejaka TABULKOVA data, ulozim je
         $addtionalDataToMerge = array();
         $action = null;
         /* if($needToSaveEvenWithoutData)
         				d("Saving even without update data (forced save)");
         			else
         				d("Trying to save with update date", $updateData); */
         if (count($updateData) > 0 || $needToSaveEvenWithoutData) {
             $insertData = $allTableFields;
             $now = new \DateTime();
             // Automaticke casy vytvoreni / modifikace
             foreach ($fields as $curr) {
                 $type = $entity->metadata->getFieldType($curr);
                 if ($type == 'CreatedDateTime') {
                     if (!isset($insertData[$entity->metadata->getFieldColumn($curr)])) {
                         $insertData[$entity->metadata->getFieldColumn($curr)] = $now->format('Y-m-d H:i:s');
                     }
                 } elseif ($type == 'ModifiedDateTime') {
                     $insertData[$entity->metadata->getFieldColumn($curr)] = $now->format('Y-m-d H:i:s');
                     $updateData[$entity->metadata->getFieldColumn($curr)] = $now->format('Y-m-d H:i:s');
                 }
             }
             $mergeAutoDateTime = function () {
             };
             $this->db->query('INSERT IGNORE ', $entity->metadata->getTableName(), $insertData, '%if', $updateData, ' ON DUPLICATE KEY UPDATE %a', $updateData);
             // Provedl se INSERT
             if ($this->db->affectedRows() == 1) {
                 // Zjistim ID pro generovane sloupce
                 $addtionalDataToMerge = $autoField === null ? array() : array($autoField => $this->db->insertId());
                 $entity->data->mergeData($addtionalDataToMerge);
                 $action = 'create';
             } elseif ($this->db->affectedRows() == 2) {
                 $action = 'update';
                 // Merge data modifikace
                 foreach ($fields as $curr) {
                     $type = $entity->metadata->getFieldType($curr);
                     if ($type == 'ModifiedDateTime') {
                         $entity->data->mergeData(array($entity->metadata->getFieldColumn($curr) => $now->format('Y-m-d H:i:s')));
                     }
                 }
             }
             // Data se nezmenila
             /* else {
             					// Nevim jestli je to takhle uplne idealni, sice insert ignore ... on duplicate key update
             					// setri zamykani tabulky, ale zese je treba overovat, jestli se neco neposralo
             					// a pokud jo, tak nemam zadny chybovy report
             					// Zkontroluju, jeslti byl zaznam opravdu ulozen do DB
             					$query = $this->db->select('1')->from($entity->metadata->getTableName());
             					$idFields = $entity->metadata->getIdFields();
             					foreach($idFields as $name)
             						$query = $query->where("[".$entity->metadata->getFieldColumn($name)."] = %s", $entity->data->$name);
             
             					$result = $query->fetch();
             					if($result === false)
             						throw new EntityException('Error saving entity. Missing mandatory fields?', EntityException::SAVE_FAILED);
             				} */
         }
         // KONEC ULOZENI ENTITY -----------------------------------------------
         // Relace (OneToMany) -> ulozeni externich sloupcu
         foreach ($externalFields as $curr) {
             // Reverzni OneToOne relace
             if ($entity->metadata->getFieldType($curr) == 'OneToOne') {
                 if ($entity->metadata->getFieldMappedBy($curr) !== null && (get_class($entity) == $entity->metadata->getFieldMappedBy($curr) || is_subclass_of(get_class($entity), $entity->metadata->getFieldMappedBy($curr)))) {
                     // Pro ukladani reverzni vazby, ale zpusobuje mnohonasobne ulozeni kolekce
                     /*$targetEntity = $entity->{$curr};
                     
                     						$pairs = $entity->metadata->getFieldJoinPairs($curr);
                     						list($entityField, $targetField) = $pairs[0];
                     
                     						$targetEntity->{$targetField} = $entity->$entityField;
                     
                     						$this->save($targetEntity); */
                     // Zakomentovano! Bylo to tu jen pro sanity check a zpusobovalo to vynucene nacteni target entity => vyjimka, pokud neexistovaly
                     /*
                     						// Bacha na to, ze to nesmim brat z dat (kvuli tomu, ze tam muze bejt
                     						// pri nacteni z DB pouze ID)
                     						$targetEntity = $entity->{$curr};
                     						if($targetEntity !== null) {
                     							if($targetEntity->hasChanged())
                     								throw new Nette\NotImplementedException("Saving of reversed OneToOne entities is currently not implemented");
                     						} */
                 }
                 continue;
             }
             // Dale resim pouze OneToMany
             if ($entity->metadata->getFieldType($curr) != 'OneToMany') {
                 continue;
             }
             // OneToMany zalozene na kolekcich
             if ($entity->{$curr} instanceof EntityCollection) {
                 $entity->{$curr}->save($this);
                 continue;
             }
             // Puvodni save pro OneToMany (TODO: prepsat taky na kolekce)
             // Pokud se data zmenila
             if (array_key_exists($curr, $entity->data->getChangedData())) {
                 // Momentalne nepodporuju relace s plnou entitou
                 if ($entity->metadata->getFieldEntityName($curr) !== null) {
                     throw new Nette\NotImplementedException("Entity based OneToMany save is currently not implemented");
                 }
                 // Smazu soucasny zaznamy a vytvorim si ID data pro nove
                 $joinIdFields = array();
                 $query2 = $this->db->delete($entity->metadata->getFieldTableName($curr));
                 foreach ($entity->metadata->getFieldJoinPairs($curr) as $join) {
                     $query2->where("[" . $join[1] . "] = %s", $entity->{$join[0]});
                     $joinIdFields[$join[1]] = $entity->{$join[0]};
                 }
                 $query2->execute();
                 $ch = $entity->data->getChangedData();
                 $dataToSave = (array) $ch[$curr];
                 if (count($dataToSave) > 0) {
                     // Pokud se jedna o neassociativni pole, musim zjistit nazvy sloupcu
                     if (!is_array(reset($dataToSave))) {
                         $columnNames = $this->db->query("SHOW COLUMNS FROM [" . $entity->metadata->getFieldTableName($curr) . "]")->fetchAll();
                         $singleColumnKey = null;
                         foreach ($columnNames as $column) {
                             if (!array_key_exists($column["Field"], $joinIdFields)) {
                                 if ($singleColumnKey != null) {
                                     throw new \LogicException("Saving joined single column data into multi column table");
                                 }
                                 $singleColumnKey = $column["Field"];
                             }
                         }
                     }
                     // Nahazim tam nove
                     foreach ($dataToSave as $joinFields) {
                         $iData = array_merge(!is_array($joinFields) ? array($singleColumnKey => $joinFields) : $joinFields, $joinIdFields);
                         $this->db->insert($entity->metadata->getFieldTableName($curr), $iData)->execute();
                     }
                 }
             }
         }
         // Zavolani eventu -------------------
         if ($entity instanceof ActiveEntity) {
             if ($action == 'create') {
                 $entity->onCreate($entity);
             } elseif ($action == 'update') {
                 $entity->onUpdate($entity);
             }
             $entity->onPostSave($entity);
         }
         // Cache update ----------------------
         foreach ($entity->data->getChangedData() as $fieldName => $value) {
             if ($entity->metadata->hasFieldProperty($fieldName, 'cached')) {
                 $cacheSetData = array($fieldName);
                 foreach ($entity->metadata->getIdFields() as $idFieldName) {
                     $cacheSetData[] = $entity->{$idFieldName};
                 }
                 $cacheSetData[] = $value;
                 call_user_func_array(array($this->cache(get_class($entity)), 'set'), $cacheSetData);
             }
         }
         // Commitnuti dat --------------------
         $this->db->commit();
         // Update dat v ramci entiy -----------
         $entity->data->performSaveMerge();
     } catch (\Exception $e) {
         $this->db->rollback();
         throw $e;
     }
 }
 public static function sync($e)
 {
     $entity = Entity::load($e->entity_service, $e->entity_type, $e->entity_id);
     if (empty($entity)) {
         // create
         Entity::create($e);
     } else {
         // sync
         $entity->update($e);
     }
 }