Example #1
0
 /**
  * Initializes the {@link $targetid} and {@link $model} properties.
  *
  * @param \ICanBoogie\ActiveRecord $target
  *
  * @throws Exception
  */
 public function __construct(\ICanBoogie\ActiveRecord $target)
 {
     if ($target instanceof \Icybee\Modules\Nodes\Node) {
         $this->targetid = $target->nid;
         $type = 'node';
     } else {
         if ($target instanceof \Icybee\Modules\Users\User) {
             $this->targetid = $target->uid;
             $type = 'user';
         } else {
             if ($target instanceof \Icybee\Modules\Sites\Site) {
                 $this->targetid = $target->siteid;
                 $type = 'site';
             } else {
                 throw new \Exception(\ICanBoogie\format('Metadatas are not supported for instances of %class', ['%class' => get_class($target)]));
             }
         }
     }
     if (empty(self::$models[$type])) {
         self::$models[$type] = \ICanBoogie\ActiveRecord\get_model('registry/' . $type);
     }
     $this->model = self::$models[$type];
 }
Example #2
0
 /**
  * Finds records using their constructor.
  *
  * Unlike {@link find()} this method is designed to find records that where created by
  * different constructors. The result is the same, bu where {@link find()} uses a new request
  * for each record that is not created by the current model, this method only needs one query
  * by constructor plus one extra query.
  *
  * @param array $keys
  *
  * @throws RecordNotFound If a record was not found.
  *
  * @return array
  */
 public function find_using_constructor(array $keys)
 {
     if (!$keys) {
         return array();
     }
     $records = array_combine($keys, array_fill(0, count($keys), null));
     $missing = $records;
     $constructors = $this->select('constructor, {primary}')->where(array('{primary}' => $keys))->all(\PDO::FETCH_COLUMN | \PDO::FETCH_GROUP);
     foreach ($constructors as $constructor => $constructor_keys) {
         try {
             $constructor_records = \ICanBoogie\ActiveRecord\get_model($constructor)->find($constructor_keys);
             foreach ($constructor_records as $key => $record) {
                 $records[$key] = $record;
                 unset($missing[$key]);
             }
         } catch (RecordNotFound $e) {
             foreach ($e->records as $key => $record) {
                 if ($record === null) {
                     continue;
                 }
                 $records[$key] = $record;
                 unset($missing[$key]);
             }
         }
     }
     if ($missing) {
         if (count($missing) > 1) {
             throw new RecordNotFound("Records " . implode(', ', array_keys($missing)) . " do not exists.", $records);
         } else {
             $key = array_keys($missing);
             $key = array_shift($key);
             throw new RecordNotFound("Record <q>{$key}</q> does not exists.", $records);
         }
     }
     return $records;
 }