isValid() public static method

Check if a value is a valid ObjectId
public static isValid ( mixed $value ) : boolean
$value mixed The value to check for validity.
return boolean
 public function gen_value($input)
 {
     //如果为空,返回空
     $input = trim($input);
     if ($input == "" || $input == "-") {
         return "";
     }
     //先检查是不是已经是 mongoid
     if (strlen($input) == 24 && MongoId::isValid($input)) {
         return $input;
     }
     $this->db->select(array($this->valueField, $this->showField))->where(array($this->showField => $input));
     if (!isset($this->whereOrgId)) {
         $this->whereOrgId = $this->CI->myOrgId;
     }
     $this->db->where(array('orgId' => $this->whereOrgId));
     $query = $this->db->get($this->tableName);
     if ($query->num_rows() > 0) {
         $result = $query->row_array();
         $real_id = $result['_id']->{'$id'};
     } else {
         $new_id = $this->plusCreate($input);
         $real_id = $new_id->{'$id'};
     }
     return $real_id;
 }
Esempio n. 2
0
 /**
  * Match the eagerly loaded results to their parents.
  *
  * @param  array   $models
  * @param  \Illuminate\Database\Eloquent\Collection  $results
  * @param  string  $relation
  * @return array
  */
 public function match(array $models, Collection $results, $relation)
 {
     $foreign = $this->foreignKey;
     $other = $this->otherKey;
     // First we will get to build a dictionary of the child models by their primary
     // key of the relationship, then we can easily match the children back onto
     // the parents using that dictionary and the primary key of the children.
     $dictionary = [];
     foreach ($results as $result) {
         $dictionary[(string) $result->getAttribute($other)] = $result;
     }
     // Once we have the dictionary constructed, we can loop through all the parents
     // and match back onto their children using these keys of the dictionary and
     // the primary key of the children to map them onto the correct instances.
     foreach ($models as $model) {
         if (\MongoId::isValid((string) $model->{$foreign})) {
             $modelForeign = (string) $model->{$foreign};
         } else {
             $modelForeign = $model->{$foreign};
         }
         if (isset($dictionary[$modelForeign])) {
             $model->setRelation($relation, $dictionary[$modelForeign]);
         }
     }
     return $models;
 }
Esempio n. 3
0
 public static function getMapped($value)
 {
     if (!$value or !\MongoId::isValid($value)) {
         return false;
     }
     return self::$list[(string) $value];
 }
 public function setPageId($data)
 {
     if (!MongoId::isValid($data)) {
         throw new Exception('INVALID MENUITEMINTERNAL PAGEID', 500);
     }
     $this->pageId = (string) $data;
 }
Esempio n. 5
0
 /**
  * @param $jobId
  * @return JobBase
  */
 public function getJob($jobId)
 {
     if (!\MongoId::isValid($jobId) || !($data = $this->collection()->findOne(['_id' => new \MongoId($jobId)])) || !($class = $this->getClass($data['type']))) {
         return null;
     }
     return new $class($data);
 }
Esempio n. 6
0
 /**
  * Sets the id
  * @param int|Object $arg0
  */
 function setId($arg0)
 {
     if ($this->getIdType() == self::ID_TYPE_MONGO) {
         if (is_string($arg0) && \MongoId::isValid($arg0)) {
             parent::setId(new \MongoId($arg0));
         } else {
             if ($arg0 instanceof \MongoId) {
                 parent::setId($arg0);
             } else {
                 if (is_null($arg0)) {
                     parent::setId($arg0);
                 } else {
                     if (is_string($arg0) && trim($arg0) == '') {
                         parent::setId(null);
                     } else {
                         if (is_int($arg0) && $arg0 == 0) {
                             parent::setId(null);
                         } else {
                             try {
                                 throw new \Exception('Invalid ID set: ' . var_export($arg0, true));
                             } catch (\Exception $e) {
                                 \Mojavi\Logging\LoggerManager::error(__METHOD__ . " :: " . $e->getTraceAsString());
                             }
                             parent::setId(null);
                         }
                     }
                 }
             }
         }
     } else {
         if ($this->getIdType() == self::ID_TYPE_STRING) {
             if (is_string($arg0)) {
                 parent::setId($arg0);
             } else {
                 if ($arg0 instanceof \MongoId) {
                     parent::setId((string) $arg0);
                 } else {
                     if (is_null($arg0)) {
                         parent::setId($arg0);
                     } else {
                         if (is_string($arg0) && trim($arg0) == '') {
                             parent::setId(null);
                         } else {
                             if (is_int($arg0) && $arg0 == 0) {
                                 parent::setId(null);
                             } else {
                                 try {
                                     throw new \Exception('Invalid ID set: ' . var_export($arg0, true));
                                 } catch (\Exception $e) {
                                     \Mojavi\Logging\LoggerManager::error(__METHOD__ . " :: " . $e->getTraceAsString());
                                 }
                                 parent::setId(null);
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Esempio n. 7
0
 /**
  * 
  * @param type $var
  */
 public function loadTodo($var)
 {
     if (MongoId::isValid($var)) {
         $this->loadDocument($var);
     } else {
         $this->loadDocument($var, "some field");
     }
 }
 /**
  * Get the key value of the parent's local key.
  *
  * @param $value
  * @return mixed
  */
 public function evaluateObjectID($value)
 {
     $isObject = config('database.connections.mongodb.mongoid', false);
     if ($isObject && \MongoId::isValid($value)) {
         return new \MongoId($value);
     }
     return $value;
 }
Esempio n. 9
0
 /**
  * Retrieves the _id portion of the route.
  * If it's not there, errors and returns null.
  */
 protected static function getIdFromRoute(array $restOfRoute)
 {
     if (!isset($restOfRoute[0]) || !MongoId::isValid($restOfRoute[0])) {
         self::error("invalid access");
         self::render('notice');
         return null;
     }
     return new MongoId($restOfRoute[0]);
 }
Esempio n. 10
0
 public static final function toMongoId($id)
 {
     if ($id and is_string($id) and MongoId::isValid($id)) {
         $id = new MongoId($id);
     } elseif ($id and is_array($id)) {
         $id = array_map([__CLASS__, 'toMongoId'], $id);
     }
     return $id;
 }
Esempio n. 11
0
 function queryFix($query)
 {
     if (!is_array($query)) {
         if (MongoId::isValid($query)) {
             $query = array("_id" => new MongoId($query));
         } else {
             $query = array("_id" => $query);
         }
     }
     return $query;
 }
Esempio n. 12
0
 public function getById($id)
 {
     if (!MongoId::isValid($id)) {
         return null;
     }
     $datas = KLib\MongoDB::findOne(array('_id' => $id), 'kn_block');
     if (is_array($datas) && !empty($datas) && array_key_exists('type', $datas) && is_string($datas['type']) && class_exists($datas['type'])) {
         return KLib\instance::addOne($datas['type'], $datas);
     }
     return null;
 }
Esempio n. 13
0
 public function init($value)
 {
     if (gettype($value) != "array") {
         $value = array();
     }
     $this->value = $value;
     foreach ($value as $key => $this_item) {
         if (MongoId::isValid($this_item)) {
             $this->real_data[$key] = new User_model();
             $this->real_data[$key]->init_with_id($this_item);
         }
     }
 }
Esempio n. 14
0
 /**
  * @param Validation $validation
  * @param string $attribute
  * @return bool
  * @throws Exception
  */
 public function validate(Validation $validation, $attribute)
 {
     if (!extension_loaded('mongo')) {
         throw new Exception('Mongo extension is not available');
     }
     $value = $validation->getValue($attribute);
     $allowEmpty = $this->hasOption('allowEmpty');
     $result = $allowEmpty && empty($value) ? true : Id::isValid($value);
     if (!$result) {
         $message = $this->hasOption('message') ? $this->getOption('message') : 'MongoId is not valid';
         $validation->appendMessage(new Message($message, $attribute, 'MongoId'));
     }
     return $result;
 }
Esempio n. 15
0
 /**
  * Transform the value in a MongoDBRef if needed
  * @param $attr
  * @param $value
  * @return mixed
  */
 protected function _val($attr, $value)
 {
     $reference = \Rocketr\Schema\Reference::get($this->get_collection_name(), $attr);
     $collection = \Rocketr\Schema\HasCollection::get($this->get_collection_name(), $attr);
     if ($reference xor $collection) {
         $ref_attr = \Rocketr\Schema\Map::on($this->get_collection_name(), $attr);
         $_id = is_array($value) && isset($value[$ref_attr]) || is_object($value) && $value->{$ref_attr} ? is_array($value) ? $value[$ref_attr] : $value->{$ref_attr} : $value;
         $target = $reference ? $reference : $collection;
         $_id = $ref_attr == '_id' && \MongoId::isValid($_id) ? new \MongoId($_id) : $_id;
         return \MongoDBRef::create($target, $_id);
     } else {
         return $value;
     }
 }
Esempio n. 16
0
 /**
  * Fetches a document from the collection
  * 
  * This function is a way of getting a document from the collection into the object
  * Since there will always be an _id field its a safe bet to load from there
  * however there will generally always be another unique field to search by
  * so this function allows classes that extend this class to specify which field
  * 
  * @param String|MongoId $var The value of the field to check
  * @param String $field
  * @return array
  */
 public function loadDocument($var, $field = "_id")
 {
     $query = null;
     if ($field === "_id" && MongoId::isValid($var)) {
         $query = array($field => new MongoId($var));
     } else {
         $query = array($field => $var);
     }
     $this->document = $this->collection->findOne($query);
     if ($this->document !== null) {
         $this->qry = $query;
     }
     return $this->document;
 }
Esempio n. 17
0
 public function load($type, array $id)
 {
     $type = (int) $type;
     $id = (string) $id['id'];
     $collectionName = $this->_getCollectionName($type);
     if (!MongoId::isValid($id)) {
         return false;
     }
     $mongoId = new MongoId($id);
     $data = $this->_getMongoDb()->findOne($collectionName, ['_id' => $mongoId]);
     if (null === $data) {
         return false;
     }
     return $data;
 }
Esempio n. 18
0
 /**
  * Validate the given request with the given rules.
  *
  * @param  array  $data
  * @param  array  $rules
  * @param  array  $messages
  * @return void
  */
 public function validate(array $data, array $rules, array $messages = array(), $connection = '')
 {
     Validator::extend('mongo_id', function ($attribute, $value, $parameters) {
         return true === \MongoId::isValid($value);
     });
     $validator = Validator::make($data, $rules, $messages);
     if (!empty($connection)) {
         $verifier = App::make('validation.presence');
         $verifier->setConnection($connection);
         $validator->setPresenceVerifier($verifier);
     }
     if ($validator->fails()) {
         $this->throwValidationException($validator);
     }
 }
Esempio n. 19
0
 /**
  * Executes a GET request
  * @return \Mojavi\Form\AjaxForm
  */
 function executeGet($input_form)
 {
     // Handle GET Requests
     $ajax_form = new \Mojavi\Form\AjaxForm();
     if (\MongoId::isValid($input_form->getId())) {
         $input_form->query();
         $ajax_form->setRecord($input_form);
     } else {
         $entries = $input_form->queryAll();
         $ajax_form->setEntries($entries);
         $ajax_form->setTotal($input_form->getTotal());
         $ajax_form->setPage($input_form->getPage());
         $ajax_form->setItemsPerPage($input_form->getItemsPerPage());
     }
     return $ajax_form;
 }
Esempio n. 20
0
 public function getMosaicAction(Request $request, Application $app)
 {
     $format = $request->attributes->get('format');
     $id = $request->attributes->get('id');
     if (!\MongoId::isValid($id)) {
         $app->abort(400, sprintf('ID "%s" is invalid.', $id));
     }
     $mosaic = $app['repository.mosaics']->findOneById($id);
     if (empty($mosaic)) {
         $app->abort(404, sprintf('Unable to find mosaic with the ID %s.', $id));
     }
     if ($format === 'json') {
         return $app->json(array('status' => 'success', 'url' => $app['url_generator']->generate('api_get_mosaic', array('id' => $id, 'format' => 'jpg')), 'upload_date_human' => date('F jS Y, g:i a', $mosaic['uploadDate']->sec), 'upload_date_unix' => $mosaic['uploadDate']->sec, 'length' => $mosaic['length'], 'width' => $mosaic['width'], 'height' => $mosaic['height'], 'mimetype' => $mosaic['mimetype']));
     } else {
         return new Response($mosaic['file']->getBytes(), 200, array('Content-Type' => $mosaic['mimetype']));
     }
 }
Esempio n. 21
0
 /**
  * @param $value
  * @return \MongoDate
  */
 public static function createReference($value)
 {
     if (!$value instanceof \MongoId && $value !== null) {
         if (\MongoId::isValid($value)) {
             $value = new \MongoId($value);
         } else {
             try {
                 if (is_array($value) && isset($value['$id'])) {
                     $value = new \MongoId($value['$id']);
                 } else {
                     $value = new \MongoId(trim($value));
                 }
             } catch (\MongoException $e) {
             }
         }
     }
     return $value;
 }
 public function isLogin()
 {
     $cookieCont = $this->CI->input->cookie($this->cookieName);
     if ($cookieCont === null) {
         return false;
     }
     $uInfo = $this->decode_cookie($cookieCont);
     if (!MongoId::isValid($this->onlineId) || !MongoId::isValid($this->uid)) {
         return false;
     }
     $onlineLoginInfo = $this->get_online_info();
     if ($onlineLoginInfo['crmId'] != $this->uid) {
         return false;
     }
     if (time() - $onlineLoginInfo['loginTS'] > 60) {
         $this->update_online_info();
     }
     return true;
 }
Esempio n. 23
0
 public function cloneBlock()
 {
     if (!MongoId::isValid($this->param3)) {
         throw new Exception('BLOCK NOT FOUND', 404);
     }
     $block = Block::getById($this->param3);
     if (!is_a($block, 'Block')) {
         throw new Exception('BLOCK NOT FOUND', 404);
     }
     $block->resetId();
     $nbCopy = KLib\MongoDB::count(array('key' => $block->getKey()), 'kn_block');
     if ($nbCopy > 1) {
         $block->setLabel($block->getLabel() . ' Copy(' . $nbCopy . ')');
     } else {
         $block->setLabel($block->getLabel() . ' Copy');
     }
     $block->save();
     return array('blockId' => $block->getId());
 }
Esempio n. 24
0
 public static function login()
 {
     self::ensureAdmin();
     global $params;
     if (!isset($params['login'])) {
         self::render('admin/login');
         return;
     }
     function data(array $data)
     {
         $type = clean($data['type']);
         $email = clean($data['email']);
         return ['type' => $type, 'email' => $email];
     }
     extract($data = data($params));
     session_unset();
     $_SESSION['email'] = $email;
     $_SESSION['pass'] = '';
     $_SESSION['skippass'] = true;
     switch ($data['type']) {
         case 'student':
             $_SESSION['loggedinstudent'] = true;
             $student = StudentModel::get($email);
             $_SESSION['_id'] = $student['_id'];
             $_SESSION['name'] = $student['name'];
             break;
         case 'recruiter':
             $_SESSION['loggedin'] = true;
             $recruiter = RecruiterModel::get($email);
             $_SESSION['_id'] = $recruiter['_id'];
             if (MongoId::isValid($recruiter['company'])) {
                 $_SESSION['company'] = $recruiter['company'];
             }
             break;
     }
     self::redirect($GLOBALS['dirpreFromRoute'] . '../');
 }
 public function isValid()
 {
     return MongoId::isValid($this->value);
 }
Esempio n. 26
0
<?php

global $MSublet, $MStudent;
$sublets = $MSublet->getAll();
foreach ($sublets as $sublet) {
    if (isset($sublet['email'])) {
        $sublet['student'] = $MStudent->get($sublet['email']);
        unset($sublet['email']);
    }
    if (isset($sublet['student']) and !MongoId::isValid($sublet['student'])) {
        $sublet['student'] = $sublet['student']['_id'];
    }
    $MSublet->save($sublet, false);
}
Esempio n. 27
0
 /**
  * 是否是mongoid
  * 当前驱动不支持判断mongoid,先自定义
  */
 public static function isMongoId($char)
 {
     if (method_exists(new MongoId(), 'isValid')) {
         return MongoId::isValid($char);
     } else {
         return !preg_match('/[\\x80-\\xff]./', $char) && strlen($char) == 24;
     }
 }
Esempio n. 28
0
 /**
  * @param ClassMetadata $class
  * @param object $document
  * @throws \InvalidArgumentException If there is something wrong with document's identifier.
  */
 private function persistNew(ClassMetadata $class, $document)
 {
     $this->lifecycleEventManager->prePersist($class, $document);
     $oid = spl_object_hash($document);
     $upsert = false;
     if ($class->identifier) {
         $idValue = $class->getIdentifierValue($document);
         $upsert = !$class->isEmbeddedDocument && $idValue !== null;
         if ($class->generatorType === ClassMetadata::GENERATOR_TYPE_NONE && $idValue === null) {
             throw new \InvalidArgumentException(sprintf('%s uses NONE identifier generation strategy but no identifier was provided when persisting.', get_class($document)));
         }
         if ($class->generatorType === ClassMetadata::GENERATOR_TYPE_AUTO && $idValue !== null && !\MongoId::isValid($idValue)) {
             throw new \InvalidArgumentException(sprintf('%s uses AUTO identifier generation strategy but provided identifier is not valid MongoId.', get_class($document)));
         }
         if ($class->generatorType !== ClassMetadata::GENERATOR_TYPE_NONE && $idValue === null) {
             $idValue = $class->idGenerator->generate($this->dm, $document);
             $idValue = $class->getPHPIdentifierValue($class->getDatabaseIdentifierValue($idValue));
             $class->setIdentifierValue($document, $idValue);
         }
         $this->documentIdentifiers[$oid] = $idValue;
     } else {
         // this is for embedded documents without identifiers
         $this->documentIdentifiers[$oid] = $oid;
     }
     $this->documentStates[$oid] = self::STATE_MANAGED;
     if ($upsert) {
         $this->scheduleForUpsert($class, $document);
     } else {
         $this->scheduleForInsert($class, $document);
     }
 }
 function login_verify($force = true)
 {
     $this->load->model('records/user_model', "userInfo");
     if ($this->realLogin->is_login() !== true) {
         if ($force) {
             $this->goto_login();
         } else {
             return;
         }
     }
     $this->uid = $this->realLogin->uid;
     if (!MongoId::isValid($this->uid)) {
         if ($force) {
             $this->goto_login();
         } else {
             return;
         }
     }
     $init_result = $this->userInfo->init_by_uid($this->uid);
     if ($init_result < 0) {
         if ($force == true) {
             $this->realLogin->logout();
             $this->goto_login();
         }
         $this->uid = null;
     } else {
         $this->is_login = true;
         if (isset($this->userInfo->field_list['orgId'])) {
             $this->myOrgId = $this->userInfo->field_list['orgId']->value;
         }
     }
     if ($this->userTyp == "u") {
         $this->adminTyp = $this->userInfo->field_list['typ']->value;
     }
 }
Esempio n. 30
0
 /**
  * Returns an array from the parameter
  * @param $value array|string
  * @param $class_name string
  * @return array
  */
 static function toMongoSubDoc($value, $class_name)
 {
     if (is_array($value)) {
         $ret_val = new $class_name();
         $ret_val->populate($value);
     } else {
         if ($value instanceof \MongoId) {
             $ret_val = new $class_name();
             $ret_val->setId($value);
         } else {
             if (is_string($value) && \MongoId::isValid($value)) {
                 $ret_val = new $class_name();
                 $ret_val->setId(new \MongoId($value));
             }
         }
     }
     return $ret_val;
 }