_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q257800
NoteController.destroy
test
public function destroy($id, $noteId) { if ($this->inventory->deleteNote($id, $noteId)) { $message = 'Successfully updated note.'; return redirect()->route('maintenance.inventory.show', [$id])->withSuccess($message); } else { $message = 'There was an issue deleting this note. Please try again.'; return redirect()->route('maintenance.inventory.notes.show', [$id, $noteId])->withErrors($message); } }
php
{ "resource": "" }
q257801
InventoryStock.getLastMovementAttribute
test
public function getLastMovementAttribute() { if ($this->movements->count() > 0) { $movement = $this->movements->first(); if ($movement instanceof InventoryStockMovement && $movement->after > $movement->before) { return sprintf('<b>%s</b> (Stock was added - %s) - <b>Reason:</b> %s', $movement->change, $movement->created_at, $movement->reason); } elseif ($movement->before > $movement->after) { return sprintf('<b>%s</b> (Stock was removed - %s) - <b>Reason:</b> %s', $movement->change, $movement->created_at, $movement->reason); } else { return sprintf('<b>%s</b> (No Change - %s) - <b>Reason:</b> %s', $movement->change, $movement->created_at, $movement->reason); } } return; }
php
{ "resource": "" }
q257802
InventoryStock.getLastMovementByAttribute
test
public function getLastMovementByAttribute() { if ($this->movements->count() > 0) { $movement = $this->movements->first(); if ($movement instanceof InventoryStockMovement && $movement->user instanceof User) { return $movement->user->getRecipientName(); } } return; }
php
{ "resource": "" }
q257803
InventoryStock.getQuantityMetricAttribute
test
public function getQuantityMetricAttribute() { $quantity = $this->getAttribute('quantity'); if ($this->item && $this->item->metric) { $metric = $this->item->metric->name; } else { $metric = null; } return trim(sprintf('%s %s', $quantity, $metric)); }
php
{ "resource": "" }
q257804
InventoryStockViewer.btnPutBackSomeForWorkOrder
test
public function btnPutBackSomeForWorkOrder(WorkOrder $workOrder) { if ($this->entity->item) { return view('viewers.inventory.stock.buttons.put-back-some-work-order', [ 'workOrder' => $workOrder, 'stock' => $this->entity, ]); } return; }
php
{ "resource": "" }
q257805
InventoryStockViewer.btnPutBackAllForWorkOrder
test
public function btnPutBackAllForWorkOrder(WorkOrder $workOrder) { if ($this->entity->item) { return view('viewers.inventory.stock.buttons.put-back-all-work-order', [ 'workOrder' => $workOrder, 'stock' => $this->entity, ]); } return; }
php
{ "resource": "" }
q257806
WorkOrderSessionController.end
test
public function end($workOrderId) { if ($this->processor->end($workOrderId)) { flash()->success('Success!', 'Successfully ended your session. Your hours have been logged.'); return redirect()->route('maintenance.work-orders.show', [$workOrderId]); } else { flash()->error('Error!', 'There was an issue ending your session. Please try again.'); return redirect()->route('maintenance.work-orders.show', [$workOrderId]); } }
php
{ "resource": "" }
q257807
WorkRequestPresenter.table
test
public function table($workRequest) { return $this->table->of('work-requests', function (TableGrid $table) use ($workRequest) { $table->with($workRequest)->paginate($this->perPage); $table->attributes([ 'class' => 'table table-hover table-striped', ]); $table->column('ID', 'id'); $table->column('subject', function (Column $column) { $column->value = function (WorkRequest $workRequest) { return link_to_route('maintenance.work-requests.show', $workRequest->subject, [$workRequest->getKey()]); }; }); $table->column('best_time'); $table->column('created_at'); }); }
php
{ "resource": "" }
q257808
WorkRequestPresenter.form
test
public function form(WorkRequest $request) { return $this->form->of('work-requests', function (FormGrid $form) use ($request) { if ($request->exists) { $method = 'PATCH'; $url = route('maintenance.work-requests.update', [$request->getKey()]); $form->submit = 'Save'; } else { $method = 'POST'; $url = route('maintenance.work-requests.store'); $form->submit = 'Create'; } $form->with($request); $form->attributes(compact('method', 'url')); $form->fieldset(function (Fieldset $fieldset) { $fieldset ->control('input:text', 'subject') ->attributes([ 'placeholder' => 'Enter Subject', ]); $fieldset ->control('input:text', 'best_time') ->attributes([ 'placeholder' => 'Enter Best Time', ]); $fieldset ->control('input:textarea', 'description'); }); }); }
php
{ "resource": "" }
q257809
AssignmentController.store
test
public function store($workOrder_id) { if ($this->assignmentValidator->passes()) { $workOrder = $this->workOrder->find($workOrder_id); $data = $this->inputAll(); $data['work_order_id'] = $workOrder->id; $records = $this->assignment->setInput($data)->create(); if ($records) { $this->message = 'Successfully assigned worker(s)'; $this->messageType = 'success'; $this->redirect = route('maintenance.work-orders.show', [$workOrder->id]); } else { $this->message = 'There was an error trying to assign workers to this work order. Please try again.'; $this->messageType = 'danger'; $this->redirect = route('maintenance.work-orders.show', [$workOrder->id]); } } else { $this->errors = $this->assignmentValidator->getErrors(); $this->redirect = route('maintenance.work-orders.show', [$workOrder_id]); } return $this->response(); }
php
{ "resource": "" }
q257810
AssignmentController.destroy
test
public function destroy($workOrder_id, $assignment_id) { if ($this->assignment->destroy($assignment_id)) { $this->message = 'Successfully removed worker from this work order.'; $this->messageType = 'success'; $this->redirect = route('maintenance.work-orders.show', [$workOrder_id]); } else { $this->message = 'There was an error trying to remove this worker from this work order. Please try again later.'; $this->messageType = 'danger'; $this->redirect = route('maintenance.work-orders.show', [$workOrder_id]); } return $this->response(); }
php
{ "resource": "" }
q257811
Selection.datalist
test
public function datalist(string $id, array $list = []): Htmlable { $this->type = 'datalist'; $attributes['id'] = $id; $html = []; if (Arr::isAssoc($list)) { foreach ($list as $value => $display) { $html[] = $this->option($display, $value, null, []); } } else { foreach ($list as $value) { $html[] = $this->option($value, $value, null, []); } } $attributes = $this->getHtmlBuilder()->attributes($attributes); $list = \implode('', $html); return $this->toHtmlString("<datalist{$attributes}>{$list}</datalist>"); }
php
{ "resource": "" }
q257812
Selection.placeholderOption
test
protected function placeholderOption(string $display, $selected): Htmlable { $options = [ 'selected' => $this->getSelectedValue(null, $selected), 'disabled' => true, 'value' => '', ]; return $this->toHtmlString(\sprintf( '<option%s>%s</option>', $this->getHtmlBuilder()->attributes($options), $this->entities($display) )); }
php
{ "resource": "" }
q257813
Creator.getAppendage
test
protected function getAppendage(string $method): string { list($method, $appendage) = [\strtoupper($method), '']; // If the HTTP method is in this list of spoofed methods, we will attach the // method spoofer hidden input to the form. This allows us to use regular // form to initiate PUT and DELETE requests in addition to the typical. if (\in_array($method, $this->spoofedMethods)) { $appendage .= $this->hidden('_method', $method); } // If the method is something other than GET we will go ahead and attach the // CSRF token to the form, as this can't hurt and is convenient to simply // always have available on every form the developers creates for them. if ($method != 'GET') { $appendage .= $this->token(); } return $appendage; }
php
{ "resource": "" }
q257814
Componentable.renderComponent
test
protected function renderComponent(string $name, array $arguments): Htmlable { $component = static::$components[$name]; $data = $this->getComponentData($component['signature'], $arguments); return new HtmlString( $this->view->make($component['view'], $data)->render() ); }
php
{ "resource": "" }
q257815
Componentable.getComponentData
test
protected function getComponentData(array $signature, array $arguments): array { $data = []; $i = 0; foreach ($signature as $variable => $default) { // If the "variable" value is actually a numeric key, we can assume that // no default had been specified for the component argument and we'll // just use null instead, so that we can treat them all the same. if (\is_numeric($variable)) { $variable = $default; $default = null; } $data[$variable] = $arguments[$i] ?? $default; ++$i; } return $data; }
php
{ "resource": "" }
q257816
BladeServiceProvider.register
test
protected function register() { $this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) { $namespaces = [ 'Html' => \get_class_methods(HtmlBuilder::class), 'Form' => \get_class_methods(FormBuilder::class), ]; foreach ($namespaces as $namespace => $methods) { foreach ($methods as $method) { if (\in_array($method, $this->directives)) { $snakeMethod = Str::snake($method); $directive = \strtolower($namespace).'_'.$snakeMethod; $bladeCompiler->directive($directive, function ($expression) use ($namespace, $method) { return "<?php echo $namespace::$method($expression); ?>"; }); } } } }); }
php
{ "resource": "" }
q257817
FormBuilder.model
test
public function model($model, array $options = []): Htmlable { $this->model = $model; return $this->open($options); }
php
{ "resource": "" }
q257818
FormBuilder.formatLabel
test
protected function formatLabel(string $name, ?string $value): string { return $value ?? \ucwords(\str_replace('_', ' ', $name)); }
php
{ "resource": "" }
q257819
FormBuilder.reset
test
public function reset(?string $value = null, array $attributes = []): Htmlable { return $this->input('reset', null, $value, $attributes); }
php
{ "resource": "" }
q257820
FormBuilder.submit
test
public function submit(?string $value = null, array $options = []): Htmlable { return $this->input('submit', null, $value, $options); }
php
{ "resource": "" }
q257821
FormBuilder.request
test
protected function request(string $name) { if (! $this->considerRequest || ! isset($this->request)) { return null; } return $this->request->input($this->transformKey($name)); }
php
{ "resource": "" }
q257822
HtmlBuilder.linkAsset
test
public function linkAsset(string $url, ?string $title = null, array $attributes = [], ?bool $secure = null): Htmlable { $url = $this->url->asset($url, $secure); return $this->link($url, $title ?: $url, $attributes, $secure); }
php
{ "resource": "" }
q257823
HtmlBuilder.linkRoute
test
public function linkRoute(string $name, ?string $title = null, array $parameters = [], array $attributes = []): Htmlable { return $this->link($this->url->route($name, $parameters), $title, $attributes); }
php
{ "resource": "" }
q257824
HtmlBuilder.listingElement
test
protected function listingElement($key, string $type, $value): string { if (\is_array($value)) { return $this->nestedListing($key, $type, $value); } else { return '<li>'.$this->entities($value).'</li>'; } }
php
{ "resource": "" }
q257825
HtmlBuilder.attributes
test
public function attributes(array $attributes): string { $html = []; // For numeric keys we will assume that the key and the value are the same // as this will convert HTML attributes such as "required" to a correct // form like required="required" instead of using incorrect numerics. foreach ((array) $attributes as $key => $value) { if (\is_array($value) && $key !== 'class') { foreach ((array) $value as $name => $val) { $element = $this->attributeElement($key.'-'.$name, $val); if (! \is_null($element)) { $html[] = $element; } } } else { $element = $this->attributeElement($key, $value); if (! \is_null($element)) { $html[] = $element; } } } return \count($html) > 0 ? ' '.\implode(' ', $html) : ''; }
php
{ "resource": "" }
q257826
HtmlServiceProvider.registerHtmlBuilder
test
protected function registerHtmlBuilder(): void { $this->app->singleton('html', function ($app) { return new HtmlBuilder( $app->make('url'), $app->make('view') ); }); }
php
{ "resource": "" }
q257827
HtmlServiceProvider.registerFormBuilder
test
protected function registerFormBuilder(): void { $this->app->singleton('form', function ($app) { return (new FormBuilder( $app->make('html'), $app->make('url'), $app->make('view'), $app->make('request') ))->setSessionStore($app->make('session.store')); }); }
php
{ "resource": "" }
q257828
Input.search
test
public function search(string $name, ?string $value = null, array $options = []): Htmlable { return $this->input('search', $name, $value, $options); }
php
{ "resource": "" }
q257829
Input.datetime
test
public function datetime(string $name, $value = null, array $options = []): Htmlable { if ($value instanceof DateTime) { $value = $value->format(DateTime::RFC3339); } return $this->input('datetime', $name, $value, $options); }
php
{ "resource": "" }
q257830
Input.file
test
public function file(string $name, array $options = []): Htmlable { return $this->input('file', $name, null, $options); }
php
{ "resource": "" }
q257831
BaseXmlResponse.removeXmlFirstLine
test
protected function removeXmlFirstLine($str) { $first = '<?xml version="1.0"?>'; if (Str::startsWith($str, $first)) { return trim(substr($str, strlen($first))); } return $str; }
php
{ "resource": "" }
q257832
Dictionary.load
test
public function load($locale) { $locale = $this->unifyLocale($locale); $file = self::$fileLocation . DIRECTORY_SEPARATOR . $locale . '.ini'; $this->dictionary = array(); if (! file_exists(realpath($file))) { return $this; } foreach (parse_ini_file($file) as $key => $val) { $this->dictionary[str_replace('@:', '', $key)] = $val; } return $this; }
php
{ "resource": "" }
q257833
Dictionary.parseFile
test
public static function parseFile($locale) { $path = self::$fileLocation . DIRECTORY_SEPARATOR; $file = $path . 'hyph_' . $locale . '.dic'; if (! file_Exists($file)) { throw new \Org\Heigl\Hyphenator\Exception\PathNotFoundException('The given Path does not exist'); } $items = file($file); $source = trim($items[0]); if (0===strpos($source, 'ISO8859')) { $source = str_Replace('ISO8859', 'ISO-8859', $source); } unset($items[0]); $fh = fopen($path . $locale . '.ini', 'w+'); foreach ($items as $item) { // Remove comment-lines starting with '#' or '%'. if (in_array(mb_substr($item, 0, 1), array('#', '%'))) { continue; } // Ignore empty lines. if ('' == trim($item)) { continue; } // Remove all Upper-case items as they are OOo-specific if ($item === mb_strtoupper($item)) { continue; } // Ignore lines containing an '=' sign as these are specific // instructions for non-standard-hyphenations. These will be // implemented later. if (false !== mb_strpos($item, '=')) { continue; } $item = mb_convert_Encoding($item, 'UTF-8', $source); $result = Pattern::factory($item); $string = '@:' . $result->getText() . ' = "' . $result->getPattern() . '"' . "\n"; fwrite($fh, $string); } fclose($fh); return $path . $locale . '.ini'; }
php
{ "resource": "" }
q257834
Dictionary.getPatternsForWord
test
public function getPatternsForWord($word) { $return = array(); $word = '.' . $word . '.'; $strlen = mb_strlen($word); for ($i = 0; $i <= $strlen; $i ++) { for ($j = 2; $j <= ($strlen-$i); $j++) { $substr = mb_substr($word, $i, $j); if (! isset($this->dictionary[$substr])) { continue; } $return[$substr] = $this->dictionary[$substr]; } } return $return; }
php
{ "resource": "" }
q257835
Dictionary.unifyLocale
test
private function unifyLocale($locale) { if (2 == strlen($locale)) { return strtolower($locale); } if (preg_match('/([a-zA-Z]{2})[^a-zA-Z]+([a-zA-Z]{2})/i', $locale, $result)) { return strtolower($result[1]) . '_' . strtoupper($result[2]); } return (string) $locale; }
php
{ "resource": "" }
q257836
TokenizerRegistry.tokenize
test
public function tokenize($string) { if (! $string instanceof TokenRegistry) { $wt = new WordToken($string); $string = new TokenRegistry(); $string->add($wt); } foreach ($this as $tokenizer) { $string = $tokenizer->run($string); } return $string; }
php
{ "resource": "" }
q257837
CustomHyphenationTokenizer.run
test
public function run($input) { if ($input instanceof TokenRegistry) { // Tokenize a TokenRegistry $f = clone($input); foreach ($input as $token) { if (! $token instanceof WordToken) { continue; } $newTokens = $this->tokenize($token->get()); $f->replace($token, $newTokens); } return $f ; } // Tokenize a simple string. $array = $this->tokenize($input); $registry = new TokenRegistry(); foreach ($array as $item) { $registry->add($item); } return $registry; }
php
{ "resource": "" }
q257838
Filter.setOptions
test
public function setOptions(\Org\Heigl\Hyphenator\Options $options) { $this->options =$options; return $this; }
php
{ "resource": "" }
q257839
DictionaryRegistry.add
test
public function add(Dictionary $dict) { if (! in_array($dict, $this->registry)) { $this->registry[] = $dict; } return $this; }
php
{ "resource": "" }
q257840
DictionaryRegistry.getHyphenationPattterns
test
public function getHyphenationPattterns($word) { $pattern = array(); foreach ($this as $dictionary) { $pattern = array_merge($pattern, $dictionary->getPatternsForWord($word)); } return $pattern; }
php
{ "resource": "" }
q257841
Options.setFilters
test
public function setFilters($filters) { $this->filters = array(); if (! is_array($filters)) { $filters = explode(',', $filters); } foreach ($filters as $filter) { $this->addFilter($filter); } return $this; }
php
{ "resource": "" }
q257842
Options.addFilter
test
public function addFilter($filter) { if (is_string($filter)) { $filter = trim($filter); } elseif (! $filter instanceof Filter) { throw new \UnexpectedValueException('Expceted instanceof Org\Heigl\Hyphenator\Filter\Filter or string'); } if (! $filter) { return $this; } $this->filters[] = $filter; return $this; }
php
{ "resource": "" }
q257843
Options.setTokenizers
test
public function setTokenizers($tokenizers) { $this->tokenizers = array(); if (! is_array($tokenizers)) { $tokenizers = explode(',', $tokenizers); } foreach ($tokenizers as $tokenizer) { $this->addTokenizer($tokenizer); } return $this; }
php
{ "resource": "" }
q257844
Options.addTokenizer
test
public function addTokenizer($tokenizer) { if (is_string($tokenizer)) { $tokenizer = trim($tokenizer); } elseif (! $tokenizer instanceof Tokenizer) { throw new \UnexpectedValueException( 'Expceted instanceof Org\Heigl\Hyphenator\Tokenizer\Tokenizer or string' ); } if (! $tokenizer) { return $this; } $this->tokenizers[] = $tokenizer; return $this; }
php
{ "resource": "" }
q257845
Options.factory
test
public static function factory($file) { if (! file_Exists($file)) { $file = $file . '.dist'; if (! file_exists($file)) { throw new \Org\Heigl\Hyphenator\Exception\PathNotFoundException($file); } } $params = parse_ini_file($file); if (! is_array($params) || 1 > count($params)) { throw new \Org\Heigl\Hyphenator\Exception\InvalidArgumentException($file . ' is not a parseable file'); } $option = new Options(); foreach ($params as $key => $val) { if (! method_Exists($option, 'set' . $key)) { continue; } call_user_Func(array($option,'set' . $key), $val); } return $option; }
php
{ "resource": "" }
q257846
Pattern.getText
test
public function getText() { if (! $this->text) { throw new \Org\Heigl\Hyphenator\Exception\NoPatternSetException('No Pattern set'); } return $this->text; }
php
{ "resource": "" }
q257847
Pattern.getPattern
test
public function getPattern() { if (! $this->pattern) { throw new \Org\Heigl\Hyphenator\Exception\NoPatternSetException('No Pattern set'); } return $this->pattern; }
php
{ "resource": "" }
q257848
Hyphenator.setOptions
test
public function setOptions(Options $options) { $this->options = $options; $this->tokenizers->cleanup(); foreach ($this->options->getTokenizers() as $tokenizer) { $this->addTokenizer($tokenizer); } return $this; }
php
{ "resource": "" }
q257849
Hyphenator.getOptions
test
public function getOptions() { if (null === $this->options) { $optFile = $this->getHomePath() . DIRECTORY_SEPARATOR . 'Hyphenator.properties'; $this->setOptions(Options::factory($optFile)); } return $this->options; }
php
{ "resource": "" }
q257850
Hyphenator.addDictionary
test
public function addDictionary($dictionary) { if (! $dictionary instanceof \Org\Heigl\Hyphenator\Dictionary\Dictionary) { \Org\Heigl\Hyphenator\Dictionary\Dictionary::setFileLocation($this->getHomePath() . '/files/dictionaries'); $dictionary = \Org\Heigl\Hyphenator\Dictionary\Dictionary::factory($dictionary); } $this->dicts->add($dictionary); return $this; }
php
{ "resource": "" }
q257851
Hyphenator.addFilter
test
public function addFilter($filter) { if (! $filter instanceof \Org\Heigl\Hyphenator\Filter\Filter) { $filter = '\\Org\\Heigl\\Hyphenator\\Filter\\' . ucfirst($filter) . 'Filter'; $filter = new $filter(); } $filter->setOptions($this->getOptions()); $this->filters->add($filter); return $this; }
php
{ "resource": "" }
q257852
Hyphenator.addTokenizer
test
public function addTokenizer($tokenizer) { if (! $tokenizer instanceof \Org\Heigl\Hyphenator\Tokenizer\Tokenizer) { $tokenizer = '\\Org\\Heigl\Hyphenator\\Tokenizer\\' . ucfirst($tokenizer) . 'Tokenizer'; $tokenizer = new $tokenizer(); } $this->tokenizers->add($tokenizer); return $this; }
php
{ "resource": "" }
q257853
Hyphenator.getTokenizers
test
public function getTokenizers() { if (0 == $this->tokenizers->count()) { foreach ($this->getOptions()->getTokenizers() as $tokenizer) { $this->addTokenizer($tokenizer); } } return $this->tokenizers; }
php
{ "resource": "" }
q257854
Hyphenator.getDictionaries
test
public function getDictionaries() { if (0 == $this->dicts->count()) { $this->addDictionary($this->getOptions()->getDefaultLocale()); } return $this->dicts; }
php
{ "resource": "" }
q257855
Hyphenator.getFilters
test
public function getFilters() { if (0 == $this->filters->count()) { foreach ($this->getOptions()->getFilters() as $filter) { $this->addFilter($filter); } } return $this->filters; }
php
{ "resource": "" }
q257856
Hyphenator.hyphenate
test
public function hyphenate($string) { $tokens = $this->tokenizers->tokenize($string); $tokens = $this->getHyphenationPattern($tokens); $tokens = $this->filter($tokens); if (1 === count($tokens) && 1 === $this->getFilters()->count()) { $tokens->rewind(); return $tokens->current()->getHyphenatedContent(); } return $this->getFilters()->concatenate($tokens); }
php
{ "resource": "" }
q257857
Hyphenator.getHyphenationPattern
test
public function getHyphenationPattern(Tokenizer\TokenRegistry $registry) { $minWordLength = $this->getOptions()->getMinWordLength(); foreach ($registry as $token) { if (! $token instanceof \Org\Heigl\Hyphenator\Tokenizer\WordToken) { continue; } if ($minWordLength > $token->length()) { continue; } $this->getPatternForToken($token); } return $registry; }
php
{ "resource": "" }
q257858
Hyphenator.getPatternForToken
test
public function getPatternForToken(Tokenizer\WordToken $token) { foreach ($this->getDictionaries() as $dictionary) { $token->addPattern($dictionary->getPatternsForWord($token->get())); } return $token; }
php
{ "resource": "" }
q257859
Hyphenator.setDefaultHomePath
test
public static function setDefaultHomePath($homePath) { if (! file_exists($homePath)) { throw new Exception\PathNotFoundException($homePath . ' does not exist'); } if (! is_Dir($homePath)) { throw new Exception\PathNotDirException($homePath . ' is not a directory'); } self::$defaultHomePath = realpath($homePath); }
php
{ "resource": "" }
q257860
Hyphenator.getDefaultHomePath
test
public static function getDefaultHomePath() { if (is_Dir(self::$defaultHomePath)) { return self::$defaultHomePath; } if (defined('HYPHENATOR_HOME') && is_Dir(HYPHENATOR_HOME)) { return realpath(HYPHENATOR_HOME); } if ($home = getenv('HYPHENATOR_HOME')) { if (is_Dir($home)) { return $home; } } return __DIR__ . '/share'; }
php
{ "resource": "" }
q257861
Hyphenator.setHomePath
test
public function setHomePath($homePath) { if (! file_exists($homePath)) { throw new Exception\PathNotFoundException($homePath . ' does not exist'); } if (! is_Dir($homePath)) { throw new Exception\PathNotDirException($homePath . ' is not a directory'); } $this->homePath = realpath($homePath); return $this; }
php
{ "resource": "" }
q257862
Hyphenator.factory
test
public static function factory($path = null, $locale = null) { $hyphenator = new Hyphenator(); if (null !== $path && file_Exists($path)) { $hyphenator->setHomePath($path); } if (null !== $locale) { $hyphenator->getOptions()->setDefaultLocale($locale); } return $hyphenator; }
php
{ "resource": "" }
q257863
Hyphenator.__autoload
test
public static function __autoload($className) { if (0 !== strpos($className, 'Org\\Heigl\\Hyphenator')) { return false; } $className = substr($className, strlen('Org\\Heigl\\Hyphenator\\')); $file = str_replace('\\', '/', $className) . '.php'; $fileName = __DIR__ . DIRECTORY_SEPARATOR . $file; if (! file_exists(realpath($fileName))) { return false; } if (! @include_once $fileName) { return false; } return true; }
php
{ "resource": "" }
q257864
TokenRegistry.replace
test
public function replace(Token $oldToken, array $newTokens) { // Get the current key of the element. $key = array_search($oldToken, $this->registry, true); if (false === $key) { return $this; } $replacement = array(); // Check for any non-token-elements and remove them. foreach ($newTokens as $token) { if (! $token instanceof Token) { continue; } $replacement[] = $token; } // Replace the old element with the newly created array array_splice($this->registry, $key, 1, $replacement); return $this; }
php
{ "resource": "" }
q257865
TokenRegistry.getTokenWithKey
test
public function getTokenWithKey($key) { if (array_key_exists($key, $this->registry)) { return $this->registry[$key]; } return null; }
php
{ "resource": "" }
q257866
WordToken.getMergedPattern
test
public function getMergedPattern($quality = \Org\Heigl\Hyphenator\Hyphenator::QUALITY_HIGHEST) { $content = $this->getHyphenateContent(); $endPattern = str_repeat('0', mb_strlen($content)+1); foreach ($this->pattern as $string => $pattern) { $strStart = -1; while (false !== $strStart = @mb_strpos($content, $string, $strStart + 1)) { $strLen = mb_strlen($string); for ($i=0; $i <= $strLen; $i++) { $start = $i+$strStart; $currentQuality = substr($endPattern, $start, 1); $patternQuality = substr($pattern, $i, 1); if ($currentQuality >= $patternQuality) { continue; } if ($quality < $patternQuality) { continue; } $endPattern = substr($endPattern, 0, $start) . $patternQuality . substr($endPattern, $start+1); } } } return substr($endPattern, 1, strlen($endPattern)-2); }
php
{ "resource": "" }
q257867
FilterRegistry.getFilterWithKey
test
public function getFilterWithKey($key) { if (array_key_exists($key, $this->registry)) { return $this->registry[$key]; } return null; }
php
{ "resource": "" }
q257868
FilterRegistry.filter
test
public function filter(\Org\Heigl\Hyphenator\Tokenizer\TokenRegistry $tokens) { foreach ($this as $filter) { $tokens = $filter->run($tokens); } return $tokens; }
php
{ "resource": "" }
q257869
ThreeLeggedAuth.fetchToken
test
public function fetchToken($authorizationCode) { $additionalParams = [ 'code' => $authorizationCode, 'redirect_uri' => $this->configuration->getRedirectUrl(), ]; $response = parent::fetchAccessToken('authentication/v1/gettoken', 'authorization_code', $additionalParams); $this->saveRefreshToken($response); }
php
{ "resource": "" }
q257870
ShopMigrationTask.migrateOrders
test
public function migrateOrders() { $start = $count = 0; $batch = Order::get()->sort('Created', 'ASC')->limit($start, self::$batch_size); while ($batch->exists()) { foreach ($batch as $order) { $this->migrate($order); echo '. '; $count++; } $start += self::$batch_size; $batch = $batch->limit($start, self::$batch_size); }; echo "$count orders updated.\n<br/>"; }
php
{ "resource": "" }
q257871
ShopMigrationTask.migrate
test
public function migrate(Order $order) { //TODO: set a from / to version to preform a migration with $this->migrateStatuses($order); $this->migrateMemberFields($order); $this->migrateShippingValues($order); $this->migrateOrderCalculation($order); $order->write(); }
php
{ "resource": "" }
q257872
ShopMigrationTask.migrateShippingValues
test
public function migrateShippingValues($order) { //TODO: see if this actually works..it probably needs to be writeen to a SQL query if ($order->hasShippingCost && abs($order->Shipping)) { $modifier1 = Base::create(); $modifier1->Amount = $order->Shipping < 0 ? abs($order->Shipping) : $order->Shipping; $modifier1->Type = 'Chargable'; $modifier1->OrderID = $order->ID; $modifier1->ShippingChargeType = 'Default'; $modifier1->write(); $order->hasShippingCost = null; $order->Shipping = null; } if ($order->AddedTax) { $modifier2 = \SilverShop\Model\Modifiers\Tax\Base::create(); $modifier2->Amount = $order->AddedTax < 0 ? abs($order->AddedTax) : $order->AddedTax; $modifier2->Type = 'Chargable'; $modifier2->OrderID = $order->ID; //$modifier2->Name = 'Undefined After Ecommerce Upgrade'; $modifier2->TaxType = 'Exclusive'; $modifier2->write(); $order->AddedTax = null; } }
php
{ "resource": "" }
q257873
ShopMigrationTask.migrateOrderCalculation
test
public function migrateOrderCalculation($order) { if (!is_numeric($order->Total) || $order->Total <= 0) { $order->calculate(); $order->write(); } }
php
{ "resource": "" }
q257874
CalculateProductPopularity.viaphp
test
public function viaphp() { $ps = singleton(Product::class); $q = $ps->buildSQL('"SilverShop_Product"."AllowPurchase" = 1'); $select = $q->select; $select['NewPopularity'] = self::config()->number_sold_calculation_type . '("SilverShop_OrderItem"."Quantity") AS "NewPopularity"'; $q->select($select); $q->groupby('"Product"."ID"'); $q->orderby('"NewPopularity" DESC'); $q->leftJoin('SilverShop_Product_OrderItem', '"SilverShop_Product"."ID" = "SilverShop_Product_OrderItem"."ProductID"'); $q->leftJoin('SilverShop_OrderItem', '"SilverShop_Product_OrderItem"."ID" = "SilverShop_OrderItem"."ID"'); $records = $q->execute(); $productssold = $ps->buildDataObjectSet($records, "DataObjectSet", $q, Product::class); //TODO: this could be done faster with an UPDATE query (SQLQuery doesn't support this yet @11/06/2010) foreach ($productssold as $product) { if ($product->NewPopularity != $product->Popularity) { $product->Popularity = $product->NewPopularity; $product->writeToStage('Stage'); $product->publishSingle(); } } }
php
{ "resource": "" }
q257875
CheckoutPage.requireDefaultRecords
test
public function requireDefaultRecords() { parent::requireDefaultRecords(); if (!self::get()->exists() && $this->config()->create_default_pages) { $page = self::create()->update( [ 'Title' => 'Checkout', 'URLSegment' => CheckoutPageController::config()->url_segment, 'ShowInMenus' => 0, ] ); $page->write(); $page->publishSingle(); $page->flushCache(); DB::alteration_message('Checkout page created', 'created'); } }
php
{ "resource": "" }
q257876
OrderProcessor.makePayment
test
public function makePayment($gateway, $gatewaydata = array(), $successUrl = null, $cancelUrl = null) { //create payment $payment = $this->createPayment($gateway); if (!$payment) { //errors have been stored. return null; } $payment->setSuccessUrl($successUrl ? $successUrl : $this->getReturnUrl()); // Explicitly set the cancel URL if ($cancelUrl) { $payment->setFailureUrl($cancelUrl); } // Create a payment service, by using the Service Factory. This will automatically choose an // AuthorizeService or PurchaseService, depending on Gateway configuration. // Set the user-facing success URL for redirects /** * @var ServiceFactory $factory */ $factory = ServiceFactory::create(); $service = $factory->getService($payment, ServiceFactory::INTENT_PAYMENT); // Initiate payment, get the result back try { $serviceResponse = $service->initiate($this->getGatewayData($gatewaydata)); } catch (\SilverStripe\Omnipay\Exception\Exception $ex) { // error out when an exception occurs $this->error($ex->getMessage()); return null; } // Check if the service response itself contains an error if ($serviceResponse->isError()) { if ($opResponse = $serviceResponse->getOmnipayResponse()) { $this->error($opResponse->getMessage()); } else { $this->error('An unspecified payment error occurred. Please check the payment messages.'); } } // For an OFFSITE payment, serviceResponse will now contain a redirect // For an ONSITE payment, ShopPayment::onCaptured will have been called, which will have called completePayment return $serviceResponse; }
php
{ "resource": "" }
q257877
OrderProcessor.getGatewayData
test
protected function getGatewayData($customData) { $shipping = $this->order->getShippingAddress(); $billing = $this->order->getBillingAddress(); $numPayments = Payment::get() ->filter(array('OrderID' => $this->order->ID)) ->count() - 1; $transactionId = $this->order->Reference . ($numPayments > 0 ? "-$numPayments" : ''); return array_merge( $customData, array( 'transactionId' => $transactionId, 'firstName' => $this->order->FirstName, 'lastName' => $this->order->Surname, 'email' => $this->order->Email, 'company' => $this->order->Company, 'billingAddress1' => $billing->Address, 'billingAddress2' => $billing->AddressLine2, 'billingCity' => $billing->City, 'billingPostcode' => $billing->PostalCode, 'billingState' => $billing->State, 'billingCountry' => $billing->Country, 'billingPhone' => $billing->Phone, 'shippingAddress1' => $shipping->Address, 'shippingAddress2' => $shipping->AddressLine2, 'shippingCity' => $shipping->City, 'shippingPostcode' => $shipping->PostalCode, 'shippingState' => $shipping->State, 'shippingCountry' => $shipping->Country, 'shippingPhone' => $shipping->Phone, ) ); }
php
{ "resource": "" }
q257878
OrderProcessor.createPayment
test
public function createPayment($gateway) { if (!GatewayInfo::isSupported($gateway)) { $this->error( _t( __CLASS__ . ".InvalidGateway", "`{gateway}` isn't a valid payment gateway.", 'gateway is the name of the payment gateway', array('gateway' => $gateway) ) ); return false; } if (!$this->order->canPay(Security::getCurrentUser())) { $this->error(_t(__CLASS__ . ".CantPay", "Order can't be paid for.")); return false; } $payment = Payment::create()->init( $gateway, $this->order->TotalOutstanding(true), ShopConfigExtension::config()->base_currency ); $this->order->Payments()->add($payment); return $payment; }
php
{ "resource": "" }
q257879
OrderProcessor.completePayment
test
public function completePayment() { if (!$this->order->IsPaid()) { // recalculate order to be sure we have the correct total $this->order->calculate(); $this->order->extend('onPayment'); //a payment has been made //place the order, if not already placed if ($this->canPlace($this->order)) { $this->placeOrder(); } else { if ($this->order->Locale) { ShopTools::install_locale($this->order->Locale); } } if (($this->order->GrandTotal() > 0 && $this->order->TotalOutstanding(false) <= 0) // Zero-dollar order (e.g. paid with loyalty points) || ($this->order->GrandTotal() == 0 && Order::config()->allow_zero_order_total) ) { //set order as paid $this->order->Status = 'Paid'; $this->order->write(); } } }
php
{ "resource": "" }
q257880
OrderProcessor.canPlace
test
public function canPlace(Order $order) { if (!$order) { $this->error(_t(__CLASS__ . ".NoOrder", "Order does not exist.")); return false; } //order status is applicable if (!$order->IsCart()) { $this->error(_t(__CLASS__ . ".NotCart", "Order is not a cart.")); return false; } //order has products if ($order->Items()->Count() <= 0) { $this->error(_t(__CLASS__ . ".NoItems", "Order has no items.")); return false; } return true; }
php
{ "resource": "" }
q257881
ShopCountry.Nice
test
public function Nice() { $val = ShopConfigExtension::countryCode2name($this->value); if (!$val) { $val = $this->value; } return _t(__CLASS__ . '.' . $this->value, $val); }
php
{ "resource": "" }
q257882
Checkout.setPaymentMethod
test
public function setPaymentMethod($paymentmethod) { $methods = GatewayInfo::getSupportedGateways(); if (!isset($methods[$paymentmethod])) { ShopTools::getSession() ->set('Checkout.PaymentMethod', null) ->clear('Checkout.PaymentMethod'); return $this->error(_t(__CLASS__ . '.NoPaymentMethod', 'Payment method does not exist')); } ShopTools::getSession()->set('Checkout.PaymentMethod', $paymentmethod); return true; }
php
{ "resource": "" }
q257883
Checkout.getSelectedPaymentMethod
test
public function getSelectedPaymentMethod($nice = false) { $methods = GatewayInfo::getSupportedGateways(); reset($methods); $method = count($methods) === 1 ? key($methods) : ShopTools::getSession()->get('Checkout.PaymentMethod'); if ($nice && isset($methods[$method])) { $method = $methods[$method]; } return $method; }
php
{ "resource": "" }
q257884
OrderEmailNotifier.sendConfirmation
test
public function sendConfirmation() { $subject = _t( 'SilverShop\ShopEmail.ConfirmationSubject', 'Order #{OrderNo} confirmation', '', array('OrderNo' => $this->order->Reference) ); return $this->sendEmail( 'SilverShop/Model/Order_ConfirmationEmail', $subject, self::config()->bcc_confirmation_to_admin ); }
php
{ "resource": "" }
q257885
OrderEmailNotifier.sendAdminNotification
test
public function sendAdminNotification() { $subject = _t( 'SilverShop\ShopEmail.AdminNotificationSubject', 'Order #{OrderNo} notification', '', array('OrderNo' => $this->order->Reference) ); $email = $this->buildEmail('SilverShop/Model/Order_AdminNotificationEmail', $subject) ->setTo(Email::config()->admin_email); if ($this->debugMode) { return $this->debug($email); } else { return $email->send(); } }
php
{ "resource": "" }
q257886
OrderEmailNotifier.sendCancelNotification
test
public function sendCancelNotification() { $email = Email::create() ->setSubject(_t( 'SilverShop\ShopEmail.CancelSubject', 'Order #{OrderNo} cancelled by member', '', ['OrderNo' => $this->order->Reference] )) ->setFrom(Email::config()->admin_email) ->setTo(Email::config()->admin_email) ->setBody($this->order->renderWith(Order::class)); if ($this->debugMode) { return $this->debug($email); } else { return $email->send(); } }
php
{ "resource": "" }
q257887
ShoppingCartController.build_url
test
protected static function build_url($action, $buyable, $params = []) { if (!$action || !$buyable) { return false; } if (SecurityToken::is_enabled() && !self::config()->disable_security_token) { $params[SecurityToken::inst()->getName()] = SecurityToken::inst()->getValue(); } $className = get_class($buyable); $link = Controller::join_links( [ self::config()->url_segment, $action, ShopTools::sanitiseClassName($className), $buyable->ID ] ); return empty($params) ? $link : $link . '?' . http_build_query($params); }
php
{ "resource": "" }
q257888
ShoppingCartController.direct
test
public static function direct($status = true) { if (Director::is_ajax()) { return (string)$status; } if (self::config()->direct_to_cart_page && ($cartlink = CartPage::find_link())) { return Controller::curr()->redirect($cartlink); } else { return Controller::curr()->redirectBack(); } }
php
{ "resource": "" }
q257889
ShoppingCartController.index
test
public function index() { if ($cart = $this->Cart()) { return $this->redirect($cart->CartLink); } elseif ($response = ErrorPage::response_for(404)) { return $response; } return $this->httpError(404, _t('SilverShop\Cart\ShoppingCart.NoCartInitialised', 'no cart initialised')); }
php
{ "resource": "" }
q257890
ShoppingCartController.debug
test
public function debug() { if (Director::isDev() || Permission::check('ADMIN')) { //TODO: allow specifying a particular id to debug Requirements::css('silvershop/core: client/dist/css/cartdebug.css'); $order = ShoppingCart::curr(); $content = ($order) ? Debug::text($order) : 'Cart has not been created yet. Add a product.'; return ['Content' => $content]; } }
php
{ "resource": "" }
q257891
MatchObjectFilter.getFilter
test
public function getFilter() { if (!is_array($this->data)) { return null; } $allowed = array_keys(DataObject::getSchema()->databaseFields($this->className)); $fields = array_flip(array_intersect($allowed, $this->required)); $singleton = singleton($this->className); $new = []; foreach ($fields as $field => $value) { $field = Convert::raw2sql($field); if (in_array($field, $allowed)) { if (isset($this->data[$field])) { // allow wildcard in filter if ($this->data[$field] === '*') { continue; } $dbfield = $singleton->dbObject($field); $value = $dbfield->prepValueForDB($this->data[$field]); $new[] = "\"$field\" = '$value'"; } else { $new[] = "\"$field\" IS NULL"; } } else { if (isset($this->data[$field])) { $value = Convert::raw2sql($this->data[$field]); $new[] = "\"$field\" = '$value'"; } else { $new[] = "\"$field\" IS NULL"; } } } return $new; }
php
{ "resource": "" }
q257892
ShopAccountForm.submit
test
public function submit($data, $form, $request) { $member = Security::getCurrentUser(); if (!$member) { return false; } $form->saveInto($member); $member->write(); $form->sessionMessage(_t(__CLASS__ . '.DetailsSaved', 'Your details have been saved'), 'good'); $this->extend('updateShopAccountFormResponse', $request, $form, $data, $response); return $response ?: $this->getController()->redirectBack(); }
php
{ "resource": "" }
q257893
ShopAccountForm.proceed
test
public function proceed($data, $form, $request) { $member = Security::getCurrentUser(); if (!$member) { return false; } $form->saveInto($member); $member->write(); $form->sessionMessage(_t(__CLASS__ . '.DetailsSaved', 'Your details have been saved'), 'good'); $this->extend('updateShopAccountFormResponse', $request, $form, $data, $response); return $response ?: $this->getController()->redirect(CheckoutPage::find_link()); }
php
{ "resource": "" }
q257894
OrderTotalCalculator.getModifier
test
public function getModifier($className, $forcecreate = false) { if (!ClassInfo::exists($className)) { user_error("Modifier class \"$className\" does not exist."); } //search for existing $modifier = $className::get() ->filter("OrderID", $this->order->ID) ->first(); if ($modifier) { //remove if no longer valid if (!$modifier->valid()) { //TODO: need to provide feedback message - why modifier was removed $modifier->delete(); $modifier->destroy(); return null; } return $modifier; } $modifier = new $className(); if ($modifier->required() || $forcecreate) { //create any modifiers that are required for every order $modifier->OrderID = $this->order->ID; $modifier->write(); $this->order->Modifiers()->add($modifier); return $modifier; } return null; }
php
{ "resource": "" }
q257895
OrderItem.UnitPrice
test
public function UnitPrice() { if ($this->Order()->IsCart()) { $buyable = $this->Buyable(); $unitprice = ($buyable) ? $buyable->sellingPrice() : $this->UnitPrice; $this->extend('updateUnitPrice', $unitprice); return $this->UnitPrice = $unitprice; } return $this->UnitPrice; }
php
{ "resource": "" }
q257896
OrderItem.calculatetotal
test
protected function calculatetotal() { $total = $this->UnitPrice() * $this->Quantity; $this->extend('updateTotal', $total); $this->CalculatedTotal = $total; return $total; }
php
{ "resource": "" }
q257897
OrderItem.uniquedata
test
public function uniquedata() { $required = self::config()->required_fields; //TODO: also combine with all ancestors of this->class $unique = []; $hasOnes = $this->hasOne(); //reduce record to only required fields if ($required) { foreach ($required as $field) { if ($hasOnes === $field || isset($hasOnes[$field])) { $field = $field . 'ID'; //add ID to hasones } $unique[$field] = $this->$field; } } return $unique; }
php
{ "resource": "" }
q257898
OrderItem.onBeforeWrite
test
public function onBeforeWrite() { parent::onBeforeWrite(); if ($this->OrderID && $this->Order() && $this->Order()->isCart()) { $this->calculatetotal(); } }
php
{ "resource": "" }
q257899
OrderItem.ProductVariation
test
public function ProductVariation($forcecurrent = false) { if ($this->ProductVariationID && $this->ProductVariationVersion && !$forcecurrent) { return Versioned::get_version( Variation::class, $this->ProductVariationID, $this->ProductVariationVersion ); } elseif ($this->ProductVariationID && $product = Variation::get()->byID($this->ProductVariationID) ) { return $product; } return null; }
php
{ "resource": "" }