_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q240500
|
Gdn_Session.End
|
train
|
public function End($Authenticator = NULL) {
if ($Authenticator == NULL)
$Authenticator = Gdn::Authenticator();
$Authenticator->AuthenticateWith()->DeAuthenticate();
$this->SetCookie('-Vv', NULL, -3600);
$this->UserID = 0;
$this->User = FALSE;
$this->_Attributes = array();
$this->_Permissions = array();
$this->_Preferences = array();
$this->_TransientKey = FALSE;
}
|
php
|
{
"resource": ""
}
|
q240501
|
Gdn_Session.HourOffset
|
train
|
public function HourOffset() {
static $GuestHourOffset;
if ($this->UserID > 0) {
return $this->User->HourOffset;
} else {
if (!isset($GuestHourOffset)) {
$GuestTimeZone = C('Garden.GuestTimeZone');
if ($GuestTimeZone) {
try {
$TimeZone = new DateTimeZone($GuestTimeZone);
$Offset = $TimeZone->getOffset(new DateTime('now', new DateTimeZone('UTC')));
$GuestHourOffset = floor($Offset / 3600);
} catch (Exception $Ex) {
$GuestHourOffset = 0;
LogException($Ex);
}
}
}
return $GuestHourOffset;
}
}
|
php
|
{
"resource": ""
}
|
q240502
|
Gdn_Session.Start
|
train
|
public function Start($UserID = FALSE, $SetIdentity = TRUE, $Persist = FALSE) {
if (!C('Garden.Installed', FALSE)) return;
// Retrieve the authenticated UserID from the Authenticator module.
$UserModel = Gdn::Authenticator()->GetUserModel();
$this->UserID = $UserID !== FALSE ? $UserID : Gdn::Authenticator()->GetIdentity();
$this->User = FALSE;
// Now retrieve user information
if ($this->UserID > 0) {
// Instantiate a UserModel to get session info
$this->User = $UserModel->GetSession($this->UserID);
if ($this->User) {
if ($SetIdentity)
Gdn::Authenticator()->SetIdentity($this->UserID, $Persist);
$UserModel->EventArguments['User'] =& $this->User;
$UserModel->FireEvent('AfterGetSession');
$this->_Permissions = Gdn_Format::Unserialize($this->User->Permissions);
$this->_Preferences = Gdn_Format::Unserialize($this->User->Preferences);
$this->_Attributes = Gdn_Format::Unserialize($this->User->Attributes);
$this->_TransientKey = is_array($this->_Attributes) ? ArrayValue('TransientKey', $this->_Attributes) : FALSE;
if ($this->_TransientKey === FALSE)
$this->_TransientKey = $UserModel->SetTransientKey($this->UserID);
// Save any visit-level information.
$UserModel->UpdateVisit($this->UserID);
} else {
$this->UserID = 0;
$this->User = FALSE;
if ($SetIdentity)
Gdn::Authenticator()->SetIdentity(NULL);
}
} else {
// Grab the transient key from the cookie. This doesn't always get set but we'll try it here anyway.
$this->_TransientKey = GetAppCookie('tk');
}
// Load guest permissions if necessary
if ($this->UserID == 0)
$this->_Permissions = Gdn_Format::Unserialize($UserModel->DefinePermissions(0));
}
|
php
|
{
"resource": ""
}
|
q240503
|
Gdn_Session.TransientKey
|
train
|
public function TransientKey($NewKey = NULL) {
if (!is_null($NewKey)) {
$this->_TransientKey = Gdn::Authenticator()->GetUserModel()->SetTransientKey($this->UserID, $NewKey);
}
// if ($this->_TransientKey)
return $this->_TransientKey;
// else
// return RandomString(12); // Postbacks will never be authenticated if transientkey is not defined.
}
|
php
|
{
"resource": ""
}
|
q240504
|
IntrospectedWorkflow.guessIsIntrospectedStateRootOrLeaf
|
train
|
private function guessIsIntrospectedStateRootOrLeaf()
{
foreach ($this->introspectedStates as $introspectedState) {
$this->guessIsIntrospectedStateRoot($introspectedState);
$this->guessIsIntrospectedStateLeaf($introspectedState);
}
}
|
php
|
{
"resource": ""
}
|
q240505
|
OptionPolicy.update
|
train
|
public function update(User $user, $option, $categoryKey)
{
if (!empty($option)) {
return $user->hasPermission('options-update-' . $categoryKey);
}
return false;
}
|
php
|
{
"resource": ""
}
|
q240506
|
Middleman.executePipeline
|
train
|
public function executePipeline($pipeline, Request $request, Response $response = null)
{
$middleman = new \mindplay\middleman\Dispatcher($pipeline, $this->resolver);
return $middleman->dispatch($request);
}
|
php
|
{
"resource": ""
}
|
q240507
|
endpoint_form.automatic_form
|
train
|
public function automatic_form(){
@header('text/html; charset=UTF-8');
$rtn = '';
if( !strlen($this->options['table']) ){
// --------------------
// 対象のテーブルが選択されていない
echo $this->page_table_list();
return null;
}
$table_definition = $this->get_current_table_definition();
// var_dump($table_definition);
if( !$table_definition ){
@header("HTTP/1.0 404 Not Found");
$rtn = $this->page_fatal_error('Table NOT Exists.');
echo $rtn;
return null;
}
if( !strlen($this->options['id']) ){
// ID無指定の場合、一覧情報を返す
echo $this->page_list($this->options['table']);
return null;
}elseif( $this->options['id'] == ':create' ){
// IDの代わりに文字列 `:create` が指定されたら、新規作成画面を返す
echo $this->page_edit($this->options['table']);
return null;
}else{
// ID指定がある場合、詳細情報1件を返す
$row_data = $this->get_current_row_data();
if( !$row_data && !($this->options['action'] == 'delete' && $this->query_options['action'] == 'done') ){
@header("HTTP/1.0 404 Not Found");
$rtn = $this->page_fatal_error('ID NOT Exists.');
echo $rtn;
return null;
}
if( $this->options['action'] == 'delete' ){
echo $this->page_delete($this->options['table'], $this->options['id']);
}elseif( $this->options['action'] == 'edit' ){
echo $this->page_edit($this->options['table'], $this->options['id']);
}else{
echo $this->page_detail($this->options['table'], $this->options['id']);
}
return null;
}
// エラー画面
$rtn = $this->page_fatal_error('Unknown method');
echo $rtn;
return null;
}
|
php
|
{
"resource": ""
}
|
q240508
|
endpoint_form.automatic_signup_form
|
train
|
public function automatic_signup_form($table_name, $init_cols, $options = array()){
@header('text/html; charset=UTF-8');
$param_options = $this->get_options();
$data = $param_options['post_params'];
$this->table_definition = $this->exdb->get_table_definition($table_name);
$is_login = $this->exdb->user()->is_login($table_name);
if( $is_login ){
// ログイン処理済みなら終了
echo '<p>Already Logging in.</p>';
return true;
}
$page_edit = new endpoint_form_signup($this->exdb, $this, $table_name, $init_cols, $options);
echo $page_edit->execute();
return true;
}
|
php
|
{
"resource": ""
}
|
q240509
|
endpoint_form.auth
|
train
|
public function auth($table_name, $inquiries){
$options = $this->get_options();
$data = $options['post_params'];
if(@$this->query_options['action'] == 'login'){
// ログインを試みる
$result = $this->exdb->user()->login( $table_name, $inquiries, $data );
}
$is_login = $this->exdb->user()->is_login($table_name);
if( $is_login ){
// ログイン処理済みなら終了
return true;
}
$table_definition = $this->exdb->get_table_definition($table_name);
// var_dump($table_definition->columns);
$rtn = '';
foreach( $inquiries as $column_name ){
$column_definition = $table_definition->columns->{$column_name};
$type_info = $this->exdb->form_elements()->get_type_info($column_definition->type);
$form_elm = $this->render(
$type_info['templates']['preview'],
array(
'value'=>@$list[0][$column_definition->name],
'name'=>@$column_definition->name,
'def'=>@$column_definition,
)
);
$rtn .= $this->render(
'form_elms_unit.html',
array(
'label'=>@$column_definition->label,
'content'=>$form_elm,
'error'=>null,
)
);
}
$rtn = $this->render(
'form_login.html',
array(
'is_error'=>(@$this->query_options['action'] == 'login'),
'content'=>$rtn,
)
);
// var_dump($table_list);
$rtn = $this->wrap_theme($rtn);
echo $rtn;
return false;
}
|
php
|
{
"resource": ""
}
|
q240510
|
ProcessRunner.run
|
train
|
public function run($commandline, callable $callback = null, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60)
{
$process = new Process(
$commandline,
$cwd,
$env,
$input,
$timeout
);
$helper = new DebugFormatterHelper();
$output = $this->output;
$output->writeln($helper->start(
spl_object_hash($process),
'Executing: '.$commandline,
'STARTED'
));
$process->run(function ($type, $buffer) use ($helper,$output,$process,$callback) {
if (is_callable($callback)) {
call_user_func($callback, $type, $buffer);
}
$contents = $helper->progress(
spl_object_hash($process),
$buffer,
Process::ERR === $type
);
$output->write($contents);
});
return $process;
}
|
php
|
{
"resource": ""
}
|
q240511
|
Translation.translate
|
train
|
public function translate($string, Array $vars = array())
{
// Use custom translator
if ($this->translator) {
return $this->translator($this->getString($string), $vars);
}
return $this->compileString($this->getString($string), $vars);
}
|
php
|
{
"resource": ""
}
|
q240512
|
Translation.getString
|
train
|
public function getString($string)
{
// Exact match?
if (isset($this->strings[$string])) {
return $this->strings[$string];
} else {
return $string;
}
}
|
php
|
{
"resource": ""
}
|
q240513
|
Translation.calculateNumeral
|
train
|
public function calculateNumeral($numeral)
{
// Use custom enumerator
if ($this->enumerator) {
return $this->enumerator($numeral);
}
return ($numeral > 1 or $numeral < -1 or $numeral == 0) ? 1 : 0;
}
|
php
|
{
"resource": ""
}
|
q240514
|
Translation.compileString
|
train
|
protected function compileString($string, $vars)
{
$translation = $string;
// Loop through and replace the placeholders
// with the values from the $vars array.
$count = 0;
foreach ($vars as $key => $val) {
$count++;
// If array key is an integer,
// use the counter to avoid clashes
// with numbered placeholders.
if (is_integer($key)) {
$key = $count;
}
// Replace placeholder with value
$translation = str_replace(array("{{$key}}", "{{$count}}"), $val, $translation);
}
// Match plural:n,{x, y}
if (preg_match_all("/{plural:(?<value>-{0,1}\d+)(,|, ){(?<replacements>.*?)}}/i", $translation, $matches)) {
foreach($matches[0] as $id => $match) {
// Split the replacements into an array.
// There's an extra | at the start to allow for better matching
// with values.
$replacements = explode('|', $matches['replacements'][$id]);
// Get the value
$value = $matches['value'][$id];
// Check what replacement to use...
$replacement_id = $this->calculateNumeral($value);
if ($replacement_id !== false) {
$translation = str_replace($match, $replacements[$replacement_id], $translation);
}
// Get the last value then
else {
$translation = str_replace($match, end($replacements), $translation);
}
}
}
// We're done here.
return $translation;
}
|
php
|
{
"resource": ""
}
|
q240515
|
Sport.initObjects
|
train
|
public function initObjects($overrideExisting = true)
{
if (null !== $this->collObjects && !$overrideExisting) {
return;
}
$this->collObjects = new ObjectCollection();
$this->collObjects->setModel('\gossi\trixionary\model\Object');
}
|
php
|
{
"resource": ""
}
|
q240516
|
Sport.getObjects
|
train
|
public function getObjects(Criteria $criteria = null, ConnectionInterface $con = null)
{
$partial = $this->collObjectsPartial && !$this->isNew();
if (null === $this->collObjects || null !== $criteria || $partial) {
if ($this->isNew() && null === $this->collObjects) {
// return empty collection
$this->initObjects();
} else {
$collObjects = ChildObjectQuery::create(null, $criteria)
->filterBySport($this)
->find($con);
if (null !== $criteria) {
if (false !== $this->collObjectsPartial && count($collObjects)) {
$this->initObjects(false);
foreach ($collObjects as $obj) {
if (false == $this->collObjects->contains($obj)) {
$this->collObjects->append($obj);
}
}
$this->collObjectsPartial = true;
}
return $collObjects;
}
if ($partial && $this->collObjects) {
foreach ($this->collObjects as $obj) {
if ($obj->isNew()) {
$collObjects[] = $obj;
}
}
}
$this->collObjects = $collObjects;
$this->collObjectsPartial = false;
}
}
return $this->collObjects;
}
|
php
|
{
"resource": ""
}
|
q240517
|
Sport.countObjects
|
train
|
public function countObjects(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null)
{
$partial = $this->collObjectsPartial && !$this->isNew();
if (null === $this->collObjects || null !== $criteria || $partial) {
if ($this->isNew() && null === $this->collObjects) {
return 0;
}
if ($partial && !$criteria) {
return count($this->getObjects());
}
$query = ChildObjectQuery::create(null, $criteria);
if ($distinct) {
$query->distinct();
}
return $query
->filterBySport($this)
->count($con);
}
return count($this->collObjects);
}
|
php
|
{
"resource": ""
}
|
q240518
|
Sport.addObject
|
train
|
public function addObject(ChildObject $l)
{
if ($this->collObjects === null) {
$this->initObjects();
$this->collObjectsPartial = true;
}
if (!$this->collObjects->contains($l)) {
$this->doAddObject($l);
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q240519
|
Sport.initPositions
|
train
|
public function initPositions($overrideExisting = true)
{
if (null !== $this->collPositions && !$overrideExisting) {
return;
}
$this->collPositions = new ObjectCollection();
$this->collPositions->setModel('\gossi\trixionary\model\Position');
}
|
php
|
{
"resource": ""
}
|
q240520
|
Sport.getPositions
|
train
|
public function getPositions(Criteria $criteria = null, ConnectionInterface $con = null)
{
$partial = $this->collPositionsPartial && !$this->isNew();
if (null === $this->collPositions || null !== $criteria || $partial) {
if ($this->isNew() && null === $this->collPositions) {
// return empty collection
$this->initPositions();
} else {
$collPositions = ChildPositionQuery::create(null, $criteria)
->filterBySport($this)
->find($con);
if (null !== $criteria) {
if (false !== $this->collPositionsPartial && count($collPositions)) {
$this->initPositions(false);
foreach ($collPositions as $obj) {
if (false == $this->collPositions->contains($obj)) {
$this->collPositions->append($obj);
}
}
$this->collPositionsPartial = true;
}
return $collPositions;
}
if ($partial && $this->collPositions) {
foreach ($this->collPositions as $obj) {
if ($obj->isNew()) {
$collPositions[] = $obj;
}
}
}
$this->collPositions = $collPositions;
$this->collPositionsPartial = false;
}
}
return $this->collPositions;
}
|
php
|
{
"resource": ""
}
|
q240521
|
Sport.countPositions
|
train
|
public function countPositions(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null)
{
$partial = $this->collPositionsPartial && !$this->isNew();
if (null === $this->collPositions || null !== $criteria || $partial) {
if ($this->isNew() && null === $this->collPositions) {
return 0;
}
if ($partial && !$criteria) {
return count($this->getPositions());
}
$query = ChildPositionQuery::create(null, $criteria);
if ($distinct) {
$query->distinct();
}
return $query
->filterBySport($this)
->count($con);
}
return count($this->collPositions);
}
|
php
|
{
"resource": ""
}
|
q240522
|
Sport.addPosition
|
train
|
public function addPosition(ChildPosition $l)
{
if ($this->collPositions === null) {
$this->initPositions();
$this->collPositionsPartial = true;
}
if (!$this->collPositions->contains($l)) {
$this->doAddPosition($l);
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q240523
|
Sport.getSkillsJoinObject
|
train
|
public function getSkillsJoinObject(Criteria $criteria = null, ConnectionInterface $con = null, $joinBehavior = Criteria::LEFT_JOIN)
{
$query = ChildSkillQuery::create(null, $criteria);
$query->joinWith('Object', $joinBehavior);
return $this->getSkills($query, $con);
}
|
php
|
{
"resource": ""
}
|
q240524
|
Sport.initGroups
|
train
|
public function initGroups($overrideExisting = true)
{
if (null !== $this->collGroups && !$overrideExisting) {
return;
}
$this->collGroups = new ObjectCollection();
$this->collGroups->setModel('\gossi\trixionary\model\Group');
}
|
php
|
{
"resource": ""
}
|
q240525
|
Sport.getGroups
|
train
|
public function getGroups(Criteria $criteria = null, ConnectionInterface $con = null)
{
$partial = $this->collGroupsPartial && !$this->isNew();
if (null === $this->collGroups || null !== $criteria || $partial) {
if ($this->isNew() && null === $this->collGroups) {
// return empty collection
$this->initGroups();
} else {
$collGroups = ChildGroupQuery::create(null, $criteria)
->filterBySport($this)
->find($con);
if (null !== $criteria) {
if (false !== $this->collGroupsPartial && count($collGroups)) {
$this->initGroups(false);
foreach ($collGroups as $obj) {
if (false == $this->collGroups->contains($obj)) {
$this->collGroups->append($obj);
}
}
$this->collGroupsPartial = true;
}
return $collGroups;
}
if ($partial && $this->collGroups) {
foreach ($this->collGroups as $obj) {
if ($obj->isNew()) {
$collGroups[] = $obj;
}
}
}
$this->collGroups = $collGroups;
$this->collGroupsPartial = false;
}
}
return $this->collGroups;
}
|
php
|
{
"resource": ""
}
|
q240526
|
Sport.addGroup
|
train
|
public function addGroup(ChildGroup $l)
{
if ($this->collGroups === null) {
$this->initGroups();
$this->collGroupsPartial = true;
}
if (!$this->collGroups->contains($l)) {
$this->doAddGroup($l);
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q240527
|
PagesController.getAll
|
train
|
public function getAll(Request $request)
{
// Get the views' directory
$viewsPath = base_path() . '/resources/views/';
if (!is_dir($viewsPath)) {
error_log("The directory /resources/views/ doesn't exists.");
throw new PathNotFoundException();
}
// Get the lang' directory
$langPath = base_path() . '/resources/lang/';
if (!is_dir($langPath)) {
error_log("The directory /resources/lang/ doesn't exists.");
throw new PathNotFoundException();
}
// Get the language directory from the current url
$path = $request->input('path');
$pathInfo = LocaleService::parsePath($path);
// Set the active language
LocaleService::setLang($pathInfo->lang);
// Init the response object
$resp = new \stdClass();
$resp->langDir = $pathInfo->langDir;
$resp->pages = null;
// Get last modification time on views or lang's messages
$pagesLastMod = max(
self::getLastMod($viewsPath),
self::getLastMod($langPath)
);
// Init current cache keys (language-dependent)
$pagesKey = "pages.{$pathInfo->lang}";
$pagesTimestampKey = "pages.{$pathInfo->lang}.timestamp";
// Check if the cache is enabled
$cacheEnabled = false;
if (env('CACHE_DRIVER') !== null) {
$cacheEnabled = true;
}
// If the cache is valid return the cached value
if ($cacheEnabled) {
$pagesLastCache = Cache::get($pagesTimestampKey);
if ($pagesLastCache !== null && $pagesLastCache >= $pagesLastMod) {
$resp->pages = Cache::get($pagesKey);
return response()->json($resp);
}
}
// Get the list of views
$viewsList = self::getViewsList($viewsPath);
// Initialize the LocaleLinkService used inside views to set links
LocaleLinkService::setLang($pathInfo->lang);
LocaleLinkService::setLangDir($pathInfo->langDir);
// Fill the $pages array, containing all the pages' content
$pages = [];
foreach ($viewsList as $viewName) {
$page = new \stdClass();
// Page path
$page->path = ($viewName === 'index') ? '' : $viewName;
$page->path = '/' . str_replace('.', '/', $page->path);
// Set the page's path inside the LocaleLinkService
LocaleLinkService::setPagePath($page->path);
// Page title
$page->title = view(
$viewName,
[
'benjamin' => 'benjamin::title',
'activeLang' => LocaleService::getActiveLang(),
]
)->render();
// Page body
$page->body = view(
$viewName,
[
'benjamin' => 'benjamin::body',
'activeLang' => LocaleService::getActiveLang(),
]
)->render();
// bodyClass
$page->bodyClass = view(
$viewName,
[
'benjamin' => 'benjamin::bodyClass',
'activeLang' => LocaleService::getActiveLang(),
]
)->render();
$pages[] = $page;
}
// Cache the value
if ($cacheEnabled) {
Cache::forever($pagesKey, $pages);
Cache::forever($pagesTimestampKey, time());
}
// Response
$resp->pages = $pages;
return response()->json($resp);
}
|
php
|
{
"resource": ""
}
|
q240528
|
PagesController.getLastMod
|
train
|
private function getLastMod($dirPath)
{
$dirInfo = new \SplFileInfo($dirPath);
$lastMod = $dirInfo->getMTime();
// Check files and subdirectories
$iter = new \FilesystemIterator($dirPath);
foreach ($iter as $fileInfo) {
if ($fileInfo->isDir()) {
$mtime = self::getLastMod($fileInfo->getPathname());
}
else {
$mtime = $fileInfo->getMTime();
}
if ($mtime > $lastMod) {
$lastMod = $mtime;
}
}
return $lastMod;
}
|
php
|
{
"resource": ""
}
|
q240529
|
PagesController.getViewsList
|
train
|
private function getViewsList($dirPath, $checkSubDir = true)
{
$viewsList = [];
$iter = new \FilesystemIterator($dirPath);
foreach ($iter as $fileInfo) {
$filename = $fileInfo->getFilename();
if ($filename[0] === '_') {
continue;
}
// Directories
if ($fileInfo->isDir()) {
if (!$checkSubDir) {
continue;
}
if ($filename === 'errors' || $filename === 'layouts' ||
$filename === 'templates' || $filename === 'vendor') {
continue;
}
// $subViews = self::getViewsList($fileInfo->getPathname(), false);
$subViews = self::getViewsList($fileInfo->getPathname());
// Prepend directory name and add the view name to current list
foreach ($subViews as $subViewName) {
$viewsList[] = $filename . '.' . $subViewName;
}
continue;
}
// Files
if (substr($filename, -10) !== '.blade.php') {
continue;
}
$viewName = substr($filename, 0, -10);
$viewsList[] = $viewName;
}
return $viewsList;
}
|
php
|
{
"resource": ""
}
|
q240530
|
Engine.loadLanguages
|
train
|
private function loadLanguages()
{
$app = $this->app;
$engine = $this;
$languages = $app['config.app.languages'];
$app['multi_languages'] = count($languages) > 1;
$app->register(new LocaleServiceProvider());
$app->register(new TranslationServiceProvider(), [
'locale_fallbacks' => $languages,
]);
$app['translator.domains'] = function () use ($app, $engine) {
$translator_domains = [
'messages' => [],
'validators' => [],
];
$languages = $app['config.app.languages'];
foreach ($languages as $language) {
if (is_readable($engine->getAppPath('language').DIRECTORY_SEPARATOR.strtolower($language).'.php')) {
$trans = include $engine->getAppPath('language').DIRECTORY_SEPARATOR.strtolower($language).'.php';
$translator_domains['messages'][$language] = isset($trans['messages']) ? $trans['messages'] : [];
$translator_domains['validators'][$language] = isset($trans['validators']) ? $trans['validators'] : [];
}
}
return $translator_domains;
};
}
|
php
|
{
"resource": ""
}
|
q240531
|
Engine.loadRouting
|
train
|
private function loadRouting()
{
$app = $this->app;
$maps = [];
$routing_file_path = $this->getAppPath('config').DIRECTORY_SEPARATOR.'routing.php';
if (is_readable($routing_file_path)) {
$maps = require $routing_file_path;
}
if ($maps) {
$prefix_locale = $app['multi_languages'] ? '/{_locale}' : '';
$app_controller_prefix = $app['app.vendor_name'].'\\Controller\\';
foreach ($maps as $prefix => $routes) {
$map = $this->app['controllers_factory'];
foreach ($routes as $pattern => $target) {
if ($pattern == '.' && is_callable($target)) {
call_user_func($target, $map);
} else {
$params = is_array($target) ? $target : explode(':', $target);
$controller_name = $app_controller_prefix.$params[0];
$action = $params[1].'Action';
$bind_name = isset($params[2]) ? $params[2] : false;
$method = isset($params[4]) ? strtolower($params[4]) : 'get|post';
$tmp = $map->match($pattern, $controller_name.'::'.$action)->method($method);
if ($bind_name) {
$tmp->bind($bind_name);
}
if (!empty($params[3])) {
if (is_array($params[3])) {
foreach ($params[3] as $key => $value) {
$tmp->value($key, $value);
}
} else {
$defaults = explode(',', $params[3]);
foreach ($defaults as $default) {
$values = explode('=', $default);
$tmp->value($values[0], $values[1]);
}
}
}
if ($prefix_locale != '' && $prefix == '/' && $pattern == '/') {
$app->match('/', $controller_name.'::'.$action)->method($method);
}
}
}
$app->mount($prefix_locale.$prefix, $map);
}
}
}
|
php
|
{
"resource": ""
}
|
q240532
|
Factory.setLoader
|
train
|
public function setLoader(Loader $loader)
{
$this->loader = $loader;
$this->loader->setNamespace($this->getNamespace());
}
|
php
|
{
"resource": ""
}
|
q240533
|
HaringoBuilderImpl.getSerializerValSourceExtBasedOn
|
train
|
private function getSerializerValSourceExtBasedOn(ValueSourceExtension $ext)
{
return new SerializerValueSourceExtensionImpl(
$ext->getMapper(),
$ext->getSupportedValueSourceClass(),
$ext->getUniqueExtensionId()
);
}
|
php
|
{
"resource": ""
}
|
q240534
|
MediaType.getTitle
|
train
|
public function getTitle($code)
{
if (!isset($this->titles[$code])) {
$code = key($this->getTitles());
}
return $this->titles[$code];
}
|
php
|
{
"resource": ""
}
|
q240535
|
RequestSigner.getSignatureContent
|
train
|
public function getSignatureContent(\TYPO3\Flow\Http\Request $httpRequest) {
$date = $httpRequest->getHeader('Date');
$dateValue = $date instanceof \DateTime ? $date->format(DATE_RFC2822) : '';
$signData = $httpRequest->getMethod() . chr(10)
. sha1($httpRequest->getContent()) . chr(10)
. $httpRequest->getHeader('Content-Type') . chr(10)
. $dateValue . chr(10)
. $httpRequest->getUri();
return $signData;
}
|
php
|
{
"resource": ""
}
|
q240536
|
Model.assignAttribute
|
train
|
public function assignAttribute($name, $value)
{
$table = static::table();
if (!is_object($value)) {
if (array_key_exists($name, $table->columns)) {
$value = $table->columns[$name]->cast($value, static::connection());
} else {
$col = $table->getColumnByInflectedName($name);
if (!is_null($col)){
$value = $col->cast($value, static::connection());
}
}
}
// convert php's \DateTime to ours
if ($value instanceof \DateTime) {
$value = new DateTime($value->format('Y-m-d H:i:s T'));
}
// make sure DateTime values know what model they belong to so
// dirty stuff works when calling set methods on the DateTime object
if ($value instanceof DateTime) {
$value->attributeOf($this, $name);
}
$this->_attributes[$name] = $value;
$this->flagDirty($name);
return $value;
}
|
php
|
{
"resource": ""
}
|
q240537
|
Model.&
|
train
|
public function &readAttribute($name)
{
// check for aliased attribute
if (array_key_exists($name, static::$aliasAttribute))
$name = static::$aliasAttribute[$name];
// check for attribute
if (array_key_exists($name,$this->_attributes))
return $this->_attributes[$name];
// check relationships if no attribute
if (array_key_exists($name,$this->_relationships))
return $this->_relationships[$name];
$table = static::table();
// this may be first access to the relationship so check Table
if (($relationship = $table->getRelationship($name))) {
$this->_relationships[$name] = $relationship->load($this);
return $this->_relationships[$name];
}
// Shortcut to get primary key
if ($name == 'id') {
$pk = $this->getPrimaryKey(true);
if (isset($this->_attributes[$pk])) return $this->_attributes[$pk];
}
//do not remove - have to return null by reference in strict mode
$null = null;
foreach (static::$delegate as &$item) {
if (($delegated_name = $this->isDelegated($name, $item))) {
$to = $item['to'];
if ($this->$to) {
$val =& $this->$to->__get($delegated_name);
return $val;
} else {
return $null;
}
}
}
throw new UndefinedPropertyException(get_called_class(),$name);
}
|
php
|
{
"resource": ""
}
|
q240538
|
Model.hasAttribute
|
train
|
public function hasAttribute($attrName)
{
// In default attributes
if (array_key_exists($attrName, $this->_attributes)) return true;
// A getter available?
if (method_exists($this, "__get_$attrName")) return true;
return false;
}
|
php
|
{
"resource": ""
}
|
q240539
|
Model.flagDirty
|
train
|
public function flagDirty($name, $dirty = true)
{
if (!$this->_dirty) $this->_dirty = array();
if ($dirty) {
$this->_dirty[$name] = true;
} else {
if (array_key_exists($name, $this->_dirty)) {
unset($this->_dirty[$name]);
}
}
}
|
php
|
{
"resource": ""
}
|
q240540
|
Model.dirtyAttributes
|
train
|
public function dirtyAttributes()
{
if (!$this->_dirty)
return null;
$dirty = array_intersect_key($this->_attributes, $this->_dirty);
return !empty($dirty) ? $dirty : null;
}
|
php
|
{
"resource": ""
}
|
q240541
|
Model.attributeIsDirty
|
train
|
public function attributeIsDirty($attribute)
{
return $this->_dirty && isset($this->_dirty[$attribute]) && array_key_exists($attribute, $this->_attributes);
}
|
php
|
{
"resource": ""
}
|
q240542
|
Model.create
|
train
|
public static function create($attributes, $validate = true, $guardAttributes=true)
{
// Get class and instantiate it
$className = get_called_class();
$model = new $className($attributes, $guardAttributes);
$model->save($validate);
return $model;
}
|
php
|
{
"resource": ""
}
|
q240543
|
Model.insert
|
train
|
private function insert($validate = true)
{
$this->verifyNotReadonly('insert');
// Check if validation or beforeCreate returns false.
if (($validate && !$this->_validate() || !$this->invokeCallback('beforeCreate',false))) {
return false;
}
$table = static::table();
// Get dirty attributes, or when nothing is dirty we just take all atrributes
if (!($attributes = $this->dirtyAttributes())) {
$attributes = $this->_attributes;
}
$pk = $this->getPrimaryKey(true);
$useSequence = false;
if ($table->sequence && !isset($attributes[$pk]))
{
if (($conn = static::connection()) instanceof OciAdapter) {
// terrible oracle makes us select the nextval first
$attributes[$pk] = $conn->getNextSequenceValue($table->sequence);
$table->insert($attributes);
$this->_attributes[$pk] = $attributes[$pk];
} else {
// unset pk that was set to null
if (array_key_exists($pk, $attributes)) {
unset($attributes[$pk]);
}
$table->insert($attributes, $pk, $table->sequence);
$useSequence = true;
}
} else {
// Simple insert
$table->insert($attributes);
}
// if we've got an autoincrementing/sequenced pk set it
// don't need this check until the day comes that we decide to support composite pks
// if (count($pk) == 1)
{
$column = $table->getColumnByInflectedName($pk);
if ($column->autoIncrement || $useSequence) {
$this->_attributes[$pk] = static::connection()->insertId($table->sequence);
}
}
$this->_newRecord = false;
$this->invokeCallback('afterCreate', false);
return true;
}
|
php
|
{
"resource": ""
}
|
q240544
|
Model.update
|
train
|
private function update($validate = true)
{
$this->verifyNotReadonly('update');
// Valid record?
if ($validate && !$this->_validate()) {
return false;
}
// Anything to update?
if ($this->isDirty()) {
// Check my primary key
$pk = $this->valuesForPk();
if (empty($pk)) {
throw new ActiveRecordException("Cannot update, no primary key defined for: " . get_called_class());
}
// Check callback
if (!$this->invokeCallback('beforeUpdate',false)) {
return false;
}
// Do the update
$dirty = $this->dirtyAttributes();
static::table()->update($dirty, $pk);
$this->invokeCallback('afterUpdate',false);
}
return true;
}
|
php
|
{
"resource": ""
}
|
q240545
|
Model.delete
|
train
|
public function delete()
{
$this->verifyNotReadonly('delete');
$pk = $this->valuesForPk();
if (empty($pk))
throw new ActiveRecordException("Cannot delete, no primary key defined for: " . get_called_class());
if (!$this->invokeCallback('beforeDestroy',false))
return false;
static::table()->delete($pk);
$this->invokeCallback('afterDestroy',false);
return true;
}
|
php
|
{
"resource": ""
}
|
q240546
|
Model.valuesFor
|
train
|
public function valuesFor($attributeNames)
{
$filter = array();
foreach ($attributeNames as $name)
$filter[$name] = $this->$name;
return $filter;
}
|
php
|
{
"resource": ""
}
|
q240547
|
Model._validate
|
train
|
protected function _validate()
{
// Check if validation is necessary and parsed
if (static::$validates === false) return true;
if (is_null(static::$_validation)) {
require_once("Validation/Validation.php");
static::$_validation = Validation\Validation::onModel(get_called_class());
}
// Go validate!
$result = static::$_validation->validate($this);
// Success?
if ($result->success == false) {
// Store errors
$this->_errors = $result->errors;
return false;
} else {
// Clear errors
$this->_errors = null;
}
// True
return true;
}
|
php
|
{
"resource": ""
}
|
q240548
|
Model.setTimestamps
|
train
|
public function setTimestamps()
{
$now = date('Y-m-d H:i:s');
if (isset($this->updated_at))
$this->updated_at = $now;
if (isset($this->created_at) && $this->isNewRecord())
$this->created_at = $now;
}
|
php
|
{
"resource": ""
}
|
q240549
|
Model.updateAttribute
|
train
|
public function updateAttribute($name, $value)
{
$this->__set($name, $value);
return $this->update(false);
}
|
php
|
{
"resource": ""
}
|
q240550
|
Model.reload
|
train
|
public function reload()
{
$this->_relationships = array();
$pk = array_values($this->getValuesFor($this->getPrimaryKey()));
$this->setAttributesViaMassAssignment($this->find($pk)->attributes, false);
$this->resetDirty();
return $this;
}
|
php
|
{
"resource": ""
}
|
q240551
|
Model.count
|
train
|
public static function count(/* ... */)
{
$args = func_get_args();
$options = static::extractAndValidateOptions($args);
$options['select'] = 'COUNT(*)';
if (!empty($args) && !is_null($args[0]) && !empty($args[0]))
{
if (is_hash($args[0]))
$options['conditions'] = $args[0];
else
$options['conditions'] = call_user_func_array('static::pk_conditions',$args);
}
$table = static::table();
$sql = $table->options_to_sql($options);
$values = $sql->get_where_values();
return static::connection()->query_and_fetch_one($sql->to_s(),$values);
}
|
php
|
{
"resource": ""
}
|
q240552
|
Model.find
|
train
|
public static function find(/* $type, $options */)
{
$class = get_called_class();
if (func_num_args() <= 0)
throw new RecordNotFound("Couldn't find $class without an ID");
$args = func_get_args();
$options = static::extractAndValidateOptions($args);
$num_args = count($args);
$single = true;
if ($num_args > 0 && ($args[0] === 'all' || $args[0] === 'first' || $args[0] === 'last'))
{
switch ($args[0])
{
case 'all':
$single = false;
break;
case 'last':
if (!array_key_exists('order',$options))
$options['order'] = join(' DESC, ', static::table()->pk) . ' DESC';
else
$options['order'] = SQLBuilder::reverseOrder($options['order']);
// fall thru
case 'first':
$options['limit'] = 1;
$options['offset'] = 0;
break;
}
$args = array_slice($args,1);
$num_args--;
}
//find by pk
elseif (1 === count($args) && 1 == $num_args)
$args = $args[0];
// anything left in $args is a find by pk
if ($num_args > 0 && !isset($options['conditions']))
return static::findByPk($args, $options);
$options['mappedNames'] = static::$aliasAttribute;
$list = static::table()->find($options);
return $single ? (!empty($list) ? $list[0] : null) : $list;
}
|
php
|
{
"resource": ""
}
|
q240553
|
Model.findByPk
|
train
|
public static function findByPk($values, $options)
{
$options['conditions'] = static::pkConditions($values);
$list = static::table()->find($options);
$results = count($list);
if ($results != ($expected = count($values)))
{
$class = get_called_class();
if ($expected == 1)
{
if (!is_array($values))
$values = array($values);
throw new RecordNotFound("Couldn't find $class with ID=" . join(',',$values));
}
$values = join(',',$values);
throw new RecordNotFound("Couldn't find all $class with IDs ($values) (found $results, but was looking for $expected)");
}
return $expected == 1 ? $list[0] : $list;
}
|
php
|
{
"resource": ""
}
|
q240554
|
Model.isOptionsHash
|
train
|
public static function isOptionsHash($array, $throw = true)
{
if (Arry::isHash($array))
{
$keys = array_keys($array);
$diff = array_diff($keys,self::$validOptions);
if (!empty($diff) && $throw) {
throw new ActiveRecordException("Unknown key(s): " . join(', ',$diff));
}
$intersect = array_intersect($keys,self::$validOptions);
if (!empty($intersect)) {
return true;
}
}
return false;
}
|
php
|
{
"resource": ""
}
|
q240555
|
Model.invokeCallback
|
train
|
private function invokeCallback($method_name, $must_exist=true)
{
return static::table()->callback->invoke($this,$method_name,$must_exist);
}
|
php
|
{
"resource": ""
}
|
q240556
|
Model.transaction
|
train
|
public static function transaction($closure)
{
$connection = static::connection();
try
{
$connection->transaction();
if ($closure() === false)
{
$connection->rollback();
return false;
}
else
$connection->commit();
}
catch (\Exception $e)
{
$connection->rollback();
throw $e;
}
return true;
}
|
php
|
{
"resource": ""
}
|
q240557
|
FlashData.isFromRoute
|
train
|
public function isFromRoute($routeName)
{
$session = $this->getSession();
/** @noinspection PhpUndefinedFieldInspection */
if ($session->data === null || !is_array($session->source)) {
return null;
}
/** @noinspection PhpUndefinedFieldInspection */
return $session->source['routeName'] === $routeName;
}
|
php
|
{
"resource": ""
}
|
q240558
|
FlashData.removeData
|
train
|
public function removeData()
{
$session = $this->getSession();
/** @noinspection PhpUndefinedFieldInspection */
if ($session->data !== null) {
unset($session->data);
return true;
}
return false;
}
|
php
|
{
"resource": ""
}
|
q240559
|
DBALGenerator.generate
|
train
|
public function generate(Module $module, $modelName, array $arrayValues)
{
$modelClass = $module->getNamespace() . '\\Model\\' . $modelName;
$modelPath = $module->getPath() . '/Model/' . str_replace('\\', '/', $modelName) . '.php';
$modelCode = $this->generateCode($module, $modelName, $arrayValues);
if (file_exists($modelPath)) {
throw new \RuntimeException(sprintf('Model "%s" already exists.', $modelClass));
}
$this->explorer->mkdir(dirname($modelPath));
file_put_contents($modelPath, $modelCode);
}
|
php
|
{
"resource": ""
}
|
q240560
|
DBALGenerator.generateCode
|
train
|
protected function generateCode(Module $module, $modelName, $arrayValues)
{
$replaces = array(
'<namespace>' => 'namespace ' . $module->getNamespace() . '\\Model;',
'<modelAnnotation>' => $this->generateDocBlock($modelName),
'<modelClassName>' => $modelName,
'<construct>' => self::$constructorMethodTemplate,
'<modelBody>' => $this->generateBody($modelName, $arrayValues),
'<spaces>' => " ",
'<table>' => strtolower($modelName)
);
$classTemplate = str_replace(array_keys($replaces), array_values($replaces), self::$classTemplate);
return $classTemplate;
}
|
php
|
{
"resource": ""
}
|
q240561
|
Helper.fileNameStrategy
|
train
|
public function fileNameStrategy($database, $name)
{
$name = join('_', array_map('lcfirst', preg_split('/(?=[A-Z])/', $name)));
return $database . DS . $this->generateVersion() . $name . '.php';
}
|
php
|
{
"resource": ""
}
|
q240562
|
Token.style
|
train
|
public function style(): Style
{
$type = StyleType::get($this->style);
return StyleFactory::factory($type)
->lineWidth($this->lineWidth);
}
|
php
|
{
"resource": ""
}
|
q240563
|
Token.value
|
train
|
public function value(): ?string
{
if (is_empty($this->key)) {
return $this->original;
}
$value = $this->replacements->get($this->key, null);
return $this->convertToString($value);
}
|
php
|
{
"resource": ""
}
|
q240564
|
Token.width
|
train
|
public function width(): int
{
$lines = explode("\n", $this->value());
$width = [];
foreach ($lines as $line) {
$raw = strip_tags($line);
$width[] = strlen(trim($raw));
}
return max($width);
}
|
php
|
{
"resource": ""
}
|
q240565
|
Content.setUserId
|
train
|
public function setUserId( $userId )
{
$this->_user = null;
$this->userId = ( (int) $userId ) ?: null;
return $this;
}
|
php
|
{
"resource": ""
}
|
q240566
|
Content.getUserMapper
|
train
|
protected function getUserMapper()
{
if ( null === $this->_userMapper )
{
$mapper = $this->getMapper();
$this->_userMapper = $this->getServiceLocator()
->get( 'Di' )
->get( 'Grid\User\Model\User\Mapper', array(
'dbAdapter' => $mapper->getDbAdapter(),
'dbSchema' => $mapper->getDbSchema(),
) );
}
return $this->_userMapper;
}
|
php
|
{
"resource": ""
}
|
q240567
|
Content.setPublishedFrom
|
train
|
public function setPublishedFrom( $date, $format = null )
{
$this->publishedFrom = empty( $date ) ? null : $this->inputDate( $date, $format );
return $this;
}
|
php
|
{
"resource": ""
}
|
q240568
|
Content.setPublishedTo
|
train
|
public function setPublishedTo( $date, $format = null )
{
$this->publishedTo = empty( $date ) ? null : $this->inputDate( $date, $format );
return $this;
}
|
php
|
{
"resource": ""
}
|
q240569
|
Content.isPublished
|
train
|
public function isPublished( $now = null )
{
if ( ! $this->published )
{
return false;
}
if ( empty( $now ) )
{
$now = new DateTime();
}
else
{
$now = $this->inputDate( $now );
}
if ( ! empty( $this->publishedTo ) &&
! $this->publishedTo->diff( $now )->invert )
{
return false;
}
if ( ! empty( $this->publishedFrom ) &&
$this->publishedFrom->diff( $now )->invert )
{
return false;
}
return true;
}
|
php
|
{
"resource": ""
}
|
q240570
|
Content.setAccessUsers
|
train
|
public function setAccessUsers( $users )
{
$this->accessUsers = array_unique(
is_array( $users ) ? $users : preg_split( '/[,\s]+/', $users )
);
return $this;
}
|
php
|
{
"resource": ""
}
|
q240571
|
Content.setAccessGroups
|
train
|
public function setAccessGroups( $groups )
{
$this->accessGroups = array_unique(
is_array( $groups ) ? $groups : preg_split( '/[,\s]+/', $groups )
);
return $this;
}
|
php
|
{
"resource": ""
}
|
q240572
|
Content.setEditUsers
|
train
|
public function setEditUsers( $users )
{
$this->editUsers = array_unique(
is_array( $users ) ? $users : preg_split( '/[,\s]+/', $users )
);
return $this;
}
|
php
|
{
"resource": ""
}
|
q240573
|
Content.setEditGroups
|
train
|
public function setEditGroups( $groups )
{
$this->editGroups = array_unique(
is_array( $groups ) ? $groups : preg_split( '/[,\s]+/', $groups )
);
return $this;
}
|
php
|
{
"resource": ""
}
|
q240574
|
Content.getSeoUri
|
train
|
public function getSeoUri()
{
if ( ! empty( $this->_seoUri ) )
{
return $this->_seoUri;
}
if ( empty( $this->id ) )
{
return '';
}
if ( empty( $this->_seoUri ) )
{
$this->_seoUriStructure = $this->getUriStructure( array(
$this->getMapper()
->getLocale()
) );
if ( ! empty( $this->_seoUriStructure ) )
{
$this->_seoUri = $this->_seoUriStructure->uri;
}
}
return $this->_seoUri;
}
|
php
|
{
"resource": ""
}
|
q240575
|
Container.getUri
|
train
|
public function getUri()
{
if ( $this->hasChildren() )
{
foreach( $this->getChildren() as $child )
{
$uri = $child->getUri();
if ( '#' != $uri[0] )
{
return $uri;
}
}
}
else
{
return '#';
}
}
|
php
|
{
"resource": ""
}
|
q240576
|
OperationState.execute
|
train
|
public function execute()
{
$returnValues = array();
while ($execute = array_shift($this->executeParameters)) {
$returnValues[] = $this->run($execute);
}
return $returnValues;
}
|
php
|
{
"resource": ""
}
|
q240577
|
OperationState.undo
|
train
|
public function undo()
{
$returnValues = array();
while ($undo = array_shift($this->undoParameters)) {
$returnValues[] = $this->run($undo);
}
return $returnValues;
}
|
php
|
{
"resource": ""
}
|
q240578
|
OperationState.run
|
train
|
protected function run($call)
{
if (!isset($call['callable'])) {
throw new OperationStateException("\$call['callable'] was not set");
}
if (!isset($call['arguments'])) {
try {
is_null($call['arguments']);
} catch (\Exception $e) {
throw new OperationStateException("\$call['arguments'] was not set");
}
}
if (is_callable($call['callable'])) {
if ($call['arguments'] == self::NO_ARGUMENT) {
return call_user_func($call['callable']);
} else {
return call_user_func_array($call['callable'], $call['arguments']);
}
} else {
throw new OperationStateException("\$call and \$arguments passed did not pass is_callable() check");
}
}
|
php
|
{
"resource": ""
}
|
q240579
|
OperationState.getKey
|
train
|
public function getKey()
{
if (!isset($this->key)) {
$this->key = md5(microtime().rand());
}
return $this->key;
}
|
php
|
{
"resource": ""
}
|
q240580
|
ComposerLoader.getFile
|
train
|
public function getFile(Repo $repo)
{
$file = tempnam(sys_get_temp_dir(), 'composer');
$content = file_get_contents($this->helper->getRawFileUrl($repo->getSlug(), 'master', 'composer.json'));
file_put_contents($file, $content);
return $file;
}
|
php
|
{
"resource": ""
}
|
q240581
|
CheckoutManager.calculateTotalAmountForDeliveryExpenses
|
train
|
private function calculateTotalAmountForDeliveryExpenses(Transaction $transaction)
{
$total = 0;
foreach ($transaction->getItems() as $productPurchase) {
if($productPurchase->getProduct() instanceof Product){
if(!$productPurchase->getProduct()->isFreeTransport()){
$addPercent = 0;
if($this->deliveryExpensesPercentage > 0)
$addPercent = $productPurchase->getTotalPrice() * $this->deliveryExpensesPercentage;
$total += $productPurchase->getTotalPrice() + $addPercent;
}
}else{
$total += $productPurchase->getTotalPrice();
}
}
return $total;
}
|
php
|
{
"resource": ""
}
|
q240582
|
CheckoutManager.getCurrentTransaction
|
train
|
public function getCurrentTransaction()
{
if (false === $this->session->has('transaction-id')) {
throw new AccessDeniedHttpException();
}
return $this->manager->getRepository('EcommerceBundle:Transaction')->find($this->session->get('transaction-id'));
}
|
php
|
{
"resource": ""
}
|
q240583
|
CheckoutManager.updateTransaction
|
train
|
public function updateTransaction()
{
$cart = $this->cartProvider->getCart();
if (0 === $cart->countItems() || $this->isTransactionUpdated($cart)) {
return;
}
/** @var TransactionRepository $transactionRepository */
$transactionRepository = $this->manager->getRepository('EcommerceBundle:Transaction');
if ($this->session->has('transaction-id')) {
/** @var Transaction $transaction */
$transaction = $transactionRepository->find($this->session->get('transaction-id'));
$transactionRepository->removeItems($transaction);
} else {
$transactionKey = $transactionRepository->getNextNumber();
// create a new transaction
$transaction = new Transaction();
$transaction->setTransactionKey($transactionKey);
$transaction->setStatus(Transaction::STATUS_CREATED);
$transaction->setActor($this->securityContext->getToken()->getUser());
$cartItem = $cart->getItems()->first();
$product = $cartItem->getProduct();
}
$orderTotalPrice = 0;
foreach ($cart->getItems() as $cartItem) {
/** @var Product $product */
$product = $cartItem->getProduct();
$productPurchase = new ProductPurchase();
$productPurchase->setProduct($product);
$productPurchase->setBasePrice($cartItem->getUnitPrice());
$productPurchase->setQuantity($cartItem->getQuantity());
$productPurchase->setDiscount($product->getDiscount());
$productPurchase->setTotalPrice($cartItem->getTotal());
$productPurchase->setTransaction($transaction);
$productPurchase->setReturned(false);
//free transport
if($cartItem->isFreeTransport()){
$productPurchase->setDeliveryExpenses(0);
}else{
$productPurchase->setDeliveryExpenses($cartItem->getShippingCost());
}
$orderTotalPrice += $cartItem->getProduct()->getPrice() * $cartItem->getQuantity();
$this->manager->persist($productPurchase);
}
$transaction->setTotalPrice($orderTotalPrice);
$this->manager->persist($transaction);
$this->manager->flush();
$this->session->set('transaction-id', $transaction->getId());
$this->session->save();
}
|
php
|
{
"resource": ""
}
|
q240584
|
CheckoutManager.isTransactionUpdated
|
train
|
private function isTransactionUpdated(Cart $cart)
{
if (false === $this->session->has('transaction-id')) {
return false;
}
/** @var TransactionRepository $transactionRepository */
$transactionRepository = $this->manager->getRepository('EcommerceBundle:Transaction');
/** @var Order $order */
$transaction = $transactionRepository->find($this->session->get('transaction-id'));
/** @var ArrayCollection $cartItems */
$cartItems = $cart->getItems();
/** @var ArrayCollection $orderItems */
$productPurchases = $transaction->getItems();
if ($cartItems->count() !== $productPurchases->count()) {
return false;
}
for ($i=0; $i<$cartItems->count(); $i++) {
/** @var CartItem $cartItem */
$cartItem = $cartItems[$i];
/** @var OrderItem $orderItem */
$productPurchase = $productPurchases[$i];
if ($cartItem->getProduct()->getId() !== $productPurchase->getProduct()->getId() ||
$cartItem->getQuantity() !== $productPurchase->getQuantity()) {
return false;
}
}
return true;
}
|
php
|
{
"resource": ""
}
|
q240585
|
CheckoutManager.getDelivery
|
train
|
public function getDelivery(Transaction $transaction = null)
{
if ($this->session->has('delivery-id')) {
$delivery = $this->manager->getRepository('EcommerceBundle:Delivery')->find($this->session->get('delivery-id'));
return $delivery;
}
$delivery = new Delivery();
/** @var Address $billingAddress */
$billingAddress = $this->manager->getRepository('EcommerceBundle:Address')->findOneBy(array(
'actor' => $this->securityContext->getToken()->getUser(),
'forBilling' => true
));
if (false === is_null($billingAddress)) {
$delivery->setFullName($this->securityContext->getToken()->getUser()->getFullName());
$delivery->setContactPerson($billingAddress->getContactPerson());
$delivery->setDni($billingAddress->getDni());
$delivery->setAddressInfo($billingAddress->getAddressInfo());
$delivery->setPhone($billingAddress->getPhone());
$delivery->setPhone2($billingAddress->getPhone2());
$delivery->setPreferredSchedule($billingAddress->getPreferredSchedule());
}
$country = $this->manager->getRepository('CoreBundle:Country')->find('es');
$delivery->setCountry($country);
if (false === is_null($transaction)) {
$delivery->setTransaction($transaction);
}
return $delivery;
}
|
php
|
{
"resource": ""
}
|
q240586
|
CheckoutManager.saveDelivery
|
train
|
public function saveDelivery(Delivery $delivery, array $params, $cart)
{
/** @var Carrier $carrier */
// $carrier = $this->manager->getRepository('ModelBundle:Carrier')->find($delivery->getCarrier());
if ('same' === $params['selectDelivery']) {
$delivery->setDeliveryContactPerson($delivery->getContactPerson());
$delivery->setDeliveryDni($delivery->getDni());
$delivery->setDeliveryAddressInfo($delivery->getAddressInfo());
$delivery->setDeliveryPhone($delivery->getPhone());
$delivery->setDeliveryPhone2($delivery->getPhone2());
$delivery->setDeliveryPreferredSchedule($delivery->getPreferredSchedule());
} else if ('existing' === $params['selectDelivery']) {
/** @var Address $address */
$address = $this->manager->getRepository('EcommerceBundle:Address')->find($params['existingDeliveryAddress']);
$delivery->setDeliveryContactPerson($address->getContactPerson());
$delivery->setDeliveryDni($address->getDni());
$delivery->setDeliveryAddressInfo($address->getAddressInfo());
$delivery->setDeliveryPhone($address->getPhone());
$delivery->setDeliveryPhone2($address->getPhone2());
$delivery->setDeliveryPreferredSchedule($address->getPreferredSchedule());
} else if ('new' === $params['selectDelivery']) {
$this->addUserDeliveryAddress($delivery);
}
$deliveryCountry = $this->manager->getRepository('CoreBundle:Country')->find('es');
$delivery->setDeliveryCountry($deliveryCountry);
$total = 0;
$productPurchases = $this->manager->getRepository('EcommerceBundle:ProductPurchase')->findByTransaction($delivery->getTransaction());
foreach ($productPurchases as $item) {
if($item->getDeliveryExpenses()>0)
$total = $total + $item->getDeliveryExpenses();
}
$delivery->setExpenses($total);
if($total>0) $delivery->setExpensesType('store_pickup');
else $delivery->setExpensesType('send');
$this->saveUserBillingAddress($delivery);
$this->manager->persist($delivery);
$this->manager->flush();
$this->session->set('delivery-id', $delivery->getId());
$this->session->set('select-delivery', $params['selectDelivery']);
if ('existing' === $params['selectDelivery']) {
$this->session->set('existing-delivery-address', intval($params['existingDeliveryAddress']));
} else {
$this->session->remove('existing-delivery-address');
}
$this->session->save();
}
|
php
|
{
"resource": ""
}
|
q240587
|
CheckoutManager.saveUserBillingAddress
|
train
|
private function saveUserBillingAddress($delivery)
{
// get billing address
/** @var Address $billingAddress */
$billingAddress = $this->manager->getRepository('EcommerceBundle:Address')->findOneBy(array(
'actor' => $this->securityContext->getToken()->getUser(),
'forBilling' => true
));
// build new billing address when it does not exist
if (is_null($billingAddress)) {
$billingAddress = new Address();
$billingAddress->setForBilling(true);
$billingAddress->setActor($this->securityContext->getToken()->getUser());
}
$billingAddress->setContactPerson($delivery->getContactPerson());
$billingAddress->setDni($delivery->getDni());
$billingAddress->setAddressInfo($delivery->getAddressInfo());
$billingAddress->setPhone($delivery->getPhone());
$billingAddress->setPhone2($delivery->getPhone2());
$billingAddress->setPreferredSchedule($delivery->getPreferredSchedule());
$country = $this->manager->getRepository('CoreBundle:Country')->find('es');
$billingAddress->setCountry($country);
$this->manager->persist($billingAddress);
$this->manager->flush();
}
|
php
|
{
"resource": ""
}
|
q240588
|
CheckoutManager.cleanSession
|
train
|
public function cleanSession()
{
// remove checkout session parameters
$this->session->remove('select-delivery');
$this->session->remove('delivery-id');
$this->session->remove('existing-delivery-address');
$this->session->remove('transaction-id');
// abandon cart
$this->cartProvider->abandonCart();
}
|
php
|
{
"resource": ""
}
|
q240589
|
CheckoutManager.getBillingAddress
|
train
|
public function getBillingAddress($actor=null)
{
if(is_null($actor)){
$actor = $this->securityContext->getToken()->getUser();
if (!$actor || !is_object($actor)) {
throw new \LogicException(
'The getBillingAddress cannot be used without an authenticated user!'
);
}
}
/** @var Address $address */
$address = $this->manager->getRepository('EcommerceBundle:Address')
->findOneBy(array(
'actor' => $actor,
'forBilling' => true
));
// if it does not exist, create a new one
if (is_null($address)) {
$address = new Address();
$address->setForBilling(true);
$country = $this->manager->getRepository('CoreBundle:Country')->find('es');
$address->setCountry($country);
$address->setActor($actor);
}
return $address;
}
|
php
|
{
"resource": ""
}
|
q240590
|
CheckoutManager.isCurrentUserOwner
|
train
|
public function isCurrentUserOwner(Transaction $transaction)
{
if($this->securityContext->getToken()->getUser()->isGranted('ROLE_ADMIN')){
return true;
}
$currentUserId = $this->securityContext->getToken()->getUser()->getId();
//actor owner
if($transaction->getActor() instanceof Actor){
if($currentUserId == $transaction->getActor()->getId()){
return true;
}elseif($currentUserId == $transaction->getItems()->first()->getProduct()->getActor()->getId()){
return true;
}
}
return false;
}
|
php
|
{
"resource": ""
}
|
q240591
|
CheckoutManager.processBankTransfer
|
train
|
public function processBankTransfer(Transaction $transaction)
{
$transaction->setStatus(Transaction::STATUS_PENDING_TRANSFER);
$pm = $this->manager->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('bank-transfer-test');
$transaction->setPaymentMethod($pm);
$this->manager->persist($transaction);
$this->manager->flush();
return true;
}
|
php
|
{
"resource": ""
}
|
q240592
|
CheckoutManager.processRedsysTransaction
|
train
|
public function processRedsysTransaction($ds_response, Transaction $transaction)
{
if ($ds_response > 99) {
return false;
}
$transaction->setStatus(Transaction::STATUS_PAID);
$pm = $this->manager->getRepository('EcommerceBundle:PaymentMethod')->findOneBySlug('redsys');
$transaction->setPaymentMethod($pm);
$this->manager->persist($transaction);
$this->manager->flush();
return true;
}
|
php
|
{
"resource": ""
}
|
q240593
|
ResponseCookieCollection.get
|
train
|
public function get(string $name): ?ResponseCookieInterface
{
if (!isset($this->responseCookies[$name])) {
return null;
}
return $this->responseCookies[$name];
}
|
php
|
{
"resource": ""
}
|
q240594
|
ResponseCookieCollection.set
|
train
|
public function set(string $name, ResponseCookieInterface $responseCookie): void
{
$this->responseCookies[$name] = $responseCookie;
}
|
php
|
{
"resource": ""
}
|
q240595
|
LocalAccess.isLocalIp
|
train
|
private function isLocalIp ()
{
$ip = $this->serverData["REMOTE_ADDR"];
if (!is_string($ip))
{
return false;
}
if (in_array($ip, ['127.0.0.1', 'fe80::1', '::1'], true))
{
return true;
}
// allowed (= local) IPs include
// 10.0.0.0 – 10.255.255.255
// 172.16.0.0 – 172.31.255.255
// 192.168.0.0 – 192.168.255.255
return 1 === preg_match("/^(10\\.|192\\.168\\.|172\\.(1[6-9]|2[0-9]|3[0-1])\\.)/", $ip);
}
|
php
|
{
"resource": ""
}
|
q240596
|
SerpPageSerializer.serialize
|
train
|
public function serialize($serializablePage, $format)
{
// check if supported serialization format
if (!SerpPageSerializerHelper::validFormat($format, self::$supportedFormatSerialization))
throw new \Franzip\SerpPageSerializer\Exceptions\UnsupportedSerializationFormatException('Invalid SerpPageSerializer $format: supported serialization formats are JSON, XML and YAML.');
// typecheck the object to serialize
if (!SerpPageSerializerHelper::serializablePage($serializablePage))
throw new \Franzip\SerpPageSerializer\Exceptions\NonSerializableObjectException('Invalid SerpPageSerializer $serializablePage: you must supply a SerializableSerpPage object to serialize.');
$format = strtolower($format);
$entries = $this->createEntries($serializablePage, $format);
$serializablePage = $this->prepareForSerialization($serializablePage, $format, $entries);
$serializedPage = $this->getSerializer()->serialize($serializablePage, $format);
// beautify output if JSON
$content = ($format == 'json') ? SerpPageSerializerHelper::prettyJSON($serializedPage) : $serializedPage;
return new SerializedSerpPage($content);
}
|
php
|
{
"resource": ""
}
|
q240597
|
SerpPageSerializer.deserialize
|
train
|
public function deserialize($serializedPage, $format)
{
// check if supported deserialization format
if (!SerpPageSerializerHelper::validFormat($format, self::$supportedFormatDeserialization))
throw new \Franzip\SerpPageSerializer\Exceptions\UnsupportedDeserializationFormatException('Invalid SerpPageSerializer $format: supported deserialization formats are JSON and XML.');
// TODO: typecheck object
if (!SerpPageSerializerHelper::deserializablePage($serializedPage))
throw new \Franzip\SerpPageSerializer\Exceptions\RuntimeException('Invalid SerpPageSerializer $serializedPage: you must supply a SerializedSerpPage object to deserialize.');
$format = strtolower($format);
$targetClass = self::SERIALIZABLE_OBJECT_PREFIX . strtoupper($format);
return $this->getSerializer()->deserialize($serializedPage->getContent(), $targetClass, $format);
}
|
php
|
{
"resource": ""
}
|
q240598
|
SerpPageSerializer.prepareForSerialization
|
train
|
private function prepareForSerialization($serializablePage, $format, $entries)
{
$engine = $serializablePage->getEngine();
$keyword = $serializablePage->getKeyword();
$pageUrl = $serializablePage->getPageUrl();
$pageNumber = $serializablePage->getPageNumber();
$age = $serializablePage->getAge();
return self::getFormatClassName($format, array($engine, $pageNumber, $pageUrl,
$keyword, $age, $entries));
}
|
php
|
{
"resource": ""
}
|
q240599
|
SerpPageSerializer.createEntries
|
train
|
private function createEntries($serializablePage, $format)
{
$result = array();
$entries = $serializablePage->getEntries();
for ($i = 0; $i < count($entries); $i++) {
$args = array(($i + 1), $entries[$i]['url'], $entries[$i]['title'], $entries[$i]['snippet']);
array_push($result, self::getFormatClassName($format, $args, true));
}
return $result;
}
|
php
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.