protected function execute(InputInterface $input, OutputInterface $output) { $this->formatter = $this->getHelper('formatter'); $text = "Initializing all dates to 'public'..."; $this->writeOutput($output, $text, 'comment'); $this->dm = $this->getContainer()->get('doctrine_mongodb')->getManager(); $this->mmobjRepo = $this->dm->getRepository('PumukitSchemaBundle:MultimediaObject'); $numberMmobjs = $this->mmobjRepo->createQueryBuilder()->count()->getQuery()->execute(); $allMmobjs = $this->mmobjRepo->createQueryBuilder()->getQuery()->execute(); $todayDate = new \MongoDate(); $text = sprintf('There are %s objects. Initializing to %s', $numberMmobjs, $todayDate->toDateTime()->format('d/m/Y')); $this->writeOutput($output, $text, 'comment'); $count = 0; $time_started = microtime(true); foreach ($allMmobjs as $mmobj) { ++$count; $mmobj->setPublicDate($todayDate); $this->dm->persist($mmobj); if ($count % 300 == 0) { $this->dm->flush(); $this->dm->clear(); $this->showProgressEstimation($output, $count, $numberMmobjs, $time_started); } } $this->showProgressEstimation($output, $count, $numberMmobjs, $time_started); $text = 'Script FINISHED.'; $this->writeOutput($output, $text, 'comment'); }
/** * @param $attribute * @param \MongoDate|string|int $oldValue * @param \MongoDate|string|int $newValue * @return array|bool */ private function getLogRow($attribute, $oldValue, $newValue) { $row = ['date' => new \MongoDate(), 'user' => \Yii::$app->user->identity['fullName']]; switch ($attribute) { case 'date': $row['action'] = "Изменилась дата с " . \Yii::$app->formatter->asDate($oldValue->toDateTime()) . " на " . \Yii::$app->formatter->asDate($newValue->toDateTime()); return $row; case 'beginTime': $row['action'] = "Изменилось время начала с " . MinuteFormatter::asString($oldValue) . " на " . MinuteFormatter::asString($newValue); return $row; case 'endTime': $row['action'] = "Изменилось время окончания с " . MinuteFormatter::asString($oldValue) . " на " . MinuteFormatter::asString($newValue); return $row; case 'participantsId': $action = ''; foreach ($newValue as $item) { $index = array_search($item, $oldValue); if ($index !== false) { unset($oldValue[$index]); } else { $action .= "Участник '" . Participant::findOne(['_id' => $item])->shortName . "' был добавлен\n"; } } foreach ($oldValue as $item) { $action .= "Участник '" . Participant::findOne(['_id' => $item])->shortName . "' был удалён\n"; } $row['action'] = $action; return $row; default: return false; } }
/** * Do some conversions for some types */ public function __set($key, $val) { // If it is a Mongo entity, convert it to its reference if ($val instanceof ZFE_Model_Mongo) { $val = $val->getReference(); } // If it is a DateTime, convert it to MongoDate if ($val instanceof DateTime) { $val = new MongoDate($val->getTimestamp()); } // If it is an array of Mongo entities or DateTimes if (is_array($val)) { $_val = array(); foreach ($val as $i => $v) { if ($v instanceof ZFE_Model_Mongo) { $v = $v->getReference(); } if ($v instanceof DateTime) { $v = new MongoDate($v->getTimestamp()); } $_val[$i] = $v; } $val = $_val; } parent::__set($key, $val); }
public function insert($collectionName, $userid, $record) { if (!$this->verifyCollection($collectionName)) { return false; } $collection = $this->db->selectCollection($collectionName); //Set core fields $newRec = array(); $newRec[FIELD_USERID] = $userid; $newRec[FIELD_CREATED] = new MongoTimestamp(); $newRec[FIELD_UPDATED] = new MongoTimestamp(); //Check type of fields to convert to mongo types foreach ($record as $key => $value) { $type = gettype($value); if ($type == "object") { $type = get_class($value); } if ($type == "DateTime") { $value = new MongoDate($value->getTimestamp()); } $newRec[$key] = $value; } //Insert to dataase $result = $collection->insert($newRec); if ($result['ok'] == 1) { return (string) $newRec['_id']; } return false; }
/** * @depends testCreate */ public function testConvertToBson(\MongoDate $date) { $this->skipTestUnless($date instanceof TypeInterface); $dateTime = $date->toDateTime(); $bsonDate = $date->toBSONType(); $this->assertInstanceOf('MongoDB\\BSON\\UTCDateTime', $bsonDate); $this->assertSame('1234567890123', (string) $bsonDate); $bsonDateTime = $bsonDate->toDateTime(); // Compare timestamps to avoid issues with DateTime $timestamp = $dateTime->format('U') . '.' . $dateTime->format('U'); $bsonTimestamp = $bsonDateTime->format('U') . '.' . $bsonDateTime->format('U'); $this->assertSame((double) $timestamp, (double) $bsonTimestamp); }
public function __construct($date = null) { if ($date instanceof \DateTime) { $date = $date->getTimestamp(); } parent::__construct($date); }
public function set($key, $value) { switch ($key) { case 'date': if (!$value instanceof \MongoDate) { if ($value instanceof \DateTime) { $value = new \MongoDate($value->getTimestamp()); } elseif (is_string($value)) { $value = new \MongoDate(strtotime($value)); } elseif (is_int($value)) { $value = new \MongoDate($value); } } break; } parent::set($key, $value); }
/** * @DataType date * @Validate(Date) * @Embed */ function is_date(&$date) { /* is_date */ if ($date instanceof \MongoDate) { return true; } if ($date instanceof \Datetime) { $date = new \MongoDate($date->getTimestamp()); } if (is_string($date)) { $date = strtotime($date); } if (is_integer($date) && $date > 0) { $date = new \MongoDate($date); return true; } return false; }
/** * Parse value with specific definition in $attrs * * @param string $key key * @param mixed $value value * * @throws Exception\InvalidDataTypeException * @return mixed */ public function parseValue($key, $value) { $attrs = $this->getAttrs(); if (!isset($attrs[$key]) && is_object($value)) { // Handle dates if (!$value instanceof \MongoDate || !$value instanceof \MongoId || !$value instanceof \MongoDBRef) { if ($value instanceof \DateTime) { $value = new \MongoDate($value->getTimestamp()); } else { if (method_exists($value, 'toArray')) { $value = (array) $value->toArray(); } elseif (method_exists($value, 'to_array')) { $value = (array) $value->to_array(); } else { //ingore this object when saving $this->ignoreData[$key] = $value; } } } } elseif (isset($attrs[$key]) && isset($attrs[$key]['type'])) { switch ($attrs[$key]['type']) { case self::DATA_TYPE_INT: case self::DATA_TYPE_INTEGER: $value = (int) $value; break; case self::DATA_TYPE_STR: case self::DATA_TYPE_STRING: $value = (string) $value; break; case self::DATA_TYPE_FLT: case self::DATA_TYPE_FLOAT: case self::DATA_TYPE_DBL: case self::DATA_TYPE_DOUBLE: $value = (double) $value; break; case self::DATA_TYPE_TIMESTAMP: if (!$value instanceof \MongoTimestamp) { try { $value = new \MongoTimestamp($value); } catch (\Exception $e) { throw new InvalidDataTypeException('$key cannot be parsed by \\MongoTimestamp', $e->getCode(), $e); } } break; case self::DATA_TYPE_DATE: if (!$value instanceof \MongoDate) { try { if (!$value instanceof \MongoDate) { if (is_numeric($value)) { $value = '@' . $value; } if (!$value instanceof \DateTime) { $value = new \DateTime($value); } $value = new \MongoDate($value->getTimestamp()); } } catch (\Exception $e) { throw new InvalidDataTypeException('$key cannot be parsed by \\DateTime', $e->getCode(), $e); } } break; case self::DATA_TYPE_BOOL: case self::DATA_TYPE_BOOLEAN: $value = (bool) $value; break; case self::DATA_TYPE_OBJ: case self::DATA_TYPE_OBJECT: if (!empty($value) && !is_array($value) && !is_object($value)) { throw new InvalidDataTypeException("[{$key}] is not an object"); } $value = (object) $value; break; case self::DATA_TYPE_ARRAY: if (!empty($value) && !is_array($value)) { throw new InvalidDataTypeException("[{$key}] is not an array"); } $value = (array) $value; break; case self::DATA_TYPE_EMBED: case self::DATA_TYPE_EMBEDS: case self::DATA_TYPE_MIXED: case self::DATA_TYPE_REFERENCE: case self::DATA_TYPE_REFERENCES: break; default: throw new InvalidDataTypeException("{$attrs[$key]['type']} is not a valid type"); break; } } return $value; }
/** * save ingredientImportingInfo array * @param ingredientImportingInfo array * @return boolean true when successful */ public function saveImporting($MaCTHDs, $unitPrices, $amounts) { $idSize = count($MaCTHDs); $unitSize = count($unitPrices); $amountSize = count($amounts); if ($idSize != $unitSize || $idSize != $amountSize || $unitSize != $amountSize) { return; } // saving importing info // 1. Get currently staff and restaurant session_start(); $currentStaff = isset($_SESSION['staff_id']) ? $_SESSION['staff_id'] : null; $restaurant = isset($_SESSION['restaurant']) ? $_SESSION['restaurant'] : null; if ($currentStaff == null || $restaurant == null) { return; } // 2. get date $date = new DateTime(); $date = new MongoDate(strtotime($date->format('Y-m-d H:i:s'))); $temp = array(); $debt = 0; $dao = new ContractDAO(); for ($i = 0; $i < $idSize; $i++) { $temp["MaCTHD"] = $MaCTHDs[$i]; $temp["NgayNhap"] = $date; $temp["DonGia"] = (int) $unitPrices[$i]; $temp["SoLuong"] = (int) $amounts[$i]; $temp["MaNH"] = $restaurant; $temp["MaNV"] = $currentStaff; $debt += $amounts[$i] * $unitPrices[$i]; // 3. insert // if insert one of ingredient info failed if ($dao->saveIngredientImportingInfo($temp) == false) { return false; } } $dao = new SupplierDAO(); $dao->addDebtInfo($MaCTHDs[0], $debt); return true; }
public function setTranslation($key, $val, $lang) { // If it is a Mongo entity, convert it to its reference if ($val instanceof ZFE_Model_Mongo) { $val = $val->getReference(); } // If it is a DateTime, convert it to MongoDate if ($val instanceof DateTime) { $val = new MongoDate($val->getTimestamp()); } parent::setTranslation($key, $val, $lang); }
/** * */ public function __set($parameter, $value) { // Transform 'id' to a MongoId if ('id' == $parameter || '_id' == $parameter) { $parameter = '_id'; $value = $value instanceof \MongoId ? $value : new \MongoId($value); } // Transform DateTime objects to MongoDate if ($value instanceof \DateTime) { $value = new \MongoDate($value->getTimestamp()); } // Set the saved state to false and save the parameter $this->__saved = false; $this->__data[$parameter] =& $value; // Return the value return $value; }
private static function decElement($data, &$offset) { $sig = ord($data[$offset]); $offset++; $name = Util::parseCString($data, $offset); switch ($sig) { case self::ETYPE_ID: $binId = Util::unpack('a12id', $data, $offset, 12)['id']; $value = new \MongoId(str_pad(bin2hex($binId), 24, '0')); break; case self::ETYPE_STRING: case self::ETYPE_SYMBOL: $len = Util::unpack('Vlen', $data, $offset, 4)['len']; $value = substr($data, $offset, $len - 1); // subtract 1 for nul-terminator $offset += $len; break; case self::ETYPE_ARRAY: case self::ETYPE_DOCUMENT: $value = self::decDocument($data, $offset); break; case self::ETYPE_INT32: $value = Util::unpack('lint', $data, $offset, 4)['int']; break; case self::ETYPE_BOOL: $value = Util::unpack('C', $data, $offset, 1); if ($value[1]) { $value = true; } else { $value = false; } break; case self::ETYPE_UNDEF: case self::ETYPE_NULL: $value = null; break; case self::ETYPE_INT64: $vars = Util::unpack('V2i', $data, $offset, 8); $value = $vars['i1'] | $vars['i2'] << 32; break; case self::ETYPE_DOUBLE: $value = Util::unpack('ddouble', $data, $offset, 8)['double']; break; case self::ETYPE_CODE_W_S: $offset += 4; // skip whole element size int // skip whole element size int case self::ETYPE_CODE: $scope = []; $len = Util::unpack('Vlen', $data, $offset, 4)['len']; $code = substr($data, $offset, $len - 1); // subtract 1 for nul-terminator $offset += $len; if ($sig === self::ETYPE_CODE_W_S) { $scope = self::decDocument($data, $offset); } $value = new \MongoCode($code, $scope); break; case self::ETYPE_REGEX: $regex = Util::parseCString($data, $offset); $flags = Util::parseCString($data, $offset); $value = new \MongoRegex('/' . $regex . '/' . $flags); break; case self::ETYPE_DATE: $vars = Util::unpack('V2i', $data, $offset, 8); $ms = ($vars['i2'] << 32) + $vars['i1']; $value = \MongoDate::createFromMs($ms); break; case self::ETYPE_TIMESTAMP: $vars = Util::unpack('V2i', $data, $offset, 8); $value = new \MongoTimestamp($vars['i2'], $vars['i1']); break; case self::ETYPE_BINARY: $vars = Util::unpack('Vlen/Csubtype', $data, $offset, 5); $len = $vars['len']; $subtype = $vars['subtype']; if ($subtype == 2) { // binary subtype 2 special case $len2 = Util::unpack('Vlen', $data, $offset, 4)['len']; if ($len2 == $len - 4) { $len = $len2; } else { // something is not right, restore offset $offset -= 4; } } if ($len < 0) { throw new \RuntimeException(sprintf('invalid binary length for key "%s": %d', $name, $len), 22); } $bin = substr($data, $offset, $len); $value = new \MongoBinData($bin, $subtype); $offset += strlen($bin); break; case self::ETYPE_MAXKEY: $value = new \MongoMaxKey(); break; case self::ETYPE_MINKEY: $value = new \MongoMinKey(); break; default: throw new \RuntimeException('Invalid signature: 0x' . dechex($sig)); } return [$name, $value]; }
/** * Set additional query, fields will be merged to currently existed request using array_merge. * * @link http://docs.mongodb.org/manual/tutorial/query-documents/ * @param array $query Fields and conditions to query by. * @return $this */ public function query(array $query = []) { array_walk_recursive($query, function (&$value) { if ($value instanceof \DateTime) { //MongoDate is always UTC, which is good :) $value = new \MongoDate($value->getTimestamp()); } }); $this->query = array_merge($this->query, $query); return $this; }