Inheritance: implements Countable, implements IteratorAggregate, implements ArrayAccess
Example #1
13
 /**
  * Generate the alelo orders file.
  *
  * @return string
  */
 public function generate()
 {
     if ($this->productType === null) {
         throw new ProductTypeIsRequiredException();
     }
     $this->header = new HeaderRegistry(['requesterUser' => $this->orderUser, 'orderDate' => (new Carbon())->format('Ymd'), 'orderTime' => (new Carbon())->format('H.i.s')]);
     $this->generateTraillerRegistry();
     $this->fileLayout = $this->fileLayout->append($this->header->__toString());
     $this->fileLayout = $this->fileLayout->append(PHP_EOL);
     $this->fileLayout = $this->fileLayout->append($this->headerEletronic->__toString());
     $this->fileLayout = $this->fileLayout->append(PHP_EOL);
     $this->fileLayout = $this->fileLayout->append($this->branch->__toString());
     $this->fileLayout = $this->fileLayout->append(PHP_EOL);
     foreach ($this->getAllEmployees() as $employeeRegistry) {
         $this->fileLayout = $this->fileLayout->append($employeeRegistry->__toString());
         $this->fileLayout = $this->fileLayout->append(PHP_EOL);
     }
     $this->fileLayout = $this->fileLayout->append($this->traillerRegistry->__toString());
     return $this->fileLayout->__toString();
 }
Example #2
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;
 }
Example #3
8
 /**
  * Generate the alelo orders file.
  *
  * @return string
  */
 public function generate()
 {
     $this->generateTraillerRegistry();
     $this->fileLayout = $this->fileLayout->append($this->header->__toString());
     $this->fileLayout = $this->fileLayout->append(PHP_EOL);
     $this->fileLayout = $this->fileLayout->append($this->branch->__toString());
     $this->fileLayout = $this->fileLayout->append(PHP_EOL);
     foreach ($this->getAllEmployees() as $employeeRegistry) {
         $this->fileLayout = $this->fileLayout->append($employeeRegistry->__toString());
         $this->fileLayout = $this->fileLayout->append(PHP_EOL);
     }
     $this->fileLayout = $this->fileLayout->append($this->traillerRegistry->__toString());
     return (string) $this->fileLayout;
 }
Example #4
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);
     }
 }
Example #5
5
File: Part.php Project: 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);
 }
Example #6
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');
 }
Example #7
4
File: Tidy.php Project: 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();
 }
Example #8
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('');
 }
Example #10
2
 private function isAlbum()
 {
     if (!empty($this->parsedUrl['path'])) {
         // TODO: как правильно вызывать Stringy чтобы не создавать 100 экземпляров внутри кода?
         $stringy = new Stringy();
         $result = $stringy->endsWith(Urls::ALBUM);
         if ($result === true) {
             return true;
         }
     }
     return false;
 }
Example #11
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');
 }
Example #12
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');
 }
 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();
 }
Example #15
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());
 }
Example #16
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);
         }
     }
 }
Example #17
0
 /**
  * Get the required packages.
  *
  * @return array
  */
 private function getPackages()
 {
     $file = getcwd() . '/composer.json';
     if (!file_exists($file)) {
         return [];
     }
     $json = json_decode(file_get_contents($file), true);
     $packages = [];
     if (isset($json['require'])) {
         $packages = array_merge($packages, $json['require']);
     }
     if (isset($json['require-dev'])) {
         $packages = array_merge($packages, $json['require-dev']);
     }
     if (count($packages) <= 0) {
         return [];
     }
     $array = [];
     foreach ($packages as $name => $version) {
         $string = new Stringy($name);
         if ($string->startsWith('php') || $string->startsWith('ext')) {
             continue;
         }
         $array[$name] = $version;
     }
     return $array;
 }
Example #18
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);
     }
 }
 /**
  * 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;
 }
Example #21
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;
     }
 }
Example #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;
 }
Example #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();
 }
Example #24
-1
File: Slug.php Project: 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);
 }
Example #25
-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;
 }
Example #26
-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()
 }
Example #27
-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() : "";
 }
Example #28
-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);
 }
Example #29
-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);
 }
 /**
  * Guesses possible raw data keys from a constructor parameter name.
  *
  * @param \ReflectionParameter $parameter The parameter to guess keys for
  *
  * @return array
  */
 private function getPossibleParameterKeys(\ReflectionParameter $parameter)
 {
     $parameterString = new Stringy($parameter->getName());
     return array((string) $parameterString->underscored(), (string) $parameterString->regexReplace('([a-z]+)([0-9]+)', '\\1_\\2'), $parameter->getName());
 }