public static function register($data) { static::$error = false; $user = new static(); if (!$user->set($data)->success()) { static::$error = 'REGISTER_VALIDATION_FALSE'; return false; } $login = isset($data[static::ROW_LOGIN]) ? $data[static::ROW_LOGIN] : ''; if (!$login) { static::$error = 'REGISTER_NO_LOGIN'; return false; } $found = static::findBy(static::ROW_LOGIN, $login)->getFirst(); if ($found) { static::$error = 'REGISTER_DUBLICATE_USER'; return false; } $password = isset($data[static::ROW_PASSWORD]) ? $data[static::ROW_PASSWORD] : ''; if (!$password) { static::$error = 'REGISTER_NO_PASSWORD'; return false; } $user->{static::ROW_HASH_RESTORE} = static::makeHash(); $user->save(); return $user; }
/** * Create and save a new item * @param array $data * @return Comment */ public static function create(array $data) { $item = new static(); // Check required fields foreach (self::$requiredFields as $field) { if (!isset($data[$field])) { throw new Exception("Required field {$field} not specified."); } } // Set field values foreach ($data as $key => $val) { if ($item->exists($key)) { if (empty($val)) { $val = null; } $item->set($key, $val); } } // Set auto values if they exist if ($item->exists("created_date") && !isset($data["created_date"])) { $item->set("created_date", date("Y-m-d H:i:s")); } $item->save(); return $item; }
/** * After controller finished all logic, render view */ public function __destruct() { if (false === $this->render) { return true; } if (is_null($this->template)) { $this->template = $this->templateFromRoute(); } $this->f3->set('content', $this->template); echo \Template::instance()->render('layout.xhtml'); }
public static function trash($document) { if ($document instanceof \Dsc\Mongo\Collection) { $trash = new static(); $trash->set('instanceof', (string) get_class($document)); $trash->set('collection', $document->collectionName()); $trash->set('document', $document->cast()); if (!empty($document->type)) { $trash->set('type', $document->type); } $trash->save(); } else { //do something else if we are not using a mapper } }
/** * @param array $data * @return static */ public static function fromArray(array $data) { $out = new static(); foreach ($data as $key => $value) { $out->set($out::deserializeKey($key), $out::deserializeValue($value)); } return $out; }
/** * @param array $config * * @return configuration */ public static function unserialize(array $config) { $configuration = new static(); if (false !== ($clientConfiguration = unserialize($config['watched_files']))) { $configuration->set($clientConfiguration); } return $configuration; }
/** * Creates an instance * * @param array $fields Initialize with fields values * @return static */ public static function create($fields = []) { $record = new static(self::getLoader()->getFieldsDefinition(get_called_class())); if (!empty($fields) && is_array($fields)) { $record->set($fields); } return $record; }
/** * 作成する */ public static function create($flg = 0) { $hash = new static($flg); for ($i = 1; $i < func_num_args(); $i++) { $hash->set(func_get_arg($i)); } return $hash; }
/** * Create a Map. * * @param mixed $element,... Elements to include in the collection. * * @return Map */ public static function create() { $map = new static(); foreach (func_get_args() as $element) { list($key, $value) = $element; $map->set($key, $value); } return $map; }
/** * Constructs entity from array. * * @param array $input * @return \Paybox\Entity */ public static function fromArray($input) { $entity = new static(); if (is_array($input)) { foreach ($input as $name => $value) { $entity->set($name, $value); } } return $entity; }
/** * Set configuration namespace * * @param string $namespace * @param mixed $value * @return void */ public function __set($namespace, $value) { $bag = new static(); $this->namespaces[$namespace] = $bag; if (is_array($value)) { $bag->set($value, null); } elseif (is_string($value)) { $bag->loadDir($value); } }
/** * return AuthorizeOptionsQueryString */ public static function fromAuthorizeOptions(AuthorizeOptions $options) { $q = new static(); $q->set('type', $options->getType()); $via = $options->getVia(); if ($via) { $q->set('via', $via); } if ($options->getSkipConfirmation()) { $q->set('skipConfirmation', 'true'); } if ($options->getSkipAuthorization()) { $q->set('skipAuthorization', 'true'); } $lang = $options->getLang(); if ($lang) { $q->set('lang', $lang); } return $q; }
public static function add($message, $priority = 'INFO', $category = 'General') { $model = new static(); $model->created = \Dsc\Mongo\Metastamp::getDate('now'); $model->set('created.microtime', microtime(true)); $model->priority = $priority; $model->category = $category; $model->message = $message; $model->store(); return $model; }
/** * shortcut function * * @param string cachekey * @param callback * @return mixed */ public static function invoke($cache_key, $callback = null, $namespace = '_global_') { $cache = new static($namespace); if ($cache->has($cache_key)) { return $cache->get($cache_key); } if (is_callable($callback)) { $value = $callback(); $cache->set($cache_key, $value); return $value; } return null; }
/** * * @param array $resource * @param string $action * @param string $diff * @param array $actor * @param string $message * @param string $priority * @param string $category * * @return \Dsc\Mongo\Collections\AuditLogs */ public static function add($resource, $action, $diff, $actor, $message = null, $priority = 'INFO', $category = 'Audit') { $model = new static(); $model->created = \Dsc\Mongo\Metastamp::getDate('now'); $model->set('created.microtime', microtime(true)); $model->priority = $priority; $model->category = $category; $model->message = $message; $model->resource_type = !empty($resource['type']) ? $resource['type'] : null; $model->resource_id = !empty($resource['id']) ? $resource['id'] : null; $model->action = $action; $model->diff = $diff; $model->actor_type = !empty($actor['type']) ? $actor['type'] : null; $model->actor_id = !empty($actor['id']) ? $actor['id'] : null; $model->actor_name = !empty($actor['name']) ? $actor['name'] : null; $model->store(); return $model; }
/** * @return array * @throws Exception */ public static function findAll() { $pdo = self::getPdo(); $tableName = self::tableName(); $statement = $pdo->prepare("SELECT * FROM {$tableName}"); Application::getInstance()->logger->d('ACTIVE RECORD', 'Find all records.'); if (!$statement->execute()) { $errorInfo = $statement->errorInfo(); throw new Exception("PDO [{$errorInfo[0]}]: {$errorInfo[2]}."); } $activeRecords = []; while ($record = $statement->fetch(\PDO::FETCH_ASSOC)) { $activeRecord = new static(); foreach ($record as $name => $value) { $activeRecord->set($name, $value); } $activeRecords[] = $activeRecord; } return $activeRecords; }
/** * Gets the asset id for the object instance * * @return int * @since 2.0.0 **/ public function getId() { // Check for current asset id and compute other vars $current = $this->model->get('asset_id', null); $parentId = $this->getAssetParentId(); $name = $this->getAssetName(); $title = $this->getAssetTitle(); // Get joomla jtable model for assets $asset = \JTable::getInstance('Asset', 'JTable', array('dbo' => \App::get('db'))); $asset->loadByName($name); // Re-inject the asset id into the model $this->model->set('asset_id', $asset->id); if ($asset->getError()) { return false; } // Specify how a new or moved node asset is inserted into the tree if (!$this->model->get('asset_id', null) || $asset->parent_id != $parentId) { $asset->setLocation($parentId, 'last-child'); } // Prepare the asset to be stored $asset->parent_id = $parentId; $asset->name = $name; $asset->title = $title; if ($this->model->assetRules instanceof \JAccessRules) { $asset->rules = (string) $this->model->assetRules; } if (!$asset->check() || !$asset->store()) { return false; } // Register an event to update the asset name once we know the model id if ($this->model->isNew()) { $me = $this; Event::listen(function ($event) use($asset, $me) { $asset->name = $me->getAssetName(); $asset->store(); }, $this->model->getTableName() . '_new'); } // Return the id return (int) $asset->id; }
/** * Returns all the items of this collection that satisfy the predicate p. * The order of the items is preserved. * If no predicate, all items that equal false will be removed. * * @param callable|null $p The predicate used for filtering. Function can be passed value, key, or key/value. * * @return static A collection with the results of the filter operation. */ public function filter($p) { if ($p === null) { return new static(array_filter($this->items)); } $func = new \ReflectionFunction($p); $params = $func->getParameters(); if (count($params) === 1 && $params[0]->getName() !== 'key') { return new static(array_filter($this->items, $p)); } $newItems = new static(); foreach ($this->items as $key => $value) { if ($p($key, $value)) { $newItems->set($key, $value); } } return $newItems; }
/** * Creates collection of items. * * Override it if you need to implement * derived collection that requires specific initialization. * * @param array $items * * @return static */ protected function createCollection(array $items) { $collection = new static(); $collection->set($items); return $collection; }
/** * @param callable(key:mixed,value:mixed):bool $callback * @return static */ public function filter($callback) { $this->assertCallback($callback); $map = new static(); foreach ($this->mapArray as $key => $value) { if ($callback($key, $value)) { $map->set($key, $value); } } return $map; }
/** * Sets the `Etag` header */ public static function setEtag($value) { if (!Header::isSent()) { $header = new static("Etag", $value); $header->set(); return $header; } return false; }
/** * @param callable $callable * @return MapInterface */ public function map(callable $callable) { $newMap = new static(); foreach ($this->elements as $k => $e) { $newMap->set($k, $callable($k, $e)); } return $newMap; }
/** * Get all items, except given keys * * @param array $keys * @return array */ public function except($keys, $result_array = false) { $keys = (array) $keys; $bag = new static(); foreach ($this->all(false) as $key => $value) { $key = $this->resolveKey($key); $bag->set($key, $value); } foreach ($keys as $key) { $key = $this->resolveKey($key); $bag->remove($key); } return $result_array ? $bag->all() : $bag; }
/** * Create a new log entry * @param string $type log type - create, update or delete * @param object $obj1 object changed, created or deleted * @param object $obj2 new object with changed values, only required for update type, must be the same object as $obj1 * @param array $exclude Attributes from an update that are not being updated * @param string $user created_by field, default to self::$user * @param integer $userID user_id field, default to self::$userID * @param string $ip IP address of request * @return boolean */ public static function _Log($type, $obj1, $obj2 = FALSE, $exclude = array(), $user = FALSE, $userID = 0, $ip = FALSE) { // Set user if (!$user) { $user = static::$user; } if (!$userID) { $userID = static::$userID; } // Check object is a model object if (!$obj1 instanceof \Sonic\Model) { new \Sonic\Message('error', 'Cannot create changelog - object must extend \\Sonic\\Model'); return FALSE; } // Create new log object $log = new static(); // Set log variables try { $log->set('name', get_class($obj1)); $log->set('type', $type); $log->set('created_by', $user); $log->set('object_id', $obj1->get($obj1::$pk)); $log->set('user_id', $userID); // Log IP // If an IP is specified use that otherwise // check for Client-IP header before using REMOTE_ADDR // This gets around the netscaler reverse-proxy with the additional host header if ($ip) { $log->set('ip', $ip); } else { if (isset($_SERVER['HTTP_CLIENT_IP'])) { $log->set('ip', $_SERVER['HTTP_CLIENT_IP']); } else { if (isset($_SERVER['REMOTE_ADDR'])) { $log->set('ip', $_SERVER['REMOTE_ADDR']); } } } } catch (\Exception $e) { new \Sonic\Message('error', 'Error setting changelog attributes - ' . $e->getMessage()); return FALSE; } // Begin transaction $log->db->beginTransaction(); // Create log entry if (!$log->Create()) { new \Sonic\Message('error', $e->getMessage()); $log->db->rollBack(); return FALSE; } // Set column class to log class\Column $column_class = get_class($log) . '\\Column'; $oldValueAttr = $column_class::_attributeProperties('old_value'); $newValueAttr = $column_class::_attributeProperties('new_value'); // Switch log type to create columns try { switch ($type) { // Create case 'create': // Log object attributes foreach ($obj1->toArray() as $name => $val) { if (isset($newValueAttr['max']) && strlen((string) $val) > $newValueAttr['max']) { $val = substr((string) $val, 0, $newValueAttr['max']); } $column = new $column_class(); $column->set('change_log_id', $log->get('id')); $column->set('name', $name); $column->set('new_value', $val); if (!$column->Create()) { new \Sonic\Message('error', 'Error creating changelog column - ' . $e->getMessage()); $log->db->rollBack(); return FALSE; } } break; // Update // Update case 'update': // Check objects are the same class if (get_class($obj1) != get_class($obj2)) { new \Sonic\Message('error', 'Cannot create changelog - objects must be the same class. obj1: ' . get_class($obj1) . ', obj2: ' . get_class($obj2)); $log->db->rollBack(); return FALSE; } // Get updated attributes $arrNew = $obj2->toArray(); // Remove any that are excluded foreach ($exclude as $attr) { unset($arrNew[$attr]); } // Log object attributes foreach ($arrNew as $name => $val) { $originalVal = $obj1->get($name); if (isset($oldValueAttr['max']) && strlen($originalVal) > $oldValueAttr['max']) { $originalVal = substr($originalVal, 0, $oldValueAttr['max']); } if (isset($newValueAttr['max']) && strlen($val) > $newValueAttr['max']) { $val = substr($val, 0, $newValueAttr['max']); } if ($val !== $originalVal) { $column = new $column_class(); $column->set('change_log_id', $log->get('id')); $column->set('name', $name); $column->set('old_value', $originalVal); $column->set('new_value', $val); if (!$column->Create()) { new \Sonic\Message('error', 'Error creating changelog column - ' . $e->getMessage()); $log->db->rollBack(); return FALSE; } } } break; // Delete // Delete case 'delete': // Log object attributes foreach ($obj1->toArray() as $name => $val) { if (isset($oldValueAttr['max']) && strlen($val) > $oldValueAttr['max']) { $val = substr($val, 0, $oldValueAttr['max']); } $column = new $column_class(); $column->set('change_log_id', $log->get('id')); $column->set('name', $name); $column->set('old_value', $val); if (!$column->Create()) { new \Sonic\Message('error', 'Error creating changelog column - ' . $e->getMessage()); $log->db->rollBack(); return FALSE; } } break; // Catch anything else // Catch anything else default: // Error new \Sonic\Message('error', 'Cannot create changelog - invalid log type: ' . $type); $log->db->rollBack(); return FALSE; break; } } catch (\Exception $e) { new \Sonic\Message('error', 'Exception creating changelog column - ' . $e->getMessage()); $log->db->rollBack(); return FALSE; } // Set last ID self::$_lastID = $log->get('id'); // Commit and return TRUE $log->db->commit(); return TRUE; }
/** * Will convert an array of data from mongo to a Mongo instance object * Will also convert any DBRefs to instances of their objects * @param array $data * @return Mongo */ protected static function createObjectFromDataArray($data = array()) { // we'll loop here because we don't want $data to be filtered (as this // has come from the database) $obj = new static(); foreach ($data as $key => $value) { // $obj->$key = $value; $obj->set($key, $value, false); } return $obj; }
/** * Returns beginning or ending of a period * * @param string $phrase * @param bool $beginning True for boundary beginning, False for boundary ending * * @throws \Exception if $beginning=false * * @return self */ public function getBoundaryDateByPeriod($period, $beginning = true) { $this_timestamp = $this->get(); switch ($period) { case static::DATE_PERIOD_DAY: if ($beginning) { // get the beginning of the day $result_ts = strtotime('today', $this_timestamp); } else { throw new \Exception('Bounday ending not yet supported'); } break; case static::DATE_PERIOD_WEEKTODATE: if ($beginning) { // get date of the first day in week from '2012-W12-1' $result_ts = strtotime(date("Y-\\WW-1", $this_timestamp)); } else { throw new \Exception('Bounday ending not yet supported'); } break; case static::DATE_PERIOD_MONTHTODATE: if ($beginning) { // get beginning of month $result_ts = strtotime(sprintf('%s %s', date('M', $this_timestamp), date('Y', $this_timestamp))); break; } else { throw new \Exception('Bounday ending not yet supported'); } case static::DATE_PERIOD_YEARTODATE: if ($beginning) { // get beginning of year $result_ts = mktime(0, 0, 0, 1, 1, date('Y', $this_timestamp)); break; } else { throw new \Exception('Bounday ending not yet supported'); } default: // if period not recognized, // throw exception throw new \Exception('Period not recognized'); } // switch if ($result_ts) { $result_date = new static(); $result_date->set($result_ts); return $result_date; } }
/** * Sets up the environment * * @return void */ static function setup() { if (!static::$set) { assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_QUIET_EVAL, 1); assert_options(ASSERT_WARNING, 0); register_shutdown_function(function () { $time = \Tracy\Debugger::timer(static::NAME); static::printLine(""); static::printLine("Total run time: {$time} second(s)"); }); \Tracy\Debugger::timer(static::NAME); static::$mode = PHP_SAPI == "cli" ? "cli" : "http"; static::$set = true; } else { static::printLine("Warning: Testing Environment was already set up."); } }
/** * Partitions this collection in two collections according to a predicate. * Keys are preserved in the resulting collections. * * @param Closure $p The predicate on which to partition. * * @return array An array with two elements. The first element contains the collection * of elements where the predicate returned TRUE, the second element * contains the collection of elements where the predicate returned FALSE. */ public function partition(Closure $p) { $trueColl = new static(); $falseColl = new static(); iterator_apply($this, function () use($p, $trueColl, $falseColl) { $key = $this->key(); $current = $this->current(); if ($p($current, $key)) { $trueColl->set($key, $current); } else { $falseColl->set($key, $current); } return true; }); return array($trueColl, $falseColl); }
/** * Factory method to construct a new document using the values passed to populate it * * @throws ClientException * * @param array $values - initial values for document * @param array $options - optional, initial options for document * * @return Document|Edge */ public static function createFromArray(array $values, array $options = array()) { $document = new static($options); foreach ($values as $key => $value) { $document->set($key, $value); } $document->setChanged(true); return $document; }
/** * Instantiates a new record or document object, initialized with any data passed in. * * ### Example * * {{{ * $user = User::create(array("username" => "Jhon")); * echo $user->username; // echoes "Jhon" * $success = $user->save(); * }}} * * @param array $data set of fields to be passed to the set() function * @return CakeDocument new instance of object with initialized data */ public static function create($data = null) { $document = new static(); if ($data) { $document->set($data); } return $document; }