public function parse(RequestInterface $request, ResponseInterface $response, MapInterface $attributes) : MapInterface { $start = $this->clock->now(); if (!$this->isHtml($attributes)) { return $attributes; } $document = $this->reader->read($response->body()); try { $metas = (new Elements('meta'))((new Head())($document)); } catch (ElementNotFoundException $e) { return $attributes; } $meta = $metas->filter(function (ElementInterface $meta) : bool { return $meta->attributes()->contains('name') && $meta->attributes()->get('name')->value() === 'apple-itunes-app' && $meta->attributes()->contains('content'); }); if ($meta->size() !== 1) { return $attributes; } $content = $meta->current()->attributes()->get('content')->value(); $content = new Str($content); if (!$content->match(self::PATTERN)) { return $attributes; } $matches = $content->getMatches(self::PATTERN); return $attributes->put(self::key(), new Attribute(self::key(), (string) $matches['uri'], $this->clock->now()->elapsedSince($start)->milliseconds())); }
public function make(Str $name, Str $value) : HeaderInterface { if ((string) $name->toLower() !== 'content-type') { throw new InvalidArgumentException(); } $matches = $value->getMatches('~(?<type>[\\w*]+)/(?<subType>[\\w*]+)(?<params>(; ?\\w+=\\"?[\\w\\-.]+\\"?)+)?~'); return new ContentType(new ContentTypeValue((string) $matches->get('type'), (string) $matches->get('subType'), $this->buildParams($matches->hasKey('params') ? $matches->get('params') : new Str('')))); }
private function buildSubPropertyCondition(ComparatorInterface $specification) : SequenceInterface { $prop = new Str($specification->property()); $pieces = $prop->split('.'); $var = (new Str('entity_'))->append($pieces->pop()->join('_')); $key = $var->append('_')->append((string) $pieces->last())->append((string) $this->count); return new Sequence(sprintf('%s %s %s', $var->append('.')->append((string) $pieces->last()), $specification->sign(), $key->prepend('{')->append('}')), new Collection([(string) $key => $specification->value()])); }
public function test_it_replaces_between_haystack_with_closure() { $Str = new Str(); $outcome = $Str->replaceBetween('something @here(...) and @here(...)', '@here', function ($between) { return "[ {$between} ]"; }); assertEquals('something [ ... ] and [ ... ]', $outcome); }
public static function fromString(string $type, Types $types) : TypeInterface { $type = new Str($type); if (!$type->match(self::PATTERN)) { throw new InvalidArgumentException(); } return new self($types->build((string) $type->getMatches(self::PATTERN)->get('inner'))); }
private function buildSubPropertyMapping(ComparatorInterface $specification) : MapInterface { $prop = new Str($specification->property()); $pieces = $prop->split('.'); $var = (new Str('entity_'))->append($pieces->pop()->join('_')); $key = $var->append('_')->append((string) $pieces->last()); return (new Map('string', SequenceInterface::class))->put((string) $var, new Sequence(new Collection([(string) $pieces->last() => (string) $key->prepend('{')->append('}')]), new Collection([(string) $key => $specification->value()]))); }
public function make(Str $name, Str $value) : HeaderInterface { if ((string) $name->toLower() !== 'content-language') { throw new InvalidArgumentException(); } $values = new Set(HeaderValueInterface::class); foreach ($value->split(',') as $language) { $values = $values->add(new ContentLanguageValue((string) $language->trim())); } return new ContentLanguage($values); }
public function make(Str $name, Str $value) : HeaderInterface { if ((string) $name->toLower() !== 'allow') { throw new InvalidArgumentException(); } $values = new Set(HeaderValueInterface::class); foreach ($value->split(',') as $allow) { $values = $values->add(new AllowValue((string) $allow->trim()->toUpper())); } return new Allow($values); }
public function make(Str $name, Str $value) : HeaderInterface { if ($this->factories->contains((string) $name->toLower())) { return $this->factories->get((string) $name->toLower())->make($name, $value); } $values = new Set(HeaderValueInterface::class); foreach ($value->split(',') as $headerValue) { $values = $values->add(new HeaderValue((string) $headerValue->trim())); } return new Header((string) $name, $values); }
public function make(Str $name, Str $value) : HeaderInterface { if ((string) $name->toLower() !== 'accept') { throw new InvalidArgumentException(); } $values = new Set(HeaderValueInterface::class); foreach ($value->split(',') as $accept) { $matches = $accept->getMatches('~(?<type>[\\w*]+)/(?<subType>[\\w*]+)(?<params>(; ?\\w+=\\"?[\\w\\-.]+\\"?)+)?~'); $values = $values->add(new AcceptValue((string) $matches->get('type'), (string) $matches->get('subType'), $this->buildParams($matches->hasKey('params') ? $matches->get('params') : new Str('')))); } return new Accept($values); }
public function make(Str $name, Str $value) : HeaderInterface { if ((string) $name->toLower() !== 'accept-charset') { throw new InvalidArgumentException(); } $values = new Set(HeaderValueInterface::class); foreach ($value->split(',') as $accept) { $matches = $accept->getMatches('~(?<charset>[a-zA-Z0-9\\-_:\\(\\)]+)(; ?q=(?<quality>\\d+(\\.\\d+)?))?~'); $values = $values->add(new AcceptCharsetValue((string) $matches->get('charset'), new Quality($matches->hasKey('quality') ? (double) (string) $matches->get('quality') : 1))); } return new AcceptCharset($values); }
public function make(Str $name, Str $value) : HeaderInterface { if ((string) $name->toLower() !== 'accept-language') { throw new InvalidArgumentException(); } $values = new Set(HeaderValueInterface::class); foreach ($value->split(',') as $accept) { $matches = $accept->getMatches('~(?<lang>([a-zA-Z0-9]+(-[a-zA-Z0-9]+)*|\\*))(; ?q=(?<quality>\\d+(\\.\\d+)?))?~'); $values = $values->add(new AcceptLanguageValue((string) $matches->get('lang'), new Quality($matches->hasKey('quality') ? (double) (string) $matches->get('quality') : 1))); } return new AcceptLanguage($values); }
public function make(Str $name, Str $value) : HeaderInterface { if ((string) $name->toLower() !== 'cache-control') { throw new InvalidArgumentException(); } $splits = $value->split(','); $values = new Set(HeaderValueInterface::class); foreach ($splits as $split) { $split = $split->trim(); switch (true) { case $split->match('~^max-age=\\d+$~'): $values = $values->add(new CacheControlValue\MaxAge((int) (string) $split->substring(8))); break; case $split->match('~^max-stale(=\\d+)?$~'): $values = $values->add(new CacheControlValue\MaxStale($split->length() > 10 ? (int) (string) $split->substring(10) : 0)); break; case $split->match('~^min-fresh=\\d+$~'): $values = $values->add(new CacheControlValue\MinimumFresh((int) (string) $split->substring(10))); break; case (string) $split === 'must-revalidate': $values = $values->add(new CacheControlValue\MustRevalidate()); break; case $split->match('~^no-cache(="?\\w+"?)?$~'): $matches = $split->getMatches('~^no-cache(="?(?<field>\\w+)"?)?$~'); $values = $values->add(new CacheControlValue\NoCache($matches->hasKey('field') ? (string) $matches->get('field') : '')); break; case (string) $split === 'no-store': $values = $values->add(new CacheControlValue\NoStore()); break; case (string) $split === 'no-transform': $values = $values->add(new CacheControlValue\NoTransform()); break; case (string) $split === 'only-if-cached': $values = $values->add(new CacheControlValue\OnlyIfCached()); break; case $split->match('~^private(="?\\w+"?)?$~'): $matches = $split->getMatches('~^private(="?(?<field>\\w+)"?)?$~'); $values = $values->add(new CacheControlValue\PrivateCache($matches->hasKey('field') ? (string) $matches->get('field') : '')); break; case (string) $split === 'proxy-revalidate': $values = $values->add(new CacheControlValue\ProxyRevalidate()); break; case (string) $split === 'public': $values = $values->add(new CacheControlValue\PublicCache()); break; case $split->match('~^s-maxage=\\d+$~'): $values = $values->add(new CacheControlValue\SharedMaxAge((int) (string) $split->substring(9))); break; } } return new CacheControl($values); }
public function make(Str $name, Str $value) : HeaderInterface { if ((string) $name->toLower() !== 'link') { throw new InvalidArgumentException(); } $links = new Set(HeaderValueInterface::class); foreach ($value->split(',') as $link) { $matches = $link->trim()->getMatches('~^<(?<url>\\S+)>(?<params>(; ?\\w+=\\"?[\\w\\-.]+\\"?)+)?$~'); $params = $this->buildParams($matches->hasKey('params') ? $matches->get('params') : new Str('')); $links = $links->add(new LinkValue(Url::fromString((string) $matches->get('url')), $params->contains('rel') ? $params->get('rel')->value() : 'related', $params->contains('rel') ? $params->remove('rel') : $params)); } return new Link($links); }
public function getPaymentCart() { $values = Session::get('payment'); foreach ($values as $key => $value) { $product[$key]['name'] = $value['name']; $price = round((int) $value['price'] / 21270); $product[$key]['price'] = $price; $product[$key]['quantity'] = 1; $product[$key]['product_id'] = $value['id']; } $tmpTransaction = new TmpTransaction(); $st = Str::random(16); $baseUrl = URL::to('/product/payment/return?order_id=' . $st); // $value[1]['name'] = "sản phẩm 1"; // $value[1]['price'] = "20000"; // $value[1]['quantity'] = "1"; // $value[1]['product_id'] = "3"; // $value[2]['name'] = "sản phẩm 2"; // $value[2]['price'] = "20000"; // $value[2]['quantity'] = "1"; // $value[2]['product_id'] = "3"; $payment = $this->makePaymentUsingPayPalCart($product, 'USD', "{$baseUrl}&success=true", "{$baseUrl}&success=false"); $tmpTransaction->order_id = $st; $tmpTransaction->payment_id = $payment->getId(); $tmpTransaction->save(); header("Location: " . $this->getLink($payment->getLinks(), "approval_url")); exit; return "index"; }
/** * Show the form for creating a new resource. * GET /ob/create * * @return Response */ public function create() { $validate = LeaveOB::validate(Input::all()); if ($validate->passes()) { if (Input::get('totalleaves') <= 0.0 or Input::get('totalleaves') === 'NaN') { $message = 'Please select correct date!'; return Redirect::to('applyob')->with('error_message', $message); } else { $lastrow = LeaveOB::orderBy('created_at', 'desc')->first(); } $data = new LeaveOB(); $data->employee_id = Auth::user()->employee_id; if ($lastrow == null) { $data->leave_id = Str::random(8); } else { $data->leave_id = Str::random(8) . $lastrow->id; } $data->days_of_leave = Input::get('totalleaves'); $data->wdays_of_leave = Input::get('totalleave'); $data->date_from = Input::get('date_from'); $data->time_from = Input::get('time_from'); $data->date_to = Input::get('date_to'); $data->time_to = Input::get('time_to'); $data->company = Input::get('company'); $data->address = Input::get('address'); $data->reason = Input::get('reason'); $data->save(); return Redirect::to('applyob')->with('message', 'Your Application for Official Business (OB) is successfully send.Please Check Your Notification box to see if your leave has been approved.'); } else { return Redirect::to('applyob')->withErrors($validate); } }
public function __construct($query, &$conn, &$orm = null) { $this->conn = $conn; $this->res = null; $this->orm = $orm; $this->rowOrm = null; $this->success = false; $this->fields = null; $this->EOF = true; $this->BOF = true; $this->index = 0; $this->count = 0; $this->insertID = 0; $type = strtolower(substr(trim(str_replace("\n", " ", $query)), 0, 7)); $typeIsSelect = $type == "select "; $typeIsShowTables = $type == "show ta"; $typeIsInsert = $type == "insert "; $query = Str::finish($query, ";"); if ($this->res = @mysql_query($query, $this->conn->res)) { $this->success = true; if ($typeIsSelect || $typeIsShowTables) { $this->count = mysql_num_rows($this->res); $this->moveFirst(); } else { if ($typeIsInsert) { $this->insertID = mysql_insert_id($this->conn->res); } } } else { trigger_error("SQL error: " . $query . "\n<br><b>'" . mysql_error($this->conn->res) . "'</b>"); } }
public static function setReplyToEmail($user, $email) { Cache::forget('replyToEmail_' . $user->id); return Cache::rememberForever('replyToEmail_' . $user->id, function () use($email) { return Str::lower($email); }); }
/** * Make a new Keyword Value Object. * * @param \Orchestra\Support\Keyword|string $value */ public function __construct($value) { $this->value = $value; if (is_string($value)) { $this->slug = trim(Str::slug($value, '-')); } }
/** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { $familia = Familia::findOrFail($id); $validator = Familia::validator(Input::all()); if ($validator->fails()) { return Redirect::back()->withErrors($validator)->withInput(); } $datos = Input::all(); if (Input::file('foto')) { $file = Input::file('foto'); $destinationPath = 'uploads/images/'; $filename = Str::random(20) . '.' . $file->getClientOriginalExtension(); $mimeType = $file->getMimeType(); $extension = $file->getClientOriginalExtension(); $upload_success = $file->move($destinationPath, $filename); if ($familia->foto != 'fam.jpg') { File::delete($destinationPath . $familia->foto); } $datos['foto'] = $filename; } else { unset($datos['foto']); } $familia->update($datos); Session::flash('message', 'Actualizado Correctamente'); Session::flash('class', 'success'); return Redirect::to('/dashboard/familia'); }
public function getDatatable() { $products = $this->ProductRepo->find(Input::get('sSearch')); return Datatable::query($products)->addColumn('checkbox', function ($model) { return '<input type="checkbox" name="ids[]" value="' . $model->public_id . '">'; })->addColumn('product_key', function ($model) { return link_to('products/' . $model->public_id, $model->product_key); })->addColumn('notes', function ($model) { return nl2br(Str::limit($model->notes, 50)); })->addColumn('cost', function ($model) { return Utils::formatMoney($model->cost, 1); })->addColumn('name', function ($model) { return nl2br($model->category_name); })->addColumn('dropdown', function ($model) { return '<div class="btn-group tr-action" style="visibility:hidden;"> <button type="button" class="btn btn-xs btn-default dropdown-toggle" data-toggle="dropdown"> ' . trans('texts.select') . ' <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu"> <li><a href="' . URL::to('products/' . $model->public_id) . '/edit">' . uctrans('texts.edit_product') . '</a></li> <li class="divider"></li> <li><a href="' . URL::to('products/' . $model->public_id) . '/archive">' . uctrans('texts.delete_product') . '</a></li> </ul> </div>'; })->make(); }
public function postEdit($id) { if (!$this->checkRoute()) { return Redirect::route('index'); } $title = 'Edit A Modpack Creator - ' . $this->site_name; $creator = Creator::find($id); $input = Input::only('name', 'deck', 'website', 'donate_link', 'bio', 'slug'); $messages = ['unique' => 'The modpack creator already exists in the database.', 'url' => 'The :attribute field is not a valid URL.']; $validator = Validator::make($input, ['name' => 'required|unique:creators,name,' . $creator->id, 'website' => 'url', 'donate_link' => 'url'], $messages); if ($validator->fails()) { return Redirect::action('CreatorController@getAdd')->withErrors($validator)->withInput(); } $creator->name = $input['name']; $creator->deck = $input['deck']; $creator->website = $input['website']; $creator->donate_link = $input['donate_link']; $creator->bio = $input['bio']; if ($input['slug'] == '' || $input['slug'] == $creator->slug) { $slug = Str::slug($input['name']); } else { $slug = $input['slug']; } $creator->slug = $slug; $creator->last_ip = Request::getClientIp(); $success = $creator->save(); if ($success) { return View::make('creators.edit', ['title' => $title, 'creator' => $creator, 'success' => true]); } return Redirect::action('CreatorController@getEdit', [$id])->withErrors(['message' => 'Unable to edit modpack creator.'])->withInput(); }
/** * Sets and returns the expression. * * @param string Method that has been called * @param array Given parameters * * @return string Expression */ public function __call($func, $args = array()) { if (Str::substring($func, 0, 3) == "set" && isset($args[0])) { $this->value = (string) $args[0]; } return $this->value; }
/** * Execute the console command. * * @return mixed */ public function fire() { $file = $this->argument('file'); if (!file_exists($file) || !is_file($file)) { $this->error('Please provide a valid file.'); } if ($handle = fopen($file, 'r')) { while (($data = fgetcsv($handle, 0, ';')) !== false) { // If the "level" column is present, use it instead of the // "level" option. $level = $this->option('level'); if (count($data) === 7) { $level = $data[6]; } elseif ($this->option('level') === null) { $this->error('The file does not include the level of the newcomer, please provide it via the "level" flag.'); return; } // See the class description for file format. $attributes = ['first_name' => $data[2], 'last_name' => $data[1], 'password' => Str::random(6), 'sex' => strpos($data[0], 'M') !== false ? 'M' : 'F', 'email' => $data[5], 'phone' => $data[4], 'level' => $level, 'birth' => new DateTime($data[3])]; $newcomer = Newcomer::create($attributes); if ($newcomer->save() === false) { $this->error('Error while adding ' . $newcomer->first_name . ' ' . $newcomer->last_name); } } } }
public function beforeValidate() { // Generate a URL slug for this model if (!$this->exists && !$this->slug) { $this->slug = Str::slug($this->name); } }
public static function make($string, $table = [], $exclude_id = 0, $column = 'slug') { # $table can be array if (is_array($table)) { $uniques = array_values($table); } else { $uniques = DB::table($table)->where('id', '<>', $exclude_id)->lists($column); if (empty($uniques)) { $uniques = []; } } # Convert string into array of url-friendly words $words = explode('-', Str::slug($string, '-')); # Words should be unique $words = array_unique($words); # Remove stop words $words = array_diff($words, self::$stop_words); # Reset indexes $words = array_values($words); # Limit length of slug down to fewer than 50 characters while (self::checkLength($words) === false) { array_pop($words); } # Check uniqueness while (self::checkUniqueness($words, $uniques) === false) { self::increment($words); } return self::makeFromWords($words); }
/** * Display a listing of the resource. * * @return Response */ public function solicpremium() { $authuser = Auth::user(); $clasificado = Clasificado::find(Input::get('clasfid')); $clasificado->solicitar_premium = 1; $clasificado->save(); //Generar row en cobros y cobros_pendientes $cobrotipoSerProveedor = CobroTipo::where('tipo', 'clasificado_premium')->first(); $cobro = new Cobro(); $cobro->tipo_id = $cobrotipoSerProveedor->id; $cobro->usuario_id = $authuser->id; $cobro->estado = 'pendiente'; $cobro->datosAdicionales = $clasificado->id; //Al entrar a este metodo estoy seguro que el usuario tiene un registro de proveedor asociado $cobro->save(); $id = Str::random(4); $date_now = new DateTime(); $cobrop = new CobroPendiente(); $cobrop->cobro_id = $cobro->id; $cobrop->fecha = $date_now; $cobrop->cobro_concepto = 'TODCONS' . $cobro->id . 'CLASF' . $clasificado->id . $date_now->format('YmdHi') . $id; // Concepto = clave_empresa+ clave_cobro+ clave_tipo_cobro + clave_objeto_de_cobro + fecha+4_digitos_random (Por favor mejorar!!) $cobrop->save(); return Redirect::to('vistausuario/clasificados')->with(array('usuarioimg' => $authuser->imagen, 'usuarionombre' => $authuser->nombre, 'usuarioid' => $authuser->id)); }
public function post_resetlogin() { $validatekey = Str::random(32, 'alpha'); $uname = Str::random(16, 'alpha'); $user = Admin_User::find(Auth::user()->userid); $user->username = $uname; $user->password = $uname; $user->status = 3; $user->validationkey = $validatekey; $user->save(); try { $mailer = Message::to($user->userprofile->emel); $mailer->from('*****@*****.**', 'System Generate'); $mailer->subject('Account Reset'); $mailer->body('view: plugins.emailAccReset'); $mailer->body->username = $uname; $mailer->body->password = $uname; $mailer->body->key = $key; $mailer->html(true); $mailer->send(); } catch (Exception $e) { Log::write('email', 'Message was not sent.'); Log::write('email', 'Mailer error: ' . $e->getMessage()); } }
public function postIndex($id = 0) { $input = (object) Input::only('title', 'content', 'tags', 'category_id'); // ToDo !! User Input Validation ! $post = new TalkPost(); $post->title = $input->title; $post->content = $input->content; $post->category_id = $input->category_id; $post->parent_id = 0; $post->user_id = Auth::user()->id; if ($post->save()) { $post->slug = $post->id . '-' . Str::slug($input->title); if ($post->save()) { // ToDo !! Do something with the tags! $tags = Input::only('tags'); if (is_array($tags)) { foreach ($tags['tags'] as $tag_id) { $postTag = new TalkPostTag(); $postTag->post_id = $post->id; $postTag->tag_id = $tag_id; $postTag->save(); } } return Redirect::to(Config::get('talk::routes.base') . '/read/' . $post->slug); } } }
/** * Run the database seeds. * * @return void */ public function run() { Eloquent::unguard(); DB::table('tags')->truncate(); //DB::table('pastes')->truncate(); $faker = Faker\Factory::create(); $paste_count = 10; $tags = array('php', 'javascript', 'ruby', 'js', 'cpp', 'c++', 'c#', 'go', 'html', 'css'); for ($i = 0; $i < $paste_count; $i++) { $tags_per_paste = rand(1, 3); // Generate the paste $examplePaste = new Paste(); $examplePaste->paste = $faker->paragraph; $examplePaste->title = $faker->realText(46); $examplePaste->expire = $faker->dateTime($max = 'now'); $examplePaste->token = Str::random(40); $examplePaste->private = rand(0, 1); $examplePaste->delete_token = Str::random(40); $examplePaste->save(); // Attach some tags to the new paste for ($i = 0; $i < $tags_per_paste; ++$i) { $exampleTag = new Tag(); $exampleTag->tag = $tags[rand(0, sizeof($tags) - 1)]; $exampleTag->paste_id = $examplePaste->id; $examplePaste->tags()->save($exampleTag); } print "Seeded paste with ID of " . $examplePaste->id . "\n"; } }