示例#1
0
 protected function removeTrailingSlash($path)
 {
     if (Str::endsWith($path, '/') && $path != '/') {
         unset($path[strlen($path) - 1]);
     }
     return $path;
 }
 /**
  * Gets the value of an environment variable. Supports boolean, empty and null.
  *
  * @param  string $key
  * @param  mixed  $default
  *
  * @return mixed
  */
 function env($key, $default = null)
 {
     $value = getenv($key);
     if ($value === false) {
         return value($default);
     }
     switch (strtolower($value)) {
         case 'true':
         case '(true)':
             return true;
         case 'false':
         case '(false)':
             return false;
         case 'empty':
         case '(empty)':
             return '';
         case 'null':
         case '(null)':
             return;
     }
     if (strlen($value) > 1 && Str::startsWith($value, '"') && Str::endsWith($value, '"')) {
         return substr($value, 1, -1);
     }
     return $value;
 }
 public final function getConfigPathFile($file)
 {
     if (!Str::endsWith($file, '.php')) {
         $file = $file . '.php';
     }
     return config_path($this->getConfigShortPath() . '/' . $file);
 }
 /**
  * @param array $rules
  *
  * @return callable[]
  * @throws Exception
  */
 public function postProcessRules(array &$rules)
 {
     $postProcessors = [];
     $hasArrayRule = false;
     foreach ($rules as $attribute => &$attributeRules) {
         foreach ($attributeRules as $ruleIndex => &$ruleData) {
             list($ruleName, $ruleParams) = $this->parseRule($ruleData);
             if ('array' == $ruleName) {
                 $hasArrayRule = true;
             }
             if (!Str::endsWith($ruleName, '[]')) {
                 continue;
             }
             $ruleName = substr($ruleName, 0, -2);
             if (Str::endsWith($ruleName, '[]')) {
                 throw new Exception("Error in rule '{$ruleName}' for attribute '{$attribute}'. Multidimensional arrays are not currently supported");
             }
             if ($hasArrayRule) {
                 unset($attributeRules[$ruleIndex]);
             } else {
                 $ruleData = ['array', []];
             }
             $postProcessors[] = function (Validator $validator) use($attribute, $ruleName, $ruleParams) {
                 $validator->each($attribute, [$ruleName . ':' . implode(', ', $ruleParams)]);
             };
         }
     }
     return $postProcessors;
 }
示例#5
0
 private function replaceParagraphsByBr($html)
 {
     $html = preg_replace("/<p[^>]*?>/", "", $html);
     $html = trim(str_replace("</p>", "<br />", $html));
     if (Str::endsWith($html, "<br />")) {
         $html = substr($html, 0, strlen($html) - strlen("<br />"));
     }
     return $html;
 }
示例#6
0
 /**
  * Purges confirmation fields from the attributes.
  *
  * @return void
  */
 public function purge()
 {
     foreach ($this->attributes as $k => $attr) {
         // If the attribute ends in "_confirmation"
         if (Str::endsWith($k, '_confirmation')) {
             // We unset the value
             unset($this->attributes[$k]);
         }
     }
 }
示例#7
0
 /**
  * Get unique random filename with $extenstion within $path directory
  * @param string $path
  * @param string $extension
  * @return string
  */
 public static function get($path, $extension)
 {
     if (!Str::endsWith($path, '/')) {
         $path .= '/';
     }
     do {
         $name = Str::random(10) . '.' . $extension;
     } while (file_exists($path . $name));
     return $name;
 }
示例#8
0
 protected function loadFilesRecursively($path)
 {
     foreach ($this->files->files($path) as $file) {
         if (Str::endsWith($file, '.php')) {
             require_once $file;
         }
     }
     foreach ($this->files->directories($path) as $directory) {
         $this->loadFilesRecursively($directory);
     }
 }
 public function bladeDirective($name, $class, $method)
 {
     $this->getBlade()->directive($name, function ($expression) use($class, $method) {
         // for Laravel 5.2 and lower
         $expression = isset($expression) ? $expression : '()';
         if (Str::startsWith($expression, '(') && Str::endsWith($expression, ')')) {
             $expression = mb_substr($expression, 1, -1, 'UTF-8');
         }
         return "<?=app({$class}::class)->{$method}({$expression});?>";
     });
 }
示例#10
0
 private static function isAcademicEmail($mail)
 {
     //TODO add academic domains
     $acdomains = array('auth.gr');
     $email = explode('@', $mail);
     $domain = $email[1];
     if (Str::endsWith($domain, $acdomains)) {
         return true;
     }
     return false;
 }
 /**
  * Registers specified class as a validation rule to Laravel Validator
  *
  * @param $className
  */
 public static function register($className)
 {
     $ruleName = Str::snake(class_basename($className));
     if (Str::endsWith($ruleName, self::RULE_NAME_SUFFIX)) {
         $ruleName = substr($ruleName, 0, -strlen(self::RULE_NAME_SUFFIX));
     }
     static::$registry[$ruleName] = $className;
     /** @var Factory $validatorFactory */
     $validatorFactory = Application::getInstance()->make(Factory::class);
     $validatorFactory->extend($ruleName, $className . '@validate');
     $validatorFactory->replacer($ruleName, $className . '@replace');
 }
 public function testStringEndsWith()
 {
     $str = 'Laravel is really awesome';
     $result = Str::endsWith($str, 'awesome');
     $this->assertEquals($result, true);
     $str = 'Laravel is really awesome';
     $result = Str::endsWith($str, 'Awesome');
     $this->assertEquals($result, false);
     $str = 'Laravel is really awesome';
     $result = Str::endsWith($str, ['Awesome', 'awesome']);
     $this->assertEquals($result, true);
 }
示例#13
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     $packageName = 'laravel-deploy';
     $basePath = \Config::get("{$packageName}::base-path");
     $appName = \Config::get("{$packageName}::application-name");
     $basePath = \Config::get("{$packageName}::base-path");
     $branch = \Config::get("{$packageName}::branch");
     $gitUrl = \Config::get("{$packageName}::git");
     $ownership = \Config::get("{$packageName}::ownership");
     $remoteEnv = \Config::get("{$packageName}::remote-env", "production");
     if (!$appName) {
         $this->error("Please configure application-name inside configuration file. Use `php artisan config:publish quiborgue/{$packageName}` to create it.");
         return;
     }
     if (!$gitUrl) {
         $this->error("Please configure git inside configuration file. Use `php artisan config:publish quiborgue/{$packageName}` to create it.");
         return;
     }
     $release = Carbon::now()->getTimestamp();
     $appPath = "{$basePath}/{$appName}";
     $releasePath = "{$appPath}/releases/{$release}";
     $writables = array();
     $shareds = array('app/storage/sessions/', 'app/storage/logs/', 'app/database/production.sqlite');
     $commandList = array();
     $commandList[] = "export LARAVEL_ENV={$remoteEnv}";
     $commandList[] = "mkdir -p {$releasePath}";
     $commandList[] = "git clone --depth 1 -b {$branch} \"{$gitUrl}\" {$releasePath}";
     $commandList[] = "cd {$releasePath}";
     $commandList[] = "composer install --no-interaction --no-dev --prefer-dist";
     foreach ($shareds as $shared) {
         $sharedPath = "{$appPath}/shared/{$shared}";
         if (Str::endsWith($shared, "/")) {
             $sharedPath = rtrim($sharedPath, "/");
             $shared = rtrim($shared, "/");
             $commandList[] = "mkdir -p {$sharedPath}";
         } else {
             $sharedDirPath = dirname($sharedPath);
             $commandList[] = "mkdir -p {$sharedDirPath}";
             // $commandList[] = "touch $sharedPath";
         }
         $commandList[] = "rm -rf {$releasePath}/{$shared}";
         $commandList[] = "ln -s {$sharedPath} {$releasePath}/{$shared}";
     }
     foreach ($writables as $writable) {
         $commandList[] = "chmod -R 755 {$releasePath}/{$writable}";
         $commandList[] = "chmod -R g+s {$releasePath}/{$writable}";
         $commandList[] = "chown -R {$ownership} {$releasePath}/{$writable}";
     }
     $commandList[] = "rm -f {$appPath}/current";
     $commandList[] = "ln -s {$releasePath} {$appPath}/current";
     $commandList[] = "php artisan migrate --force";
     $this->runCommandList($commandList);
 }
 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request $request
  * @param  \Closure $next
  * @param  string $target_field
  * @param  string $source_field
  * @param  string $pattern
  * @return mixed
  */
 public function handle($request, Closure $next, $target_field, $source_field = null, $pattern = '/\\s*([\\t\\v]|\\s*,\\s*)+\\s*/')
 {
     //Commas can’t be used by \Illuminate\Pipeline\Pipeline::parsePipeString
     $pattern = str_replace('COMMA', ',', $pattern);
     if (!Str::startsWith($pattern, '/') or !Str::endsWith($pattern, '/') or $pattern == '/') {
         $pattern = '/' . preg_quote($pattern, '/') . '/';
     }
     if (empty($source_field)) {
         $source_field = $target_field;
     }
     $this->setRequestInput($request, $target_field, preg_split($pattern, $request->input($source_field)));
     return $next($request);
 }
 public function addFolder()
 {
     $folder = Input::get('name');
     $path = Input::get('path');
     if (Media::checkPath($path)) {
         if (Str::endsWith($path, "/")) {
             $newFolder = $path . $folder;
         } else {
             $newFolder = $path . "/" . $folder;
         }
         return response()->json(mkdir($newFolder));
     }
     return response()->json(false);
 }
示例#16
0
 public function each($attribute, $rules)
 {
     $data = $this->dot($this->initializeAttributeOnData($attribute));
     $pattern = str_replace('\\*', '[^\\.]+', preg_quote($attribute));
     foreach ($data as $key => $value) {
         if (Str::startsWith($key, $attribute) || (bool) preg_match('/^' . $pattern . '\\z/', $key)) {
             foreach ((array) $rules as $ruleKey => $ruleValue) {
                 if (!is_string($ruleKey) || Str::endsWith($key, $ruleKey)) {
                     $this->mergeRules($key, $ruleValue);
                 }
             }
         }
     }
 }
示例#17
0
 public function handle()
 {
     if (($table = $this->option('table')) === null) {
         $tables = $this->DBHelper->listTables();
         $table = $this->choice('Choose table:', $tables, null);
     }
     $columns = collect($this->DBHelper->listColumns($table));
     $this->transformer->setColumns($columns);
     $namespace = config('thunderclap.namespace');
     $moduleName = str_replace('_', '', title_case($table));
     $containerPath = config('thunderclap.target_dir', base_path('modules'));
     $modulePath = $containerPath . DIRECTORY_SEPARATOR . $moduleName;
     // 1. check existing module
     if (is_dir($modulePath)) {
         $overwrite = $this->confirm("Folder {$modulePath} already exist, do you want to overwrite it?");
         if ($overwrite) {
             File::deleteDirectory($modulePath);
         } else {
             return false;
         }
     }
     // 2. create modules directory
     $this->info('Creating modules directory...');
     $this->packerHelper->makeDir($containerPath);
     $this->packerHelper->makeDir($modulePath);
     // 3. copy module skeleton
     $stubs = __DIR__ . '/../../stubs';
     $this->info('Copying module skeleton into ' . $modulePath);
     File::copyDirectory($stubs, $modulePath);
     $templates = ['module-name' => str_replace('_', '-', $table), 'route-prefix' => config('thunderclap.routes.prefix')];
     // 4. rename file and replace common string
     $search = [':Namespace:', ':module_name:', ':module-name:', ':module name:', ':Module Name:', ':moduleName:', ':ModuleName:', ':FILLABLE:', ':TRANSFORMER_FIELDS:', ':VALIDATION_RULES:', ':LANG_FIELDS:', ':TABLE_HEADERS:', ':TABLE_FIELDS:', ':DETAIL_FIELDS:', ':FORM_CREATE_FIELDS:', ':FORM_EDIT_FIELDS:', ':VIEW_EXTENDS:', ':route-prefix:', ':route-middleware:', ':route-url-prefix:'];
     $replace = [$namespace, snake_case($table), $templates['module-name'], str_replace('_', ' ', strtolower($table)), ucwords(str_replace('_', ' ', $table)), str_replace('_', '', camel_case($table)), str_replace('_', '', title_case($table)), $this->transformer->toFillableFields(), $this->transformer->toTransformerFields(), $this->transformer->toValidationRules(), $this->transformer->toLangFields(), $this->transformer->toTableHeaders(), $this->transformer->toTableFields(), $this->transformer->toDetailFields(), $this->transformer->toFormCreateFields(), $this->transformer->toFormUpdateFields(), config('thunderclap.view.extends'), $templates['route-prefix'], $this->toArrayElement(config('thunderclap.routes.middleware')), $this->getRouteUrlPrefix($templates['route-prefix'], $templates['module-name'])];
     foreach (File::allFiles($modulePath) as $file) {
         if (is_file($file)) {
             $newFile = $deleteOriginal = false;
             if (Str::endsWith($file, '.stub')) {
                 $newFile = Str::substr($file, 0, -5);
                 $deleteOriginal = true;
             }
             $this->packerHelper->replaceAndSave($file, $search, $replace, $newFile, $deleteOriginal);
         }
     }
     $this->warn('Add following service provider to config/app.php ====> ' . $namespace . '\\' . ucwords(str_replace('_', ' ', $table)) . '\\ServiceProvider::class,');
 }
示例#18
0
 public function extractOperatorAndValue($value)
 {
     $matchedOperator = '=';
     if (is_array($value)) {
         $matchedOperator = 'IN';
     } else {
         foreach ($this->operators as $operator) {
             if (Str::startsWith($value, $operator)) {
                 $matchedOperator = $operator;
                 $value = substr($value, strlen($operator));
                 break;
             }
         }
         if (Str::startsWith($value, '%') || Str::endsWith($value, '%')) {
             $matchedOperator = 'LIKE';
         }
     }
     return array($matchedOperator, $value);
 }
示例#19
0
 /**
  * Compile views.
  *
  * @param  array  $paths
  * @param  string $storagePath
  * @return $this
  */
 public function compileViews(array $paths, $storagePath)
 {
     $this->makeDestination($storagePath);
     $compiler = new BladeCompiler($this->files, $storagePath);
     foreach ($paths as $path) {
         $files = $this->files->glob(realpath($path) . '/{,**/}*.php', GLOB_BRACE);
         foreach ($files as $file) {
             if (!Str::endsWith(strtolower($file), '.blade.php')) {
                 continue;
             }
             $compiler->setPath($file);
             $contents = $this->parseToken($this->files->get($file));
             $contents = $compiler->compileString($contents);
             $compiledPath = $compiler->getCompiledPath($compiler->getPath());
             $this->files->put($compiledPath . '.php', $contents);
         }
     }
     return $this;
 }
示例#20
0
 /**
  * Parses the input string as an argument.
  *
  * @param  string $option
  *
  * @return \Symfony\Component\Console\Input\InputOption
  */
 public static function parseOption($option)
 {
     list($command, $description) = self::parse($option);
     list($shortcut, $command) = self::parseShortcut($command);
     // --example= or --example
     if (Str::endsWith($command, '=')) {
         return new InputOption(trim($command, '='), $shortcut, InputOption::VALUE_OPTIONAL, $description);
     }
     // --example=hello --example=world
     if (Str::endsWith($command, '=*')) {
         return new InputOption(trim($command, '=*'), $shortcut, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, $description);
     }
     // --example=hello or --example
     if (preg_match('/(.+)\\=(.+)/', $command, $data)) {
         return new InputOption($data[1], $shortcut, InputOption::VALUE_OPTIONAL, $description, $data[2]);
     }
     // --example
     return new InputOption($command, $shortcut, InputOption::VALUE_NONE, $description);
 }
示例#21
0
 public function getAttribute($key)
 {
     if ($this->isUseImageMax()) {
         $attribute = parent::getAttribute($key);
         if (!$attribute) {
             $profiles = config('imagemax.profiles', []);
             foreach ($profiles as $profile => $options) {
                 if (Str::endsWith($key, $last = '_' . str_slug($profile, '_'))) {
                     $image = Str::replaceLast($last, '', $key);
                     if (in_array($image, $this->getImagableAttributes()) && $this->getAttribute($image)) {
                         return ImageMax::make($this->getAttribute($image), $options);
                     }
                 }
             }
         }
         return $attribute;
     }
     return $this->thumbnailerGetAttribute($key);
 }
 protected function registerDatabaseConfig($app)
 {
     $app['db.options'] = $app->share(function ($app) {
         $config = $app['config']->get('app/database');
         if (isset($config['driver']) && in_array($config['driver'], array('pdo_sqlite', 'sqlite'))) {
             $basename = isset($config['databasename']) ? basename($config['databasename']) : 'bolt';
             if (!Str::endsWith($basename, '.db')) {
                 $basename .= '.db';
             }
             $options = array('driver' => 'pdo_sqlite', 'path' => $app['paths']['storage'] . '/' . $basename, 'randomfunction' => 'RANDOM()');
         } else {
             // Assume we configured it correctly. Yeehaa!
             if (empty($config['password'])) {
                 $config['password'] = '';
             }
             $driver = isset($config['driver']) ? $config['driver'] : 'pdo_mysql';
             $randomfunction = '';
             if (in_array($driver, array('mysql', 'mysqli'))) {
                 $driver = 'pdo_mysql';
                 $randomfunction = 'RAND()';
             }
             if (in_array($driver, array('postgres', 'postgresql'))) {
                 $driver = 'pdo_pgsql';
                 $randomfunction = 'RANDOM()';
             }
             $options = array('driver' => $driver, 'host' => isset($config['host']) ? $config['host'] : 'localhost', 'dbname' => $config['databasename'], 'user' => $config['username'], 'password' => $config['password'], 'randomfunction' => $randomfunction);
             $options['charset'] = isset($config['charset']) ? $config['charset'] : 'utf8';
         }
         switch ($options['driver']) {
             case 'pdo_mysql':
                 $options['port'] = isset($config['port']) ? $config['port'] : '3306';
                 $options['reservedwords'] = explode(',', 'accessible,add,all,alter,analyze,and,as,asc,asensitive,before,between,' . 'bigint,binary,blob,both,by,call,cascade,case,change,char,character,check,collate,column,condition,constraint,' . 'continue,convert,create,cross,current_date,current_time,current_timestamp,current_user,cursor,database,databases,' . 'day_hour,day_microsecond,day_minute,day_second,dec,decimal,declare,default,delayed,delete,desc,describe,' . 'deterministic,distinct,distinctrow,div,double,drop,dual,each,else,elseif,enclosed,escaped,exists,exit,explain,' . 'false,fetch,float,float4,float8,for,force,foreign,from,fulltext,get,grant,group,having,high_priority,hour_microsecond,' . 'hour_minute,hour_second,if,ignore,in,index,infile,inner,inout,insensitive,insert,int,int1,int2,int3,int4,int8,' . 'integer,interval,into,io_after_gtids,io_before_gtids,is,iterate,join,key,keys,kill,leading,leave,left,like,limit,' . 'linear,lines,load,localtime,localtimestamp,lock,long,longblob,longtext,loop,low_priority,master_bind,' . 'master_ssl_verify_server_cert,match,maxvalue,mediumblob,mediumint,mediumtext,middleint,minute_microsecond,' . 'minute_second,mod,modifies,natural,nonblocking,not,no_write_to_binlog,null,numeric,on,optimize,option,optionally,' . 'or,order,out,outer,outfile,partition,precision,primary,procedure,purge,range,read,reads,read_write,real,references,' . 'regexp,release,rename,repeat,replace,require,resignal,restrict,return,revoke,right,rlike,schema,schemas,' . 'second_microsecond,select,sensitive,separator,set,show,signal,smallint,spatial,specific,sql,sqlexception,sqlstate,' . 'sqlwarning,sql_big_result,sql_calc_found_rows,sql_small_result,ssl,starting,straight_join,table,terminated,then,' . 'tinyblob,tinyint,tinytext,to,trailing,trigger,true,undo,union,unique,unlock,unsigned,update,usage,use,using,utc_date,' . 'utc_time,utc_timestamp,values,varbinary,varchar,varcharacter,varying,when,where,while,with,write,xor,year_month,' . 'zerofill,nonblocking');
                 break;
             case 'pdo_sqlite':
                 $options['reservedwords'] = explode(',', 'abort,action,add,after,all,alter,analyze,and,as,asc,attach,autoincrement,' . 'before,begin,between,by,cascade,case,cast,check,collate,column,commit,conflict,constraint,create,cross,current_date,' . 'current_time,current_timestamp,database,default,deferrable,deferred,delete,desc,detach,distinct,drop,each,else,end,' . 'escape,except,exclusive,exists,explain,fail,for,foreign,from,full,glob,group,having,if,ignore,immediate,in,index,' . 'indexed,initially,inner,insert,instead,intersect,into,is,isnull,join,key,left,like,limit,match,natural,no,not,' . 'notnull,null,of,offset,on,or,order,outer,plan,pragma,primary,query,raise,references,regexp,reindex,release,rename,' . 'replace,restrict,right,rollback');
                 break;
             case 'pdo_pgsql':
                 $options['port'] = isset($config['port']) ? $config['port'] : '5432';
                 $options['reservedwords'] = explode(',', 'all,analyse,analyze,and,any,as,asc,authorization,between,bigint,binary,bit,' . 'boolean,both,case,cast,char,character,check,coalesce,collate,column,constraint,convert,create,cross,current_date,' . 'current_time,current_timestamp,current_user,dec,decimal,default,deferrable,desc,distinct,do,else,end,except,exists,' . 'extract,float,for,foreign,freeze,from,full,grant,group,having,ilike,in,initially,inner,int,integer,intersect,interval,' . 'into,is,isnull,join,leading,left,like,limit,localtime,localtimestamp,natural,nchar,new,none,not,notnull,null,nullif,' . 'numeric,off,offset,old,on,only,or,order,outer,overlaps,overlay,placing,position,primary,real,references,right,row,' . 'select,session_user,setof,similar,smallint,some,substring,table,then,time,timestamp,to,trailing,treat,trim,union,' . 'unique,user,using,varchar,verbose,when,where,false,true');
         }
         return $options;
     });
 }
示例#23
0
 protected function parseName($name)
 {
     $rootNamespace = $this->laravel->getNamespace();
     if (!Str::endsWith($name, 'Repository')) {
         $name .= 'Repository';
     }
     if (Str::contains($name, ['Models', 'Eloquent'])) {
         $name = str_replace(['Models', 'Eloquent'], '', $name);
     }
     if (Str::contains($name, '/')) {
         $name = str_replace('/', '\\', $name);
     }
     $name = str_replace('\\\\', '\\', $name);
     if (Str::startsWith($name, $rootNamespace)) {
         if (!Str::contains($name, 'Repositories')) {
             return str_replace($rootNamespace, $this->getDefaultNamespace($rootNamespace), $name);
         }
         return $name;
     }
     return $this->parseName($this->getDefaultNamespace(trim($rootNamespace, '\\')) . '\\' . $name);
 }
示例#24
0
 protected function processDatatables($datatables)
 {
     $datatables = parent::processDatatables($datatables);
     $datatables = $datatables->addColumn('category', function ($data) {
         return dataImplode($data->categories, 'category');
     })->addColumn('tag', function ($data) {
         return dataImplode($data->tags, 'tag');
     });
     if (Str::endsWith(get_called_class(), 'Backend\\ArticleController')) {
         return $datatables->editColumn('is_featured', function ($data) {
             return $data->is_featured ? Form::open(['style' => 'display: inline!important', 'method' => 'put', 'action' => [$this->baseClass . '@putUpdateFeatured', $data->{$this->model->getKeyName()}]]) . '  <button type="submit" name="is_featured" value="0" onClick="return confirm(\'' . $this->getTrans('unsetfeaturedconfirmation') . '\');" 
                     class="btn btn-small btn-link" title="' . $this->getTrans('unsetfeatured') . '">
                         <i class="fa fa-xs fa-star text-yellow"></i> 
                 </button>
                 </form>' : Form::open(['style' => 'display: inline!important', 'method' => 'put', 'action' => [$this->baseClass . '@putUpdateFeatured', $data->{$this->model->getKeyName()}]]) . '  <button type="submit" name="is_featured" value="1" onClick="return confirm(\'' . $this->getTrans('setfeaturedconfirmation') . '\');" 
                     class="btn btn-small btn-link" title="' . $this->getTrans('setfeatured') . '">
                         <i class="fa fa-xs fa-star-o"></i> 
                 </button>
                 </form>';
         });
     }
     return $datatables;
 }
示例#25
0
文件: helpers.php 项目: saj696/pipe
 /**
  * Determine if a given string ends with a given substring.
  *
  * @param  string $haystack
  * @param  string|array $needles
  * @return bool
  */
 function ends_with($haystack, $needles)
 {
     return Str::endsWith($haystack, $needles);
 }
示例#26
0
文件: Validator.php 项目: imydou/dkuu
 /**
  * Gather a copy of the attribute data filled with any missing attributes.
  *
  * @param  string  $attribute
  * @return array
  */
 protected function initializeAttributeOnData($attribute)
 {
     $explicitPath = $this->getLeadingExplicitAttributePath($attribute);
     $data = $this->extractDataFromPath($explicitPath);
     if (!Str::contains($attribute, '*') || Str::endsWith($attribute, '*')) {
         return $data;
     }
     return data_set($data, $attribute, null, true);
 }
示例#27
0
 /**
  * Format the given key and value into a JSON string for expectation checks.
  *
  * @param  string  $key
  * @param  mixed  $value
  * @return string
  */
 protected function formatToExpectedJson($key, $value)
 {
     $expected = json_encode([$key => $value]);
     if (Str::startsWith($expected, '{')) {
         $expected = substr($expected, 1);
     }
     if (Str::endsWith($expected, '}')) {
         $expected = substr($expected, 0, -1);
     }
     return trim($expected);
 }
示例#28
0
 /**
  * Get the extension used by the view file.
  *
  * @param  string  $path
  * @return string
  */
 protected function getExtension($path)
 {
     $extensions = array_keys($this->extensions);
     return Arr::first($extensions, function ($key, $value) use($path) {
         return Str::endsWith($path, $value);
     });
 }
示例#29
0
 /**
  * Parse an option expression.
  *
  * @param  string  $token
  * @return \Symfony\Component\Console\Input\InputOption
  */
 protected static function parseOption($token)
 {
     if (Str::contains($token, ' : ')) {
         list($token, $description) = explode(' : ', $token);
         $token = trim($token);
         $description = trim($description);
     } else {
         $description = null;
     }
     $matches = preg_split('/\\s*\\|\\s*/', $token, 2);
     if (isset($matches[1])) {
         $shortcut = $matches[0];
         $token = $matches[1];
     } else {
         $shortcut = null;
     }
     switch (true) {
         case Str::endsWith($token, '='):
             return new InputOption(trim($token, '='), $shortcut, InputOption::VALUE_OPTIONAL, $description);
         case Str::endsWith($token, '=*'):
             return new InputOption(trim($token, '=*'), $shortcut, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, $description);
         case preg_match('/(.+)\\=(.+)/', $token, $matches):
             return new InputOption($matches[1], $shortcut, InputOption::VALUE_OPTIONAL, $description, $matches[2]);
         default:
             return new InputOption($token, $shortcut, InputOption::VALUE_NONE, $description);
     }
 }
示例#30
0
 function ends_with($haystack, $needle)
 {
     return \Illuminate\Support\Str::endsWith($haystack, $needle);
 }