public function validate($data) { $validator = Validator::make($data, static::$rules); if ($validator->fails()) { $messages = array_flatten($validator->messages()); App::abort(400, "Validation Error: {$messages['0']}", $this->header); } }
public function test_w_seed() { $array = ["three" => ["three" => ["one" => 1, "two" => 2], "one" => 1, "two" => 2, "four" => null, "five" => new stdClass(), 6 => "six"], "one" => 1, "two" => 2, 6 => "six", "four" => true, "five" => false]; $dt = date(\DateTime::RFC3339); $expected = ["dt" => $dt, "three.three.one" => 1, "three.three.two" => 2, "three.one" => 1, "three.two" => 2, "three.four" => "NULL", "three.five" => "object", "one" => 1, "two" => 2, "four" => 1, "five" => "", 'three.6' => 'six', 6 => 'six']; $this->assertEquals($expected, array_flatten($array, null, ["dt" => $dt])); }
/** * Returns product information for one product. * * @method getProduct * @param int $productId * @return array */ public function getProduct($productId) { /** @var \Mage_Catalog_Model_Product $product */ $product = \Mage::getModel('catalog/product')->load((int) $productId); $products = array(); $models = array(); if ($product->getTypeId() === 'configurable') { $products = $this->getProductVariations($productId); $productIds = array_flatten(array_map(function ($product) { return $product['id']; }, $products['collection'])); foreach ($productIds as $productId) { array_push($models, $this->getProduct($productId)); } } /** @var \Mage_Sendfriend_Model_Sendfriend $friendModel */ $friendModel = \Mage::getModel('sendfriend/sendfriend'); /** @var Mage_CatalogInventory_Model_Stock_Item $stockModel */ $stockModel = \Mage::getModel('cataloginventory/stock_item')->loadByProduct($product); /** @var \Mage_Catalog_Helper_Image $helper */ $helper = \Mage::helper('catalog/image'); $images = $product->getMediaGallery('images'); $imageUrls = []; foreach ($images as $image) { $imageUrls[] = strstr($helper->init($product, 'image', $image['file'])->resize(480)->__toString(), 'catalog/product'); } $foo = 'bar'; return array('id' => $product->getId(), 'sku' => $product->getSku(), 'name' => $product->getName(), 'type' => $product->getTypeId(), 'price' => (double) $product->getFinalPrice(), 'oldPrice' => (double) $product->getPrice(), 'condition' => $product->getAttributeText('condition'), 'size' => $product->getAttributeText('size'), 'colour' => (int) $product->getData('color'), 'manufacturer' => (int) $product->getData('manufacturer'), 'status' => intval($product->getIsSalable()), 'designer' => $product->getAttributeText('designer'), 'description' => nl2br(trim($product->getDescription())), 'largeImage' => strstr($product->getMediaConfig()->getMediaUrl($product->getData('image')), 'catalog/product'), 'similar' => $product->getRelatedProductIds(), 'images' => $imageUrls, 'products' => $products, 'models' => $models); }
/** * Get all permission slugs from all permissions of all roles * * @return Array of permission slugs */ protected function getAllPermissionsFromAllRoles() { $permissions = $this->roles->load('permissions')->fetch('permissions')->toArray(); return array_map('strtolower', array_unique(array_flatten(array_map(function ($permission) { return array_fetch($permission, 'permission_slug'); }, $permissions)))); }
public function getSearchFieldsAndValues($format, $domain) { $fields = array(); $fields['formats'] = array("text", "image", "video"); if (is_null($format)) { $domains = Entity::distinct('domain')->get(); $usersInvolvedInEntities = array_flatten(Entity::distinct('user_id')->get()->toArray()); } else { $domains = Entity::where('format', $format)->distinct('domain')->get(); $usersInvolvedInEntities = array_flatten(Entity::where('format', $format)->distinct('user_id')->get()->toArray()); if ($key = array_search($format, $fields['formats'])) { $value = $fields['formats'][$key]; unset($fields['formats'][$key]); array_unshift($fields['formats'], $value); } } if (is_null($domain)) { $documentTypes = Entity::where('format', $format)->distinct('documentType')->get(); } else { $documentTypes = Entity::where('format', $format)->where('domain', $domain)->distinct('documentType')->get(); $usersInvolvedInEntities = array_flatten(Entity::where('format', $format)->where('domain', $domain)->distinct('user_id')->get()->toArray()); } foreach ($usersInvolvedInEntities as $key => $user_id) { $fields['userAgents'][$key] = User::find($user_id); } $fields['domains'] = array_flatten($domains->toArray()); $fields['documentTypes'] = array_flatten($documentTypes->toArray()); return $fields; }
public function query($sql, $values = array()) { if (getenv('LOG') == 'true') { $GLOBALS['logger']->log($sql, PEAR_LOG_INFO); } $sql = new Expressions($sql); $sql->set_connection($this); $sql->bind_values($values); $sql = trim($sql->to_s()); $values = $values ? array_flatten($values) : array(); if (!($sth = @$this->connection->prepare($sql))) { throw new DatabaseException($this->connection->lastErrorMsg(), $this->connection->lastErrorCode()); } for ($i = 0, $n = count($values); $i < $n; ++$i) { if (is_string($values[$i])) { $type = SQLITE3_TEXT; } elseif (is_float($values[$i])) { $type = SQLITE3_FLOAT; } elseif (is_numeric($values[$i])) { $type = SQLITE3_INTEGER; } elseif (is_null($values[$i])) { $type = SQLITE3_NULL; } else { $type = SQLITE3_TEXT; } $sth->bindParam($i + 1, $values[$i], $type); } return $sth->execute(); }
/** * Get all access module from all permissions of all roles. * * @return Array of permission slugs */ public function hasAccess() { $permissions = $this->roles->load('permissions')->fetch('permissions')->toArray(); return array_map('strtolower', array_unique(array_flatten(array_map(function ($permission) { return array_fetch($permission, 'permission_slug'); }, $permissions)))); }
/** * Creates the table * * @param Tableman $ref * @param Config $conf * @config config, headers, extra_classes * @usage https://github.com/mechanicious/tableman/wiki/Bs3Table-Extension-Usage * @return string */ public function make(Tableman &$ref, Config $conf) { $items = $ref->getColumns(); $columnNames = $ref->getColumnHeaders(); $rows = $ref->getRows(); $table = new BootstrapTable(); $table->setConfig($conf->get('config')); $table->setHeader($conf->get('header')); $table->setTableExtraClasses($conf->get('extra_classes')); $limit = $conf->get('limit'); array_walk($rows, function ($row, $rowIndex) use(&$table, &$columnNames, $limit) { if (!is_null($limit) && $rowIndex > $limit) { return; } // Flatten I mean from boundary: array('columnName' => 'rowData'), to: array('rowData'). foreach ($columnNames as $columnName) { $flattenRows = array(); foreach ($row as $columnHeader => $cell) { $mockedRow = array(); if (isset($row[$columnName])) { // If this is false then data got somehow mixed up $mockedRow[] = array($row[$columnName]); } } $flattenRows[] = $row; } $table->addRows(array_flatten($flattenRows)); }); // __toString do the work! return (string) $table; }
/** * Execute the console command. * * @return mixed */ public function handle() { list($rootFolder, $current, $folder) = $this->setFolder(); $counter = 1; $measurementsCounter = 0; $file = fopen($folder . 'file' . $counter . '.csv', "w"); $maxRows = self::MAX_ROWS - 500; Measurement::with('station')->where('time', '>', Carbon::now()->subMonths(3))->orderBy('time', 'asc')->chunk(500, function ($measurements) use($folder, &$file, &$measurementsCounter, &$counter, $maxRows) { if ($measurementsCounter > $maxRows) { echo "measurements: " . $measurementsCounter . "\n"; echo "file created: " . $counter . ".csv\n"; $measurementsCounter = 0; if (is_resource($file)) { fclose($file); } $counter++; $file = fopen($folder . 'file' . $counter . '.csv', "w"); } foreach ($measurements as $measurement) { $array = $measurement->toArray(); unset($array['station_id'], $array['station']['id']); fputcsv($file, array_flatten($array)); } $measurementsCounter += 500; }); File::put($rootFolder . 'finished.txt', $current); }
/** * Set the order of branches in the tree. * * @param array $order * * @return void */ protected static function setBranchOrder(array $order) { static::$branchOrder = array_flip(array_flatten($order)); static::$branchOrder = array_map(function ($item) { return ++$item; }, static::$branchOrder); }
public function filterResults() { $input = Input::all(); if (array_key_exists('wasDerivedFrom', $input)) { array_push($this->appends, 'wasDerivedFrom'); } if (array_key_exists('wasGeneratedBy', $input)) { array_push($this->with, 'wasGeneratedBy'); } if (array_key_exists('wasAttributedTo', $input)) { $this->with = array_merge($this->with, array('wasAttributedToUserAgent', 'wasAttributedToCrowdAgent')); } if (array_key_exists('wasAttributedToUserAgent', $input)) { array_push($this->with, 'wasAttributedToUserAgent'); } if (array_key_exists('wasAttributedToCrowdAgent', $input)) { array_push($this->with, 'wasAttributedToCrowdAgent'); } if (array_key_exists('hasConfiguration', $input)) { array_push($this->with, 'hasConfiguration'); } if (isset($input['wasDerivedFrom']['without'])) { $this->hidden = array_merge($this->hidden, array_flatten(array($input['wasDerivedFrom']['without']))); } if (isset($input['without'])) { $this->hidden = array_merge($this->hidden, array_flatten(array($input['without']))); } }
public function getAdminEntitiesIDs($entity_name) { if (\Auth::check()) { return array_flatten(\Access::where('user_id', \Auth::user()->id)->where('entity_name', $entity_name)->get(['entity_id'])->toArray()); } return []; }
/** * Ajax. * * @Post("all", as="user.tool.kataomoi.all") * * @return \Illuminate\Http\JsonResponse */ public function postAll() { try { /** @var \stdClass $me */ $me = $this->session('twitter.me.all'); $to = $this->TwistOAuth; $params = ['screen_name' => $me->screen_name, 'count' => '5000', 'stringify_ids' => true]; $following = $to->get('friends/ids', $params); $followers = $to->get('followers/ids', $params); $data = ['data' => []]; $ids = []; $response = []; if (count($following) === 0) { throw new RuntimeException('following list is empty.'); } foreach ($following->ids as $id) { if (in_array($id, $followers->ids, true)) { continue; } $ids[] = $id; } foreach (array_chunk($ids, 100) as $item) { $response[] = $to->get('users/lookup', ['user_id' => implode(',', $item)]); } foreach (array_flatten($response) as $item) { $data['data'][] = ['id' => $item->id_str, 'screen_name' => $item->screen_name, 'name' => $item->name, 'icon_url' => $item->profile_image_url_https]; } $data['csrf_token'] = csrf_token(); return $this->onSuccess($data); } catch (\Exception $e) { return $this->onError($e); } }
/** * Add a route to the underlying route collection. * * @param array|string $methods * @param string $uri * @param \Closure|array|string $action * * @return \Illuminate\Routing\Route */ protected function addRoute($methods, $uri, $action) { if (in_array('restful', array_flatten($this->groupStack))) { parent::addRoute($methods, $uri . $this->formatSuffix, $action); } return $this->routes->add($this->createRoute($methods, $uri, $action)); }
/** * Get all objects and their related variants for a section * @param $where * @param array $selectedColumns * @return mixed * @throws Exception * @since 08-01-2016 * @author Dinanath Thakur <*****@*****.**> */ public function getAllObjectsAndVariantsOfASectionWhere($where, $selectedColumns = ['*']) { if (func_num_args() > 0) { $where = func_get_arg(0); $cacheKey = $this->table . "::" . implode('-', array_flatten($where)); if (cacheGet($cacheKey)) { return cacheGet($cacheKey); } // die("no cache"); DB::statement('SET SESSION group_concat_max_len = 10000'); $result = DB::table($this->table)->join('settings_sections', 'settings_sections.section_id', '=', 'settings_objects.section_id')->join('settings_descriptions', 'settings_descriptions.object_id', '=', 'settings_objects.object_id')->leftJoin('settings_variants', 'settings_variants.object_id', '=', 'settings_objects.object_id')->leftJoin('settings_descriptions as sd', function ($join) { $join->on('sd.object_id', '=', 'settings_variants.variant_id'); })->whereRaw($where['rawQuery'], isset($where['bindParams']) ? $where['bindParams'] : array())->select(DB::raw('settings_objects.object_id , settings_objects.*, settings_sections.name AS section_name, settings_descriptions.value AS setting_name, settings_descriptions.tooltip, GROUP_CONCAT(DISTINCT(settings_variants.variant_id) ORDER BY settings_variants.position) AS variant_ids, GROUP_CONCAT(DISTINCT(BINARY settings_variants.name) ORDER BY settings_variants.position SEPARATOR "____") AS variant_names, GROUP_CONCAT(CASE sd.object_type WHEN "V" THEN sd.value END ORDER BY settings_variants.position SEPARATOR "____") AS var_names'))->orderBy('settings_objects.position')->groupBy('settings_objects.object_id')->get(); cachePut($cacheKey, $result, $this->minutes); return $result; } else { throw new Exception('Argument Not Passed'); } }
/** * Handle the form. * * @param PermissionFormBuilder $builder * @param RoleRepositoryInterface $roles * @param Redirector $redirect */ public function handle(PermissionFormBuilder $builder, RoleRepositoryInterface $roles, Redirector $redirect) { /* @var RoleInterface|EloquentModel $role */ $role = $builder->getEntry(); $roles->save($role->setAttribute('permissions', array_filter(array_flatten($builder->getFormInput())))); $builder->setFormResponse($redirect->refresh()); }
/** * Get all permission slugs from all permissions of all roles. * * @return array of permission slugs */ protected function getAllPermissionsFormAllRoles() { $permissions = $this->roles->load('permissions')->pluck('permissions')->toArray(); return array_map('strtolower', array_unique(array_flatten(array_map(function ($permission) { return array_pluck($permission, 'Pm_Slug'); }, $permissions)))); }
public function query($sql, $values = array()) { $sql = new Expressions($sql); $sql->set_connection($this); $sql->bind_values($values); $sql = trim($sql->to_s()); $values = $values ? array_flatten($values) : array(); if (!($sth = mysqli_prepare($this->connection, $sql))) { throw new DatabaseException(mysqli_error($this->connection), mysqli_errno($this->connection)); } if (count($values) > 0) { $params = array($sth, ''); foreach ($values as &$value) { if (is_int($value)) { $params[1] .= 'i'; } elseif (is_float($value)) { $params[1] .= 'd'; } else { $params[1] .= 's'; } $params[] =& $value; } if ($params[1]) { call_user_func_array('mysqli_stmt_bind_param', $params); } } if (is_int($ret = mysqli_stmt_execute($sth))) { return $ret; } return new MysqliResultSet($sth); }
public function setAuditoria($file, $accion, $data = array()) { $ruta = '../app/auditorias/' . $file . '.csv'; $file = fopen($ruta, 'a+'); $auditoria = array_flatten([$accion, date('d-m-Y H:i:s'), $data]); fputcsv($file, $auditoria); fclose($file); }
public function getAllPermissionsFormAllRoles() { $permissionArray = []; $permission = $this->roles->load('permissions')->fetch('permissions')->toArray(); return array_map('strtolower', array_unique(array_flatten(array_map(function ($permission) { return array_pluck($permission, 'permission_slug'); }, $permission)))); }
/** * Update the specified resource in storage. * * @param TutoringRequest $request * @param int $id * * @return Response */ public function update(TutoringRequest $request, $id) { $tutoring = Tutoring::findOrFail($id); $modules = array_flatten($request->only('modules')); $tutoring->update($request->only(['class_id', 'date', 'start_time', 'end_time'])); $tutoring->modules()->sync($modules); return redirect(action('TutoringController@index')); }
public function index(Asset $asset) { $asset->add('scripts.js', 'bloveless.module.migrator::js/admin/column.js'); $tables = DB::select('SHOW TABLES'); $tables = array_flatten(array_map(function ($table) { return array_values((array) $table); }, $tables)); return view('bloveless.module.migrator::admin/columns/index', compact('tables')); }
public function response(array $errors) { $data['msg'] = 'Gagal'; // $data['errors']=$errors; $data['errors'] = array_flatten($errors); $data['code'] = 403; // echo json_encode($data); return \Response::make(json_encode($data), 403); }
private static function getRelatedObjects($id) { $objects = \DB::table('log_values')->where('log_id', $id)->get(); $array = []; foreach ($objects as $object) { array_push($array, [$object->key => \App::make($object->key)->find($object->value)]); } return array_flatten($array); }
public function updateRole($request) { $id = $request->route('role'); $model = Role::findOrFail($id); $model->fill(['name' => $request->name, 'label' => $request->label]); $permissions = array_flatten($request->permissions); $model->permissions()->sync($permissions); return $model->save(); }
public function update($id, UserRequest $request) { $user = User::findOrFail($id); $groups = array_filter(array_flatten([$request->input('primary_group'), $request->input('secondary_group')])); $updateData = ['email' => $request->input('email'), 'password' => bcrypt($request->input('password'))]; $user->update($updateData); $user->groups()->sync($groups); return Redirect::action('UserController@index'); }
public function index($slug) { $category = Category::findBySlug($slug); $sizes = array_flatten(Attribute::where("attr", "Shoe Size")->first()->attributeoptions()->select('option_name')->get()->toArray()); $parts = scandir(public_path() . "/Frontend/shoes/" . $category->folder); $parts = array_diff($parts, array('.', '..')); $savedList = User::find(Session::get('user')->id)->savedlist; //print_r($savedList); return view(Config('constants.frontView') . '.design', compact('category', 'parts', 'sizes', 'savedList')); }
function action() { $args = func_get_args(); $vars = array(); if (count($args) > 0) { $action = array_shift($args); $vars = array_flatten($args); return register_action($action, $action, $vars); } }
/** * 将属性数组转换为字符串, 支持传入多个数组, 会进行递归合并, 统一属性值会通过空格拼接在一起。 * * @return array */ public static function mergeAttributes() { $attributes = call_user_func_array('array_merge_recursive', func_get_args()); foreach ($attributes as $attribute => &$value) { if (is_array($value)) { $value = join(' ', array_flatten($value)); } } return $attributes; }
protected function sanitizeProperties($options) { if (isset($options['class'])) { if (!is_array($options['class'])) { $options['class'] = array($options['class']); } else { $options['class'] = array_flatten($options['class']); } } return $options; }