/** * Add an image to the grid * * @param string|array $imageData An image */ protected function addRichImage($imageData) { $imageData = $this->present($imageData); if ($this->presenter) { return $this->nest($imageData); } // If we provided a rich thumbnail $link = Arrays::get($imageData, 'link'); $label = Arrays::get($imageData, 'label'); $caption = Arrays::get($imageData, 'caption'); // Create image $image = Arrays::get($imageData, 'image'); $image = HtmlImage::create($image); // Linked thumbnail if (!$caption and !$label and $link) { $image = Link::create($link, $image)->addClass('thumbnail'); // Plain thumbnail } else { $thumbnail = Element::create('div', $image)->addClass('thumbnail'); if ($label) { $thumbnail->nest(Element::create('h3', $label)); } if ($caption) { $thumbnail->nest(Element::create('p', $caption)); } $image = $thumbnail; } return $this->nest(Element::create('li', $image)); }
/** * Get an option from the config file * * @param string $option The key of the option * * @return mixed Its value */ public static function option($option) { // Get config file if (!static::$options) { static::$options = (include __DIR__ . '/../config/config.php'); } return ArraysMethods::get(static::$options, $option); }
/** * Get a particular option in the array * * @param string $option An option * * @return mixed Its value */ public function getOption($option = null) { $globalOptions = Menu::getOption(); $combinedOptions = array_replace_recursive($globalOptions, $this->options); if (!$option) { return $combinedOptions; } return ArraysMethods::get($combinedOptions, $option); }
/** * Set a particular option in the array * * @param string $option The option * @param mixed $value Its new value * * @return MenuObject */ public function setOption($option, $value) { // forward item config values to the items if (Str::startsWith($option, 'item.')) { foreach ($this->children as $child) { $child->setOption($option, $value); } } elseif (Str::startsWith($option, 'item_list.')) { $this->options = ArraysMethods::set($this->options, $option, $value); } else { Menu::setOption($option, $value); } return $this; }
/** * Get the list of tables in the database * * @return array An array of tables names */ protected function getTables() { // Get database name $database = $this->connection->getDatabaseName(); $database = basename($database); // Create query switch ($this->connection->getDriverName()) { case 'mysql': $results = $this->pdo("SHOW TABLES FROM `" . $database . "`"); $results = Arrays::pluck($results, 0); break; case 'sqlite': $results = $this->app['db']->table('sqlite_master')->where('type', 'table')->get(); $results = Arrays::pluck($results, 'name'); break; } return $results; }
/** * Insert data into the database * * @param array $data Data */ protected function seed($seeds) { $table = $this->getTableName(); $model = $this->getModelName(); // Format data $seeds = Arrays::each($seeds, function ($seed) use($model) { $seed = new $model($seed); return $seed->getAttributes(); }); // Slice for SQLite $slicer = floor(999 / sizeof($seeds[0])); $slices = array_chunk($seeds, $slicer); foreach ($slices as $slice) { DB::table($table)->insert($slice); } // Print number of seeds // $element = String::remove(get_called_class(), 'Seeder'); // print sizeof($seeds).' '.lcfirst($element).' seeded successfully'.PHP_EOL; }
/** * Group values from a collection according to the results of a closure */ public static function group($collection, $grouper) { $collection = (array) $collection; $result = array(); // Iterate over values, group by property/results from closure foreach ($collection as $key => $value) { $key = is_callable($grouper) ? $grouper($value, $key) : ArraysMethods::get($value, $grouper); if (!isset($result[$key])) { $result[$key] = array(); } // Add to results $result[$key][] = $value; } return $result; }
public static function findBy($collection, $property, $value, $comparisonOp = "eq") { $filtered = static::filterBy($collection, $property, $value, $comparisonOp); return \Underscore\Methods\ArraysMethods::first($filtered); }
/** * Catch aliases and reroute them to the right methods */ public static function __callStatic($method, $parameters) { // Get base class and methods class $callingClass = static::computeClassToCall(get_called_class(), $method, $parameters); $methodsClass = Method::getMethodsFromType($callingClass); // Defer to Methods class if (method_exists($methodsClass, $method)) { return Repository::callMethod($methodsClass, $method, $parameters); } // Check for an alias if ($alias = Method::getAliasOf($method)) { return Repository::callMethod($methodsClass, $alias, $parameters); } // Check for parsers if (method_exists('Underscore\\Parse', $method)) { return Repository::callMethod('Underscore\\Parse', $method, $parameters); } // Defered methods if ($defered = Dispatch::toNative($callingClass, $method)) { return call_user_func_array($defered, $parameters); } // Look in the macros if ($macro = ArraysMethods::get(static::$macros, $callingClass . '.' . $method)) { return call_user_func_array($macro, $parameters); } throw new BadMethodCallException('The method ' . $callingClass . '::' . $method . ' does not exist'); }
/** * Invoke a function on all of an array's values */ public static function invoke($array, $callable, $arguments = array()) { // If one argument given for each iteration, create an array for it if (!is_array($arguments)) { $arguments = ArraysMethods::repeat($arguments, sizeof($array)); } // If the callable has arguments, pass them if ($arguments) { return array_map($callable, $array, $arguments); } return array_map($callable, $array); }
/** * Group values from a collection according to the results of a closure. */ public static function group($collection, $grouper, $saveKeys = false) { $collection = (array) $collection; $result = []; // Iterate over values, group by property/results from closure foreach ($collection as $key => $value) { $groupKey = is_callable($grouper) ? $grouper($value, $key) : ArraysMethods::get($value, $grouper); $newValue = static::get($result, $groupKey); // Add to results if ($groupKey !== null && $saveKeys) { $result[$groupKey] = $newValue; $result[$groupKey][$key] = $value; } elseif ($groupKey !== null) { $result[$groupKey] = $newValue; $result[$groupKey][] = $value; } } return $result; }
/** * Converts data to CSV * * @param mixed $data The data to convert * * @return string Converted data */ public static function toCSV($data, $delimiter = ';', $exportHeaders = false) { $csv = array(); // Convert objects to arrays if (is_object($data)) { $data = (array) $data; } // Don't convert if it's not an array if (!is_array($data)) { return $data; } // Fetch headers if requested if ($exportHeaders) { $headers = array_keys(ArraysMethods::first($data)); $csv[] = implode($delimiter, $headers); } // Quote values and create row foreach ($data as $header => $row) { // If single column if (!is_array($row)) { $csv[] = '"' . $header . '"' . $delimiter . '"' . $row . '"'; continue; } // Else add values foreach ($row as $key => $value) { $row[$key] = '"' . stripslashes($value) . '"'; } $csv[] = implode($delimiter, $row); } return implode(PHP_EOL, $csv); }
/** * Get the caching hash of the Method * * @param array $parameters The parameters to hash * * @return string */ protected function createHashFromParameters($parameters) { $parameters = Arrays::sortKeys($parameters); $parameters = Arrays::clean($parameters); $hash = array(); foreach ($parameters as $k => $v) { $hash[] = $k . '-' . $v; } if ($this->user) { $hash[] = $this->user->getUid(); } return implode('-', $hash); }
/** * Custom post action to build upon */ public function customUpdate() { // Filter out foreign input that aren't model-related $attributes = (array) DB::table($this->object->getTable())->first(); $attributes = array_keys($attributes); // If no model already exists, attempt a SHOW COLUMNS if (!$attributes) { $attributes = array_pluck(DB::query('SHOW COLUMNS FROM ' . $this->object->getTable()), 'field'); } // Fetch input and its rules $input = Input::all(); $item_id = Arrays::get($input, 'id'); $isAdd = !$item_id; $item = $isAdd ? new $this->model() : $this->object->find($item_id); // Autocomplete uniqueness rules $rules = $this->rules(); foreach ($rules as $field => $rulz) { if (str_contains($rulz, 'unique:')) { $modifiedRules = preg_replace('#unique:([^,]+)([^|,])(\\||$)#', 'unique:$1$2,' . $field, $rulz); $modifiedRules = preg_replace('#unique:([^,]+)(,[^,]+)(\\||$)#', 'unique:$1$2,' . $item_id, $modifiedRules); $rules[$field] = $modifiedRules; } } // Get localized fields $model = $this->model; if (isset($model::$polyglot)) { $localization = Input::only($model::$polyglot); } // Validate input if ($rules) { $validation = Validator::make($input, $rules); if ($validation->fails()) { $return = Redirect::action($this->controller . '@' . ($isAdd ? 'getCreate' : 'getUpdate'), array($item->id))->withInput()->with('items', $item->id)->withErrors($validation); return array('new' => $isAdd, 'errors' => $validation, 'message' => null, 'model' => null, 'return' => $return, 'state' => false); } } // Save attributes $model = $item->fill($input); $model->touch(); // Update localized fields if (isset($localization)) { $model->localize($localization); } // Create message $verb = $isAdd ? 'create' : 'update'; //$message = Babel::restful($this->item, Arrays::get($input, 'name'), $verb); $message = 'The item ' . $input['name'] . ' was correctly updated'; return array('errors' => false, 'message' => $message, 'model' => $model, 'new' => $isAdd, 'return' => $this->here, 'state' => true); }
/** * Clean old save folders * * @return Manager */ public function cleanup() { // Fetch all dumps folders $folders = $this->getAllFolders(); $folders = Arrays::filter($folders, function ($folder) { return is_dir($folder); }); // Parse the date for each one foreach ($folders as $folder) { // Get date from folder name $date = $this->getDateFromFolder($folder); // If dump from last year, remove if ($date->format('Y') < date('Y')) { $this->app['files']->deleteDirectory($folder); continue; } // If dump from last months, just keep main checkpoints if ($date->format('m') < date('m') and !in_array($date->format('d'), array(1, 15))) { $this->app['files']->deleteDirectory($folder); continue; } } return $this; }
/** * Some shortcuts */ public function __call($method, $parameters) { // Resource verbs if (String::endsWith($method, 'Resource')) { $verb = String::remove($method, 'Resource'); $parameters = Arrays::prepend($parameters, $verb); return call_user_func_array(array($this, 'resource'), $parameters); } return parent::__call($method, $parameters); }