/** * Get an item from an array or object using "dot" notation. * * @param mixed $target * @param string|array $key * @param mixed $default * @return mixed */ function data_get($target, $key, $default = null) { if (is_null($key)) { return $target; } $key = is_array($key) ? $key : explode('.', $key); while (($segment = array_shift($key)) !== null) { if ($segment === '*') { if ($target instanceof Collection) { $target = $target->all(); } elseif (!is_array($target)) { return value($default); } $result = Arr::pluck($target, $key); return in_array('*', $key) ? Arr::collapse($result) : $result; } if (Arr::accessible($target) && Arr::exists($target, $segment)) { $target = $target[$segment]; } elseif (is_object($target) && isset($target->{$segment})) { $target = $target->{$segment}; } else { return value($default); } } return $target; }
/** * @return array */ public static function getRules($scene = 'saving') { $rules = []; array_walk(static::$_rules, function ($v, $k) use(&$rules, $scene) { $rules[$k] = []; array_walk($v, function ($vv, $kk) use(&$rules, $scene, $k) { if (isset($v['on'])) { $scenes = explode(',', $vv['on']); $rule = Arr::get($vv, 'rule', false); if ($rule && in_array($scene, $scenes)) { $rules[$k][] = $rule; } } else { if ($scene == 'saving') { $rule = Arr::get($vv, 'rule', false); if ($rule) { $rules[$k][] = $rule; } } } }); if (empty($rules[$k])) { unset($rules[$k]); } else { $rules[$k] = implode('|', $rules[$k]); } }); return $rules; }
/** * Create a new menu. * * @return $this */ public function create() { $menu = $this->handler->add($this->name, $this->getAttribute('position'))->title($this->getAttribute('title'))->link($this->getAttribute('link'))->handles(Arr::get($this->menu, 'link')); $this->attachIcon($menu); $this->handleNestedMenu(); return $this; }
/** * Run migrations for the specified module. * * @param string $slug * @return mixed */ protected function migrate($slug) { if ($this->module->exists($slug)) { $pretend = Arr::get($this->option(), 'pretend', false); $options = ['pretend' => $pretend]; $path = $this->getMigrationPath($slug); $this->migrator->run($path, $options); // Once the migrator has run we will grab the note output and send it out to // the console screen, since the migrator itself functions without having // any instances of the OutputInterface contract passed into the class. foreach ($this->migrator->getNotes() as $note) { if (!$this->option('quiet')) { $this->line($note); } } // Finally, if the "seed" option has been given, we will re-run the database // seed task to re-populate the database, which is convenient when adding // a migration and a seed at the same time, as it is only this command. if ($this->option('seed')) { $this->call('module:seed', ['module' => $slug, '--force' => true]); } } else { return $this->error("Module does not exist."); } }
/** * Set a given configuration value. * * @param array|string $key * @param mixed $value * @return void */ public function set($key, $value = null) { $keys = is_array($key) ? $key : [$key => $value]; foreach ($keys as $key => $value) { Arr::set($this->items, $key, $value); } }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $referer = $request->server->get('referer'); // Referer is not provided, we continue if (is_null($referer) or env('APP_ENV', 'production') !== 'production') { return $next($request); } // Handle the dictionnary. // @todo Refactor that $dir = realpath(dirname(__FILE__) . '/../../../../../') . '/'; $path = $dir . 'spammers.json'; $file = file_get_contents($path); // Dictionnary is not readable, abort. if (empty($file)) { abort(500, 'Unable to read spammers.json'); } $dictionary = json_decode($file); // Parse the referer $url = new Parser(new PublicSuffixList([])); $host = $url->parseHost($referer)->host; // Compare dictionary against the referer... $search = Arr::where($dictionary, function ($key, $value) use($host) { return mb_stripos($host, $value) !== false; }); // ...and check for results if (count($search) > 0) { abort(500, 'Spammers protection'); } // No spam, we can continue :) return $next($request); }
protected function handleDotCase(&$array, $key, $value) { if (strpos($key, '.') !== false) { unset($array[$key]); Arr::set($array, $key, $value); } }
public function getConnector() { $options = Arr::get($this->config, 'options', []); $user = $this->request->user(); $accessControl = Arr::get($this->config, 'accessControl'); $roots = Arr::get($options, 'roots', []); foreach ($roots as $key => $disk) { $disk['driver'] = empty($disk['driver']) === true ? 'LocalFileSystem' : $disk['driver']; $disk['autoload'] = true; if (empty($disk['path']) === false && $disk['path'] instanceof Closure === true) { $disk['path'] = call_user_func($disk['path']); } switch ($disk['driver']) { case 'LocalFileSystem': if (strpos($disk['path'], '{user_id}') !== -1 && is_null($user) === true) { continue; } $userId = $user->id; $disk['path'] = str_replace('{user_id}', $userId, $disk['path']); $disk['URL'] = $this->urlGenerator->to(str_replace('{user_id}', $userId, $disk['URL'])); if ($this->filesystem->exists($disk['path']) === false) { $this->filesystem->makeDirectory($disk['path'], 0755, true); } $disk = array_merge(['mimeDetect' => 'internal', 'utf8fix' => true, 'tmbCrop' => false, 'tmbBgColor' => 'transparent', 'accessControl' => $accessControl], $disk); break; } $roots[$key] = $disk; } $options = array_merge($options, ['roots' => $roots, 'session' => $this->session]); return new Connector(new BaseElfinder($options)); }
public function handle(Request $request, Closure $next) { $route = $request->route(); $parameters = $route->parameters(); $parameterKeys = array_keys($parameters); // Look for parameters that match {*_morph_type} and {*_morph_id} $morphTypeName = Arr::first($parameterKeys, function ($item) { return ends_with($item, '_type'); }); $morphIdName = Arr::first($parameterKeys, function ($item) { return ends_with($item, '_id'); }); if (!$morphTypeName or !$morphIdName) { return $next($request); } $morphKey = preg_replace("/_type\$/", '', $morphTypeName); if ($morphKey !== preg_replace("/_id\$/", '', $morphIdName)) { return $next($request); } $morphTypeName = $morphKey . '_type'; $morphIdName = $morphKey . '_id'; $morphType = $parameters[$morphTypeName]; $morphId = $parameters[$morphIdName]; // Not going to worry about custom keys here. $morphInstance = requireMorphInstance($morphType, $morphId); $route->forgetParameter($morphTypeName); $route->forgetParameter($morphIdName); $route->setParameter($morphKey, $morphInstance); return $next($request); }
/** * Replace all of the named parameters in the path. * * @param string $path * @param array $parameters * * @return string */ protected function replaceNamedParameters($path, &$parameters) { $this->ensureTenancyInParameters($path, $parameters); return preg_replace_callback('/\\{(.*?)\\??\\}/', function ($m) use(&$parameters) { return isset($parameters[$m[1]]) ? Arr::pull($parameters, $m[1]) : $m[0]; }, $path); }
static function denormalize($phone) { $p = self::normalize($phone); $length = mb_strlen($p); if (6 == $length) { $p = '83522' . $p; $length = mb_strlen($p); } $config = \Config::get('larakit::phones.' . $length, []); if (!count($config)) { return $p; } $codes = array_keys($config); rsort($codes); foreach ($codes as $code) { if ($code == mb_substr($p, 0, mb_strlen($code))) { $mask = Arr::get($config, $code . '.mask'); $phone_array = str_split(mb_substr($p, mb_strlen($code))); $mask_array = str_split($mask); foreach ($mask_array as $key => $symbol) { if ('#' == $symbol) { $mask_array[$key] = array_shift($phone_array); } } return implode('', $mask_array); } } return null; }
/** * Update documentation. * * @param string $doc * @param string $version * @return void */ protected function updateDoc($doc, $version = null) { $path = config('docs.path'); if (!($data = Arr::get($this->docs->getDocs(), $doc))) { return; } if (!$this->files->exists("{$path}/{$doc}")) { $this->git->clone($data['repository'], "{$path}/{$doc}"); } $this->git->setRepository("{$path}/{$doc}"); $this->git->checkout('master'); $this->git->pull('origin'); if ($version) { $versions = [$version]; } else { $versions = $this->getVersions(); } foreach ($versions as $version) { $this->git->checkout($version); $this->git->pull('origin', $version); $this->git->checkout($version); $storagePath = storage_path("docs/{$doc}/{$version}"); $this->files->copyDirectory("{$path}/{$doc}", $storagePath); $this->docs->clearCache($doc, $version); } }
public static final function onDeletedResource($response) { $data = (array) json_decode($response->getBody(), true); Arr::forget($data, ['code', 'message']); $data = json_encode($data); return $response->withBody(Psr7\stream_for($data)); }
/** * Get the class's history. * * @param string|null $type * * @return array */ public function getHistory($type = null) { $handle = $this->getHistoryHandle(); $history = $this->history[$handle]; $history = Arr::get($history, $type); return $history; }
/** * Get recipe files location * * @return string */ public function getRecipePath() { $directory = $this->getDirectoryPath(); $content = $this->filesystem->get($directory . '/' . self::CONFIGFILE); $contentArr = json_decode($content, true); return Arr::get($contentArr, 'recipe_path', null); }
/** * Create multiple clusters (aggregate clients). * * @param array $clusters * @param array $options * @return void */ protected function createClusters(array $clusters, array $options = []) { $options = array_merge($options, (array) Arr::pull($clusters, 'options')); foreach ($clusters as $name => $servers) { $this->clients += $this->createAggregateClient($name, $servers, array_merge($options, (array) Arr::pull($servers, 'options'))); } }
/** * Create a new PDO connection. * * @param string $dsn * @param array $config * @param array $options * @return PDO * @throws Exception */ public function createConnection($dsn, array $config, array $options) { $username = Arr::get($config, 'username'); $password = Arr::get($config, 'password'); $create_pdo = function ($dsn, $username, $password, $options) { try { $pdo = new PDO($dsn, $username, $password, $options); } catch (Exception $e) { $pdo = $this->tryAgainIfCausedByLostConnection($e, $dsn, $username, $password, $options); } $this->isClusterNodeReady($pdo); return $pdo; }; if (is_array($dsn)) { foreach ($dsn as $idx => $dsn_string) { try { return $create_pdo($dsn_string, $username, $password, $options); } catch (Exception $e) { if (!$this->causedByLostConnection($e) || $idx >= count($dsn) - 1) { throw $e; } } } } return $create_pdo($dsn, $username, $password, $options); }
/** * Run migrations for the specified module. * * @param string $slug * * @return mixed */ protected function migrate($slug = null) { $pretend = Arr::get($this->option(), 'pretend', false); if (!is_null($slug) && $this->module->exists($slug)) { $path = $this->getMigrationPath($slug); if (floatval(App::version()) > 5.1) { $pretend = ['pretend' => $pretend]; } $this->migrator->run($path, $pretend); // Once the migrator has run we will grab the note output and send it out to // the console screen, since the migrator itself functions without having // any instances of the OutputInterface contract passed into the class. foreach ($this->migrator->getNotes() as $note) { if (!$this->option('quiet')) { $this->line($note); } } // Finally, if the "seed" option has been given, we will re-run the database // seed task to re-populate the database, which is convenient when adding // a migration and a seed at the same time, as it is only this command. if ($this->option('seed')) { $this->call('module:seed', ['module' => $slug, '--force' => true]); } } else { $modules = $this->module->all(); if (count($modules) == 0) { return $this->error("Your application doesn't have any modules."); } $migrationsAll = []; foreach ($modules as $module) { $path = $this->getMigrationPath($module['slug']); $files = $this->migrator->getMigrationFiles($path); $ran = $this->migrator->getRepository()->getRan(); $migrations = array_diff($files, $ran); $this->migrator->requireFiles($path, $migrations); $migrationsAll = array_merge($migrationsAll, $migrations); } if (floatval(App::version()) > 5.1) { $pretend = ['pretend' => $pretend]; } sort($migrationsAll); $this->migrator->runMigrationList($migrationsAll, $pretend); // Once the migrator has run we will grab the note output and send it out to // the console screen, since the migrator itself functions without having // any instances of the OutputInterface contract passed into the class. foreach ($this->migrator->getNotes() as $note) { if (!$this->option('quiet')) { $this->line($note); } } // Finally, if the "seed" option has been given, we will re-run the database // seed task to re-populate the database, which is convenient when adding // a migration and a seed at the same time, as it is only this command. if ($this->option('seed')) { foreach ($modules as $module) { $this->call('module:seed', ['module' => $module['slug'], '--force' => true]); } } } }
/** * Register new BroadcastManager in boot * * @return void */ public function boot() { $self = $this; $this->app->make(BroadcastManager::class)->extend('redisreliable', function ($app, $config) use($self) { return new RedisReliableBroadcaster($app->make('redis'), Arr::get($config, 'connection'), Arr::get($config, 'sub_min'), Arr::get($config, 'sub_list')); }); }
/** * Execute the console command. * * @return void */ public function handle() { $roles = $this->file->getRequire(base_path(config('trust.permissions'))); $this->call('trust:permissions'); $all = Permission::all(['id', 'slug']); $create = 0; $update = 0; foreach ($roles as $slug => $attributes) { $role = $this->findRole($slug); if ($role) { if ($this->option('force')) { ++$update; $role->update($attributes + compact('slug')); } } else { ++$create; $role = Role::create($attributes + compact('slug')); } $permissions = array_reduce(Arr::get($attributes, 'permissions', []), function (Collection $result, string $name) use($all) { if (hash_equals('*', $name)) { return $all->pluck('id'); } if ($all->count() === $result->count()) { return $result; } $filtered = $all->filter(function (Permission $permission) use($name) { return Str::is($name, $permission->slug); })->pluck('id'); return $result->merge($filtered); }, new Collection()); $role->permissions()->sync($permissions->toArray()); } $total = $create + $update; $this->line("Installed {$total} roles. <info>({$create} new roles, {$update} roles synced)</info>"); }
/** * Execute the console command. * * @return mixed */ public function fire() { $models = ManagerMigrator::get(); foreach ($models as $class => $migrators) { foreach ($migrators as $data) { $this->rows = []; // $this->error(str_repeat('=', 80)); $this->error(str_pad(' ' . $class . ' ', 80, '=', STR_PAD_BOTH)); // $this->error(str_repeat('=', 80)); $vendor = Arr::get($data, 'vendor'); $type = Arr::get($data, 'type'); $v = $vendor ? $vendor . '::' : ''; $key = $v . 'migrator/' . $type; $config = \Config::get($key, false); if (!$config) { $this->error('Не обнаружен конфиг мигратора ' . $key); continue; } $indexes = Arr::get($config, 'indexes', []); $fields = Arr::get($config, 'fields', []); /** @var Model $model */ $model = new $class(); $table_name = $model->getTable(); $this->syncFields($table_name, $fields); $this->rows[] = new TableSeparator(); $this->syncIndexes($table_name, $indexes); $this->table(['[#]', 'Тип', 'Имя', 'Дополнительные характеристики', 'Результат'], $this->rows); } } echo PHP_EOL; $this->question('Синхронизация зарегистрированных типов структур завершена'); }
/** * Create an instance of the SendGrid Swift Transport driver. * * @return Transport\SendgridTransport */ protected function createSendgridDriver() { $config = $this->app['config']->get('services.sendgrid', []); $client = new Client(Arr::get($config, 'guzzle', [])); $pretend = isset($config['pretend']) ? $config['pretend'] : false; return new SendgridTransport($client, $config['api_key'], $pretend); }
/** * Parse Validation input request data. * * @param $attribute * @param $value * @param $parameters * @return array */ protected function parseJsRemoteRequest($attribute, $value, $parameters) { parse_str("{$value}=", $attr_parts); $attr_parts = is_null($attr_parts) ? [] : $attr_parts; $newAttr = array_keys(Arr::dot($attr_parts)); return [$attribute, array_pop($newAttr), $parameters]; }
/** * Get the core informations to inject in the configuration created. * * @return array */ protected function getConfigurationInformations() { // Replace credentials $repositoryCredentials = $this->connections->getRepositoryCredentials(); $name = basename($this->app['path.base']); return array_merge($this->connections->getServerCredentials(), ['connection' => preg_replace('/#[0-9]+/', null, $this->connections->getConnection()), 'scm_repository' => Arr::get($repositoryCredentials, 'repository'), 'scm_username' => Arr::get($repositoryCredentials, 'username'), 'scm_password' => Arr::get($repositoryCredentials, 'password'), 'application_name' => $this->command->ask('What is your application\'s name ? (' . $name . ')', $name)]); }
public function setOriginal($data) { $relations = Arr::get($data, $this->column); foreach ($relations as $relation) { $this->original[] = array_pop($relation['pivot']); } }
/** * @param array $data * @return void */ public function __invoke($data) { $data = Arr::flatten($data); $data = array_unique($data); $this->outPorts['out']->send($data); $this->outPorts['out']->disconnect(); }
/** * Processes LDAP search results and constructs their model instances. * * @param resource $results * * @return array */ public function process($results) { // Normalize entries. Get entries returns false on failure. // We'll always want an array in this situation. $entries = $this->connection->getEntries($results) ?: []; if ($this->builder->isRaw()) { // If the builder is asking for a raw // LDAP result, we can return here. return $entries; } $models = []; if (Arr::has($entries, 'count')) { for ($i = 0; $i < $entries['count']; $i++) { // We'll go through each entry and construct a new // model instance with the raw LDAP attributes. $models[] = $this->newLdapEntry($entries[$i]); } } if (!$this->builder->isPaginated()) { // If the current query isn't paginated, // we'll sort the models array here. $models = $this->processSort($models); } return $models; }
/** * Get an element from an array. * * @param array $array * @param string $key Specify a nested element by separating keys with full stops. * @param mixed $default If the element is not found, return this. * * @return mixed */ public static function get($array, $key, $default = null) { if (is_array($key)) { return static::getArray($array, $key, $default); } return parent::get($array, $key, $default); }
/** * Delete this customer credit card in the billing gateway. * * @return Creditcard */ public function delete() { if (!$this->model->readyForBilling()) { return $this; } $this->card->delete(); $cards = array(); foreach ($this->model->billing_cards as $c) { if (Arr::get($c, 'id') != $this->id) { $cards[] = $c; } } $this->model->billing_cards = $cards; $this->model->save(); // Refresh all subscription records that referenced this card. if ($subscriptions = $this->model->subscriptionModelsArray()) { foreach ($subscriptions as $subscription) { if ($subscription->billingIsActive() && $subscription->billing_card == $this->id) { $subscription->subscription()->refresh(); } } } $this->info = array('id' => $this->id); return $this; }
public function matter(string $key = null, $default = null) { if ($key) { return Arr::get($this->matter, $key, $default); } return $this->matter; }