Example #1
7
 /**
  * @return \Illuminate\Database\Eloquent\Builder
  */
 public static function withoutOrders()
 {
     $instance = new static();
     $query = $instance->newQuery();
     $query->getQuery()->orders = [];
     return $query;
 }
 /**
  * Retrieves all Hail Api Object of a specific type
  *
  * @return void
  */
 public static function fetch()
 {
     try {
         $list = HailApi::getList(static::getObjectType());
     } catch (HailApiException $ex) {
         Debug::warningHandler(E_WARNING, $ex->getMessage(), $ex->getFile(), $ex->getLine(), $ex->getTrace());
         die($ex->getMessage());
         return;
     }
     $hailIdList = array();
     foreach ($list as $hailData) {
         // Check if we can find an existing item.
         $hailObj = static::get()->filter(array('HailID' => $hailData->id))->First();
         if (!$hailObj) {
             $hailObj = new static();
         }
         $result = $hailObj->importHailData($hailData);
         if ($result) {
             //Build up Hail ID list
             $hailIdList[] = $hailData->id;
         }
     }
     //Remove all object for which we don't have reference
     static::get()->exclude('HailID', $hailIdList)->removeAll();
 }
 /**
  * @param $key
  * @param $value
  *
  * @return static
  */
 public static function build($key, $value)
 {
     $EnvironmentVariable = new static();
     $EnvironmentVariable->setKey($key);
     $EnvironmentVariable->setValue($value);
     return $EnvironmentVariable;
 }
 /**
  * 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();
     $itemsRef =& $collection->items();
     $itemsRef = $items;
     return $collection;
 }
Example #5
1
 /**
  * Get instance 
  *
  * @return static
  */
 public static function getInstance()
 {
     if (!static::$instance instanceof static) {
         static::$instance = new static();
     }
     return static::$instance->getConnection();
 }
Example #6
1
 /**
  * 
  * @param type $array
  * @param type $throw
  * @return \storm\actions\IntentPayload
  */
 public static function simpleInvoke($array = [], $throw = true)
 {
     $action = new static();
     $payload = new IntentPayload($array);
     $action->invoke($payload, $throw);
     return $payload;
 }
Example #7
1
 /**
  * Remove any instance of the facet from the parameters and add a new one.
  *
  * @param string $field    Facet field
  * @param string $value    Facet value
  * @param string $operator Facet type to add (AND, OR, NOT)
  *
  * @return string
  */
 public function replaceFacet($field, $value, $operator = 'AND')
 {
     $newParams = clone $this->params;
     $newParams->removeAllFilters($field);
     $helper = new static($newParams);
     return $helper->addFacet($field, $value, $operator);
 }
Example #8
1
 /**
  * Handle dynamic static method calls into the method.
  *
  * @param  string $method
  * @param  array $parameters
  * @return mixed
  */
 public static function __callStatic($method, $parameters)
 {
     $instance = new static();
     $class = get_class($instance->getModel());
     $model = new $class();
     return call_user_func_array([$model, $method], $parameters);
 }
Example #9
1
 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;
 }
Example #10
1
 /**
  * Queries the table for the given primary key value ($id).  $id can also
  * contain 2 special values:
  *
  * <ul>
  * <li>'all' - Will return all of the records in the table</li>
  * <li>'first' - Will return the first record.  This will set automatically
  * set the 'limit' option to 1.</li>
  * </ul>
  *
  * The following options are available to use in the $options parameter:
  *
  * <ul>
  * <li>include - an array of associations to include in the query.  Example:
  * <code>array('group', 'posts')</code></li>
  * <li>select - an array of columns to select (defaults to '*').  Example:
  * <code>array('first_name', 'last_name')</code></li>
  * <li>limit - the maximum number of records to fetch</li>
  * <li>offset - the offset to start from</li>
  * <li>order - an array containing the ORDER BY clause.  Example:
  * <code>array('last_name', 'ASC')</code></li>
  * <li>where - an array of arrays containing the where clauses.  Example:
  * <code>array(array('enabled', '=', 1), array('blacklisted', '=', 0))</code>
  * <li>or_where - identical to 'where' except these are OR WHERE statements.</li>
  *
  * Usage:
  *
  * <code>$user = User::find(2, array('include' => array('group')));</code>
  *
  * @param	int|string	$id			the primary key value
  * @param	srray		$options	the find options
  * @return	object		the result
  */
 public static function find($id = 'all', $options = array())
 {
     $instance = new static();
     $results = $instance->run_find($id, $options);
     unset($instance);
     return $results;
 }
Example #11
1
 /**
  * Creates token
  * @param string $type Type of the token
  * @param string $name Name of the token unique for selected type
  * @param callable|AlgorithmInterface $algorithm Algorithm of the token generation
  * @param int|\DateTime|Expression $expire Expiration date of the token
  * @return static
  */
 public static function create($type, $name, $algorithm = null, $expire = null)
 {
     if ($algorithm === null) {
         $algorithm = new RandomString();
     }
     $token = static::findOne(['type' => $type, 'name' => $name]);
     if ($token == null) {
         $token = new static();
     }
     $token->type = $type;
     $token->name = $name;
     if (is_callable($algorithm)) {
         $token->token = call_user_func($algorithm);
     } else {
         $token->token = $algorithm->generate();
     }
     if (is_integer($expire)) {
         $token->expire_at = \DateTime::createFromFormat('U', $expire, new \DateTimeZone('UTC'))->setTimezone(new \DateTimeZone('MSK'))->format('Y-m-d H:i:s');
     } elseif ($expire instanceof \DateTime) {
         $token->expire_at = $expire->format('Y-m-d h:i:s');
     } else {
         $token->expire_at = $expire;
     }
     $token->created_at = new Expression('NOW()');
     $token->save(false);
     return $token;
 }
 public function createQuestion(Model $questionable, $data, Model $author)
 {
     $question = new static();
     $question->fill(array_merge($data, ['author_id' => $author->id, 'author_type' => get_class($author)]));
     $questionable->questions()->save($question);
     return $question;
 }
 /**
  * Set an API statistic in the DB
  * 
  * @param int $code		The HTTP status code from the request or cache
  * @param string $uri	The dynamic call URL or the static call name
  * @param string $api	The API to set the stats for
  * 
  * @return bool True if the stat was added/updated successfully, or false if it wasn't.
  */
 public static function set_stat($code, $uri, $api = null, $is_static = null)
 {
     // Save queries if we don't need the stats.
     if (\Config::get('engine.track_usage_stats', false) === false) {
         return true;
     }
     $api_name = $api === null ? \V1\APIRequest::get('api') : $api;
     $is_static = $is_static === null ? \V1\APIRequest::is_static() : $is_static;
     $api = \V1\Model\APIs::get_api($api_name);
     // Do we have a stat entry for this timeframe?
     $existing_api_stats_obj = static::query()->where('apis_id', '=', $api['id'])->where('code', '=', (int) $code)->where('call', '=', $uri)->where('created_at', '>', time() - (int) \Config::get('api_stats_increment', 30) * 60)->get_one();
     // If we have a row, update it.
     if (!empty($existing_api_stats_obj)) {
         $existing_api_stats_obj->count++;
         return $existing_api_stats_obj->save();
     }
     // Add the new entry.
     $api_stats_object = new static();
     $api_stats_object->apis_id = $api['id'];
     $api_stats_object->code = $code;
     $api_stats_object->count = 1;
     $api_stats_object->call = $uri;
     $api_stats_object->is_static = intval($is_static);
     return $api_stats_object->save();
 }
Example #14
0
 public static function isColumnNullable($column_name)
 {
     $instance = new static();
     // create an instance of the model to be able to get the table name
     $answer = DB::select(DB::raw("SELECT IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='" . $instance->getTable() . "' AND COLUMN_NAME='" . $column_name . "' AND table_schema='" . env('DB_DATABASE') . "'"))[0];
     return $answer->IS_NULLABLE == 'YES' ? true : false;
 }
Example #15
0
 /**
  * Register the error handler.
  *
  * @param integer $level The level at which the conversion to Exception is done (null to use the error_reporting() value and 0 to disable)
  *
  * @return The registered error handler
  */
 public static function register($level = null)
 {
     $handler = new static();
     $handler->setLevel($level);
     set_error_handler(array($handler, 'handle'));
     return $handler;
 }
Example #16
0
 /**
  * @param array $values
  * @return Folder
  */
 public static function create($values)
 {
     $object = new static();
     $object->setValues($values);
     $object->save();
     return $object;
 }
Example #17
0
 /**
  * Populates headers from string representation
  *
  * Parses a string for headers, and aggregates them, in order, in the
  * current instance, primarily as strings until they are needed (they
  * will be lazy loaded)
  *
  * @param  string $string
  * @param  string $EOL EOL string; defaults to {@link EOL}
  * @throws Exception\RuntimeException
  * @return Headers
  */
 public static function fromString($string, $EOL = self::EOL)
 {
     $headers = new static();
     $currentLine = '';
     // iterate the header lines, some might be continuations
     foreach (explode($EOL, $string) as $line) {
         // check if a header name is present
         if (preg_match('/^(?P<name>[\\x21-\\x39\\x3B-\\x7E]+):.*$/', $line, $matches)) {
             if ($currentLine) {
                 // a header name was present, then store the current complete line
                 $headers->addHeaderLine($currentLine);
             }
             $currentLine = trim($line);
         } elseif (preg_match('/^\\s+.*$/', $line, $matches)) {
             // continuation: append to current line
             $currentLine .= trim($line);
         } elseif (preg_match('/^\\s*$/', $line)) {
             // empty line indicates end of headers
             break;
         } else {
             // Line does not match header format!
             throw new Exception\RuntimeException(sprintf('Line "%s"does not match header format!', $line));
         }
     }
     if ($currentLine) {
         $headers->addHeaderLine($currentLine);
     }
     return $headers;
 }
 /**
  * Calculates total count of query records
  *
  * @param Query|SqlQuery $query
  * @param bool           $useWalker
  *
  * @return integer
  */
 public static function calculateCount($query, $useWalker = null)
 {
     /** @var QueryCountCalculator $instance */
     $instance = new static();
     $instance->setUseWalker($useWalker);
     return $instance->getCount($query);
 }
Example #19
0
 public static function send($viewPath, $data, $callback)
 {
     $config = Bootstrap::get('config');
     $mailer = Bootstrap::get('mailer');
     if (!$mailer) {
         throw new InvalidArgumentException(__t('mail_configuration_no_defined'));
     }
     $DirectusSettingsTableGateway = new \Zend\Db\TableGateway\TableGateway('directus_settings', Bootstrap::get('zendDb'));
     $rowSet = $DirectusSettingsTableGateway->select();
     $settings = [];
     foreach ($rowSet as $setting) {
         $settings[$setting['collection']][$setting['name']] = $setting['value'];
     }
     $instance = new static($mailer, $settings);
     $message = Swift_Message::newInstance();
     // default mail from address
     $mailConfig = $config['mail'];
     $message->setFrom($mailConfig['from']);
     call_user_func($callback, $message);
     if ($message->getBody() == null) {
         // Slim Extras View twig act weird on this version
         $viewContent = $instance->getViewContent($viewPath, $data);
         $message->setBody($viewContent, 'text/html');
     }
     $instance->sendMessage($message);
 }
Example #20
0
 public static function afterTopicInsert($tc)
 {
     $editor = new \app\lib\Editor(['editor' => Yii::$app->params['settings']['editor']]);
     $content = $editor->parse($tc->content);
     $pa = new PhpAnalysis();
     $pa->SetSource($tc->topic->title . strip_tags($content));
     $pa->resultType = 2;
     $pa->differMax = true;
     $pa->StartAnalysis();
     $tagNames = $pa->GetFinallyKeywords(3);
     $tagNames = explode(',', $tagNames);
     $tags = static::find()->select(['id', 'name'])->where(['in', 'name', $tagNames])->indexBy('name')->all();
     foreach ($tagNames as $tn) {
         if (!empty($tags) && !empty($tags[$tn])) {
             $tag = $tags[$tn];
             $tagTopic = new TagTopic(['tag_id' => $tag->id, 'topic_id' => $tc->topic_id]);
             $tagTopic->save(false);
             $tag->updateCounters(['topic_count' => 1]);
         } else {
             $tag = new static(['name' => $tn, 'topic_count' => 1]);
             $tag->save(false);
             $tagTopic = new TagTopic(['tag_id' => $tag->id, 'topic_id' => $tc->topic_id]);
             $tagTopic->save(false);
         }
     }
 }
Example #21
0
 public static function factory($config = array(), $required = array())
 {
     if (!defined('static::ENDPOINT')) {
         throw new Exception\ServiceEndpointException('A client must have an endpoint');
     }
     $default = array('base_url' => '{scheme}://{domain}/' . static::ENDPOINT);
     $required = array_merge(array('scheme', 'domain', 'base_url'), $required);
     $config = Collection::fromConfig($config, $default, $required);
     $client = new static($config->get('base_url'), $config);
     $refClass = new \ReflectionClass(get_called_class());
     $serviceDefinitionPath = dirname($refClass->getFileName());
     $classNamePieces = explode('\\', get_called_class());
     $serviceDefinitionFile = array_pop($classNamePieces) . '.json';
     switch (true) {
         case is_readable(dirname($serviceDefinitionPath) . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . $serviceDefinitionFile):
             $serviceDefinition = $serviceDefinitionPath . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . $serviceDefinitionFile;
             break;
         case is_readable($serviceDefinitionPath . DIRECTORY_SEPARATOR . $serviceDefinitionFile):
             $serviceDefinition = $serviceDefinitionPath . DIRECTORY_SEPARATOR . $serviceDefinitionFile;
             break;
         default:
             throw new Exception\ClientConfigurationException('A client must have a service definition. Could not read the file "' . $serviceDefinition . '"');
     }
     $description = ServiceDescription::factory($serviceDefinition);
     $client->setDescription($description);
     return $client;
 }
Example #22
0
 /**
  * @param \Nette\Latte\Compiler $compiler
  * @return \DK\NetteTranslator\Macros
  */
 public static function install(Compiler $compiler)
 {
     $me = new static($compiler);
     /** @var $me \DK\NetteTranslator\Macros */
     $me->addMacro('_', 'echo %modify($template->translate(%node.args))');
     return $me;
 }
Example #23
0
 /**
  * Forge a new object based on a request.
  * @param  RequestInterface $request
  * @return Response
  */
 public static function forge(RequestInterface $request)
 {
     $headerSize = $request->getInfo(CURLINFO_HEADER_SIZE);
     $response = $request->getRawResponse();
     $content = strlen($response) === $headerSize ? '' : substr($response, $headerSize);
     $rawHeaders = rtrim(substr($response, 0, $headerSize));
     $headers = array();
     foreach (preg_split('/(\\r?\\n)/', $rawHeaders) as $header) {
         if ($header) {
             $headers[] = $header;
         } else {
             $headers = array();
         }
     }
     $headerBag = array();
     $info = $request->getInfo();
     $status = explode(' ', $headers[0]);
     $status = explode('/', $status[0]);
     unset($headers[0]);
     foreach ($headers as $header) {
         list($key, $value) = explode(': ', $header);
         $headerBag[trim($key)] = trim($value);
     }
     $response = new static($content, $info['http_code'], $headerBag);
     $response->setProtocolVersion($status[1]);
     $response->setCharset(substr(strstr($response->headers->get('Content-Type'), '='), 1));
     return $response;
 }
 /**
  * Parse a query string into a QueryString object
  *
  * @param string $query Query string to parse
  *
  * @return self
  */
 public static function fromString($query)
 {
     $q = new static();
     if (0 !== strlen($query)) {
         if ($query[0] == '?') {
             $query = substr($query, 1);
         }
         foreach (explode('&', $query) as $kvp) {
             $parts = explode('=', $kvp, 2);
             $key = rawurldecode($parts[0]);
             $paramIsPhpStyleArray = substr($key, -2) == '[]';
             if ($paramIsPhpStyleArray) {
                 $key = substr($key, 0, -2);
             }
             if (array_key_exists(1, $parts)) {
                 $value = rawurldecode(str_replace('+', '%20', $parts[1]));
                 if ($paramIsPhpStyleArray && !$q->hasKey($key)) {
                     $value = array($value);
                 }
                 $q->add($key, $value);
             } else {
                 $q->add($key, '');
             }
         }
     }
     return $q;
 }
Example #25
0
 /**
  * Update a user's profile
  *
  * @param User $user
  * @param $attributes
  *
  * @return static
  */
 public static function updateProfile(User $user, array $attributes)
 {
     $profile = $user->profile;
     $new = false;
     if (is_null($profile)) {
         $profile = new static();
         $new = true;
     }
     $profile->first_name = $attributes['first_name'];
     $profile->last_name = $attributes['last_name'];
     $profile->location = array_key_exists('location', $attributes) ? $attributes['location'] : '';
     $profile->skill_id = array_key_exists('describe', $attributes) ? $attributes['describe'] : '';
     $profile->profession_id = array_key_exists('profession', $attributes) ? $attributes['profession'] : '';
     $profile->about = array_key_exists('about', $attributes) ? $attributes['about'] : '';
     $profile->facebook = array_key_exists('facebook', $attributes) ? $attributes['facebook'] : '';
     $profile->twitter = array_key_exists('twitter', $attributes) ? $attributes['twitter'] : '';
     $profile->youtube = array_key_exists('youtube', $attributes) ? $attributes['youtube'] : '';
     $profile->published = array_key_exists('published', $attributes) ? true : false;
     $profile->user_id = $user->id;
     // To prevent incomplete profiles from been shown, check if the main skill is missing.
     if (is_null($profile->skill()) or $profile->skill_id == 0) {
         $profile->published = false;
     }
     if ($new) {
         $profile->save();
         $user->profile = $profile;
         Event::fire(new ProfileCreated($profile, $user));
     }
     return $profile;
 }
Example #26
0
 protected static function _singletonRetrieve($options = null)
 {
     $opts = Util\RequestOptions::parse($options);
     $instance = new static(null, $opts);
     $instance->refresh();
     return $instance;
 }
 public static function fromPath(File $path)
 {
     $conv = new static();
     $conv->setRoot($path);
     $conv->setPath($path);
     return $conv;
 }
Example #28
0
 /**
  * @param \Latte\Compiler $compiler
  * @param string|null $wwwDir
  * @param \Venne\Packages\PathResolver|null $pathResolver
  */
 public static function install(Compiler $compiler, $wwwDir = null, PathResolver $pathResolver = null)
 {
     $me = new static($compiler);
     $me->setWwwDir($wwwDir);
     $me->setPathResolver($pathResolver);
     $me->addMacro('js', array($me, 'filter'));
 }
 /**
  * Create default manager
  *
  * @return StrategyManager
  */
 public static function createDefault()
 {
     /** @var StrategyManager $manager */
     $manager = new static();
     $manager->addStrategy(ObjectMetadata::STRATEGY_REFLECTION, new ReflectionStrategy());
     return $manager;
 }
Example #30
0
 public static function logMessage(AuditEntry $entry, $message, $code = 0, $file = '', $line = 0, $trace = [])
 {
     $error = new static();
     $error->entry = $entry;
     $error->recordMessage($message, $code, $file, $line, $trace);
     return $error->save(false) ? $error : null;
 }