public function transform(array $data)
 {
     $code = isset($data[$this->httpCodeKey]) ? $data[$this->httpCodeKey] : 200;
     $arrayResponse = ArrayUtils::fromObject($data);
     $response = new JsonResponse($arrayResponse, $code);
     return $response;
 }
 public function handleEntityUpdate(AbstractEntity $entity, array $allowedProperties, array $data)
 {
     $data = ArrayUtils::filterKeys($data, $allowedProperties);
     $repository = $this->knit->getRepository($entity->__getClass());
     try {
         $entity->updateWithData($data);
         $repository->save($entity);
     } catch (DataValidationFailedException $e) {
         $errors = array();
         foreach ($e->getErrors() as $error) {
             $errors[$error->getProperty()] = $error->getFailedValidators();
         }
         return array($this->httpCodeKey => 400, 'errors' => $errors);
     }
     return array();
 }
Example #3
0
 /**
  * Create an article.
  *
  * Returns path to the created markdown file.
  *
  * @param  string $title Title of the article.
  * @param  string $slug  [optional] Slug of the article. If ommitted, it will be built based on the title.
  * @param  string $image [optional] Path to cover image, relative to the web root folder.
  *
  * @return string
  */
 public function create($title, $slug = null, $image = null)
 {
     $slug = $slug ? StringUtils::urlFriendly($slug) : StringUtils::urlFriendly($title);
     $articles = $this->reader->load();
     // check if maybe there already is such article
     if (ArrayUtils::search($articles, 'slug', $slug) !== false) {
         throw new NotUniqueException('There already is a blog article with a slug "' . $slug . '".');
     }
     // create a markdown post
     $markdown = $title . NL . '==========' . NL . date('Y-m-d') . NL . ($image ? '![cover](' . $image . ')' . NL : '') . NL;
     $markdownFile = $this->articlesDir . $slug . '.md';
     // create the articles directory if doesn't exist
     $this->filesystem->dumpFile($markdownFile, $markdown);
     // add to articles array
     array_unshift($articles, array('slug' => $slug, 'title' => $title));
     $this->writer->write($this->dataFile, $articles);
     return $markdownFile;
 }
 /**
  * When the found controller method wants to have the request injected,
  * this method will do it.
  * 
  * @param  ControllerWillRespond $event Event triggered before execution of controller.
  */
 public function injectRequest(ControllerWillRespond $event)
 {
     $route = $this->router->getRoute($event->getControllerName());
     // find the method's meta data
     $methods = $route->getMethods();
     $i = ArrayUtils::search($methods, 'method', $event->getMethod());
     if ($i === false) {
         return;
     }
     $method = $methods[$i];
     $arguments = $event->getArguments();
     foreach ($method['params'] as $i => $param) {
         if ($param['class'] && Debugger::isExtending($param['class'], Request::class, true) && !$arguments[$i] instanceof Request) {
             $arguments[$i] = $this->request;
         }
     }
     $event->setArguments($arguments);
 }
Example #5
0
 /**
  * Returns list of available processes
  *
  * @return array
  */
 public function getAvailableProcesses()
 {
     $known_processes = array();
     foreach ($this->getAllProcessInfo() as $process) {
         $known_processes[ArrayUtils::get($process, 'group')] = ArrayUtils::get($process, 'name');
     }
     return $known_processes;
 }
Example #6
0
 /**
  * Returns a string containing JavaScript code that will log all the arguments into browser's JavaScript console.
  * 
  * Attempts to convert all objects into arrays.
  *
  * There is a shortcut alias function `\MD\console_string_dump()`.
  * 
  * @param mixed $variable1 Variable to be dumped.
  * @param mixed $variable2 Another variable to be dumped.
  * @param mixed $variable3 Another variable to be dumped.
  * @param ...
  * @return string
  */
 public static function consoleStringDump()
 {
     $arguments = func_get_args();
     $output = '(function(w,u) {';
     $output .= 'if(w.console===u)return;';
     foreach ($arguments as $variable) {
         $dump = null;
         if (is_object($variable)) {
             $dump = json_encode(ArrayUtils::fromObject($variable));
         } elseif (is_bool($variable)) {
             $dump = '"(bool) ' . ($variable ? 'true' : 'false') . '"';
         } else {
             $dump = json_encode($variable);
         }
         $output .= 'w.console.log(' . $dump . ');';
     }
     $output .= '})(window);';
     return $output;
 }
Example #7
0
 /**
  * Generates a URL for this route, using the given parameters.
  * 
  * If some parameters aren't in the pattern, then they will be attached as a query string.
  * 
  * @param array $params Route parameters.
  * @param string $host [optional] Host to prefix the URL with. Should also include the protocol, e.g. 'http://domain.com'.
  *                     Default: null - no host included.
  * @return string
  */
 public function generateUrl(array $params = array(), $host = null)
 {
     if ($this->isPrivate()) {
         throw new \RuntimeException('Route "' . $this->getName() . '" is set to private, so it is not reachable via URL, therefore it cannot have a URL generated.');
     }
     $routeName = $this->getName();
     $url = preg_replace_callback('/(\\{([\\w:]+)\\})(\\?)?/is', function ($matches) use(&$params, $routeName) {
         $constraints = explode(':', $matches[2]);
         $name = array_shift($constraints);
         $optional = isset($matches[3]) && $matches[3] === '?';
         if (!isset($params[$name])) {
             if (!$optional) {
                 throw new RouteParameterNotFoundException('Could not find parameter "' . $name . '" for route "' . $routeName . '".');
             } else {
                 return '';
             }
         }
         $param = urlencode($params[$name]);
         unset($params[$name]);
         /** @todo Should also check the constraints before injecting the item. */
         return $param;
     }, $this->getUrlPattern());
     // remove all optional characters from the route
     $url = preg_replace('/(\\/\\/\\?)/is', '/', $url);
     // two slashes followed by a ? (ie. //? ) change to a single slash (ie. /).
     $url = str_replace('?', '', $url);
     // remove any other ? marks
     if (!empty($params)) {
         $url .= '?' . ArrayUtils::toQueryString($params);
     }
     if ($host && !empty($host)) {
         $url = rtrim($host, '/') . '/' . ltrim($url, '/');
     }
     return $url;
 }
Example #8
0
 /**
  * Returns code status text
  *
  * @param  int        $code
  * @param  string     $default
  *
  * @return string
  */
 public static function getText($code, $default = '')
 {
     return ArrayUtils::get(self::$statusTexts, $code, $default);
 }
 /**
  * @dataProvider collectionProvider
  */
 public function testResetKeys($collection)
 {
     $this->assertTrue(ArrayUtils::isCollection(ObjectUtils::resetKeys($collection)));
     $collectionNamed = ObjectUtils::keyExplode($collection, 'name');
     $this->assertTrue(ArrayUtils::isCollection(ObjectUtils::resetKeys($collectionNamed)), 'Failed to assert that MD\\Foundation\\Utils\\Object::resetKeys() returns a collection.');
 }
 /**
  * Transforms the whole data to JSON format.
  * 
  * @return string
  */
 public function toJson()
 {
     return json_encode(ArrayUtils::fromObject($this->data));
 }
Example #11
0
 /**
  * Gets an article based on slug.
  *
  * @param  string $slug Slug of the article to get.
  *
  * @return Article
  */
 public function getArticle($slug)
 {
     $data = $this->load();
     $i = ArrayUtils::search($data, 'slug', $slug);
     if ($i === false) {
         throw new NotFoundException('Could not find blog article with slug "' . $slug . '".');
     }
     return $this->readArticle($data[$i]['slug']);
 }
Example #12
0
 /**
  * Returns connection config if defined
  *
  * @param  string     $name
  *
  * @return array|null
  */
 public function getConfiguration($name)
 {
     return ArrayUtils::get($this->configs, $name, null);
 }
Example #13
0
 public function testOnly()
 {
     $input = array('name' => 'John', 'surname' => 'Doe', 'age' => 30);
     $expected = array('name' => 'John', 'surname' => 'Doe');
     $result = ArrayUtils::only($input, array('name', 'surname'));
     $this->assertSame($expected, $result);
 }
Example #14
0
 /**
  * Resets keys of an array containing a collection of objects to numerical values starting with `0`.
  * 
  * @param array|object $objects Collection of objects - either an array or a collection object that implements `toArray` method.
  * @return array Resetted array.
  * 
  * @throws InvalidArgumentException When the `$objects` argument is not an array or cannot be converted to an array.
  */
 public static function resetKeys($objects)
 {
     // convert to array, for example for Doctrine collections
     if (is_object($objects) && method_exists($objects, 'toArray')) {
         $objects = $objects->toArray();
     }
     if (!is_array($objects)) {
         throw new InvalidArgumentException('array or object convertible to array', $objects);
     }
     return ArrayUtils::resetKeys($objects);
 }
Example #15
0
 /**
  * Expands GLOB resource patterns.
  * 
  * @param  string $resource Resource name.
  * @param  string $type    Type of the resource.
  * @return array
  */
 public function expand($resource, $type)
 {
     list($moduleName, $subDir, $filePattern) = $this->parseResourceName($resource);
     $resourceLocation = $moduleName . ':' . $subDir . ':';
     // read from application dir
     $appDir = rtrim($this->_application->getApplicationDir(), DS) . DS . 'Resources' . DS;
     // if a module name was specified then point to a subfolder with the module name
     if (!empty($moduleName)) {
         // check for module existence in the first place
         if (!$this->_application->hasModule($moduleName)) {
             throw new ResourceNotFoundException('There is no module "' . $moduleName . '" registered, so cannot find its resource.');
         }
         $appDir = $appDir . $moduleName . DS;
     }
     $appDir = $this->buildResourcePath($appDir, $type, $subDir, '');
     $appFiles = FilesystemUtils::glob($appDir . $filePattern, FilesystemUtils::GLOB_ROOTFIRST | GLOB_BRACE);
     $resources = array();
     foreach ($appFiles as $file) {
         $resources[] = $resourceLocation . substr($file, mb_strlen($appDir));
     }
     // now take care of the module dir
     if ($moduleName) {
         $module = $this->_application->getModule($moduleName);
         $moduleDir = rtrim($module->getModuleDir(), DS) . DS . 'Resources' . DS;
         $moduleDir = $this->buildResourcePath($moduleDir, $type, $subDir, '');
         $moduleFiles = FilesystemUtils::glob($moduleDir . $filePattern, GLOB_BRACE);
         foreach ($moduleFiles as $file) {
             $resources[] = $resourceLocation . substr($file, mb_strlen($moduleDir));
         }
     }
     $resources = array_unique($resources);
     return ArrayUtils::sortPaths($resources, true);
 }
Example #16
0
 /**
  * Sort the items based on `orderBy` and `orderDir` parameters.
  *
  * @param array $items  Items to be sorted.
  * @param array $params Query params.
  *
  * @return array
  */
 protected function sort(array $items, array $params)
 {
     if (is_array($params['orderBy'])) {
         foreach ($params['orderBy'] as $property => $orderDir) {
             if (is_string($orderDir)) {
                 $property = $orderDir;
                 $orderDir = Knit::ORDER_ASC;
             }
             $items = ArrayUtils::multiSort($items, $property, $orderDir === Knit::ORDER_DESC);
             // memory sorting only supports one level sorting
             break;
         }
         return $items;
     }
     $orderDir = isset($params['orderDir']) ? $params['orderDir'] : Knit::ORDER_ASC;
     return ArrayUtils::multiSort($items, $params['orderBy'], $orderDir === Knit::ORDER_DESC);
 }
 /**
  * Extended `glob()` functionality that supports double star `**` (globstar) wildcard.
  *
  * PHP's `glob()` implementation doesn't allow for `**` wildcard. In Bash 4 it can be enabled with `globstar` setting.
  *
  * In case the `**` wildcard is not used in the pattern then this method just calls PHP's `glob()`.
  *
  * For full documentation see PHP's [`glob()` documentation](http://php.net/manual/en/function.glob.php).
  *
  * It's worth noting that if you want to find files inside current directory and their subdirectories,
  * then you have to use a `GLOB_BRACE` flag and pattern, e.g.:
  * 
  *     echo \MD\Foundation\Utils\FilesystemUtils::glob('{,** /}*.js', GLOB_BRACE); // note: remove space between * and /
  *     // -> array(
  *     //      'main.js',
  *     //      'dir/script.js',
  *     //      'dir/more/scripts.js'
  *     // );
  *      
  * Implementation of this convention varies between libs in various languages and `MD\Foundation` sticks
  * with what [Bash manual states](http://www.gnu.org/software/bash/manual/bashref.html#Pattern-Matching).
  * More about this is explained in [#2](https://github.com/michaldudek/Foundation/issues/2).
  *
  * This function also supports its own implementation of `GLOB_BRACE` flag on systems that do not support it
  * (e.g. Alpine Linux, popular base for Docker containers). Because it's impossible to detect if that flag was
  * passed or not (as it has `null` or `0` value), on such systems the function assumes that yes, this flag was
  * passed if there are any `{}` braces used in the pattern. This implementation might not be so fast as a system
  * implementation, so use with caution or switch to "fuller" distro.
  *
  * Additionally it provides sorting option to the results, which you can pass along with
  * other flags. Constants `FilesystemUtils::GLOB_ROOTFIRST` and `FilesystemUtils::GLOB_CHILDFIRST`
  * sort the results either as "root first" where files in a directory are listed before directories and
  * subdirectories, or "child first" where subdirectories are listed before files.
  * 
  * @param  string  $pattern The pattern. Supports `**` wildcard.
  * @param  int $flags [optional] `glob()` flags. See `glob()`'s documentation. Default: `0`.
  * @return array|bool
  */
 public static function glob($pattern, $flags = 0)
 {
     // turn off custom flags
     $globFlags = ($flags | static::GLOB_CHILDFIRST | static::GLOB_ROOTFIRST) ^ (static::GLOB_CHILDFIRST | static::GLOB_ROOTFIRST);
     // our custom implementation will be expanding some patterns (namely globstar and braces) so we gather them all
     $patterns = array($pattern);
     // expand GLOB_BRACE if it's not defined on the system (e.g. Alpine Linux)
     // let's assume that it's passed always in such cases (most common usage)
     // and keeping the original pattern will make us safe to detect the desired files with {} in name anyway
     if (!defined('GLOB_BRACE') || !GLOB_BRACE) {
         $patterns = array_merge($patterns, self::globBraceExpand($patterns));
     }
     // expand globstar if added
     if (stripos($pattern, '**') !== false) {
         $patterns = array_merge($patterns, self::globStarExpand($patterns, $globFlags));
     }
     // finally when all patterns expanded, just rerun them and merge results
     $files = array();
     foreach ($patterns as $pat) {
         $files = array_merge($files, glob($pat, $globFlags));
     }
     // fix some paths as they might have gotten double // due to not-perfect pattern expansion
     $files = array_map(function ($file) {
         return str_replace('//', '/', $file);
     }, $files);
     // make sure no repetitions from all the patterns provided
     $files = array_unique($files);
     // sort by root first?
     if ($flags & static::GLOB_ROOTFIRST) {
         $files = ArrayUtils::sortPaths($files, true);
     } else {
         if ($flags & static::GLOB_CHILDFIRST) {
             $files = ArrayUtils::sortPaths($files, false);
         } elseif (!($flags & GLOB_NOSORT)) {
             // default sort order is alphabetically
             sort($files);
         }
     }
     return $files;
 }
Example #18
0
 /**
  * Returns concrete factory for given response type.
  *
  * @param  string  $type
  *
  * @return ConcreteFactoryInterface
  */
 protected function get($type)
 {
     return ArrayUtils::get($this->factories, $type, null);
 }
Example #19
0
 /**
  * Constructor.
  *
  * @param array                $config         Connection config.
  * @param CriteriaParser       $criteriaParser Knit criteria parser for MongoDB.
  * @param LoggerInterface|null $logger         [optional] Logger.
  *
  * @SuppressWarnings(PHPMD.CyclomaticComplexity,PHPMD.NPathComplexity)
  */
 public function __construct(array $config, CriteriaParser $criteriaParser, LoggerInterface $logger = null)
 {
     // check for all required info
     if (!ArrayUtils::checkValues($config, ['hostname', 'database'])) {
         throw new \InvalidArgumentException('Invalid config passed to ' . __CLASS__ . '.');
     }
     $this->criteriaParser = $criteriaParser;
     $this->logger = $logger ? $logger : new NullLogger();
     try {
         // define MongoClient options
         $options = ['db' => $config['database'], 'connect' => true];
         if (ArrayUtils::checkValues($config, ['username', 'password'])) {
             $options['username'] = $config['username'];
             $options['password'] = $config['password'];
         }
         if (isset($config['replica_set'])) {
             $options['replicaSet'] = $config['replica_set'];
         }
         // define the DSN or connection definition string
         $dsn = 'mongodb://' . $config['hostname'] . (isset($config['port']) && $config['port'] ? ':' . $config['port'] : '');
         // also add any additional hosts
         if (isset($config['hosts'])) {
             if (!is_array($config['hosts'])) {
                 throw new \InvalidArgumentException(__CLASS__ . ' config option "hosts" must be an array of hosts.');
             }
             foreach ($config['hosts'] as $host) {
                 if (!ArrayUtils::checkValues($host, ['hostname'])) {
                     throw new \InvalidArgumentException(__CLASS__ . ' config option "hosts" must be an array of array hosts definitions' . ' with at least "hostname" key.');
                 }
                 $dsn .= ',' . $host['hostname'] . (isset($host['port']) && $host['port'] ? ':' . $host['port'] : '');
             }
         }
         $this->dsn = $dsn;
         $this->options = $options;
         $this->databaseName = $config['database'];
     } catch (MongoException $e) {
         throw new StoreQueryErrorException($e->getMessage(), $e->getCode(), $e);
     }
 }
Example #20
0
 /**
  * Extends the config with the given config.
  * 
  * @param Config $config Config to read from.
  * @return bool
  */
 public function extend(Config $config)
 {
     $this->config = ArrayUtils::merge($this->config, $config->getNamespace());
     $this->loadedFiles = array_merge($this->loadedFiles, $config->getLoadedFiles());
     return true;
 }