/**
  * @return Timestamp
  * 
  * Emulates PostgreSQL's date_trunc() function
  * 
  **/
 public function truncate(Date $time, $ceil = false)
 {
     $time = $time->toTimestamp();
     $function = $ceil ? 'ceil' : 'floor';
     if ($this->seconds) {
         if ($this->seconds < 1) {
             return $time->spawn();
         }
         $truncated = (int) ($function($time->toStamp() / $this->seconds) * $this->seconds);
         return Timestamp::create($truncated);
     } elseif ($this->days) {
         $epochStartTruncated = Date::create('1970-01-05');
         $truncatedDate = Date::create($time->toDate());
         if ($ceil && $truncatedDate->toStamp() < $time->toStamp()) {
             $truncatedDate->modify('+1 day');
         }
         $difference = Date::dayDifference($epochStartTruncated, $truncatedDate);
         $truncated = (int) ($function($difference / $this->days) * $this->days);
         return Timestamp::create($epochStartTruncated->spawn($truncated . ' days')->toStamp());
     } elseif ($this->months) {
         $monthsCount = $time->getYear() * 12 + ($time->getMonth() - 1);
         if ($ceil && $time->getDay() - 1 + $time->getHour() + $time->getMinute() + $time->getSecond() > 0) {
             $monthsCount += 0.1;
         }
         // delta
         $truncated = (int) ($function($monthsCount / $this->months) * $this->months);
         $months = $truncated % 12;
         $years = ($truncated - $months) / 12;
         Assert::isEqual($years, (int) $years);
         $years = (int) $years;
         $months = $months + 1;
         return Timestamp::create("{$years}-{$months}-01 00:00:00");
     }
     Assert::isUnreachable();
 }
 public function unlink($key)
 {
     try {
         return unlink($this->path . $key);
     } catch (BaseException $e) {
         return false;
     }
     Assert::isUnreachable();
 }
 public function getList()
 {
     if ($this->value) {
         return ClassUtils::callStaticMethod(get_class($this->value) . '::getList');
     } elseif ($this->default) {
         return ClassUtils::callStaticMethod(get_class($this->default) . '::getList');
     } else {
         $object = new $this->className(ClassUtils::callStaticMethod($this->className . '::getAnyId'));
         return $object->getObjectList();
     }
     Assert::isUnreachable();
 }
 public function get($key)
 {
     try {
         if (!isset($this->pool[$key])) {
             $this->pool[$key] = sem_get($key, 1, ONPHP_IPC_PERMS, false);
         }
         return sem_acquire($this->pool[$key]);
     } catch (BaseException $e) {
         return null;
     }
     Assert::isUnreachable();
 }
 public function import($scope)
 {
     if (!($result = parent::import($scope))) {
         return $result;
     }
     if ($this->value = $this->isSplitByRegexp() ? preg_split($this->separator, $this->value, -1, PREG_SPLIT_NO_EMPTY) : explode($this->separator, $this->value)) {
         return true;
     } else {
         return false;
     }
     Assert::isUnreachable();
 }
 private static function calculateBoolean($logic, $left, $right)
 {
     switch ($logic) {
         case BinaryExpression::EXPRESSION_AND:
             return $left && $right;
         case BinaryExpression::EXPRESSION_OR:
             return $left || $right;
         default:
             throw new WrongArgumentException("unknown logic - '{$logic}'");
     }
     Assert::isUnreachable();
 }
 public function getList()
 {
     if ($this->value) {
         return $this->value->getObjectList();
     } elseif ($this->default) {
         return $this->default->getObjectList();
     } else {
         $object = new $this->className(call_user_func(array($this->className, 'getAnyId')));
         return $object->getObjectList();
     }
     Assert::isUnreachable();
 }
 /**
  * @return string
  */
 private function renderNode(DOMNode $node)
 {
     switch ($node->nodeType) {
         case XML_CDATA_SECTION_NODE:
             return $node->nodeValue;
         case XML_TEXT_NODE:
             return htmlspecialchars($node->nodeValue);
         case XML_ELEMENT_NODE:
             return $this->renderElementNode($node);
         default:
             Assert::isUnreachable('not-renderable node type: %s (name: %s)', $node->nodeType, $node->nodeName);
     }
 }
Beispiel #9
0
 /**
  * A shorthand getter of the view data.
  *
  * If the variable is missing, and error_reporting is turned off (by prepending the call
  * with the "@" operator) then the variable is treated as NULL. Otherwise a compilation
  * error is raised
  *
  * @return mixed
  */
 function __get($name)
 {
     Assert::isScalar($name);
     if (array_key_exists($name, $this->data)) {
         return $this->data[$name];
     } else {
         if (!error_reporting()) {
             $this->data[$name] = null;
             return null;
         } else {
             Assert::isUnreachable('unknown view data `%s` expected within %s view', $name, $this->name);
         }
     }
 }
 function assemble(array $tuple, FetchStrategy $fetchStrategy)
 {
     Assert::isTrue(sizeof($tuple) == 1);
     $value = reset($tuple);
     if (is_null($value)) {
         return null;
     } else {
         try {
             return call_user_func_array(array($this->boxableType, 'cast'), array($value));
         } catch (TypeCastException $e) {
             Assert::isUnreachable('wrong `%s` cast to %s', $value, $this->boxableType);
         }
     }
 }
 /**
  * @throws BaseException
  * @return ModelAndView
  **/
 public function run(Prototyped $subject, Form $form, HttpRequest $request)
 {
     Assert::isFalse($this->running, 'command already running');
     Assert::isTrue($subject instanceof DAOConnected);
     $this->transaction = InnerTransaction::begin($subject->dao());
     try {
         $mav = $this->command->run($subject, $form, $request);
         $this->running = true;
         return $mav;
     } catch (BaseException $e) {
         $this->transaction->rollback();
         throw $e;
     }
     Assert::isUnreachable();
 }
 /**
  * @param array $fields fields of referencing table that reference primary another table
  * @param DBTable $referencedTable object that represents referenced table
  * @param AssociationBreakAction $associationBreakAction action which is performed on reference break
  */
 function __construct(array $fields, DBTable $referencedTable, AssociationBreakAction $associationBreakAction)
 {
     foreach ($referencedTable->getConstraints() as $constraint) {
         if ($constraint instanceof DBPrimaryKeyConstraint) {
             $pkFields = $constraint->getFields();
             Assert::isTrue(sizeof($pkFields) == sizeof($fields), 'foreign key (%s) should have the same number of columns as %s`s table primary key (%s)', join(', ', $fields), $referencedTable->getName(), join(', ', $pkFields));
             $this->fields = new SqlFieldArray($fields);
             $this->pkFields = new SqlFieldArray($pkFields);
             $this->referencedTable = $referencedTable;
             $this->associationBreakAction = $associationBreakAction;
             return;
         }
     }
     Assert::isUnreachable('referenced table `%s` MUST contain DBPrimaryKeyConstraint', $referencedTable->getName());
 }
 /**
  * @return ModelAndView
  **/
 public function handleRequest(HttpRequest $request)
 {
     if ($action = $this->chooseAction($request)) {
         $method = $this->methodMap[$action];
         $mav = $this->{$method}($request);
         if ($mav->viewIsRedirect()) {
             return $mav;
         }
         $mav->getModel()->set('action', $action);
         return $mav;
     } else {
         return ModelAndView::create();
     }
     Assert::isUnreachable();
 }
 public function touch($key)
 {
     try {
         $q = msg_get_queue($this->id, ONPHP_IPC_PERMS);
     } catch (BaseException $e) {
         // race
         return false;
     }
     try {
         return msg_send($q, $key, 1, false, false);
     } catch (BaseException $e) {
         // queue is full, rotate it.
         return msg_remove_queue($q);
     }
     Assert::isUnreachable();
 }
 public function import($scope)
 {
     if (!BasePrimitive::import($scope)) {
         return null;
     }
     if ($scope[$this->getName()] instanceof $this->className) {
         $this->value = $scope[$this->getName()];
         return true;
     }
     try {
         $this->value = new $this->className($scope[$this->getName()]);
         return true;
     } catch (WrongArgumentException $e) {
         return false;
     }
     Assert::isUnreachable();
 }
 public function import($scope)
 {
     if (!BasePrimitive::import($scope)) {
         return null;
     }
     if ($this->single->isTrue()) {
         return $this->importSingle($scope);
     } elseif ($this->single->isFalse()) {
         return $this->importMarried($scope);
     } else {
         if (!$this->importMarried($scope)) {
             return $this->importSingle($scope);
         }
         return true;
     }
     Assert::isUnreachable();
 }
 private function dumpTargets(Dialect $dialect, $prepend = null, $append = null)
 {
     if (count($this->targets) == 1) {
         return $prepend . $dialect->quoteTable(reset($this->targets));
     } else {
         $tables = array();
         foreach ($this->targets as $target) {
             if ($target instanceof DialectString) {
                 $table = $dialect->quoteTable($target->toDialectString($dialect));
             } else {
                 $table = $dialect->quoteTable($target);
             }
             $tables[] = $prepend . $table;
         }
         return implode($append . ' ', $tables);
     }
     Assert::isUnreachable();
 }
 static function dumpControl(IFormControl $control)
 {
     if ($control instanceof HiddenFormControl || $control instanceof HiddenFormControlSet) {
         return;
     }
     if ($control instanceof ButtonFormControl) {
         return;
     }
     if ($control instanceof CheckboxFormControl) {
         return self::dumpCb($control);
     }
     if ($control instanceof FormControlScalar) {
         return self::dumpScalar($control);
     }
     if ($control instanceof FormControlSet) {
         return self::dumpSet($control);
     }
     Assert::isUnreachable('don`t know how to dump %s', get_class($control));
 }
 protected function guessLabel($key)
 {
     if (!$this->sorted) {
         $this->sortPeers();
     }
     $point = hexdec(substr(sha1($key), 0, 5)) % $this->summaryWeight;
     $firstPeer = reset($this->peers);
     while ($peer = current($this->peers)) {
         if ($point <= $peer['mountPoint']) {
             return key($this->peers);
         }
         next($this->peers);
     }
     if ($point <= $firstPeer['mountPoint'] + $this->summaryWeight) {
         reset($this->peers);
         return key($this->peers);
     }
     Assert::isUnreachable();
 }
 public function queryRaw($queryString)
 {
     if (PinbaClient::isEnabled()) {
         $queryLabel = substr($queryString, 0, 5);
         PinbaClient::me()->timerStart('pg_sql_query_' . $this->basename, array('group' => 'sql', 'pg_sql_query' => $queryLabel, 'pg_sql_server' => $this->hostname, 'pg_sql_base' => $this->basename));
     }
     try {
         $result = parent::queryRaw($queryString);
         if (PinbaClient::isEnabled()) {
             PinbaClient::me()->timerStop('pg_sql_query_' . $this->basename);
         }
         return $result;
     } catch (Exception $e) {
         if (PinbaClient::isEnabled()) {
             PinbaClient::me()->timerStop('pg_sql_query_' . $this->basename);
         }
         throw $e;
     }
     Assert::isUnreachable();
 }
 function toDialectString(IDialect $dialect)
 {
     $table = $dialect->quoteIdentifier($this->constraint->getTable()->getName());
     $ct = $dialect->quoteIdentifier($this->constraint->getName());
     if ($dialect->getDBDriver()->is(DBDriver::MYSQL)) {
         if ($this->constraint instanceof DBUniqueConstraint) {
             return 'ALTER TABLE ' . $table . ' DROP INDEX ' . $ct;
         } else {
             if ($this->constraint instanceof DBPrimaryKeyConstraint) {
                 return 'ALTER TABLE ' . $table . ' DROP PRIMARY KEY';
             } else {
                 if ($this->constraint instanceof DBOneToOneConstraint || $this->constraint instanceof DBForeignKeyConstraint) {
                     return 'ALTER TABLE ' . $table . ' DROP FOREIGN KEY ' . $ct;
                 }
             }
         }
         Assert::isUnreachable('Do not know how to remove constraint %s from MySQL', get_class($this->constraint));
     }
     return 'ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $ct . ' CASCADE;';
 }
 public function testWithBaseException()
 {
     $service = $this->spawnService();
     $counter = 0;
     $callback = function () use(&$counter) {
         switch ($counter++) {
             case 0:
                 return null;
             case 1:
                 throw new BaseException('include exception');
             case 2:
                 return null;
             default:
                 Assert::isUnreachable($counter - 1);
         }
     };
     $service->expects($this->exactly(3))->method('includeFile')->will($this->returnCallback($callback));
     //autoload without error, it's allow us to cache data
     $service->autoload('Form');
     //second autoload and here we throw error
     $service->setNamespaceResolver($this->spawnResolver(array('getPathsCount' => 2, 'getClassPathListCount' => 1)));
     $service->autoload('Form');
 }
    public function toGetter(MetaClass $class, MetaClassProperty $property, MetaClassProperty $holder = null)
    {
        $name = $property->getName();
        $camelName = ucfirst($name);
        $methodName = "is{$camelName}";
        $compatName = "get{$camelName}";
        if ($holder) {
            return <<<EOT

public function {$compatName}()
{
\treturn \$this->{$holder->getName()}->{$compatName}();
}

public function {$methodName}()
{
\treturn \$this->{$holder->getName()}->{$methodName}();
}

EOT;
        } else {
            return <<<EOT

public function {$compatName}()
{
\treturn \$this->{$name};
}

public function {$methodName}()
{
\treturn \$this->{$name};
}

EOT;
        }
        Assert::isUnreachable();
    }
Beispiel #24
0
 function disassemble(OrmEntity $entity)
 {
     $tuple = array();
     foreach ($this->logicalSchema->getProperties() as $property) {
         if (!$property->getVisibility()->isGettable() || !sizeof($property->getFields())) {
             continue;
         }
         $value = $entity->{$property->getGetter()}();
         if (is_null($value)) {
             if ($property->isIdentifier()) {
                 continue;
             }
             if ($property->getMultiplicity()->is(AssociationMultiplicity::ZERO_OR_ONE)) {
                 continue;
             }
             Assert::isUnreachable('%s::%s cannot be valueless', get_class($entity), $property->getName());
         }
         $fields = array_combine($property->getFields(), $property->getType()->disassemble($value));
         foreach ($fields as $field => $value) {
             $tuple[$field] = $value;
         }
     }
     return $tuple;
 }
 public function importValue($value)
 {
     Assert::isUnreachable('No import value!');
     return $this;
 }
 /**
  * @return MetaConfiguration
  **/
 private function checkClassSanity(MetaClass $class, ReflectionClass $info)
 {
     switch ($class->getTypeId()) {
         case null:
             break;
         case MetaClassType::CLASS_ABSTRACT:
             Assert::isTrue($info->isAbstract(), 'class ' . $info->getName() . ' expected to be abstract');
             Assert::isTrue($class->getPattern() instanceof AbstractClassPattern, 'class ' . $info->getName() . ' must use AbstractClassPattern');
             break;
         case MetaClassType::CLASS_FINAL:
             Assert::isTrue($info->isFinal(), 'class ' . $info->getName() . ' expected to be final');
             break;
         case MetaClassType::CLASS_SPOOKED:
         default:
             Assert::isUnreachable();
             break;
     }
     if ($public = $info->getProperties(ReflectionProperty::IS_PUBLIC)) {
         Assert::isUnreachable($class->getName() . ' contains properties with evil visibility:' . "\n" . print_r($public, true));
     }
     return $this;
 }
 private function importItem(SiteDocIndexItem $rootIndex, SimpleXMLElement $node)
 {
     switch ($node->getName()) {
         case "doc":
             $item = new SiteDocIndexXmlItem($this->absolutizeXmlPath((string) $node['xml']), $this->getHtmlUri($this->absolutizeLocation(isset($node['location']) ? (string) $node['location'] : (string) $node['xml'])), $rootIndex, isset($node['site-part']) ? new SitePart((string) $node['site-part']) : null);
             break;
         case "ref":
             $item = new SiteDocIndexRefItem((string) $node['name'], $this->absolutizeLocation((string) $node['link']), $rootIndex, isset($node['site-part']) ? new SitePart($node['site-part']) : null);
             break;
         case "include":
             $worker = new self($this->absolutizeXmlPath((string) $node['xml']), $this->absolutizeLocation((string) $node['prefix']), $rootIndex);
             $worker->xmlRoot = $this->xmlRoot;
             $worker->build();
             return;
         default:
             Assert::isUnreachable('unknown item %s', $node->getName());
     }
     $this->traverse($item, $node);
 }
 public function getListByQuery(SelectQuery $query)
 {
     $list = $this->getCachedList($query);
     if ($list) {
         if ($list === Cache::NOT_FOUND) {
             throw new ObjectNotFoundException();
         } else {
             return $list;
         }
     } else {
         if ($list = $this->fetchList($query)) {
             return $this->cacheListByQuery($query, $list);
         } else {
             $this->cacheListByQuery($query, Cache::NOT_FOUND);
             throw new ObjectNotFoundException();
         }
     }
     Assert::isUnreachable();
 }
 /**
  * @return CustomizableDaoSynchronizer
  **/
 public function run()
 {
     $masterIterator = new DaoIterator();
     $slaveIterator = new DaoIterator();
     $masterIterator->setDao($this->master);
     $slaveIterator->setDao($this->slave);
     if ($this->masterKeyProperty) {
         $masterIterator->setKeyProperty($this->masterKeyProperty);
     }
     if ($this->slaveKeyProperty) {
         $slaveIterator->setKeyProperty($this->slaveKeyProperty);
     }
     if ($this->masterProjection) {
         $masterIterator->setProjection($this->masterProjection);
     }
     if ($this->slaveProjection) {
         $slaveIterator->setProjection($this->slaveProjection);
     }
     $this->totalDeleted = 0;
     $this->totalInserted = 0;
     $this->totalUpdated = 0;
     while ($masterIterator->valid() || $slaveIterator->valid()) {
         $masterObject = $masterIterator->current();
         $slaveObject = $slaveIterator->current();
         $masterObject = $this->convertMasterObjectToSlave($masterObject);
         $masterGetter = 'get' . ucfirst($this->masterKeyProperty);
         $slaveGetter = 'get' . ucfirst($this->slaveKeyProperty);
         if ($masterObject && $slaveObject && $masterObject->{$masterGetter}() == $slaveObject->{$slaveGetter}()) {
             if ($this->sync($slaveObject, $masterObject)) {
                 $this->totalUpdated++;
             }
             $masterIterator->next();
             $slaveIterator->next();
         } elseif (!$masterObject || $slaveObject && $this->compareKeys($masterObject->{$masterGetter}(), $slaveObject->{$slaveGetter}()) > 0) {
             if ($this->delete($slaveObject)) {
                 $this->totalDeleted++;
             }
             $slaveIterator->next();
         } elseif (!$slaveObject || $masterObject && $this->compareKeys($masterObject->{$masterGetter}(), $slaveObject->{$slaveGetter}()) < 0) {
             if ($this->insert($masterObject)) {
                 $this->totalInserted++;
             }
             $masterIterator->next();
         } else {
             Assert::isUnreachable('how did you get here?');
         }
     }
     return $this;
 }
 function toSetter(IMappable $entity, OrmProperty $property)
 {
     Assert::isUnreachable();
 }