create() public static method

Creates a Stringy object and assigns both str and encoding properties the supplied values. $str is cast to a string prior to assignment, and if $encoding is not specified, it defaults to mb_internal_encoding(). It then returns the initialized object. Throws an InvalidArgumentException if the first argument is an array or object without a __toString method.
public static create ( mixed $str = '', string $encoding = null ) : Stringy
$str mixed Value to modify, after being cast to string
$encoding string The character encoding
return Stringy A Stringy object
Esempio n. 1
8
 /**
  * Generate the full registry string.
  *
  * @return string
  */
 protected function generate()
 {
     $this->resultString = Stringy::create('');
     /*
      * @var Field
      */
     foreach ($this->values as $valueName => $valueClass) {
         $this->resultString = $this->resultString->append($valueClass->getValue());
     }
     return (string) $this->resultString;
 }
Esempio n. 2
5
 /**
  * @param string $type
  */
 protected function checkType($type = '')
 {
     if (!$type) {
         throw new \BadMethodCallException(self::EXCEPTION_SCHEMA_TYPE_REQUIRED);
     }
     if (Stringy::create(substr($type, 0, 1))->isLowerCase()) {
         throw new \InvalidArgumentException(self::EXCEPTION_SCHEMA_TYPE_INVALID . ': ' . $type);
     }
 }
Esempio n. 3
5
File: Part.php Progetto: enzyme/name
 /**
  * Returns the shortened version of this name.
  *
  * @return string
  */
 public function short()
 {
     $shortened_parts = [];
     foreach ($this->segments as $part) {
         $string = S::create($part);
         if ($string->contains('.')) {
             $shortened_parts[] = $string;
         } else {
             $shortened_parts[] = $string->truncate(2, '.');
         }
     }
     return implode(' ', $shortened_parts);
 }
Esempio n. 4
5
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     try {
         $helper = $this->getHelper('question');
         $question = new Question('Please enter the login : '******'');
         $login = $helper->ask($input, $output, $question);
         if ($login == "") {
             throw new \Exception("you must specify login");
         }
         // récupération de la config securité
         $values = \Parameters::get('security');
         $class = $values['security']['classes'];
         $ss = new $class(new Session(), new Request());
         // get user instance
         $user = $ss->userFromLogin($login);
         if ($user == null) {
             throw new \Exception("User {$login} doesn't exist");
         }
         $iduser = $user->id;
         // get all roles
         $roles = $ss->getRoles();
         $strRole = "[";
         foreach ($roles as $role) {
             if ($strRole != "[") {
                 $strRole .= ",";
             }
             $strRole .= $role->role;
         }
         $strRole .= "]";
         $question = new Question('Add roles for ' . $login . ' ' . $strRole . ', type role separated by comma : ', '');
         $roles = $helper->ask($input, $output, $question);
         $output->writeln('Add roles to user');
         if ($roles != "" && $iduser != null) {
             $rolea = \Stringy\Stringy::create($roles)->split(",");
             foreach ($rolea as $role) {
                 $roles = $ss->getRolesFromName(array($role));
                 $role1 = $roles->first();
                 $ss->addUserToRole($iduser, $role1->id);
             }
         }
     } catch (\Exception $e) {
         $output->writeln('Error : ' . $e->getMessage());
     }
     $output->writeln('finished');
 }
Esempio n. 5
4
File: Tidy.php Progetto: blypo/blypo
 public function render($str = false)
 {
     if (!$str) {
         $str = isset($this->arguments['str']) ? $this->arguments['str'] : '';
     }
     $str = isset($this->arguments['str']) ? $this->arguments['str'] : '';
     return S::create($str)->tidy();
 }
Esempio n. 6
4
 protected function getCommandName()
 {
     $commandName = '';
     $namespace = $this->getNamespace();
     if (isset($namespace)) {
         $namespace = preg_replace('/(?<=\\w)(?=[A-Z])/', " \$1", $this->getNamespace());
         foreach (explode('\\', $namespace) as $item) {
             $commandName .= Stringy::create($item)->slugify()->__toString() . ':';
         }
     }
     $className = preg_replace('/(?<=\\w)(?=[A-Z])/', " \$1", $this->getClassName());
     $commandName .= Stringy::create($className)->slugify()->__toString();
     return $commandName;
 }
 public function getInitial()
 {
     $words = new Collection(explode(' ', $this->name));
     // if name contains single word, use first N character
     if ($words->count() === 1) {
         if ($this->name->length() >= $this->length) {
             return $this->name->substr(0, $this->length);
         }
         return (string) $words->first();
     }
     // otherwise, use initial char from each word
     $initials = new Collection();
     $words->each(function ($word) use($initials) {
         $initials->push(Stringy::create($word)->substr(0, 1));
     });
     return $initials->slice(0, $this->length)->implode('');
 }
Esempio n. 8
2
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     try {
         $helper = $this->getHelper('question');
         $question = new Question('Please enter the login : '******'');
         $login = $helper->ask($input, $output, $question);
         if ($login == "") {
             throw new \Exception("you must specify login");
         }
         $question = new Question('Please enter the mail : ', '');
         $email = $helper->ask($input, $output, $question);
         if ($email == "") {
             throw new \Exception("you must specify a mail");
         }
         $question = new Question('Please enter the password : '******'');
         $password = $helper->ask($input, $output, $question);
         if ($password == "") {
             throw new \Exception("you must specify a password");
         }
         // récupération de la config securité
         $values = \Parameters::get('security');
         $class = $values['security']['classes'];
         $ss = new $class(new Session(), new Request());
         if ($ss->emailExist($email)) {
             throw new \Exception("Email already exists.");
         }
         if ($ss->loginExist($login)) {
             throw new \Exception("Login already exists.");
         }
         // get all roles
         $roles = $ss->getRoles();
         $strRole = "[";
         foreach ($roles as $role) {
             if ($strRole != "[") {
                 $strRole .= ",";
             }
             $strRole .= $role->role;
         }
         $strRole .= "]";
         $question = new Question('Add roles for this user ' . $strRole . ', type role separated by comma : ', '');
         $roles = $helper->ask($input, $output, $question);
         $output->writeln('Create user');
         $ret = $ss->userCreate($login, $email, $password);
         if ($roles != "" && $ret != null) {
             $rolea = \Stringy\Stringy::create($roles)->split(",");
             foreach ($rolea as $role) {
                 $roles = $ss->getRolesFromName(array($role));
                 $role1 = $roles->first();
                 $ss->addUserToRole($ret, $role1->id);
             }
         }
     } catch (\Exception $e) {
         $output->writeln('Error : ' . $e->getMessage());
     }
     $output->writeln('finished');
 }
Esempio n. 9
2
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $fs = new Filesystem();
     try {
         Capsule::connection("default")->setFetchMode(PDO::FETCH_NUM);
         $arr = Capsule::connection("default")->select('SHOW TABLES;');
         foreach ($arr as $ts) {
             $name = $ts[0];
             $output->writeln($name);
             // search for primary
             $sql1 = "SHOW INDEX from " . $name . " WHERE Key_name='PRIMARY';";
             $pk1 = Capsule::connection("default")->select($sql1);
             if (count($pk1) > 0) {
                 $pk = $pk1[0][4];
             } else {
                 // by first unique index
                 $sql2 = "SHOW INDEX from " . $name . " WHERE Non_unique=0;";
                 $pk2 = Capsule::connection("default")->select($sql2);
                 if (count($pk2) > 0) {
                     $pk = $pk2[0][4];
                 }
             }
             $modelname = Stringy::create($name)->upperCamelize()->__toString();
             $nmodel = $this->model;
             $nmodel = str_replace('##modelname##', $modelname, $nmodel);
             $nmodel = str_replace('##tablename##', $name, $nmodel);
             $nmodel = str_replace('##foreignkey##', $pk, $nmodel);
             $path = ROOT . DS . "app" . DS . "Application" . DS . "Models" . DS;
             $filename = $path . $modelname . ".php";
             file_put_contents($filename, $nmodel);
         }
     } catch (\Exception $e) {
         $output->writeln('Error : ' . $e->getMessage());
     }
     $output->writeln('finished');
 }
Esempio n. 10
2
 /**
  * Transliterate a UTF-8 value to ASCII.
  *
  * @param  string  $value
  * @return string
  */
 public static function ascii($value)
 {
     return (string) Stringy::create($value)->toAscii();
 }
 public function distributeResources($resources, $componentPrefixedKey = 'LogicalResourceId')
 {
     Log::debug(__METHOD__ . ' start');
     $groupedResourceCollection = [];
     foreach ($this->items as $componentKey => $component) {
         foreach ($resources as $resourceKey => $resource) {
             if (Stringy::create($resource[$componentPrefixedKey])->startsWith(studly_case($componentKey), false)) {
                 $groupedResourceCollection[$componentKey][] = $resource;
                 unset($resources[$resourceKey]);
             }
             if ($resource[$componentPrefixedKey] == data_get($resource, 'StackName') or $resource[$componentPrefixedKey] == '') {
                 $groupedResourceCollection['_stack'][] = $resource;
                 unset($resources[$resourceKey]);
             }
         }
     }
     if (count($resources) > 0) {
         $groupedResourceCollection['_ungrouped'] = $resources;
     }
     $groupedResourceCollectionKeys = array_keys($groupedResourceCollection);
     $retval = Collection::make($groupedResourceCollection)->map(function ($resources) {
         return Collection::make($resources);
     })->replaceKeys(function ($k) use($groupedResourceCollectionKeys) {
         return $groupedResourceCollectionKeys[$k];
     });
     Log::debug(__METHOD__ . ' end');
     return $retval;
 }
 protected function getResourceName(InputInterface $input, OutputInterface $output)
 {
     $description = $input->getArgument('description');
     if (!$description) {
         $dialog = $this->getHelper('dialog');
         $description = $dialog->ask($output, 'Description for this migration: ');
     }
     $this->migration_description = str_replace("'", "\\'", $description);
     return 'Migration' . date('YmdHis') . Stringy::create($description)->slugify()->upperCamelize();
 }
Esempio n. 13
1
 /**
  * @param Plugin $plugin
  */
 public function __construct(Plugin $plugin)
 {
     parent::__construct($plugin);
     $this->pluginBaseDir = dirname($plugin->getFilePath());
     $this->pluginBaseDirRel = preg_replace('/^' . preg_quote(ABSPATH, '/') . '/', '', $this->pluginBaseDir);
     $uploadsData = wp_upload_dir();
     $this->uploadsBaseDir = isset($uploadsData['basedir']) ? $uploadsData['basedir'] . '/' . $plugin->getSlug() : $this->pluginBaseDir . '/uploads';
     $logFileName = Stringy::create($plugin->getName());
     $this->logFilePath = $this->uploadsBaseDir . '/log/' . (string) $logFileName->camelize() . '.log';
     $templatePluginSlugDir = get_template_directory() . '/' . $plugin->getSlug();
     /* @var FcrHooks $hookFactory */
     $hookFactory = $this->plugin->getHookFactory();
     $this->whereTemplatesMayReside = array($templatePluginSlugDir, $this->pluginBaseDir . '/templates');
     $this->whereTemplatesMayResideFilter = $hookFactory->getWhereTemplatesMayResideFilter();
     $this->whereScriptsMayReside = array($templatePluginSlugDir . '/js', $this->pluginBaseDir . '/assets/js');
     $this->whereScriptsMayResideFilter = $hookFactory->getWhereScriptsMayResideFilter();
     $this->whereStylesMayReside = array($templatePluginSlugDir . '/css', $this->pluginBaseDir . '/assets/css');
     $this->whereStylesMayResideFilter = $hookFactory->getWhereStylesMayResideFilter(array());
 }
Esempio n. 14
1
 /**
  * @param array $data
  *
  * @throws ValidatorException
  * @throws ValidatorInvalidRuleException
  */
 public function validate(array $data)
 {
     if (count($this->rules) === 0) {
         return;
     }
     foreach ($this->rules as $ruleIndex => $rules) {
         foreach ($rules as $rule) {
             if (strpos($rule, ':') !== false) {
                 list($composeRuleIndex, $composeRuleParams) = explode(':', $rule);
                 $methodName = Stringy::create($composeRuleIndex);
                 $methodName = (string) $methodName->toTitleCase();
                 $this->methodExists($methodName);
                 $valid = $this->{'validate' . $methodName}($data, $ruleIndex, $composeRuleParams);
                 $this->shouldStop($valid, $composeRuleIndex, $ruleIndex, $data);
                 continue;
             }
             $methodName = Stringy::create($rule);
             $methodName = (string) $methodName->toTitleCase();
             $this->methodExists($methodName);
             $valid = $this->{'validate' . $methodName}($data, $ruleIndex);
             $this->shouldStop($valid, $rule, $ruleIndex, $data);
         }
     }
 }
Esempio n. 15
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     try {
         $helper = $this->getHelper('question');
         $question = new Question('Please enter the role key : ', '');
         $role = $helper->ask($input, $output, $question);
         if ($role == "") {
             throw new \Exception("you must specify role key");
         }
         $roles = \Stringy\Stringy::create($role)->slugify();
         $question = new Question('Please enter the role description : ', '');
         $description = $helper->ask($input, $output, $question);
         if ($description == "") {
             throw new \Exception("you must specify a description");
         }
         // récupération de la config securité
         $values = \Parameters::get('security');
         $class = $values['security']['classes'];
         $ss = new $class(new Session(), new Request());
         $output->writeln('Create role');
         $ss->roleCreate($roles, $description);
     } catch (\Exception $e) {
         $output->writeln('Error : ' . $e->getMessage());
     }
     $output->writeln('finished');
 }
 public function stringFilter($action, $data, array $options = array())
 {
     if ($action == null) {
         return;
     }
     $customManipulators = ["cosgrove"];
     //plans for custom manipulator functions
     switch (true) {
         case in_array($action, $customManipulators):
             //Plans for custom manipulator functions
             break;
         default:
             return call_user_func_array(array(Stringy::create($data), $action), $options);
     }
 }
Esempio n. 17
0
 /**
  * Removes keys that should not be public from a data seed array.
  * Renames keys to be underscored (like serializer does),
  *
  * @param array &$array
  * @param bool  $underscore
  *
  * @return array
  */
 public function mockSerialize(array $array, $underscore = false)
 {
     foreach ($array as $k => $v) {
         if (is_array($v)) {
             unset($array[$k]);
             $k = $underscore ? (string) S::create($k)->underscored() : $k;
             $array[$k] = $this->mockSerialize($v);
         }
     }
     foreach ($this->getPrivateFields() as $key) {
         if (array_key_exists($key, $array)) {
             unset($array[$key]);
         }
     }
     return $array;
 }
Esempio n. 18
0
 /**
  * Format the given name segment/part.
  *
  * @param string $part The part.
  *
  * @return S
  */
 protected function format($part)
 {
     $part = S::create($part);
     switch ($part->substr(0, 2)) {
         case 'Pr':
             return $part->replace('Prefix', $this->tryGetLongVersion($this->name->getPrefix()));
         case 'Fi':
             return $part->replace('First', $this->tryGetLongVersion($this->name->getFirst()));
         case 'Mi':
             return $part->replace('Middle', $this->tryGetLongVersion($this->name->getMiddle()));
         case 'La':
             return $part->replace('Last', $this->tryGetLongVersion($this->name->getLast()));
         case 'P.':
             return $part->replace('P.', $this->tryGetShortVersion($this->name->getPrefix()));
         case 'F.':
             return $part->replace('F.', $this->tryGetShortVersion($this->name->getFirst()));
         case 'M.':
             return $part->replace('M.', $this->tryGetShortVersion($this->name->getMiddle()));
         case 'L.':
             return $part->replace('L.', $this->tryGetShortVersion($this->name->getLast()));
         default:
             return $part;
     }
 }
Esempio n. 19
0
 /**
  * TicketOrder constructor.
  */
 public function __construct()
 {
     $this->fileLayout = Stringy::create('');
 }
Esempio n. 20
0
 /**
  * @dataProvider regexReplaceProvider()
  */
 public function testregexReplace($expected, $str, $pattern, $replacement, $options = 'msr', $encoding = null)
 {
     $stringy = S::create($str, $encoding);
     $result = $stringy->regexReplace($pattern, $replacement, $options);
     $this->assertInstanceOf('Stringy\\Stringy', $result);
     $this->assertEquals($expected, $result);
     $this->assertEquals($str, $stringy);
 }
Esempio n. 21
0
 /**
  * Filtr tekstowy.
  * Wszystkie znaki w jednej linii + htmlspecialchars().
  *
  * @param HtmlElement $htmlElement
  * @param string $text
  * @param string $attr
  */
 private function filterText(HtmlElement $htmlElement, $text, $attr = null)
 {
     if (is_string($attr)) {
         $htmlElement->attr($attr, htmlspecialchars(S::create($text)->collapseWhitespace(), ENT_QUOTES, $this->encoding->render()));
     } else {
         $htmlElement->text(htmlspecialchars(S::create($text)->collapseWhitespace(), ENT_QUOTES, $this->encoding->render()));
     }
 }
Esempio n. 22
-1
 /**
  * Get Url from routename and parameters array
  * @param string $routename route name defined in routes.yml
  * @param array $params parameters array
  * @return string url
  */
 public static function route($routename, $params = array())
 {
     $url = "";
     try {
         $rc = \GL\Core\DI\ServiceProvider::GetDependencyContainer()->get('routes');
         $route = $rc->get($routename);
         if ($route != null) {
             $pattern = $route->getPath();
             $url = \GL\Core\Helpers\Utils::url($pattern);
             $urlo = S::create($url);
             $sep = "/";
             $defaults = $route->getDefaults();
             $param_array = array_merge($defaults, $params);
             foreach ($param_array as $key => $value) {
                 $str = '{' . $key . '}';
                 $urlo = $urlo->replace($str, $value);
             }
             $urlo = $urlo->removeRight($sep);
         }
     } catch (Exception $e) {
         $urlo = S::create("");
     }
     $ret = isset($urlo) == true ? $urlo->__toString() : "";
     return $ret;
 }
Esempio n. 23
-1
 /**
  * @param string $name      Name of method.
  * @param array $arguments  Method arguments.
  *
  * @return mixed
  *
  * @throws MultipleCallersException
  */
 public function __call($name, array $arguments)
 {
     $underscored = S::create($name)->underscored();
     $callers = [];
     $callersNames = [];
     $reflection = new \ReflectionObject($this);
     foreach ($reflection->getProperties(\ReflectionProperty::IS_PROTECTED) as $property) {
         if (is_a($this->{$property->name}, CallerInterface::class) && $underscored->indexOf($this->{$property->name}->callPrefix() . '_') === 0) {
             if (!in_array($this->{$property->name}, $callers, true)) {
                 $callers[] = $this->{$property->name};
                 $callersNames[] = $property->name;
             }
         }
     }
     $methodName = get_class($this) . '::' . $name . '()';
     $errorMessage = 'Call to undefined method ' . $methodName . '.';
     if (empty($callers)) {
         trigger_error($errorMessage, E_USER_ERROR);
     }
     if (($count = count($callers)) !== 1) {
         throw new MultipleCallersException("Found {$count} callers (" . implode(', ', $callersNames) . ") for method {$methodName}.");
     }
     try {
         $exception = null;
         $callers[0]->call($this, $name, $arguments);
     } catch (CallerException $e) {
         $exception = $e;
     }
     if (is_null($exception)) {
         trigger_error($errorMessage, E_USER_ERROR);
     }
     return $exception->getReturn();
 }
Esempio n. 24
-1
File: Slug.php Progetto: blypo/blypo
 public function render($str = false)
 {
     if (!$str) {
         $str = isset($this->arguments['str']) ? $this->arguments['str'] : '';
     }
     $replacement = isset($this->arguments['replacement']) ? $this->arguments['replacement'] : '-';
     return S::create($str)->slugify($replacement);
 }
Esempio n. 25
-1
 /**
  * AleloOrder constructor.
  * @param array $headerData
  */
 public function __construct(array $headerData)
 {
     if (isset($headerData['registryId'])) {
         unset($headerData['registryId']);
     }
     $headerData['registryId'] = 1;
     $this->header = new HeaderRegistry($headerData);
     $this->fileLayout = Stringy::create('');
     if ($this->autoBranchFill) {
         $this->generateBranchRegistryFromHeader($headerData);
     }
 }
Esempio n. 26
-1
 public function getAllMedia()
 {
     $media = collect($this->filesystem->listWith(['mimetype'], 'uploads'));
     $data = new Collection();
     $media->map(function ($file) use($data) {
         $new = ['filename' => $file['filename'], 'extension' => $file['extension'], 'mime' => $file['mimetype'], 'full_name' => $file['filename'] . '.' . $file['extension'], 'full_name_with_path' => $file['path'], 'timestamp' => $file['timestamp']];
         // Don't include hidden files
         if (!Stringy::create($new['full_name'])->startsWith('.')) {
             $data->push($new);
         }
     });
     return $data;
 }
Esempio n. 27
-1
 /**
  * Removes indentation
  * @param string $text The markdown text
  * @return mixed
  */
 protected static function transform($text)
 {
     $firstLine = explode("\n", $text, 1);
     $firstLine = Stringy::create($firstLine[0])->toSpaces();
     preg_match('/([\\s]*).*/', $firstLine, $firstLineSpacesMatches);
     if (isset($firstLineSpacesMatches[1])) {
         $spaceMatcher = "";
         for ($i = 0; $i < strlen($firstLineSpacesMatches[1]); $i++) {
             $spaceMatcher .= "\\s";
         }
         $spaceMatcher = '/^' . $spaceMatcher . '(.*)/m';
         $newText = preg_replace($spaceMatcher, '$1', $text);
         return $newText;
     }
     return $text;
     //$parsedown->text()
 }
Esempio n. 28
-1
 /**
  * @return string
  */
 private function where()
 {
     if (count($this->query->where) <= 0) {
         return "";
     }
     $q = Stringy::create("");
     foreach ($this->query->where as $where) {
         $type = $where[0];
         $arr = $where[1];
         if ($q->count() > 1) {
             $q = $q->append(" {$type} ");
         }
         if (is_string($arr)) {
             $q = $q->append($arr);
         }
         if (is_array($arr)) {
             $q = $q->append($this->buildArrWhere($arr));
             $this->params[] = $arr[2];
         }
     }
     return $q->count() ? $q->prepend(" WHERE ")->__toString() : "";
 }
Esempio n. 29
-2
 /**
  * Try to intelligently create a name from the given string.
  *
  * @param string $name The name.
  *
  * @return Simple
  */
 public static function fromString($name)
 {
     $name = S::create($name)->collapseWhitespace();
     $parts = $name->split(' ');
     $segments = array_filter($parts, function ($part) {
         return S::create($part)->trim()->length() > 0;
     });
     $count = count($segments);
     if ($count < 1) {
         throw new NameException('The string provided could not be processed.');
     }
     return static::processName($segments);
 }
Esempio n. 30
-2
 /**
  * @param array $data
  *
  * @return array
  */
 private static function filteringData(array $data)
 {
     $newKeys = [];
     foreach (array_keys($data) as $key) {
         $key = trim($key);
         if (in_array(S::create($key, "UTF-8")->toLowerCase()->__toString(), array_keys(self::$names))) {
             $newKeys[] = self::$names[S::create($key, "UTF-8")->toLowerCase()->__toString()];
         } else {
             $newKeys[] = $key;
         }
     }
     foreach ($data as $key => &$value) {
         if (is_array($value)) {
         } else {
             $value = trim($value);
         }
     }
     return array_combine($newKeys, $data);
 }