Example #1
0
 /**
  * Automatically add sort options from model.
  * @param string $field Field name.
  * @param string $fields,... Additional fields.
  */
 public function autoSortOptions($field)
 {
     assume(isset($this->model), tr('No model set'));
     $fields = func_get_args();
     foreach ($fields as $field) {
         $this->sortOptions->append(new Column($this->model->getLabel($field), $field), $field);
     }
 }
Example #2
0
 /**
  * Construct Blowfish password hasher.
  * @param int $cost A number between 4 and 31 that sets the cost of the hash
  * computation. 
  */
 public function __construct($cost = 10)
 {
     assume($cost >= 4 and $cost <= 31);
     $this->prefix = sprintf('$2y$%02d$', $cost);
     if (PHP_VERSION_ID < 50307) {
         throw new UnsupportedHashTypeException(tr('Unsupported password hasher: "%1"', get_class($this)));
     }
     parent::__construct();
 }
Example #3
0
File: Meta.php Project: jivoo/jivoo
 /**
  * {@inheritdoc}
  */
 public function addData($data, $allowedFields = null)
 {
     assume(is_array($data));
     if (is_array($allowedFields)) {
         $allowedFields = array_flip($allowedFields);
         $data = array_intersect_key($data, $allowedFields);
     }
     foreach ($data as $field => $value) {
         $this->__set($field, $data[$field]);
     }
 }
Example #4
0
 /**
  * Construct extended DES password hasher.
  * @param int $iterations Number of iterations used by algorithm.
  */
 public function __construct($iterations = 751)
 {
     assume($iterations > 0 and $iterations <= 15752960);
     $bytes = array($iterations & 0x3f, $iterations >> 6 & 0x3f, $iterations >> 12 & 0x3f, $iterations >> 18 & 0x3f);
     $base64Chars = './0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
     $iterations = '';
     foreach ($bytes as $byte) {
         $iterations .= $base64Chars[$byte];
     }
     $this->prefix = '_' . $iterations;
     parent::__construct();
 }
Example #5
0
 /**
  * Paginate a selection (using {@see ReadSelection::limit()} and
  * {@see ReadSelection::offset()}) or an array (using {@see array_slice()}).
  * @param ReadSelection|array $select Selection or array.
  * @param int $itemsPerPage Number of items per page.
  * @return ReadSelection|array Modified selection or sliced array.
  */
 public function paginate($select, $itemsPerPage = 5)
 {
     assume($itemsPerPage > 0);
     $this->limit = $itemsPerPage;
     if (!isset($this->count)) {
         if ($select instanceof ReadSelection) {
             $this->count = $select->count();
         } else {
             $this->count = count($select);
         }
     }
     $this->pages = max(ceil($this->count / $this->limit), 1);
     if (isset($this->request->query['page'])) {
         $this->page = (int) $this->request->query['page'];
         $this->page = min($this->page, $this->pages);
         $this->page = max($this->page, 1);
         $this->offset = ($this->page - 1) * $this->limit;
     } else {
         if (isset($this->request->query['from']) and isset($this->request->query['to'])) {
             $this->from = min(max($this->request->query['from'], 1), $this->count);
             $this->offset = $this->from - 1;
             $this->to = min(max($this->request->query['to'], 1), $this->count);
             $this->limit = $this->to - $this->from + 1;
         }
     }
     if (!$this->isLast()) {
         $this->view->blocks->relation('next', null, $this->getLink($this->nextLink()));
     }
     if (!$this->isFirst()) {
         $this->view->blocks->relation('prev', null, $this->getLink($this->prevLink()));
     }
     if ($select instanceof ReadSelection) {
         $select = $select->limit($this->limit);
         $select = $select->offset($this->offset);
         return $select;
     } else {
         return array_slice($select, $this->offset, $this->limit);
     }
 }
Example #6
0
 /**
  * Attach a database for migrations.
  * @param string $name Database name.
  * @param string $migrationDir Location of migrations.
  */
 public function attachDatabase($name, $migrationDir)
 {
     $db = $this->m->Databases->{$name}->getConnection();
     assume($db instanceof MigratableDatabase);
     $this->migrationDirs[$name] = $migrationDir;
     $this->connections[$name] = $db;
     if ($this->config['automigrate'] and isset($this->m->Setup)) {
         if (!$this->m->Setup->isActive() and is_dir($this->migrationDirs[$name])) {
             $mtime = filemtime($this->migrationDirs[$name] . '/.');
             if (!isset($this->config['mtimes'][$name]) or $this->config['mtimes'][$name] != $mtime) {
                 if ($this->config['silent']) {
                     $missing = $this->check($name);
                     foreach ($missing as $migration) {
                         $this->run($name, $migration);
                     }
                     $this->finalize($name);
                 } else {
                     $this->m->Setup->trigger('Jivoo\\Migrations\\MigrationUpdater');
                 }
             }
         }
     }
 }
Example #7
0
 /**
  * Read schema classes from a namespace.
  * @param string $namespace Namespace of schema classes.
  * @param string $dir Location of schema classes.
  * @return DatabaseSchemaBuilder Database schema.
  */
 public function readSchema($namespace, $dir)
 {
     $dbSchema = new DatabaseSchemaBuilder();
     assume(is_dir($dir));
     $files = scandir($dir);
     if ($files !== false) {
         foreach ($files as $file) {
             $split = explode('.', $file);
             if (isset($split[1]) and $split[1] == 'php') {
                 $class = rtrim($namespace, '\\') . '\\' . $split[0];
                 Assume::isSubclassOf($class, 'Jivoo\\Databases\\SchemaBuilder');
                 $dbSchema->addSchema(new $class());
             }
         }
     }
     return $dbSchema;
 }
Example #8
0
 /**
  * Get an installer.
  * @param string $class Installer class.
  * @param Document $state Installer state.
  * @return InstallerSnippet Instalelr.
  */
 public function getInstaller($class, Document $state = null)
 {
     if (!isset($this->installers[$class])) {
         if (!isset($state) and $this->state->isMutable('setup')) {
             $state = $this->state->write('setup');
             $state = $state[$class];
         }
         $snippet = $this->snippets->getSnippet($class);
         assume($snippet instanceof InstallerSnippet);
         if (isset($state)) {
             $snippet->setState($state);
         }
         $this->installers[$class] = $snippet;
     }
     return $this->installers[$class];
 }
Example #9
0
 /**
  * Embed another template into the current template.
  * @param string $_template Name of template.
  * @param array $_data Additional data for template.
  * @throws InvalidTemplateException If template could not be found.
  */
 protected function embed($_template, $_data = array())
 {
     assume(is_string($_template));
     extract($_data, EXTR_SKIP);
     extract($this->view->data->toArray(), EXTR_SKIP);
     extract($this->view->data[$_template]->toArray(), EXTR_SKIP);
     $_templateInfo = $this->view->findTemplate($_template);
     if (!isset($_templateInfo)) {
         throw new InvalidTemplateException(tr('Template not found: %1', $_template));
     }
     if (isset($_templateInfo['init']) and !$_templateInfo['init']) {
         $_init = $this->view->getInitFile($_templateInfo['key'], $_templateInfo['path']);
         if (isset($_init)) {
             $this->embed($_init);
         }
     }
     array_unshift($this->templateStack, $_template);
     require $_templateInfo['file'];
     array_shift($this->templateStack);
     if (isset($this->extend)) {
         $this->view->data[$this->extend] = $this->view->data[$_template];
     }
 }
Example #10
0
 /**
  * Set view data for a specific template.
  * @param string $template Template name.
  * @param ViewData|array $data The data.
  */
 public function offsetSet($template, $data)
 {
     if (!isset($this->templateData[$template])) {
         if (is_array($data)) {
             $this->templateData[$template] = new ViewData();
             $this->templateData[$template]->data = $data;
         } else {
             assume($data instanceof ViewData);
             $this->templateData[$template] = $data;
         }
     } else {
         if (!is_array($data)) {
             assume($data instanceof ViewData);
             $data = $data->toArray();
         }
         $this->templateData[$template]->data = array_merge($this->templateData[$template]->data, $data);
     }
 }
Example #11
0
 /**
  * Set association.
  * @param ActiveRecord $record A record.
  * @param array $association Association options.
  * @param ActiveRecord|Selection|ActiveRecord[] $value New value.
  * @throws InvalidAssociationException If association type unknown.
  */
 public function setAssociation(ActiveRecord $record, $association, $value)
 {
     switch ($association['type']) {
         case 'belongsTo':
             if (!isset($value)) {
                 $this->unsetAssociation($record, $association);
                 return;
             }
             assume($value instanceof ActiveRecord);
             assume($value->getModel() == $association['model']);
             $key = $association['otherKey'];
             $otherId = $association['model']->primaryKey;
             $record->{$key} = $value->{$otherId};
             return;
         case 'hasOne':
             assume($value instanceof ActiveRecord);
             assume($value->getModel() == $association['model']);
             $this->unsetAssociation($record, $association);
             $key = $association['thisKey'];
             $id = $this->primaryKey;
             $value->{$key} = $record->{$id};
             $value->save();
             return;
         case 'hasMany':
             $key = $association['thisKey'];
             $id = $this->primaryKey;
             $idValue = $record->{$id};
             if ($value instanceof Selection) {
                 $value->set($key, $idValue)->update();
                 return;
             }
             if (!is_array($value)) {
                 $value = array($value);
             }
             $this->unsetAssociation($record, $association);
             foreach ($value as $item) {
                 assume($item instanceof ActiveRecord);
                 assume($item->getModel() == $association['model']);
                 $item->{$key} = $idValue;
                 if (!$item->isNew()) {
                     $item->save();
                 }
             }
             return;
         case 'hasAndBelongsToMany':
             return;
     }
     throw new InvalidAssociationException(tr('Unknown association type: %1', $association['type']));
 }
Example #12
0
 /**
  * Event handler for {@see RenderEvent} and {@see ShowExceptionEvent}. Inserts
  * the development bar code into the response if the response type is
  * 'text/html' and the body contains '</body'.
  * @param RenderEvent|ShowExceptionEvent $event The event object.
  */
 public function injectCode(Event $event)
 {
     if (!isset($this->devbar)) {
         return;
     }
     if ($event instanceof RenderEvent) {
         if ($event->response->type !== 'text/html') {
             return;
         }
         $extraIncludes = '';
     } else {
         assume($event instanceof ShowExceptionEvent);
         $extraIncludes = $this->devbarResources;
     }
     $body = $event->body;
     $pos = strripos($body, '</body');
     if ($pos === false) {
         return;
     }
     // TODO: maybe app logger should not be replacable?
     if ($this->logger instanceof Logger) {
         $this->setVariable('jivooLog', $this->logger->getLog());
     } else {
         $this->setVariable('jivooLog', array());
     }
     $this->setVariable('jivooRequest', $this->request->toArray());
     $this->setVariable('jivooSession', $this->session->toArray());
     $this->setVariable('jivooCookies', $this->request->cookies->toArray());
     $extraVars = '<script type="text/javascript">' . $this->outputVariables() . $this->outputTools() . '</script>' . PHP_EOL;
     $event->body = substr_replace($body, $extraIncludes . $this->devbar . $extraVars, $pos, 0);
     $event->overrideBody = true;
 }
Example #13
0
 /**
  * Translate a string containing a numeric value, e.g.
  * <code>$l->nget('This post has %1 comments', 'This post has %1 comment', $numcomments);</code>
  * @param string $plural Message in english (plural).
  * @param string $singular Singular version of message in english.
  * @param int|array|\Countable $n The integer to test, replaces the
  * %1-placeholder in the message. May also be an array or a {@see \Countable},
  * in which case {@see count} will be called on the value.
  * @param mixed $vars,... Values for additional placholders starting from %2.
  * @return Translated string.
  * @throws \Jivoo\InvalidArgumentException If $n is not an integer, an 
  * array, or a {@see \Countable}. 
  */
 public function nget($plural, $singular, $n)
 {
     if (is_array($n) or $n instanceof \Countable) {
         $n = count($n);
     }
     assume(is_scalar($n));
     $n = intval($n);
     if (isset($this->messages[$plural])) {
         $i = intval(eval($this->pluralExpr));
         $message = $this->messages[$plural][0];
         if (isset($this->messages[$plural][$i])) {
             $message = $this->messages[$plural][$i];
         }
     } else {
         if (abs($n) == 1) {
             $message = $singular;
         } else {
             $message = $plural;
         }
     }
     return $this->replacePlaceholders($message, array_slice(func_get_args(), 2));
 }
Example #14
0
 /**
  * Replace a node with another node.
  * @param TemplateNode $node Node to replace.
  * @param TemplateNode $next Replacement node.
  * @return self Self.
  */
 public function replace(TemplateNode $node, TemplateNode $replacement)
 {
     assume($node->parent === $this);
     assume(!isset($replacement->parent));
     $offset = array_search($node, $this->content, true);
     $this->content[$offset] = $replacement;
     $replacement->parent = $this;
     $replacement->root = $this->root;
     $node->parent = null;
     $node->root = null;
     if (isset($node->next)) {
         $node->next->prev = $replacement;
         $replacement->next = $node->next;
     }
     if (isset($node->prev)) {
         $node->prev->next = $replacement;
         $replacement->prev = $node->prev;
     }
     $node->next = null;
     $node->prev = null;
     return $this;
 }
Example #15
0
 /**
  * Replace this node with another.
  * @param TemplateNode $node Replacement node.
  * @return TemplateNode Replacement node.
  */
 public function replaceWith(TemplateNode $node)
 {
     assume(isset($this->parent));
     $this->parent->replace($this, $node);
     return $node;
 }
Example #16
0
 /**
  * Update a document  key.
  * @param string $key The document key to access.
  * @param mixed $value The value to associate with the key.
  */
 public function set($key, $value)
 {
     assume(is_scalar($key));
     if (isset($this->emptySubset)) {
         $this->createTrueSubset();
     }
     $oldValue = null;
     if (isset($this->data[$key])) {
         $oldValue = $this->data[$key];
     }
     if (isset($key) and isset($value) and $key !== '') {
         $this->data[$key] = $value;
     } else {
         $this->data[$key] = null;
     }
     if (!$this->root->updated and $oldValue !== $value) {
         $this->root->updated = true;
         $this->root->update();
     }
 }
Example #17
0
 /**
  * Sort an array of records by a field.
  * @param string $field Field to sort by.
  * @param BasicRecord[] $selection Array of records.
  * @param bool Whether to sort in descending order.
  * @return BasicRecord[] Sorted array.
  */
 public function sortBy($field, $selection, $descending = false)
 {
     assume(is_array($selection));
     usort($selection, function (BasicRecord $a, BasicRecord $b) use($field, $descending) {
         if ($a->{$field} == $b->{$field}) {
             return 0;
         }
         if ($descending) {
             if (is_numeric($a->{$field})) {
                 return $b->{$field} - $a->{$field};
             }
             return strcmp($b->{$field}, $a->{$field});
         } else {
             if (is_numeric($a->{$field})) {
                 return $a->{$field} - $b->{$field};
             }
             return strcmp($a->{$field}, $b->{$field});
         }
     });
     return $selection;
 }
Example #18
0
 /**
  * Begins or continues (if parameter omitted) an if block around the node.
  * @param HtmlNode $node Node.
  * @param TemplateNode $value Macro parameter.
  */
 public function _if(HtmlNode $node, TemplateNode $value)
 {
     if (!isset($value)) {
         $prev = $node->prev;
         $between = array();
         do {
             if ($prev instanceof IfNode) {
                 assume(count($prev->else) == 0);
                 $between = array_reverse($between);
                 foreach ($between as $betweenNode) {
                     $betweenNode->detach();
                     $prev->then->append($betweenNode);
                 }
                 $node->detach();
                 $prev->then->append($node);
                 return;
             }
             $between[] = $prev;
             $prev = $prev->prev;
         } while (isset($prev));
         throw new InvalidTemplateException(tr('Empty if-node must follow another if-node.'));
     }
     $ifNode = new IfNode(PhpNode::expr($value)->code);
     $node->replaceWith($ifNode);
     $ifNode->then->append($node);
 }
Example #19
0
 /**
  * @param string $expression
  * @return ParseInput
  */
 public static function lex($expression, $vars)
 {
     $lexer = new RegexLexer(true, 'i');
     $lexer->is = 'is';
     $lexer->not = 'not';
     $lexer->bool = 'true|false';
     $lexer->null = 'null';
     $lexer->operator = 'like|in|!=|<>|>=|<=|!<|!>|=|<|>|and|or';
     $lexer->dot = '\\.';
     $lexer->name = '[a-z][a-z0-9]*';
     $lexer->model = '\\{(.+?)\\}';
     $lexer->modelPlaceholder = '%(model|m)';
     $lexer->field = '\\[(.+?)\\]';
     $lexer->fieldPlaceholder = '%(column|field|c)';
     $lexer->number = '-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?';
     $lexer->string = '"((?:[^"\\\\]|\\\\.)*)"';
     $lexer->placeholder = '((\\?)|%([a-z_\\\\]+))(\\(\\))?';
     $lexer->map('model', function ($value, $matches) {
         return $matches[1];
     });
     $lexer->map('field', function ($value, $matches) {
         return $matches[1];
     });
     $lexer->map('number', function ($value) {
         if (strpos($value, '.') !== false or stripos($value, 'e') !== false) {
             return new Literal(DataType::float(), floatval($value));
         } else {
             return new Literal(DataType::integer(), intval($value));
         }
     });
     $lexer->mapType('number', 'literal');
     $lexer->map('string', function ($value, $matches) {
         return new Literal(DataType::text(), stripslashes($matches[1]));
     });
     $lexer->mapType('string', 'literal');
     $lexer->map('bool', function ($value) {
         return new Literal(DataType::boolean(), strtolower($value) == 'true');
     });
     $lexer->mapType('bool', 'literal');
     $lexer->map('model', function ($value, $matches) {
         return $matches[1];
     });
     $lexer->map('field', function ($value, $matches) {
         return $matches[1];
     });
     $i = 0;
     $lexer->map('modelPlaceholder', function ($value, $matches) use(&$i, $vars) {
         $value = $vars[$i];
         $i++;
         if (!is_string($value)) {
             assume($value instanceof Model);
             $value = $value->getName();
         }
         return $value;
     });
     $lexer->mapType('modelPlaceholder', 'model');
     $lexer->map('fieldPlaceholder', function ($value, $matches) use(&$i, $vars) {
         $value = $vars[$i];
         $i++;
         assume(is_string($value));
         return $value;
     });
     $lexer->mapType('fieldPlaceholder', 'field');
     $lexer->map('placeholder', function ($value, $matches) use(&$i, $vars) {
         $value = $vars[$i];
         $i++;
         $type = null;
         if (isset($matches[3])) {
             if ($matches[3] == '_') {
                 if (!is_string($value)) {
                     assume($value instanceof DataType);
                     $value = $value->placeholder;
                 }
                 $matches[3] = ltrim($value, '%');
                 $value = $vars[$i];
                 $i++;
             }
             if ($matches[3] == 'e' or $matches[3] == 'expr' or $matches[3] == 'expression') {
                 assume($value instanceof Expression);
                 return $value;
             }
             if ($matches[3] != '()') {
                 $type = DataType::fromPlaceholder($matches[3]);
             }
         }
         if (!isset($type)) {
             $type = DataType::detectType($value);
         }
         if (isset($matches[4]) or isset($matches[3]) and $matches[3] == '()') {
             assume(is_array($value));
             foreach ($value as $key => $v) {
                 $value[$key] = $v;
             }
             return new ArrayLiteral($type, $value);
         }
         return new Literal($type, $value);
     });
     $lexer->mapType('placeholder', 'literal');
     return new ParseInput($lexer($expression));
 }
Example #20
0
 /**
  * Construct SHA-256 password hasher.
  * @param int $rounds Number of rounds for SHA-512 algorithm.
  */
 public function __construct($rounds = 5000)
 {
     assume($rounds >= 1000 and $rounds <= 999999999);
     $this->prefix = '$5$rounds=' . $rounds . '$';
     parent::__construct();
 }
Example #21
0
 /**
  * Apply filtering to a selection or an array of records.
  * @param BasicSelection|BasicRecord[] $selection Selection or array of records.
  * @param BasicModel $model Model (must be set if using {@see BasicSelection}
  * for the first parameter).
  * @return BasicSelection|BasicRecord[] Filtered selection or array of records.
  */
 public function apply($selection, BasicModel $model = null)
 {
     if (!isset($this->query) or empty($this->query)) {
         return $selection;
     }
     if (!isset($this->scanner)) {
         $this->scanner = new FilterScanner();
         if ($this->localizedOperators) {
             $this->addLocalizedOperators();
         }
     }
     if (!isset($this->parser)) {
         $this->parser = new FilterParser();
     }
     $tokens = $this->scanner->scan($this->query);
     if (count($tokens) == 0) {
         return $selection;
     }
     $root = $this->parser->parse($tokens);
     if ($selection instanceof BasicSelection) {
         if (!isset($model)) {
             assume($selection instanceof Model);
             $model = $selection;
         }
         $visitor = new SelectionFilterVisitor($this, $model);
         $selection = $selection->where($visitor->visit($root));
         return $selection;
     } else {
         $result = array();
         $visitor = new RecordFilterVisitor($this);
         foreach ($selection as $record) {
             $visitor->setRecord($record);
             if ($visitor->visit($root)) {
                 $result[] = $record;
             }
         }
         return $result;
     }
 }
Example #22
0
 /**
  * Construct Blowfish password hasher.
  * @param int $cost A number between 4 and 31 that sets the cost of the hash
  * computation. 
  */
 public function __construct($cost = 10)
 {
     assume($cost >= 4 and $cost <= 31);
     $this->prefix = sprintf('$2a$%02d$', $cost);
     parent::__construct();
 }
Example #23
0
 /**
  * Append a step. If the name of the step is 'step' and a method with the
  * name 'undoStep' exists, $undoable is set to true.
  * @param string $name Name of step and method.
  * @param string $undoable Whether or not step is undoable.
  */
 public function appendStep($name, $undoable = false)
 {
     assume(is_callable(array($this, $name)));
     $undo = array($this, 'undo' . ucfirst($name));
     if (!method_exists($this, $undo[1])) {
         if ($undoable) {
             $undo = true;
         } else {
             $undo = null;
         }
     }
     $step = new InstallerStep();
     $step->do = array($this, $name);
     $step->undo = $undo;
     $step->name = $name;
     $last = $this->getLast();
     if (isset($last)) {
         $step->previous = $this->getLast();
         $last->next = $step;
     }
     $this->steps[$name] = $step;
 }
Example #24
0
File: E.php Project: jivoo/jivoo
 /**
  * Substitute and encode variables in an expression.
  * 
  * Placeholders (see also {@see DataType::fromPlaceHolder()}:
  * <code>
  * true // Boolean true
  * false // Boolean false
  * {AnyModelName} // A model name
  * [anyFieldName] // A column/field name
  * "any string" // A string
  * ? // Any scalar value.
  * %e %expr %expression // A subexpression (instance of {@see Expression})
  * %m %model // A table/model object or name
  * %c %column %field // A column/field name
  * %_ // A placeholder placeholder, can also be a type, e.g. where(..., 'id = %_', $type, $value)
  * %i %int %integer // An integer value
  * %f %float // A floating point value
  * %s %str %string // A string
  * %t $text // Text
  * %b %bool %boolean // A boolean value
  * %date // A date value
  * %d %datetime // A date/time value
  * %n %bin %binary // A binary object
  * %AnyEnumClassName // An enum value of that class
  * %anyPlaceholder() // A tuple of values
  * </code>
  * 
  * @param string|Condition $format Expression format, use placeholders instead of values.
  * @param mixed[] $vars List of values to replace placeholders with.
  * @param Quoter $quoter Quoter object for quoting identifieres and literals.
  * @return string The interpolated expression.
  */
 public static function interpolate($format, $vars, Quoter $quoter)
 {
     if ($format instanceof self) {
         return $format->toString($quoter);
     }
     assume(is_string($format));
     $boolean = DataType::boolean();
     $true = $quoter->quoteLiteral($boolean, true);
     $false = $quoter->quoteLiteral($boolean, false);
     $format = preg_replace('/\\btrue\\b/i', $true, $format);
     $format = preg_replace('/\\bfalse\\b/i', $false, $format);
     $string = DataType::text();
     $format = preg_replace_callback('/"((?:[^"\\\\]|\\\\.)*)"|\\{(.+?)\\}|\\[(.+?)\\]/', function ($matches) use($quoter, $string) {
         if (isset($matches[3])) {
             return $quoter->quoteField($matches[3]);
         } else {
             if (isset($matches[2])) {
                 return $quoter->quoteModel($matches[2]);
             } else {
                 return $quoter->quoteLiteral($string, stripslashes($matches[1]));
             }
         }
     }, $format);
     $i = 0;
     return preg_replace_callback('/((\\?)|%([a-z_\\\\]+))(\\(\\))?/i', function ($matches) use($vars, &$i, $quoter) {
         $value = $vars[$i];
         $i++;
         $type = null;
         if (isset($matches[3])) {
             if ($matches[3] == '_') {
                 if (!is_string($value)) {
                     assume($value instanceof DataType);
                     $value = $value->placeholder;
                 }
                 $matches[3] = ltrim($value, '%');
                 $value = $vars[$i];
                 $i++;
             }
             if ($matches[3] == 'e' or $matches[3] == 'expr' or $matches[3] == 'expression') {
                 assume($value instanceof Expression);
                 return '(' . $value->toString($quoter) . ')';
             }
             if ($matches[3] == 'm' or $matches[3] == 'model') {
                 if (!is_string($value)) {
                     assume($value instanceof Model);
                     $value = $value->getName();
                 }
                 return $quoter->quoteModel($value);
             }
             if ($matches[3] == 'c' or $matches[3] == 'column' or $matches[3] == 'field') {
                 assume(is_string($value));
                 return $quoter->quoteField($value);
             }
             if ($matches[3] != '()') {
                 $type = DataType::fromPlaceholder($matches[3]);
             }
         }
         if (!isset($type)) {
             $type = DataType::detectType($value);
         }
         if (isset($matches[4]) or isset($matches[3]) and $matches[3] == '()') {
             assume(is_array($value));
             foreach ($value as $key => $v) {
                 $value[$key] = $quoter->quoteLiteral($type, $v);
             }
             return '(' . implode(', ', $value) . ')';
         }
         return $quoter->quoteLiteral($type, $value);
     }, $format);
 }
Example #25
0
 /**
  * Converts expiration timestamp, interval, {\DateInterval} or {\DateTime}
  * to a {\DateTime} or null (for no expiration date).
  * @param int|\DateInterval|\DateTime|null $expiration Timestamp or interval.
  * Null and the integer 0 is interpreted as 'no expiration date'. 
  * If the integer is less than or equal to 2,592,000 (30 days), the time
  * is relative to the current timestamp, otherwise it is interpreted as an
  * absolute UNIX timestamp. 
  * @return \DateTime|null
  */
 public static function convertExpiration($expiration)
 {
     if ($expiration === null or $expiration === 0) {
         return null;
     }
     if (is_int($expiration)) {
         if ($expiration <= 2592000) {
             $expiration += time();
         }
         return \DateTime::createFromFormat('U', $expiration);
     }
     if ($expiration instanceof \DateTime) {
         return $expiration;
     }
     assume($expiration instanceof \DateInterval);
     $d = new \DateTime();
     return $d->add($expiration);
 }
Example #26
0
 /**
  * {@inheritdoc}
  */
 public function get()
 {
     $o = $this->object;
     assume($o->model instanceof BasicModel);
     if ($o->model instanceof Model) {
         if ($o->selection instanceof ObjectMacro) {
             $o->selection = $o->selection->playMacro($o->model);
         } else {
             if (!$o->selection instanceof BasicSelection) {
                 $o->selection = $o->model;
             }
         }
         if (!isset($o->primaryKey)) {
             $o->primaryKey = $o->model->getAiPrimaryKey();
         }
         // TODO: more general?
     }
     if (count($o->columns) == 0) {
         foreach ($o->model->getFields() as $field) {
             $o->columns->appendNew($o->model->getLabel($field), $field);
         }
         $o->columns->objectAt(0)->primary = true;
     }
     $o->selection = $this->Filtering->apply($o->selection, $o->model);
     if (count($o->sortOptions) == 0) {
         $o->sortOptions = $o->columns;
     }
     $sortBy = $o->sortOptions->find(function ($column) {
         return $column->default;
     });
     if (!isset($sortBy)) {
         $sortBy = $o->sortOptions->objectAt(0);
     }
     if (isset($this->request->query['sortBy'])) {
         $field = $this->request->query['sortBy'];
         $sortBy2 = $o->sortOptions->find(function ($column) use($field) {
             return $column->field === $field;
         });
         if (isset($sortBy2)) {
             $sortBy = $sortBy2;
         }
     }
     $sortBy->selected = true;
     if (isset($this->request->query['order'])) {
         $sortBy->descending = $this->request->query['order'] == 'desc';
     }
     $o->sortBy = $sortBy;
     if ($o->selection instanceof BasicSelection) {
         if ($sortBy->descending) {
             $o->selection = $o->selection->orderByDescending($sortBy->field);
         } else {
             $o->selection = $o->selection->orderBy($sortBy->field);
         }
     } else {
         assume(is_array($o->selection));
         $records = $o->selection;
         usort($records, array($this, 'compareRecords'));
         $o->selection = $records;
     }
     $o->selection = $this->Pagination->paginate($o->selection, $o->rowsPerPage);
     return $this->render();
 }
Example #27
0
 /**
  * Prepare selection, e.g. by joining with join table.
  * @param BasicSelection $selection Input selection or null for source.
  * @return ReadSelection Resulting selection.
  */
 private function prepareSelection(BasicSelection $selection = null)
 {
     if (!isset($selection)) {
         return $this->source;
     }
     $selection->alias($this->alias);
     if (isset($this->join)) {
         assume($selection instanceof ReadSelection);
         $selection = $selection->leftJoin($this->join, $this->otherPrimary . '= J.' . $this->otherKey, 'J')->where('J.' . $this->thisKey . ' = ?', $this->recordId);
     } else {
         $selection = $selection->where($this->thisKey . ' = ?', $this->recordId);
         if ($selection instanceof SelectionBuilder) {
             $selection = $selection->toReadSelection();
         }
     }
     if (isset($this->condition)) {
         $selection = $selection->where($this->condition);
     }
     return $selection;
 }
Example #28
0
 /**
  * Create notification.
  * @param string $type Notification type, e.g. 'error' or 'success'.
  * @param string[] $parameters An array containing the notification message.
  */
 public function __call($type, $parameters)
 {
     assume(isset($parameters[0]));
     Assume::isString($parameters[0]);
     $this->__set($type, $parameters[0]);
 }
Example #29
0
 /**
  * {@inheritdoc}
  */
 public function load(Autoloader $autoloader)
 {
     if (!isset($this->manifest['autoload']) or !is_array($this->manifest['autoload'])) {
         return;
     }
     if (isset($this->manifest['autoload']['psr-4'])) {
         assume(is_array($this->manifest['autoload']['psr-4']));
         foreach ($this->manifest['autoload']['psr-4'] as $namespace => $path) {
             if (is_array($path)) {
                 foreach ($path as $p) {
                     $autoloader->addPath($namespace, $this->path . '/' . trim($p, '/'));
                 }
             } else {
                 $autoloader->addPath($namespace, $this->path . '/' . trim($path, '/'));
             }
         }
     }
     if (isset($this->manifest['autoload']['psr-0'])) {
         assume(is_array($this->manifest['autoload']['psr-0']));
         foreach ($this->manifest['autoload']['psr-0'] as $namespace => $path) {
             if (is_array($path)) {
                 foreach ($path as $p) {
                     $autoloader->addPath($namespace, $this->path . '/' . trim($p, '/'), false, true);
                 }
             } else {
                 $autoloader->addPath($namespace, $this->path . '/' . trim($path, '/'), false, true);
             }
         }
     }
     if (isset($this->manifest['autoload']['classmap'])) {
         assume(false, 'classmap support not implemented');
     }
     if (isset($this->manifest['autoload']['files'])) {
         assume(is_array($this->manifest['autoload']['files']));
         foreach ($this->manifest['autoload']['files'] as $file) {
             require $this->path . '/' . $file;
         }
     }
 }