/** * Unmarshal return value from a specified node * * @param xml.Node node * @return webservices.uddi.BusinessList * @see xp://webservices.uddi.UDDICommand#unmarshalFrom * @throws lang.FormatException in case of an unexpected response */ public function unmarshalFrom($node) { if (0 != strcasecmp($node->name, 'businessList')) { throw new \lang\FormatException('Expected "businessList", got "' . $node->name . '"'); } // Create business list object from XML representation with($list = new BusinessList(), $children = $node->nodeAt(0)->getChildren()); $list->setOperator($node->getAttribute('operator')); $list->setTruncated(0 == strcasecmp('true', $node->getAttribute('truncated'))); for ($i = 0, $s = sizeof($children); $i < $s; $i++) { $b = new Business($children[$i]->getAttribute('businessKey')); for ($j = 0, $t = sizeof($children[$i]->getChildren()); $j < $s; $j++) { switch ($children[$i]->nodeAt($j)->name) { case 'name': $b->names[] = $children[$i]->nodeAt($j)->getContent(); break; case 'description': $b->description = $children[$i]->nodeAt($j)->getContent(); break; } } $list->items[] = $b; } return $list; }
public function withKeys() { with($keys = ['id', 'name', 'email']); $in = $this->newReader(''); $this->assertEquals($in, $in->withKeys($keys)); $this->assertEquals($keys, $in->getKeys()); }
public function insertRow($data, $id) { $table = with(new static())->table; $key = with(new static())->primaryKey; if ($id == NULL) { // Insert Here if (isset($data['createdOn'])) { $data['createdOn'] = date("Y-m-d H:i:s"); } if (isset($data['updatedOn'])) { $data['updatedOn'] = date("Y-m-d H:i:s"); } $id = \DB::table($table)->insertGetId($data); } else { // Update here // update created field if any if (isset($data['createdOn'])) { unset($data['createdOn']); } if (isset($data['updatedOn'])) { $data['updatedOn'] = date("Y-m-d H:i:s"); } \DB::table($table)->where($key, $id)->update($data); } return $id; }
/** * Retrieve a new instance * * @param string oid * @param ProtocolHandler handler * @return RemoteInvocationHandler */ public static function newInstance($oid, $handler) { with($i = new RemoteInvocationHandler()); $i->oid = $oid; $i->handler = $handler; return $i; }
/** * @return mixed */ public function create() { $users = User::with('employee')->get()->reject(function ($user) { return $user->id === auth()->user()->id; }); return response()->view('messages.create', with(compact('users'))); }
/** * Create a new Console application. * * @param \Weloquent\Core\Application $app * @return \Illuminate\Console\Application */ public static function make($app) { $app->boot(); $console = with($console = new static('WEL. A w.eloquent console by artisan.', $app::VERSION))->setLaravel($app)->setExceptionHandler($app['exception'])->setAutoExit(false); $app->instance('artisan', $console); return $console; }
/** * Execute the console command. * * @return mixed */ public function fire() { $names = $this->argument('name'); foreach ($names as $name) { with(new ModuleGenerator($name))->setFilesystem($this->laravel['files'])->setModule($this->laravel['modules'])->setConfig($this->laravel['config'])->setConsole($this)->setForce($this->option('force'))->setPlain($this->option('plain'))->generate(); } }
public function call() { // The Slim application $app = $this->app; // The Environment object $environment = $app->environment; // The Request object $request = $app->request; // The Response object $response = $app->response; // Route Configuration $routeConfig = ['/api/user' => \App\Http\ApiUserController::class, '/api' => \App\Http\ApiSiteController::class, '/' => \App\Http\SiteController::class]; // Request path info $pathInfo = $request->getPathInfo(); // Searching per directory foreach ($routeConfig as $basePath => $controller) { if ($pathInfo === $basePath) { with(new $controller($app, $basePath))->map(); break; } if (starts_with(ltrim($pathInfo, '/'), ltrim($basePath, '/'))) { with(new $controller($app, $basePath))->map(); break; } } // Call next middleware $this->next->call(); }
/** * * @param int $perSize 每次迭代的数据条数 * @param bool $withRelations 是否带上关联查询 * @param int $limit 总条数限制 */ public function __construct($perSize = 100, $withRelations = true, $limit = 0) { $this->post = new Post(); $this->perSize = $perSize; $this->total_items = $this->post->count(); if ($limit > 0) { $this->total_items = max($this->total_items, $limit); } $this->postsTableName = $this->post->getSource(); $this->dbConnection = $this->post->getReadConnection(); $this->textsTableName = with(new Texts())->getSource(); $this->votesTableName = with(new Votes())->getSource(); $this->tagsPostsTableName = with(new TagsPosts())->getSource(); $this->tagsTableName = with(new Tags())->getSource(); $this->categoriesTableName = with(new CategoriesPosts())->getSource(); $this->endPosition = floor($this->total_items / $this->perSize); if ($withRelations) { $this->sql = <<<SQL SELECT \tpost.*, \tvote.upVote, \tvote.downVote, \t(SELECT GROUP_CONCAT(`categoryId`) FROM `{$this->categoriesTableName}` WHERE postId=post.id) as categoryIds, \t(SELECT GROUP_CONCAT(`tagName`) FROM `{$this->tagsTableName}` WHERE id IN (SELECT `tagId` FROM `{$this->tagsPostsTableName}` WHERE `postId`=post.id)) as tagNames, text.content FROM `{$this->postsTableName}` as post LEFT JOIN `{$this->textsTableName}` as text \tON text.postId=post.id LEFT JOIN `{$this->votesTableName}` as vote ON vote.postId=post.id SQL; } else { $this->sql = "SELECT * FROM {$this->postsTableName}"; } }
/** * Run the application and save headers. * The response is up to WordPress * * @param \Symfony\Component\HttpFoundation\Request $request * @return void */ public function run(SymfonyRequest $request = null) { /** * On testing environment the WordPress helpers * will not have context. So we stop here. */ if (defined('WELOQUENT_TEST_ENV') && WELOQUENT_TEST_ENV) { return; } $request = $request ?: $this['request']; $response = with($stack = $this->getStackedClient())->handle($request); // just set headers, but the content if (!is_admin()) { $response->sendHeaders(); } if ('cli' !== PHP_SAPI) { $response::closeOutputBuffers(0, false); } /** * Save the session data until the application dies */ add_action('wp_footer', function () use($stack, $request, $response) { $stack->terminate($request, $response); Session::save('wp_footer'); }); }
public function postChangePassword() { $rules = array('old_password' => 'required', 'password' => 'required|min:5|confirmed'); $input = Input::all(); $v = Validator::make($input, $rules); if ($v->fails()) { return Redirect::route('admin.change-password')->withErrors($v)->withInput(); } try { $user = Sentinel::getUser(); $credentials = ['email' => $user->email, 'password' => $input['old_password']]; if (Sentinel::validateCredentials($user, $credentials)) { $user->password = Hash::make($input['password']); $user->save(); Session::flash('success', 'You have successfully changed your password'); return Redirect::route('admin.change-password'); } else { $error = "Invalid old password"; $errors = with(new bag())->add('password', $error); return Redirect::route('admin.change-password')->withErrors($errors)->withInput(); } } catch (Cartalyst\Sentinel\Users\UserNotFoundException $e) { return Redirect::route('admin.logout'); } }
/** * Bootstrap the application events. * * @return void */ public function boot() { $componenentsFileName = with(new ReflectionClass('\\Componeint\\Dashboard\\DashboardServiceProvider'))->getFileName(); $componenentsPath = dirname($componenentsFileName); $this->loadViewsFrom($componenentsPath . '/../../resources/views', 'dashboard'); // include $componenentsPath . '/../routes.php'; }
/** * Issues a uses() command inside a new runtime for every class given * and returns a line indicating success or failure for each of them. * * @param string[] uses * @param string decl * @return var[] an array with three elements: exitcode, stdout and stderr contents */ protected function useAllOf($uses, $decl = '') { with($out = $err = '', $p = Runtime::getInstance()->newInstance(NULL, 'class', 'xp.runtime.Evaluate', array())); $p->in->write($decl . ' ClassLoader::registerPath(\'' . strtr($this->getClass()->getClassLoader()->path, '\\', '/') . '\'); $errors= 0; foreach (array("' . implode('", "', $uses) . '") as $class) { try { uses($class); echo "+OK ", $class, "\\n"; } catch (Throwable $e) { echo "-ERR ", $class, ": ", $e->getClassName(), "\\n"; $errors++; } } exit($errors); '); $p->in->close(); // Read output while ($b = $p->out->read()) { $out .= $b; } while ($b = $p->err->read()) { $err .= $b; } // Close child process $exitv = $p->close(); return array($exitv, explode("\n", rtrim($out)), explode("\n", rtrim($err))); }
/** * Generate a new 8-character slug. * * @param integer $id * @return Slug */ public static function fromId($id) { $salt = md5($id); $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $slug = with(new Hashids($salt, $length = 8, $alphabet))->encode($id); return new Slug($slug); }
public function entries() { $builder = with(new Entry())->newQuery(); $groups = $this->groups; $builder->whereIn('group_id', $groups); return $builder; }
/** * Creates a new CSV reader reading data from a given TextReader * * @param io.streams.TextReader reader * @param text.csv.CsvFormat format */ public function __construct(TextReader $reader, CsvFormat $format = NULL) { $this->reader = $reader; with($f = $format ? $format : CsvFormat::$DEFAULT); $this->delimiter = $f->getDelimiter(); $this->quote = $f->getQuote(); }
/** * Tail a local log file for the application. * * @param string $path * @return string */ protected function tailLocalLogs($path) { $output = $this->output; with(new Process('tail -f ' . $path))->setTimeout(null)->run(function ($type, $line) use($output) { $output->write($line); }); }
public function testChildrenRelationObeysCustomOrdering() { with(new OrderedCategorySeeder())->run(); $children = OrderedCategory::find(1)->children()->get()->all(); $expected = array(OrderedCategory::find(5), OrderedCategory::find(2), OrderedCategory::find(3)); $this->assertEquals($expected, $children); }
/** * Create the shipment for sticker. * * @param null $driver * * @return \Illuminate\Http\JsonResponse */ public function shipment($driver = null) { try { \DB::beginTransaction(); if (is_null($driver)) { $driver = $this->getAuthenticatedDriver(); } $new_shipment = ["sticker_id" => $driver->sticker->id, "address" => \Input::get('address', $driver->address), "status" => "waiting", "paypal_payment_status" => "pending"]; with(new CreateShipmentValidator())->validate($new_shipment); // Add paypal_metadata_id for future payment. $driver->paypal_metadata_id = \Input::get('metadata_id'); if ($capturedPayment = $this->paypal->buySticker($driver)) { $new_shipment['paypal_payment_id'] = $capturedPayment->parent_payment; if ($shipment = Shipment::create($new_shipment)) { \DB::commit(); return $this->setStatusCode(201)->respondWithItem($shipment); } return $this->errorInternalError('Shipment for buying sticker created failed.'); } return $this->errorInternalError(); } catch (ValidationException $e) { return $this->errorWrongArgs($e->getErrors()); } catch (\Exception $e) { print_r($e->getMessage()); return $this->errorInternalError(); } }
/** * Execute the console command. * * @return mixed */ public function fire() { $host = $this->input->getOption('host'); $port = $this->input->getOption('port'); $this->info("Lumen ReactPHP server started on http://{$host}:{$port}"); with(new \LaravelReactPHP\Server($host, $port))->run(); }
public function parseValue($value) { preg_match_all('/%([^$]+)\\$/', $this->format_string, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE); $i = count($matches[1]); $values = []; foreach (array_reverse($matches[1]) as $match) { $fragmentType = strtolower(ltrim(strrchr(get_class($this->fragment), '\\'), '\\')); // era or unit $fragmentName = $this->fragment->internal_name; $partBegin = stripos($match[0], '{'); if ($partBegin >= 0) { $partEnd = stripos($match[0], '}', $partBegin); $fragmentPart = trim(substr($match[0], $partBegin, $partEnd), '{}'); } else { $fragmentPart = 'unknown'; } $type = "{$fragmentType}.{$fragmentName}.{$fragmentPart}"; if (with($txtObj = $this->texts()->where('fragment_text', $value))->count() > 0) { $value = $txtObj->first()->fragment_value; } $invert = preg_replace('/##(\\d+|\\{[^}]+\\})/', '*${1}+{epoch}%%${1}', str_replace(['\\*', '-%', '\\', '+', '-', ':', '/', '*', ':', '%%', '%', '__', '$$'], ['__', '$$', '##', ':', '+', '-', ':', '/', '*', '+{epoch}\\*', '+{epoch}-%', '+{epoch}%%', '+{epoch}%'], $match[0])); $output = BC::parse($invert, ['epoch' => $this->fragment->getEpochValue(), $fragmentPart => $value], 0); $values[$i] = [$type, $output]; $i--; } return $values; }
public function excel() { $table = with(new Inbound())->getTable(); $data = DB::select(DB::raw("SELECT * FROM {$table}")); $data = json_encode($data); SELF::data2excel('Excel', 'Sheet1', json_decode($data, true)); }
public function getResults($filter = null) { $renderedRewards = []; $rewards = Reward::isActive(); $user = Auth::getUser(); switch ($filter) { case 'qty': $rewards->where('inventory', '>', 0); break; case 'time': $rewards->whereNotNull('date_begin'); $rewards->whereNotNull('date_end'); break; case 'bookmarked': $rewards->whereHas('bookmarks', function ($query) use($user) { $query->where('user_id', '=', $user->id); }); break; case 'all': default: $rewards->whereIn('id', function ($query) { $query->select('id')->from(with(new Reward())->getTable())->whereNull('inventory')->orWhere('inventory', '>', 0); })->whereIn('id', function ($query) { $query->select('id')->from(with(new Reward())->getTable())->whereNull('date_begin')->whereNull('date_end'); })->whereIn('id', function ($query) { $query->select('id')->from(with(new Reward())->getTable())->where('date_begin', '<=', date('c'))->where('date_end', '>=', date('c'))->where('is_published', '>', 0)->where('inventory', '>', 0); }, 'or'); break; } $rewards = $rewards->orderBy('points')->paginate($this->property('limit')); foreach ($rewards as $reward) { $renderedRewards[] = ['rendered' => View::make('dma.friends::rewardPreview', ['reward' => $reward, 'user' => $user, 'allowRedeem' => LocationManager::enableAction()])->render(), 'id' => $reward->id]; } return ['links' => $rewards->render(), 'rewards' => $renderedRewards]; }
/** * @test */ public function it_should_fire_job() { /** * * Set * */ $app = m::mock('Illuminate\\Foundation\\Application'); $config = m::mock('Menthol\\Flexible\\Config'); $logger = m::mock('Monolog\\Logger'); am::double('Husband', ['deleteDoc' => true]); $job = m::mock('Illuminate\\Queue\\Jobs\\Job'); $models = ['Husband:999']; /** * * Expectation * */ $logger->shouldReceive('info')->with('Deleting Husband with ID: 999 from Elasticsearch'); $config->shouldReceive('get')->with('logger', 'menthol.flexible.logger')->andReturn('menthol.flexible.logger'); $app->shouldReceive('make')->with('menthol.flexible.logger')->andReturn($logger); $job->shouldReceive('delete')->once(); /** * * Assertion * */ with(new DeleteJob($app, $config))->fire($job, $models); }
/** * Register the Service Provider. * * @return void */ public function register() { $this->app->bindShared('cookie', function ($app) { $config = $app['config']['session']; return with(new CookieJar())->setDefaultPathAndDomain($config['path'], $config['domain']); }); }
/** * Bootstrap the application events. * * @return void */ public function boot() { // Find path to the package $sentinelFilename = with(new ReflectionClass('Sentinel\\SentinelServiceProvider'))->getFileName(); $sentinelPath = dirname($sentinelFilename); // Register Artisan Commands $this->registerArtisanCommands(); // Establish Fallback Config settings $this->mergeConfigFrom($sentinelPath . '/../config/sentinel.php', 'sentinel'); $this->mergeConfigFrom($sentinelPath . '/../config/sentry.php', 'sentry'); // Establish Views Namespace if (is_dir(base_path() . '/resources/views/sentinel')) { // The package views have been published - use those views. $this->loadViewsFrom(base_path() . '/resources/views/sentinel', 'Sentinel'); } else { // The package views have not been published. Use the defaults. $this->loadViewsFrom($sentinelPath . '/../views/bootstrap', 'Sentinel'); } // Establish Translator Namespace $this->loadTranslationsFrom($sentinelPath . '/../lang', 'Sentinel'); // Include custom validation rules include $sentinelPath . '/../validators.php'; // Should we register the default routes? if (config('sentinel.routes_enabled')) { include $sentinelPath . '/../routes.php'; } // Set up event listeners $dispatcher = $this->app->make('events'); $dispatcher->subscribe('Sentinel\\Handlers\\UserEventHandler'); }
/** * Error handler * * @param int level * @param string message * @param string[] expected */ public function error($level, $message, $expected = array()) { with($m = new ParserMessage($level, $message, $expected)); $this->messages[$this->levels[$level]][] = $m; $this->cat && $this->cat->info($m); return FALSE; }
/** * Get the underlying instance. * * We'll always cache the instance and reuse it. * */ public static function __instance() { if (empty(self::$__instance)) { self::$__instance = with(new \ReflectionClass(self::$__class))->newInstanceArgs(self::$__args); } return self::$__instance; }
public static function queryComment($model) { try { $results = DB::connection('mysql_system')->select('select COLUMN_NAME,COLUMN_COMMENT FROM columns WHERE table_schema = ? AND table_name = ?', [env('DB_DATABASE'), with($model)->getTable()]); } catch (\Exception $ex) { return []; } $column_names = []; foreach ($results as $result) { switch ($result->COLUMN_NAME) { case 'created_at': $column_names[$result->COLUMN_NAME] = '创建时间'; break; case 'updated_at': $column_names[$result->COLUMN_NAME] = '修改时间'; break; case 'deleted_at': $column_names[$result->COLUMN_NAME] = '删除时间'; break; default: $column_names[$result->COLUMN_NAME] = $result->COLUMN_COMMENT; break; } } return $column_names; }
/** * Bootstrap the application events. * * @return void */ public function boot() { // Find path to the package $sentinelFilename = with(new \ReflectionClass('\\Sentinel\\SentinelServiceProvider'))->getFileName(); $sentinelPath = dirname($sentinelFilename); // Load the package $this->package('rydurham/sentinel'); // Register the Sentry Service Provider $this->app->register('Cartalyst\\Sentry\\SentryServiceProvider'); // Add the Views Namespace if (is_dir(app_path() . '/views/packages/rydurham/sentinel')) { // The package views have been published - use those views. $this->app['view']->addNamespace('Sentinel', array(app_path() . '/views/packages/rydurham/sentinel')); } else { // The package views have not been published. Use the defaults. $this->app['view']->addNamespace('Sentinel', __DIR__ . '/../views'); } // Add the Sentinel Namespace to $app['config'] if (is_dir(app_path() . '/config/packages/rydurham/sentinel')) { // The package config has been published $this->app['config']->addNamespace('Sentinel', app_path() . '/config/packages/rydurham/sentinel'); } else { // The package config has not been published. $this->app['config']->addNamespace('Sentinel', __DIR__ . '/../config'); } // Add the Translator Namespace $this->app['translator']->addNamespace('Sentinel', __DIR__ . '/../lang'); // Make the app aware of these files include $sentinelPath . '/../routes.php'; include $sentinelPath . '/../filters.php'; include $sentinelPath . '/../observables.php'; include $sentinelPath . '/../composers.php'; include $sentinelPath . '/../validators.php'; }