repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
symbiote/silverstripe-multisites | src/Admin/MultisitesModelAdminExtension.php | MultisitesModelAdminExtension.getListDataClass | private function getListDataClass() {
/**
* Silverstripe-recipe 4.3.0 introduces changes that broke the
* previous approach to retrieving the model class.
*
* This is/will be fixed in silverstripe-recipe 4.3.1
*
* We've taken this approach so that Multisites can work with
* SS 4.3.0 so long as you don't use the MultisitesAware extension.
*/
if ($this->listDataClass === null) {
// only true if silverstripe-recipe > 4.3.0
if ($this->owner->hasMethod('getModelClass')) {
$this->listDataClass = $this->owner->getModelClass();
}
// else false to bypass the MultisitesAware extension
else {
$this->listDataClass = false;
}
}
return $this->listDataClass;
} | php | private function getListDataClass() {
/**
* Silverstripe-recipe 4.3.0 introduces changes that broke the
* previous approach to retrieving the model class.
*
* This is/will be fixed in silverstripe-recipe 4.3.1
*
* We've taken this approach so that Multisites can work with
* SS 4.3.0 so long as you don't use the MultisitesAware extension.
*/
if ($this->listDataClass === null) {
// only true if silverstripe-recipe > 4.3.0
if ($this->owner->hasMethod('getModelClass')) {
$this->listDataClass = $this->owner->getModelClass();
}
// else false to bypass the MultisitesAware extension
else {
$this->listDataClass = false;
}
}
return $this->listDataClass;
} | [
"private",
"function",
"getListDataClass",
"(",
")",
"{",
"/**\n * Silverstripe-recipe 4.3.0 introduces changes that broke the\n * previous approach to retrieving the model class.\n *\n * This is/will be fixed in silverstripe-recipe 4.3.1\n *\n * We've tak... | Get and cache an instance of the data class currently being listed
@return DataObject | [
"Get",
"and",
"cache",
"an",
"instance",
"of",
"the",
"data",
"class",
"currently",
"being",
"listed"
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Admin/MultisitesModelAdminExtension.php#L180-L201 | train |
symbiote/silverstripe-multisites | src/Admin/MultisitesModelAdminExtension.php | MultisitesModelAdminExtension.modelIsMultiSitesAware | private function modelIsMultiSitesAware() {
$model = $this->getListDataClass();
// always false if using silverstripe-recipe <= 4.3.0
if ($model) {
$isAware = $model::has_extension(MultisitesAware::class);
$isSiteTree = in_array(SiteTree::class, ClassInfo::ancestry($model));
return $isAware || $isSiteTree;
}
return false;
} | php | private function modelIsMultiSitesAware() {
$model = $this->getListDataClass();
// always false if using silverstripe-recipe <= 4.3.0
if ($model) {
$isAware = $model::has_extension(MultisitesAware::class);
$isSiteTree = in_array(SiteTree::class, ClassInfo::ancestry($model));
return $isAware || $isSiteTree;
}
return false;
} | [
"private",
"function",
"modelIsMultiSitesAware",
"(",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"getListDataClass",
"(",
")",
";",
"// always false if using silverstripe-recipe <= 4.3.0",
"if",
"(",
"$",
"model",
")",
"{",
"$",
"isAware",
"=",
"$",
"model"... | Determines whether the current model being managed is MultiSitesAware
@return boolean | [
"Determines",
"whether",
"the",
"current",
"model",
"being",
"managed",
"is",
"MultiSitesAware"
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Admin/MultisitesModelAdminExtension.php#L208-L217 | train |
michelsalib/BCCCronManagerBundle | Controller/DefaultController.php | DefaultController.indexAction | public function indexAction()
{
$cm = new CronManager();
$this->addFlashFromCronManager($cm);
$form = $this->createCronForm(new Cron());
return $this->render('@BCCCronManager/Default/index.html.twig', array(
'crons' => $cm->get(),
'raw' => $cm->getRaw(),
'form' => $form->createView(),
));
} | php | public function indexAction()
{
$cm = new CronManager();
$this->addFlashFromCronManager($cm);
$form = $this->createCronForm(new Cron());
return $this->render('@BCCCronManager/Default/index.html.twig', array(
'crons' => $cm->get(),
'raw' => $cm->getRaw(),
'form' => $form->createView(),
));
} | [
"public",
"function",
"indexAction",
"(",
")",
"{",
"$",
"cm",
"=",
"new",
"CronManager",
"(",
")",
";",
"$",
"this",
"->",
"addFlashFromCronManager",
"(",
"$",
"cm",
")",
";",
"$",
"form",
"=",
"$",
"this",
"->",
"createCronForm",
"(",
"new",
"Cron",
... | Displays the current crons and a form to add a new one.
@return Response | [
"Displays",
"the",
"current",
"crons",
"and",
"a",
"form",
"to",
"add",
"a",
"new",
"one",
"."
] | f0c9062f3b2bc79b48b38c7374712f4bc23fb536 | https://github.com/michelsalib/BCCCronManagerBundle/blob/f0c9062f3b2bc79b48b38c7374712f4bc23fb536/Controller/DefaultController.php#L23-L35 | train |
michelsalib/BCCCronManagerBundle | Controller/DefaultController.php | DefaultController.addAction | public function addAction(Request $request)
{
$cm = new CronManager();
$cron = new Cron();
$this->addFlashFromCronManager($cm);
$form = $this->createCronForm($cron);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$cm->add($cron);
$this->addFlashFromCronManager($cm);
return $this->redirect($this->generateUrl('BCCCronManagerBundle_index'));
}
return $this->render('@BCCCronManager:Default:index.html.twig', array(
'crons' => $cm->get(),
'raw' => $cm->getRaw(),
'form' => $form->createView(),
));
} | php | public function addAction(Request $request)
{
$cm = new CronManager();
$cron = new Cron();
$this->addFlashFromCronManager($cm);
$form = $this->createCronForm($cron);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$cm->add($cron);
$this->addFlashFromCronManager($cm);
return $this->redirect($this->generateUrl('BCCCronManagerBundle_index'));
}
return $this->render('@BCCCronManager:Default:index.html.twig', array(
'crons' => $cm->get(),
'raw' => $cm->getRaw(),
'form' => $form->createView(),
));
} | [
"public",
"function",
"addAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"cm",
"=",
"new",
"CronManager",
"(",
")",
";",
"$",
"cron",
"=",
"new",
"Cron",
"(",
")",
";",
"$",
"this",
"->",
"addFlashFromCronManager",
"(",
"$",
"cm",
")",
";",
... | Add a cron to the cron table
@param Request $request
@return Response | [
"Add",
"a",
"cron",
"to",
"the",
"cron",
"table"
] | f0c9062f3b2bc79b48b38c7374712f4bc23fb536 | https://github.com/michelsalib/BCCCronManagerBundle/blob/f0c9062f3b2bc79b48b38c7374712f4bc23fb536/Controller/DefaultController.php#L44-L64 | train |
michelsalib/BCCCronManagerBundle | Controller/DefaultController.php | DefaultController.editAction | public function editAction($id, Request $request)
{
$cm = new CronManager();
$crons = $cm->get();
$this->addFlashFromCronManager($cm);
$form = $this->createCronForm($crons[$id]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$cm->write();
$this->addFlashFromCronManager($cm);
return $this->redirect($this->generateUrl('BCCCronManagerBundle_index'));
}
return $this->render('@BCCCronManager:Default:edit.html.twig', array(
'form' => $form->createView(),
));
} | php | public function editAction($id, Request $request)
{
$cm = new CronManager();
$crons = $cm->get();
$this->addFlashFromCronManager($cm);
$form = $this->createCronForm($crons[$id]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$cm->write();
$this->addFlashFromCronManager($cm);
return $this->redirect($this->generateUrl('BCCCronManagerBundle_index'));
}
return $this->render('@BCCCronManager:Default:edit.html.twig', array(
'form' => $form->createView(),
));
} | [
"public",
"function",
"editAction",
"(",
"$",
"id",
",",
"Request",
"$",
"request",
")",
"{",
"$",
"cm",
"=",
"new",
"CronManager",
"(",
")",
";",
"$",
"crons",
"=",
"$",
"cm",
"->",
"get",
"(",
")",
";",
"$",
"this",
"->",
"addFlashFromCronManager",... | Edit a cron
@param $id int The line of the cron in the cron table
@param Request $request
@return RedirectResponse|Response | [
"Edit",
"a",
"cron"
] | f0c9062f3b2bc79b48b38c7374712f4bc23fb536 | https://github.com/michelsalib/BCCCronManagerBundle/blob/f0c9062f3b2bc79b48b38c7374712f4bc23fb536/Controller/DefaultController.php#L74-L93 | train |
michelsalib/BCCCronManagerBundle | Controller/DefaultController.php | DefaultController.wakeupAction | public function wakeupAction($id)
{
$cm = new CronManager();
$crons = $cm->get();
$this->addFlashFromCronManager($cm);
$crons[$id]->setSuspended(false);
$cm->write();
$this->addFlashFromCronManager($cm);
return $this->redirect($this->generateUrl('BCCCronManagerBundle_index'));
} | php | public function wakeupAction($id)
{
$cm = new CronManager();
$crons = $cm->get();
$this->addFlashFromCronManager($cm);
$crons[$id]->setSuspended(false);
$cm->write();
$this->addFlashFromCronManager($cm);
return $this->redirect($this->generateUrl('BCCCronManagerBundle_index'));
} | [
"public",
"function",
"wakeupAction",
"(",
"$",
"id",
")",
"{",
"$",
"cm",
"=",
"new",
"CronManager",
"(",
")",
";",
"$",
"crons",
"=",
"$",
"cm",
"->",
"get",
"(",
")",
";",
"$",
"this",
"->",
"addFlashFromCronManager",
"(",
"$",
"cm",
")",
";",
... | Wake up a cron from the cron table
@param $id int The line of the cron in the cron table
@return RedirectResponse | [
"Wake",
"up",
"a",
"cron",
"from",
"the",
"cron",
"table"
] | f0c9062f3b2bc79b48b38c7374712f4bc23fb536 | https://github.com/michelsalib/BCCCronManagerBundle/blob/f0c9062f3b2bc79b48b38c7374712f4bc23fb536/Controller/DefaultController.php#L101-L111 | train |
michelsalib/BCCCronManagerBundle | Controller/DefaultController.php | DefaultController.suspendAction | public function suspendAction($id)
{
$cm = new CronManager();
$crons = $cm->get();
$this->addFlashFromCronManager($cm);
$crons[$id]->setSuspended(true);
$cm->write();
$this->addFlashFromCronManager($cm);
return $this->redirect($this->generateUrl('BCCCronManagerBundle_index'));
} | php | public function suspendAction($id)
{
$cm = new CronManager();
$crons = $cm->get();
$this->addFlashFromCronManager($cm);
$crons[$id]->setSuspended(true);
$cm->write();
$this->addFlashFromCronManager($cm);
return $this->redirect($this->generateUrl('BCCCronManagerBundle_index'));
} | [
"public",
"function",
"suspendAction",
"(",
"$",
"id",
")",
"{",
"$",
"cm",
"=",
"new",
"CronManager",
"(",
")",
";",
"$",
"crons",
"=",
"$",
"cm",
"->",
"get",
"(",
")",
";",
"$",
"this",
"->",
"addFlashFromCronManager",
"(",
"$",
"cm",
")",
";",
... | Suspend a cron from the cron table
@param $id int The line of the cron in the cron table
@return RedirectResponse | [
"Suspend",
"a",
"cron",
"from",
"the",
"cron",
"table"
] | f0c9062f3b2bc79b48b38c7374712f4bc23fb536 | https://github.com/michelsalib/BCCCronManagerBundle/blob/f0c9062f3b2bc79b48b38c7374712f4bc23fb536/Controller/DefaultController.php#L119-L129 | train |
michelsalib/BCCCronManagerBundle | Controller/DefaultController.php | DefaultController.fileAction | public function fileAction($id, $type)
{
$cm = new CronManager();
$crons = $cm->get();
$cron = $crons[$id];
$data = array();
$data['file'] = ($type == 'log') ? $cron->getLogFile(): $cron->getErrorFile();
$data['content'] = \file_get_contents($data['file']);
$serializer = new Serializer(array(), array('json' => new JsonEncoder()));
return new Response($serializer->serialize($data, 'json'));
} | php | public function fileAction($id, $type)
{
$cm = new CronManager();
$crons = $cm->get();
$cron = $crons[$id];
$data = array();
$data['file'] = ($type == 'log') ? $cron->getLogFile(): $cron->getErrorFile();
$data['content'] = \file_get_contents($data['file']);
$serializer = new Serializer(array(), array('json' => new JsonEncoder()));
return new Response($serializer->serialize($data, 'json'));
} | [
"public",
"function",
"fileAction",
"(",
"$",
"id",
",",
"$",
"type",
")",
"{",
"$",
"cm",
"=",
"new",
"CronManager",
"(",
")",
";",
"$",
"crons",
"=",
"$",
"cm",
"->",
"get",
"(",
")",
";",
"$",
"cron",
"=",
"$",
"crons",
"[",
"$",
"id",
"]"... | Gets a log file
@param $id int The line of the cron in the cron table
@param $type sting The type of file, log or error
@return \Symfony\Component\HttpFoundation\Response | [
"Gets",
"a",
"log",
"file"
] | f0c9062f3b2bc79b48b38c7374712f4bc23fb536 | https://github.com/michelsalib/BCCCronManagerBundle/blob/f0c9062f3b2bc79b48b38c7374712f4bc23fb536/Controller/DefaultController.php#L156-L169 | train |
michelsalib/BCCCronManagerBundle | Controller/DefaultController.php | DefaultController.addFlashFromCronManager | protected function addFlashFromCronManager(CronManager $cm)
{
if ($cm->getOutput()) {
$this->addFlash('message', $cm->getOutput());
}
if ($cm->getError()) {
$this->addFlash('error', $cm->getError());
}
} | php | protected function addFlashFromCronManager(CronManager $cm)
{
if ($cm->getOutput()) {
$this->addFlash('message', $cm->getOutput());
}
if ($cm->getError()) {
$this->addFlash('error', $cm->getError());
}
} | [
"protected",
"function",
"addFlashFromCronManager",
"(",
"CronManager",
"$",
"cm",
")",
"{",
"if",
"(",
"$",
"cm",
"->",
"getOutput",
"(",
")",
")",
"{",
"$",
"this",
"->",
"addFlash",
"(",
"'message'",
",",
"$",
"cm",
"->",
"getOutput",
"(",
")",
")",... | Set flash from CronManager
@param CronManager $cm | [
"Set",
"flash",
"from",
"CronManager"
] | f0c9062f3b2bc79b48b38c7374712f4bc23fb536 | https://github.com/michelsalib/BCCCronManagerBundle/blob/f0c9062f3b2bc79b48b38c7374712f4bc23fb536/Controller/DefaultController.php#L187-L196 | train |
michelsalib/BCCCronManagerBundle | Manager/Cron.php | Cron.getExpression | public function getExpression()
{
return \sprintf('%s %s %s %s %s', $this->minute, $this->hour, $this->dayOfMonth, $this->month, $this->dayOfWeek);
} | php | public function getExpression()
{
return \sprintf('%s %s %s %s %s', $this->minute, $this->hour, $this->dayOfMonth, $this->month, $this->dayOfWeek);
} | [
"public",
"function",
"getExpression",
"(",
")",
"{",
"return",
"\\",
"sprintf",
"(",
"'%s %s %s %s %s'",
",",
"$",
"this",
"->",
"minute",
",",
"$",
"this",
"->",
"hour",
",",
"$",
"this",
"->",
"dayOfMonth",
",",
"$",
"this",
"->",
"month",
",",
"$",... | Concats time data to get the time expression
@return string | [
"Concats",
"time",
"data",
"to",
"get",
"the",
"time",
"expression"
] | f0c9062f3b2bc79b48b38c7374712f4bc23fb536 | https://github.com/michelsalib/BCCCronManagerBundle/blob/f0c9062f3b2bc79b48b38c7374712f4bc23fb536/Manager/Cron.php#L399-L402 | train |
michelsalib/BCCCronManagerBundle | Manager/Cron.php | Cron.setSuspended | public function setSuspended($isSuspended = true)
{
if ($this->isSuspended != $isSuspended) {
$this->isSuspended = $isSuspended;
}
return $this;
} | php | public function setSuspended($isSuspended = true)
{
if ($this->isSuspended != $isSuspended) {
$this->isSuspended = $isSuspended;
}
return $this;
} | [
"public",
"function",
"setSuspended",
"(",
"$",
"isSuspended",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isSuspended",
"!=",
"$",
"isSuspended",
")",
"{",
"$",
"this",
"->",
"isSuspended",
"=",
"$",
"isSuspended",
";",
"}",
"return",
"$",
"... | Sets the value of isSuspended
@param boolean $isSuspended status
@return Cron | [
"Sets",
"the",
"value",
"of",
"isSuspended"
] | f0c9062f3b2bc79b48b38c7374712f4bc23fb536 | https://github.com/michelsalib/BCCCronManagerBundle/blob/f0c9062f3b2bc79b48b38c7374712f4bc23fb536/Manager/Cron.php#L421-L427 | train |
symbiote/silverstripe-multisites | src/Job/MultisitesInitAssetsTask.php | MultisitesInitAssetsTask.run | public function run($request)
{
$currentSite = Multisites::inst()->getCurrentSite();
$folderName = $currentSite->Host ? $currentSite->Host : "site-$currentSite->ID";
$folder = Folder::find_or_make($folderName);
$files = File::get()->filter('ParentID', array(0))->exclude('ID', $folder->ID);
if (!$files->count()) {
return;
}
foreach ($files as $file) {
if (file_exists($file->getFullPath())) {
$file->ParentID = $folder->ID;
$file->write();
echo $file->Filename.' moved <br />';
}
}
} | php | public function run($request)
{
$currentSite = Multisites::inst()->getCurrentSite();
$folderName = $currentSite->Host ? $currentSite->Host : "site-$currentSite->ID";
$folder = Folder::find_or_make($folderName);
$files = File::get()->filter('ParentID', array(0))->exclude('ID', $folder->ID);
if (!$files->count()) {
return;
}
foreach ($files as $file) {
if (file_exists($file->getFullPath())) {
$file->ParentID = $folder->ID;
$file->write();
echo $file->Filename.' moved <br />';
}
}
} | [
"public",
"function",
"run",
"(",
"$",
"request",
")",
"{",
"$",
"currentSite",
"=",
"Multisites",
"::",
"inst",
"(",
")",
"->",
"getCurrentSite",
"(",
")",
";",
"$",
"folderName",
"=",
"$",
"currentSite",
"->",
"Host",
"?",
"$",
"currentSite",
"->",
"... | Implement this method in the task subclass to
execute via the TaskRunner | [
"Implement",
"this",
"method",
"in",
"the",
"task",
"subclass",
"to",
"execute",
"via",
"the",
"TaskRunner"
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Job/MultisitesInitAssetsTask.php#L25-L44 | train |
symbiote/silverstripe-multisites | src/Admin/MultisitesCmsMainExtension.php | MultisitesCMSMainExtension.doAddSite | public function doAddSite() {
$site = $this->owner->getNewItem('new-' . Site::class .'-0', false);
$site->write();
return $this->owner->redirect(
singleton(CMSPageEditController::class)->Link("show/$site->ID")
);
} | php | public function doAddSite() {
$site = $this->owner->getNewItem('new-' . Site::class .'-0', false);
$site->write();
return $this->owner->redirect(
singleton(CMSPageEditController::class)->Link("show/$site->ID")
);
} | [
"public",
"function",
"doAddSite",
"(",
")",
"{",
"$",
"site",
"=",
"$",
"this",
"->",
"owner",
"->",
"getNewItem",
"(",
"'new-'",
".",
"Site",
"::",
"class",
".",
"'-0'",
",",
"false",
")",
";",
"$",
"site",
"->",
"write",
"(",
")",
";",
"return",... | AddSiteForm action to add a new site | [
"AddSiteForm",
"action",
"to",
"add",
"a",
"new",
"site"
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Admin/MultisitesCmsMainExtension.php#L91-L98 | train |
symbiote/silverstripe-multisites | src/Admin/MultisitesCmsMainExtension.php | MultisitesCMSMainExtension.updateEditForm | public function updateEditForm($form) {
$classNameField = $form->Fields()->dataFieldByName('ClassName');
if ($classNameField) {
$className = $classNameField->Value();
if ($className === 'Site')
{
$form->Fields()->removeByName(array(SilverStripeNavigator::class));
$form->removeExtraClass('cms-previewable');
}
}
} | php | public function updateEditForm($form) {
$classNameField = $form->Fields()->dataFieldByName('ClassName');
if ($classNameField) {
$className = $classNameField->Value();
if ($className === 'Site')
{
$form->Fields()->removeByName(array(SilverStripeNavigator::class));
$form->removeExtraClass('cms-previewable');
}
}
} | [
"public",
"function",
"updateEditForm",
"(",
"$",
"form",
")",
"{",
"$",
"classNameField",
"=",
"$",
"form",
"->",
"Fields",
"(",
")",
"->",
"dataFieldByName",
"(",
"'ClassName'",
")",
";",
"if",
"(",
"$",
"classNameField",
")",
"{",
"$",
"className",
"=... | If viewing 'Site', disable preview panel. | [
"If",
"viewing",
"Site",
"disable",
"preview",
"panel",
"."
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Admin/MultisitesCmsMainExtension.php#L103-L113 | train |
symbiote/silverstripe-multisites | src/Admin/MultisitesCmsMainExtension.php | MultisitesCMSMainExtension.updateSearchForm | public function updateSearchForm(Form $form) {
$cms = $this->owner;
$req = $cms->getRequest();
$sites = Site::get()->sort(array(
'IsDefault' => 'DESC',
'Title' => 'ASC'
));
$site = new DropdownField(
'q[SiteID]',
_t('Multisites.SITE', 'Site'),
$sites->map(),
isset($req['q']['SiteID']) ? $req['q']['SiteID'] : null
);
$site->setEmptyString(_t('Multisites.ALLSITES', 'All sites'));
$form->Fields()->insertAfter($site, 'q[Term]');
} | php | public function updateSearchForm(Form $form) {
$cms = $this->owner;
$req = $cms->getRequest();
$sites = Site::get()->sort(array(
'IsDefault' => 'DESC',
'Title' => 'ASC'
));
$site = new DropdownField(
'q[SiteID]',
_t('Multisites.SITE', 'Site'),
$sites->map(),
isset($req['q']['SiteID']) ? $req['q']['SiteID'] : null
);
$site->setEmptyString(_t('Multisites.ALLSITES', 'All sites'));
$form->Fields()->insertAfter($site, 'q[Term]');
} | [
"public",
"function",
"updateSearchForm",
"(",
"Form",
"$",
"form",
")",
"{",
"$",
"cms",
"=",
"$",
"this",
"->",
"owner",
";",
"$",
"req",
"=",
"$",
"cms",
"->",
"getRequest",
"(",
")",
";",
"$",
"sites",
"=",
"Site",
"::",
"get",
"(",
")",
"->"... | Adds a dropdown field to the search form to filter searches by Site | [
"Adds",
"a",
"dropdown",
"field",
"to",
"the",
"search",
"form",
"to",
"filter",
"searches",
"by",
"Site"
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Admin/MultisitesCmsMainExtension.php#L118-L136 | train |
symbiote/silverstripe-multisites | src/Admin/MultisitesCmsMainExtension.php | MultisitesCMSMainExtension.updateCurrentPageID | public function updateCurrentPageID(&$id){
if (!$id) {
if($site = Multisites::inst()->getCurrentSite()){
$id = $site->Children()->first();
}
}
} | php | public function updateCurrentPageID(&$id){
if (!$id) {
if($site = Multisites::inst()->getCurrentSite()){
$id = $site->Children()->first();
}
}
} | [
"public",
"function",
"updateCurrentPageID",
"(",
"&",
"$",
"id",
")",
"{",
"if",
"(",
"!",
"$",
"id",
")",
"{",
"if",
"(",
"$",
"site",
"=",
"Multisites",
"::",
"inst",
"(",
")",
"->",
"getCurrentSite",
"(",
")",
")",
"{",
"$",
"id",
"=",
"$",
... | Makes the default page id the first child of the current site
This makes the site tree view load with the current site open instead of just the first one | [
"Makes",
"the",
"default",
"page",
"id",
"the",
"first",
"child",
"of",
"the",
"current",
"site",
"This",
"makes",
"the",
"site",
"tree",
"view",
"load",
"with",
"the",
"current",
"site",
"open",
"instead",
"of",
"just",
"the",
"first",
"one"
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Admin/MultisitesCmsMainExtension.php#L143-L149 | train |
symbiote/silverstripe-multisites | src/Extension/MultisitesControllerExtension.php | MultisitesControllerExtension.onBeforeHTTPError | public function onBeforeHTTPError($code, $request)
{
$errorPage = ErrorPage::get()->filter(array(
'ErrorCode' => $code,
'SiteID' => Multisites::inst()->getCurrentSiteId()
))->first();
if ($errorPage) {
Requirements::clear();
Requirements::clear_combined_files();
$response = ModelAsController::controller_for($errorPage)->handleRequest($request);
throw new HTTPResponse_Exception($response, $code);
}
} | php | public function onBeforeHTTPError($code, $request)
{
$errorPage = ErrorPage::get()->filter(array(
'ErrorCode' => $code,
'SiteID' => Multisites::inst()->getCurrentSiteId()
))->first();
if ($errorPage) {
Requirements::clear();
Requirements::clear_combined_files();
$response = ModelAsController::controller_for($errorPage)->handleRequest($request);
throw new HTTPResponse_Exception($response, $code);
}
} | [
"public",
"function",
"onBeforeHTTPError",
"(",
"$",
"code",
",",
"$",
"request",
")",
"{",
"$",
"errorPage",
"=",
"ErrorPage",
"::",
"get",
"(",
")",
"->",
"filter",
"(",
"array",
"(",
"'ErrorCode'",
"=>",
"$",
"code",
",",
"'SiteID'",
"=>",
"Multisites... | Retrieve the correct error page for the current multisite instance.
@param integer
@param SS_HTTPRequest
@throws SS_HTTPResponse_Exception | [
"Retrieve",
"the",
"correct",
"error",
"page",
"for",
"the",
"current",
"multisite",
"instance",
"."
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Extension/MultisitesControllerExtension.php#L74-L87 | train |
symbiote/silverstripe-multisites | src/Extension/MultisitesAware.php | MultisitesAware.canEdit | public function canEdit($member = null)
{
$managedSites = Multisites::inst()->sitesManagedByMember();
if (count($managedSites) && in_array($this->owner->SiteID, $managedSites)) {
// member has permission to manage MultisitesAware objects on this site,
// hand over to the object's canEdit method
return null;
} else {
// member does not have permission to edit objects on this object's Site
return false;
}
} | php | public function canEdit($member = null)
{
$managedSites = Multisites::inst()->sitesManagedByMember();
if (count($managedSites) && in_array($this->owner->SiteID, $managedSites)) {
// member has permission to manage MultisitesAware objects on this site,
// hand over to the object's canEdit method
return null;
} else {
// member does not have permission to edit objects on this object's Site
return false;
}
} | [
"public",
"function",
"canEdit",
"(",
"$",
"member",
"=",
"null",
")",
"{",
"$",
"managedSites",
"=",
"Multisites",
"::",
"inst",
"(",
")",
"->",
"sitesManagedByMember",
"(",
")",
";",
"if",
"(",
"count",
"(",
"$",
"managedSites",
")",
"&&",
"in_array",
... | Check to see if the current user has permission to edit this MultisitesAware object
On the site this object is associated with.
@return boolean|null | [
"Check",
"to",
"see",
"if",
"the",
"current",
"user",
"has",
"permission",
"to",
"edit",
"this",
"MultisitesAware",
"object",
"On",
"the",
"site",
"this",
"object",
"is",
"associated",
"with",
"."
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Extension/MultisitesAware.php#L38-L49 | train |
symbiote/silverstripe-multisites | src/Job/TidySiteTask.php | TidySiteTask.recursiveTidy | public function recursiveTidy($children)
{
foreach ($children as $page) {
$write = false;
// This is so something (events for example) can be purged.
if ($this->purge && is_a($page, $this->purge, true)) {
$page->delete();
$this->purged++;
continue;
}
// The most common issue is that the site ID doesn't match.
if ($page->SiteID != $this->siteID) {
// Update it to match.
$page->SiteID = $this->siteID;
$write = true;
}
// The next issue is that duplicated URL segments have numbers appended (`URL-segment-2` for example).
if (preg_match('%-[0-9]$%', $page->URLSegment)) {
// When a page title ends with a number, the URL should match this.
$last = substr($page->Title, -1);
if (is_numeric($last)) {
// Determine whether this actually needs fixing.
if ($last !== substr($page->URLSegment, -1)) {
// Update it to match.
$page->URLSegment = $page->Title;
$write = true;
}
}
// The number appended shouldn't exist.
else {
// Determine whether this is considered unique (otherwise it can't be updated).
$to = substr($page->URLSegment, 0, -2);
if (!SiteTree::get()->filter(array(
'ParentID' => $page->ParentID,
'URLSegment' => $to
))->exists()) {
// This isn't unique, so update it.
$page->URLSegment = $to;
$write = true;
}
}
}
// Determine whether this page needs a write.
if ($write) {
$page->write();
$this->count++;
}
// Where necessary, continue further down.
$this->recursiveTidy($page->AllChildren());
}
} | php | public function recursiveTidy($children)
{
foreach ($children as $page) {
$write = false;
// This is so something (events for example) can be purged.
if ($this->purge && is_a($page, $this->purge, true)) {
$page->delete();
$this->purged++;
continue;
}
// The most common issue is that the site ID doesn't match.
if ($page->SiteID != $this->siteID) {
// Update it to match.
$page->SiteID = $this->siteID;
$write = true;
}
// The next issue is that duplicated URL segments have numbers appended (`URL-segment-2` for example).
if (preg_match('%-[0-9]$%', $page->URLSegment)) {
// When a page title ends with a number, the URL should match this.
$last = substr($page->Title, -1);
if (is_numeric($last)) {
// Determine whether this actually needs fixing.
if ($last !== substr($page->URLSegment, -1)) {
// Update it to match.
$page->URLSegment = $page->Title;
$write = true;
}
}
// The number appended shouldn't exist.
else {
// Determine whether this is considered unique (otherwise it can't be updated).
$to = substr($page->URLSegment, 0, -2);
if (!SiteTree::get()->filter(array(
'ParentID' => $page->ParentID,
'URLSegment' => $to
))->exists()) {
// This isn't unique, so update it.
$page->URLSegment = $to;
$write = true;
}
}
}
// Determine whether this page needs a write.
if ($write) {
$page->write();
$this->count++;
}
// Where necessary, continue further down.
$this->recursiveTidy($page->AllChildren());
}
} | [
"public",
"function",
"recursiveTidy",
"(",
"$",
"children",
")",
"{",
"foreach",
"(",
"$",
"children",
"as",
"$",
"page",
")",
"{",
"$",
"write",
"=",
"false",
";",
"// This is so something (events for example) can be purged.",
"if",
"(",
"$",
"this",
"->",
"... | This recursively goes through children to ensure everything is tidy. | [
"This",
"recursively",
"goes",
"through",
"children",
"to",
"ensure",
"everything",
"is",
"tidy",
"."
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Job/TidySiteTask.php#L65-L139 | train |
symbiote/silverstripe-multisites | src/Extension/MultisitesSiteTreeExtension.php | MultisitesSiteTreeExtension.contentcontrollerInit | public function contentcontrollerInit($controller)
{
// If we've accessed the homepage as /home/, then we should redirect to /.
if ($controller->dataRecord && $controller->dataRecord instanceof SiteTree && MultisitesRootController::should_be_on_root($controller->dataRecord)
&& (!isset($controller->urlParams['Action']) || !$controller->urlParams['Action'] ) && !$_POST && !$_FILES && !$controller->redirectedTo()) {
$getVars = $_GET;
unset($getVars['url']);
if ($getVars) $url = "?".http_build_query($getVars);
else $url = "";
$controller->redirect($url, 301);
return;
}
} | php | public function contentcontrollerInit($controller)
{
// If we've accessed the homepage as /home/, then we should redirect to /.
if ($controller->dataRecord && $controller->dataRecord instanceof SiteTree && MultisitesRootController::should_be_on_root($controller->dataRecord)
&& (!isset($controller->urlParams['Action']) || !$controller->urlParams['Action'] ) && !$_POST && !$_FILES && !$controller->redirectedTo()) {
$getVars = $_GET;
unset($getVars['url']);
if ($getVars) $url = "?".http_build_query($getVars);
else $url = "";
$controller->redirect($url, 301);
return;
}
} | [
"public",
"function",
"contentcontrollerInit",
"(",
"$",
"controller",
")",
"{",
"// If we've accessed the homepage as /home/, then we should redirect to /.",
"if",
"(",
"$",
"controller",
"->",
"dataRecord",
"&&",
"$",
"controller",
"->",
"dataRecord",
"instanceof",
"SiteT... | Make sure site home pages are loaded at the root of the site. | [
"Make",
"sure",
"site",
"home",
"pages",
"are",
"loaded",
"at",
"the",
"root",
"of",
"the",
"site",
"."
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Extension/MultisitesSiteTreeExtension.php#L60-L73 | train |
symbiote/silverstripe-multisites | src/Extension/MultisitesSiteTreeExtension.php | MultisitesSiteTreeExtension.onBeforeWrite | public function onBeforeWrite()
{
if ($this->owner instanceof Site) {
if (!$this->owner->ID) {
// Initialise a new Site to the top level
$this->owner->SiteID = 0;
$this->owner->ParentID = 0;
}
return;
}
// Set the SiteID (and ParentID if required) for all new pages.
if (!$this->owner->ID) {
$parent = $this->owner->Parent();
if ($parent && $parent->exists()) {
// Page is beneath a Site
if ($parent instanceof Site) {
$this->owner->SiteID = $parent->ID;
} else {
$this->owner->SiteID = $parent->SiteID;
}
} else {
// Create the page beneath the current Site
$this->owner->SiteID = Multisites::inst()->getDefaultSiteId();
$this->owner->ParentID = $this->owner->SiteID;
}
}
// Make sure SiteID is changed when site tree is reorganised.
if ($this->owner->ID && $this->owner->isChanged('ParentID')) {
// Get the new parent
$parent = DataObject::get_by_id(SiteTree::class, $this->owner->ParentID);
// Make sure the parent exists
if ($parent) {
// Recursively change SiteID for this and all child pages
$siteId = ($parent instanceof Site) ? $parent->ID : $parent->SiteID;
$this->owner->updateSiteID($siteId);
}
}
} | php | public function onBeforeWrite()
{
if ($this->owner instanceof Site) {
if (!$this->owner->ID) {
// Initialise a new Site to the top level
$this->owner->SiteID = 0;
$this->owner->ParentID = 0;
}
return;
}
// Set the SiteID (and ParentID if required) for all new pages.
if (!$this->owner->ID) {
$parent = $this->owner->Parent();
if ($parent && $parent->exists()) {
// Page is beneath a Site
if ($parent instanceof Site) {
$this->owner->SiteID = $parent->ID;
} else {
$this->owner->SiteID = $parent->SiteID;
}
} else {
// Create the page beneath the current Site
$this->owner->SiteID = Multisites::inst()->getDefaultSiteId();
$this->owner->ParentID = $this->owner->SiteID;
}
}
// Make sure SiteID is changed when site tree is reorganised.
if ($this->owner->ID && $this->owner->isChanged('ParentID')) {
// Get the new parent
$parent = DataObject::get_by_id(SiteTree::class, $this->owner->ParentID);
// Make sure the parent exists
if ($parent) {
// Recursively change SiteID for this and all child pages
$siteId = ($parent instanceof Site) ? $parent->ID : $parent->SiteID;
$this->owner->updateSiteID($siteId);
}
}
} | [
"public",
"function",
"onBeforeWrite",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"owner",
"instanceof",
"Site",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"owner",
"->",
"ID",
")",
"{",
"// Initialise a new Site to the top level",
"$",
"this",
"->",
... | Keep the SiteID field consistent. | [
"Keep",
"the",
"SiteID",
"field",
"consistent",
"."
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Extension/MultisitesSiteTreeExtension.php#L78-L118 | train |
hryvinskyi/magento2-base | Helper/ConsoleHelper.php | ConsoleHelper.getScreenSize | public static function getScreenSize( $refresh = false ) {
static $size;
if ( $size !== null && ! $refresh ) {
return $size;
}
if ( static::isRunningOnWindows() ) {
$output = [];
exec( 'mode con', $output );
if ( isset( $output, $output[1] ) && strpos( $output[1], 'CON' ) !== false ) {
return $size = [
(int) preg_replace( '~\D~', '', $output[4] ),
(int) preg_replace( '~\D~', '', $output[3] )
];
}
} else {
// try stty if available
$stty = [];
if ( exec( 'stty -a 2>&1', $stty ) ) {
$stty = implode( ' ', $stty );
// Linux stty output
if ( preg_match( '/rows\s+(\d+);\s*columns\s+(\d+);/mi', $stty, $matches ) ) {
return $size = [ (int) $matches[2], (int) $matches[1] ];
}
// MacOS stty output
if ( preg_match( '/(\d+)\s+rows;\s*(\d+)\s+columns;/mi', $stty, $matches ) ) {
return $size = [ (int) $matches[2], (int) $matches[1] ];
}
}
// fallback to tput, which may not be updated on terminal resize
if ( ( $width = (int) exec( 'tput cols 2>&1' ) ) > 0 && ( $height = (int) exec( 'tput lines 2>&1' ) ) > 0 ) {
return $size = [ $width, $height ];
}
// fallback to ENV variables, which may not be updated on terminal resize
if ( ( $width = (int) getenv( 'COLUMNS' ) ) > 0 && ( $height = (int) getenv( 'LINES' ) ) > 0 ) {
return $size = [ $width, $height ];
}
}
return $size = false;
} | php | public static function getScreenSize( $refresh = false ) {
static $size;
if ( $size !== null && ! $refresh ) {
return $size;
}
if ( static::isRunningOnWindows() ) {
$output = [];
exec( 'mode con', $output );
if ( isset( $output, $output[1] ) && strpos( $output[1], 'CON' ) !== false ) {
return $size = [
(int) preg_replace( '~\D~', '', $output[4] ),
(int) preg_replace( '~\D~', '', $output[3] )
];
}
} else {
// try stty if available
$stty = [];
if ( exec( 'stty -a 2>&1', $stty ) ) {
$stty = implode( ' ', $stty );
// Linux stty output
if ( preg_match( '/rows\s+(\d+);\s*columns\s+(\d+);/mi', $stty, $matches ) ) {
return $size = [ (int) $matches[2], (int) $matches[1] ];
}
// MacOS stty output
if ( preg_match( '/(\d+)\s+rows;\s*(\d+)\s+columns;/mi', $stty, $matches ) ) {
return $size = [ (int) $matches[2], (int) $matches[1] ];
}
}
// fallback to tput, which may not be updated on terminal resize
if ( ( $width = (int) exec( 'tput cols 2>&1' ) ) > 0 && ( $height = (int) exec( 'tput lines 2>&1' ) ) > 0 ) {
return $size = [ $width, $height ];
}
// fallback to ENV variables, which may not be updated on terminal resize
if ( ( $width = (int) getenv( 'COLUMNS' ) ) > 0 && ( $height = (int) getenv( 'LINES' ) ) > 0 ) {
return $size = [ $width, $height ];
}
}
return $size = false;
} | [
"public",
"static",
"function",
"getScreenSize",
"(",
"$",
"refresh",
"=",
"false",
")",
"{",
"static",
"$",
"size",
";",
"if",
"(",
"$",
"size",
"!==",
"null",
"&&",
"!",
"$",
"refresh",
")",
"{",
"return",
"$",
"size",
";",
"}",
"if",
"(",
"stati... | Returns terminal screen size.
Usage:
```php
list($width, $height) = ConsoleHelper::getScreenSize();
```
@param bool $refresh whether to force checking and not re-use cached size value.
This is useful to detect changing window size while the application is running but may
not get up to date values on every terminal.
@return array|bool An array of ($width, $height) or false when it was not able to determine size. | [
"Returns",
"terminal",
"screen",
"size",
"."
] | 7648c4d0c82a281c82aa1cf30d1808674ca40604 | https://github.com/hryvinskyi/magento2-base/blob/7648c4d0c82a281c82aa1cf30d1808674ca40604/Helper/ConsoleHelper.php#L583-L622 | train |
hryvinskyi/magento2-base | Helper/ConsoleHelper.php | ConsoleHelper.prompt | public static function prompt( $text, $options = [] ) {
$options = ArrayHelper::merge(
[
'required' => false,
'default' => null,
'pattern' => null,
'validator' => null,
'error' => 'Invalid input.',
],
$options
);
$error = null;
top:
$input = $options['default']
? static::input( "$text [" . $options['default'] . '] ' )
: static::input( "$text " );
if ( $input === '' ) {
if ( isset( $options['default'] ) ) {
$input = $options['default'];
} else if ( $options['required'] ) {
static::output( $options['error'] );
goto top;
}
} else if ( $options['pattern'] && ! preg_match( $options['pattern'], $input ) ) {
static::output( $options['error'] );
goto top;
} else if ( $options['validator'] &&
! call_user_func_array( $options['validator'], [ $input, &$error ] )
) {
static::output( isset( $error ) ? $error : $options['error'] );
goto top;
}
return $input;
} | php | public static function prompt( $text, $options = [] ) {
$options = ArrayHelper::merge(
[
'required' => false,
'default' => null,
'pattern' => null,
'validator' => null,
'error' => 'Invalid input.',
],
$options
);
$error = null;
top:
$input = $options['default']
? static::input( "$text [" . $options['default'] . '] ' )
: static::input( "$text " );
if ( $input === '' ) {
if ( isset( $options['default'] ) ) {
$input = $options['default'];
} else if ( $options['required'] ) {
static::output( $options['error'] );
goto top;
}
} else if ( $options['pattern'] && ! preg_match( $options['pattern'], $input ) ) {
static::output( $options['error'] );
goto top;
} else if ( $options['validator'] &&
! call_user_func_array( $options['validator'], [ $input, &$error ] )
) {
static::output( isset( $error ) ? $error : $options['error'] );
goto top;
}
return $input;
} | [
"public",
"static",
"function",
"prompt",
"(",
"$",
"text",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"=",
"ArrayHelper",
"::",
"merge",
"(",
"[",
"'required'",
"=>",
"false",
",",
"'default'",
"=>",
"null",
",",
"'pattern'",
"=>",
... | Prompts the user for input and validates it.
@param string $text prompt string
@param array $options the options to validate the input:
- `required`: whether it is required or not
- `default`: default value if no input is inserted by the user
- `pattern`: regular expression pattern to validate user input
- `validator`: a callable function to validate input. The function must accept two parameters:
- `input`: the user input to validate
- `error`: the error value passed by reference if validation failed.
@return string the user input | [
"Prompts",
"the",
"user",
"for",
"input",
"and",
"validates",
"it",
"."
] | 7648c4d0c82a281c82aa1cf30d1808674ca40604 | https://github.com/hryvinskyi/magento2-base/blob/7648c4d0c82a281c82aa1cf30d1808674ca40604/Helper/ConsoleHelper.php#L752-L786 | train |
hryvinskyi/magento2-base | Helper/ConsoleHelper.php | ConsoleHelper.getProgressbarWidth | private static function getProgressbarWidth( $prefix ) {
$width = self::$_progressWidth;
if ( $width === false ) {
return 0;
}
$screenSize = static::getScreenSize( true );
if ( $screenSize === false && $width < 1 ) {
return 0;
}
if ( $width === null ) {
$width = $screenSize[0];
} else if ( $width > 0 && $width < 1 ) {
$width = floor( $screenSize[0] * $width );
}
$width -= static::ansiStrlen( $prefix );
return $width;
} | php | private static function getProgressbarWidth( $prefix ) {
$width = self::$_progressWidth;
if ( $width === false ) {
return 0;
}
$screenSize = static::getScreenSize( true );
if ( $screenSize === false && $width < 1 ) {
return 0;
}
if ( $width === null ) {
$width = $screenSize[0];
} else if ( $width > 0 && $width < 1 ) {
$width = floor( $screenSize[0] * $width );
}
$width -= static::ansiStrlen( $prefix );
return $width;
} | [
"private",
"static",
"function",
"getProgressbarWidth",
"(",
"$",
"prefix",
")",
"{",
"$",
"width",
"=",
"self",
"::",
"$",
"_progressWidth",
";",
"if",
"(",
"$",
"width",
"===",
"false",
")",
"{",
"return",
"0",
";",
"}",
"$",
"screenSize",
"=",
"stat... | Return width of the progressbar
@param string $prefix an optional string to display before the progress bar.
@see updateProgress
@return int screen width
@since 2.0.14 | [
"Return",
"width",
"of",
"the",
"progressbar"
] | 7648c4d0c82a281c82aa1cf30d1808674ca40604 | https://github.com/hryvinskyi/magento2-base/blob/7648c4d0c82a281c82aa1cf30d1808674ca40604/Helper/ConsoleHelper.php#L963-L980 | train |
symbiote/silverstripe-multisites | src/Control/MultisitesFrontController.php | MultisitesFrontController.getNestedController | public function getNestedController() {
$request = $this->request;
$segment = $request->param('URLSegment');
$site = Multisites::inst()->getCurrentSiteId();
if(!$site) {
return $this->httpError(404);
}
$page = SiteTree::get()->filter(array(
'ParentID' => $site,
'URLSegment' => rawurlencode($segment)
));
$page = $page->first();
if(!$page) {
// Check to see if linkmapping module is installed and if so, if there a map for this request.
if(class_exists('LinkMapping')){
$queryString = '?';
if ($request->requestVars()){
foreach($request->requestVars() as $key => $value) {
if($key !='url'){$queryString .=$key.'='.$value.'&';}
}
$queryString = rtrim($queryString,'&');
}
$link = ($queryString != '?' ? $request->getURL().$queryString : $request->getURL());
$link = trim(Director::makeRelative($link));
$map = LinkMapping::get()->filter('MappedLink', $link)->first();
if ($map) {
$this->response = new HTTPResponse();
$this->response->redirect($map->getLink(), 301);
return $this->response;
}
}
// use OldPageRedirector if it exists, to find old page
if(class_exists(OldPageRedirector::class)){
if($redirect = OldPageRedirector::find_old_page(array($segment), Multisites::inst()->getCurrentSite())){
$redirect = SiteTree::get_by_link($redirect);
}
}else{
$redirect = self::find_old_page($segment, $site);
}
if($redirect) {
$getVars = $request->getVars();
//remove the url var as it confuses the routing
unset($getVars['url']);
$url = Controller::join_links(
$redirect->Link(
Controller::join_links(
$request->param('Action'),
$request->param('ID'),
$request->param('OtherID')
)
)
);
if(!empty($getVars)){
$url .= '?' . http_build_query($getVars);
}
$this->response->redirect($url, 301);
return $this->response;
}
return $this->httpError(404);
}
return self::controller_for($page, $request->param('Action'));
} | php | public function getNestedController() {
$request = $this->request;
$segment = $request->param('URLSegment');
$site = Multisites::inst()->getCurrentSiteId();
if(!$site) {
return $this->httpError(404);
}
$page = SiteTree::get()->filter(array(
'ParentID' => $site,
'URLSegment' => rawurlencode($segment)
));
$page = $page->first();
if(!$page) {
// Check to see if linkmapping module is installed and if so, if there a map for this request.
if(class_exists('LinkMapping')){
$queryString = '?';
if ($request->requestVars()){
foreach($request->requestVars() as $key => $value) {
if($key !='url'){$queryString .=$key.'='.$value.'&';}
}
$queryString = rtrim($queryString,'&');
}
$link = ($queryString != '?' ? $request->getURL().$queryString : $request->getURL());
$link = trim(Director::makeRelative($link));
$map = LinkMapping::get()->filter('MappedLink', $link)->first();
if ($map) {
$this->response = new HTTPResponse();
$this->response->redirect($map->getLink(), 301);
return $this->response;
}
}
// use OldPageRedirector if it exists, to find old page
if(class_exists(OldPageRedirector::class)){
if($redirect = OldPageRedirector::find_old_page(array($segment), Multisites::inst()->getCurrentSite())){
$redirect = SiteTree::get_by_link($redirect);
}
}else{
$redirect = self::find_old_page($segment, $site);
}
if($redirect) {
$getVars = $request->getVars();
//remove the url var as it confuses the routing
unset($getVars['url']);
$url = Controller::join_links(
$redirect->Link(
Controller::join_links(
$request->param('Action'),
$request->param('ID'),
$request->param('OtherID')
)
)
);
if(!empty($getVars)){
$url .= '?' . http_build_query($getVars);
}
$this->response->redirect($url, 301);
return $this->response;
}
return $this->httpError(404);
}
return self::controller_for($page, $request->param('Action'));
} | [
"public",
"function",
"getNestedController",
"(",
")",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"request",
";",
"$",
"segment",
"=",
"$",
"request",
"->",
"param",
"(",
"'URLSegment'",
")",
";",
"$",
"site",
"=",
"Multisites",
"::",
"inst",
"(",
")... | Overrides ModelAsController->getNestedController to find the nested controller
on a per-site basis | [
"Overrides",
"ModelAsController",
"-",
">",
"getNestedController",
"to",
"find",
"the",
"nested",
"controller",
"on",
"a",
"per",
"-",
"site",
"basis"
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Control/MultisitesFrontController.php#L22-L97 | train |
symbiote/silverstripe-multisites | src/Multisites.php | Multisites.init | public function init()
{
$valid = null;
if ($this->cache->has(self::CACHE_KEY)) {
$cached = $this->cache->get(self::CACHE_KEY);
$valid = $cached && isset($cached['hosts']) && count($cached['hosts']);
}
if ($valid) {
$this->map = $cached;
} else {
$this->build();
}
} | php | public function init()
{
$valid = null;
if ($this->cache->has(self::CACHE_KEY)) {
$cached = $this->cache->get(self::CACHE_KEY);
$valid = $cached && isset($cached['hosts']) && count($cached['hosts']);
}
if ($valid) {
$this->map = $cached;
} else {
$this->build();
}
} | [
"public",
"function",
"init",
"(",
")",
"{",
"$",
"valid",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"cache",
"->",
"has",
"(",
"self",
"::",
"CACHE_KEY",
")",
")",
"{",
"$",
"cached",
"=",
"$",
"this",
"->",
"cache",
"->",
"get",
"(",
"s... | Attempts to load the hostname map from the cache, and rebuilds it if
it cannot be loaded. | [
"Attempts",
"to",
"load",
"the",
"hostname",
"map",
"from",
"the",
"cache",
"and",
"rebuilds",
"it",
"if",
"it",
"cannot",
"be",
"loaded",
"."
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Multisites.php#L91-L106 | train |
symbiote/silverstripe-multisites | src/Multisites.php | Multisites.build | public function build()
{
$this->map = array(
'default' => null,
'hosts' => array()
);
if (!DB::is_active() ||
!DB::get_schema()->hasTable(Site::config()->table_name)) {
return;
}
$sites = Site::get();
/**
* After duplicating a site, the duplicate contains the same host and causes a 404 during resolution.
* IMPORTANT, this is required to prevent the site from going down.
* ---
*/
$sites = $sites->sort(array(
'ID' => 'DESC'
));
// ---
foreach ($sites as $site) {
if ($site->IsDefault) {
$this->map['default'] = $site->ID;
}
$hosts = array($site->Host);
$hosts = array_merge($hosts, (array) $site->HostAliases->getValue());
foreach ($hosts as $host) {
if (!$host) {
continue;
}
if ($site->Scheme != 'https') {
$this->map['hosts']["http://$host"] = $site->ID;
}
if ($site->Scheme != 'http') {
$this->map['hosts']["https://$host"] = $site->ID;
}
}
}
$this->cache->set(self::CACHE_KEY, $this->map);
} | php | public function build()
{
$this->map = array(
'default' => null,
'hosts' => array()
);
if (!DB::is_active() ||
!DB::get_schema()->hasTable(Site::config()->table_name)) {
return;
}
$sites = Site::get();
/**
* After duplicating a site, the duplicate contains the same host and causes a 404 during resolution.
* IMPORTANT, this is required to prevent the site from going down.
* ---
*/
$sites = $sites->sort(array(
'ID' => 'DESC'
));
// ---
foreach ($sites as $site) {
if ($site->IsDefault) {
$this->map['default'] = $site->ID;
}
$hosts = array($site->Host);
$hosts = array_merge($hosts, (array) $site->HostAliases->getValue());
foreach ($hosts as $host) {
if (!$host) {
continue;
}
if ($site->Scheme != 'https') {
$this->map['hosts']["http://$host"] = $site->ID;
}
if ($site->Scheme != 'http') {
$this->map['hosts']["https://$host"] = $site->ID;
}
}
}
$this->cache->set(self::CACHE_KEY, $this->map);
} | [
"public",
"function",
"build",
"(",
")",
"{",
"$",
"this",
"->",
"map",
"=",
"array",
"(",
"'default'",
"=>",
"null",
",",
"'hosts'",
"=>",
"array",
"(",
")",
")",
";",
"if",
"(",
"!",
"DB",
"::",
"is_active",
"(",
")",
"||",
"!",
"DB",
"::",
"... | Builds a map of hostnames to sites, and writes it to the cache. | [
"Builds",
"a",
"map",
"of",
"hostnames",
"to",
"sites",
"and",
"writes",
"it",
"to",
"the",
"cache",
"."
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Multisites.php#L111-L159 | train |
symbiote/silverstripe-multisites | src/Multisites.php | Multisites.getActiveSite | public function getActiveSite()
{
$controller = Controller::curr();
if ($controller instanceof CMSPageEditController) {
// requests to admin/pages/edit/EditorToolbar/viewfile?ID=XX
// are not reliable because $controller->currentPage()
// will return an incorrect page based on the ID $_GET parameter
if ($controller->getRequest()->param('ID') != 'viewfile') {
$page = $controller->currentPage();
if (!$page) {
// fixes fatal error when duplicating page
// TODO find the root of the problem...
return Site::get()->first();
}
if ($page instanceof Site) {
$this->setActiveSite($page);
return $page;
}
$site = $page->Site();
if ($site->ID) {
$this->setActiveSite($site);
return $site;
}
}
} else if (is_subclass_of($controller, ModelAdmin::class)) {
// if we are in a model admin that isn't using the global active_site_session,
// return it's ActiveSite. This is important for cases where a multisite aware
// data object is being saved for the first time in a model admin, we need to
// know what site to save it to
if (!$controller->config()->use_active_site_session) {
return $controller->getActiveSite();
}
}
if ($id = $controller->getRequest()->getSession()->get('Multisites_ActiveSite')) {
return Site::get()->byID($id);
}
// if($id = Session::get('MultisitesModelAdmin_SiteID')) { // legacy
// return Site::get()->byID($id);
// }
return $this->getCurrentSite();
} | php | public function getActiveSite()
{
$controller = Controller::curr();
if ($controller instanceof CMSPageEditController) {
// requests to admin/pages/edit/EditorToolbar/viewfile?ID=XX
// are not reliable because $controller->currentPage()
// will return an incorrect page based on the ID $_GET parameter
if ($controller->getRequest()->param('ID') != 'viewfile') {
$page = $controller->currentPage();
if (!$page) {
// fixes fatal error when duplicating page
// TODO find the root of the problem...
return Site::get()->first();
}
if ($page instanceof Site) {
$this->setActiveSite($page);
return $page;
}
$site = $page->Site();
if ($site->ID) {
$this->setActiveSite($site);
return $site;
}
}
} else if (is_subclass_of($controller, ModelAdmin::class)) {
// if we are in a model admin that isn't using the global active_site_session,
// return it's ActiveSite. This is important for cases where a multisite aware
// data object is being saved for the first time in a model admin, we need to
// know what site to save it to
if (!$controller->config()->use_active_site_session) {
return $controller->getActiveSite();
}
}
if ($id = $controller->getRequest()->getSession()->get('Multisites_ActiveSite')) {
return Site::get()->byID($id);
}
// if($id = Session::get('MultisitesModelAdmin_SiteID')) { // legacy
// return Site::get()->byID($id);
// }
return $this->getCurrentSite();
} | [
"public",
"function",
"getActiveSite",
"(",
")",
"{",
"$",
"controller",
"=",
"Controller",
"::",
"curr",
"(",
")",
";",
"if",
"(",
"$",
"controller",
"instanceof",
"CMSPageEditController",
")",
"{",
"// requests to admin/pages/edit/EditorToolbar/viewfile?ID=XX",
"// ... | Get's the site related to what is currently being edited in the cms
If a page or site is being edited, it will look up the site of the sitetree being edited,
If a MultisitesAware object is being managed in ModelAdmin, ModelAdmin will have set a Session variable MultisitesModelAdmin_SiteID
@return Site | [
"Get",
"s",
"the",
"site",
"related",
"to",
"what",
"is",
"currently",
"being",
"edited",
"in",
"the",
"cms",
"If",
"a",
"page",
"or",
"site",
"is",
"being",
"edited",
"it",
"will",
"look",
"up",
"the",
"site",
"of",
"the",
"sitetree",
"being",
"edited... | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Multisites.php#L239-L287 | train |
symbiote/silverstripe-multisites | src/Multisites.php | Multisites.sitesManagedByMember | public function sitesManagedByMember($member = null)
{
$member = $member ?: Member::currentUser();
if (!$member) return array();
$sites = Site::get();
if (Permission::check('ADMIN')) {
return $sites->column('ID');
}
$memberGroups = $member->Groups()->column('ID');
$sites = $sites->filter("EditorGroups.ID:ExactMatch", $memberGroups);
return $sites->column('ID');
} | php | public function sitesManagedByMember($member = null)
{
$member = $member ?: Member::currentUser();
if (!$member) return array();
$sites = Site::get();
if (Permission::check('ADMIN')) {
return $sites->column('ID');
}
$memberGroups = $member->Groups()->column('ID');
$sites = $sites->filter("EditorGroups.ID:ExactMatch", $memberGroups);
return $sites->column('ID');
} | [
"public",
"function",
"sitesManagedByMember",
"(",
"$",
"member",
"=",
"null",
")",
"{",
"$",
"member",
"=",
"$",
"member",
"?",
":",
"Member",
"::",
"currentUser",
"(",
")",
";",
"if",
"(",
"!",
"$",
"member",
")",
"return",
"array",
"(",
")",
";",
... | Finds sites that the given member is a "Manager" of
A manager is currently defined by a Member who has edit access to a Site Object
@var Member $member
@return array - Site IDs | [
"Finds",
"sites",
"that",
"the",
"given",
"member",
"is",
"a",
"Manager",
"of",
"A",
"manager",
"is",
"currently",
"defined",
"by",
"a",
"Member",
"who",
"has",
"edit",
"access",
"to",
"a",
"Site",
"Object"
] | 9b3fa1d3375ce073c050bd137b68766073efd458 | https://github.com/symbiote/silverstripe-multisites/blob/9b3fa1d3375ce073c050bd137b68766073efd458/src/Multisites.php#L311-L326 | train |
tmconsulting/uniteller-php-sdk | src/Client.php | Client.verifyCallbackRequest | public function verifyCallbackRequest(array $params)
{
return $this->signatureCallback
->setOrderId(array_get($params, 'Order_ID'))
->setStatus(array_get($params, 'Status'))
->setFields(array_except($params, ['Order_ID', 'Status', 'Signature']))
->setPassword($this->getPassword())
->verify(array_get($params, 'Signature'));
} | php | public function verifyCallbackRequest(array $params)
{
return $this->signatureCallback
->setOrderId(array_get($params, 'Order_ID'))
->setStatus(array_get($params, 'Status'))
->setFields(array_except($params, ['Order_ID', 'Status', 'Signature']))
->setPassword($this->getPassword())
->verify(array_get($params, 'Signature'));
} | [
"public",
"function",
"verifyCallbackRequest",
"(",
"array",
"$",
"params",
")",
"{",
"return",
"$",
"this",
"->",
"signatureCallback",
"->",
"setOrderId",
"(",
"array_get",
"(",
"$",
"params",
",",
"'Order_ID'",
")",
")",
"->",
"setStatus",
"(",
"array_get",
... | Verify signature when Client will be send callback request.
@param array $params
@return bool | [
"Verify",
"signature",
"when",
"Client",
"will",
"be",
"send",
"callback",
"request",
"."
] | c296f4c9416e0445b8ae93d3ca4dc99423dc8d6e | https://github.com/tmconsulting/uniteller-php-sdk/blob/c296f4c9416e0445b8ae93d3ca4dc99423dc8d6e/src/Client.php#L494-L502 | train |
silverstripe/silverstripe-environmentcheck | src/Checks/CacheHeadersCheck.php | CacheHeadersCheck.check | public function check()
{
// Using a validation result to capture messages
$this->result = new ValidationResult();
$response = $this->client->get($this->getURL());
$fullURL = $this->getURL();
if ($response === null) {
return [
EnvironmentCheck::ERROR,
"Cache headers check request failed for $fullURL",
];
}
//Check that Etag exists
$this->checkEtag($response);
// Check Cache-Control settings
$this->checkCacheControl($response);
if ($this->result->isValid()) {
return [
EnvironmentCheck::OK,
$this->getMessage(),
];
} else {
// @todo Ability to return a warning
return [
EnvironmentCheck::ERROR,
$this->getMessage(),
];
}
} | php | public function check()
{
// Using a validation result to capture messages
$this->result = new ValidationResult();
$response = $this->client->get($this->getURL());
$fullURL = $this->getURL();
if ($response === null) {
return [
EnvironmentCheck::ERROR,
"Cache headers check request failed for $fullURL",
];
}
//Check that Etag exists
$this->checkEtag($response);
// Check Cache-Control settings
$this->checkCacheControl($response);
if ($this->result->isValid()) {
return [
EnvironmentCheck::OK,
$this->getMessage(),
];
} else {
// @todo Ability to return a warning
return [
EnvironmentCheck::ERROR,
$this->getMessage(),
];
}
} | [
"public",
"function",
"check",
"(",
")",
"{",
"// Using a validation result to capture messages",
"$",
"this",
"->",
"result",
"=",
"new",
"ValidationResult",
"(",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"get",
"(",
"$",
"this",
"-... | Check that correct caching headers are present.
@return void | [
"Check",
"that",
"correct",
"caching",
"headers",
"are",
"present",
"."
] | 6fe0b1889e60678ed374735f037c4e69a87041bb | https://github.com/silverstripe/silverstripe-environmentcheck/blob/6fe0b1889e60678ed374735f037c4e69a87041bb/src/Checks/CacheHeadersCheck.php#L66-L98 | train |
silverstripe/silverstripe-environmentcheck | src/Checks/CacheHeadersCheck.php | CacheHeadersCheck.getMessage | private function getMessage()
{
$ret = '';
// Filter good messages
$goodTypes = [ValidationResult::TYPE_GOOD, ValidationResult::TYPE_INFO];
$good = array_filter(
$this->result->getMessages(),
function ($val, $key) use ($goodTypes) {
if (in_array($val['messageType'], $goodTypes)) {
return true;
}
return false;
},
ARRAY_FILTER_USE_BOTH
);
if (!empty($good)) {
$ret .= "GOOD: " . implode('; ', array_column($good, 'message')) . " ";
}
// Filter bad messages
$badTypes = [ValidationResult::TYPE_ERROR, ValidationResult::TYPE_WARNING];
$bad = array_filter(
$this->result->getMessages(),
function ($val, $key) use ($badTypes) {
if (in_array($val['messageType'], $badTypes)) {
return true;
}
return false;
},
ARRAY_FILTER_USE_BOTH
);
if (!empty($bad)) {
$ret .= "BAD: " . implode('; ', array_column($bad, 'message'));
}
return $ret;
} | php | private function getMessage()
{
$ret = '';
// Filter good messages
$goodTypes = [ValidationResult::TYPE_GOOD, ValidationResult::TYPE_INFO];
$good = array_filter(
$this->result->getMessages(),
function ($val, $key) use ($goodTypes) {
if (in_array($val['messageType'], $goodTypes)) {
return true;
}
return false;
},
ARRAY_FILTER_USE_BOTH
);
if (!empty($good)) {
$ret .= "GOOD: " . implode('; ', array_column($good, 'message')) . " ";
}
// Filter bad messages
$badTypes = [ValidationResult::TYPE_ERROR, ValidationResult::TYPE_WARNING];
$bad = array_filter(
$this->result->getMessages(),
function ($val, $key) use ($badTypes) {
if (in_array($val['messageType'], $badTypes)) {
return true;
}
return false;
},
ARRAY_FILTER_USE_BOTH
);
if (!empty($bad)) {
$ret .= "BAD: " . implode('; ', array_column($bad, 'message'));
}
return $ret;
} | [
"private",
"function",
"getMessage",
"(",
")",
"{",
"$",
"ret",
"=",
"''",
";",
"// Filter good messages",
"$",
"goodTypes",
"=",
"[",
"ValidationResult",
"::",
"TYPE_GOOD",
",",
"ValidationResult",
"::",
"TYPE_INFO",
"]",
";",
"$",
"good",
"=",
"array_filter"... | Collate messages from ValidationResult so that it is clear which parts
of the check passed and which failed.
@return string | [
"Collate",
"messages",
"from",
"ValidationResult",
"so",
"that",
"it",
"is",
"clear",
"which",
"parts",
"of",
"the",
"check",
"passed",
"and",
"which",
"failed",
"."
] | 6fe0b1889e60678ed374735f037c4e69a87041bb | https://github.com/silverstripe/silverstripe-environmentcheck/blob/6fe0b1889e60678ed374735f037c4e69a87041bb/src/Checks/CacheHeadersCheck.php#L106-L141 | train |
silverstripe/silverstripe-environmentcheck | src/Checks/CacheHeadersCheck.php | CacheHeadersCheck.checkEtag | private function checkEtag(ResponseInterface $response)
{
$eTag = $response->getHeaderLine('ETag');
$fullURL = Controller::join_links(Director::absoluteBaseURL(), $this->url);
if ($eTag) {
$this->result->addMessage(
"$fullURL includes an Etag header in response",
ValidationResult::TYPE_GOOD
);
return;
}
$this->result->addError(
"$fullURL is missing an Etag header",
ValidationResult::TYPE_WARNING
);
} | php | private function checkEtag(ResponseInterface $response)
{
$eTag = $response->getHeaderLine('ETag');
$fullURL = Controller::join_links(Director::absoluteBaseURL(), $this->url);
if ($eTag) {
$this->result->addMessage(
"$fullURL includes an Etag header in response",
ValidationResult::TYPE_GOOD
);
return;
}
$this->result->addError(
"$fullURL is missing an Etag header",
ValidationResult::TYPE_WARNING
);
} | [
"private",
"function",
"checkEtag",
"(",
"ResponseInterface",
"$",
"response",
")",
"{",
"$",
"eTag",
"=",
"$",
"response",
"->",
"getHeaderLine",
"(",
"'ETag'",
")",
";",
"$",
"fullURL",
"=",
"Controller",
"::",
"join_links",
"(",
"Director",
"::",
"absolut... | Check that ETag header exists
@param ResponseInterface $response
@return void | [
"Check",
"that",
"ETag",
"header",
"exists"
] | 6fe0b1889e60678ed374735f037c4e69a87041bb | https://github.com/silverstripe/silverstripe-environmentcheck/blob/6fe0b1889e60678ed374735f037c4e69a87041bb/src/Checks/CacheHeadersCheck.php#L149-L165 | train |
silverstripe/silverstripe-environmentcheck | src/Checks/CacheHeadersCheck.php | CacheHeadersCheck.checkCacheControl | private function checkCacheControl(ResponseInterface $response)
{
$cacheControl = $response->getHeaderLine('Cache-Control');
$vals = array_map('trim', explode(',', $cacheControl));
$fullURL = Controller::join_links(Director::absoluteBaseURL(), $this->url);
// All entries from must contain should be present
if ($this->mustInclude == array_intersect($this->mustInclude, $vals)) {
$matched = implode(",", $this->mustInclude);
$this->result->addMessage(
"$fullURL includes all settings: {$matched}",
ValidationResult::TYPE_GOOD
);
} else {
$missing = implode(",", array_diff($this->mustInclude, $vals));
$this->result->addError(
"$fullURL is excluding some settings: {$missing}"
);
}
// All entries from must exclude should not be present
if (empty(array_intersect($this->mustExclude, $vals))) {
$missing = implode(",", $this->mustExclude);
$this->result->addMessage(
"$fullURL excludes all settings: {$missing}",
ValidationResult::TYPE_GOOD
);
} else {
$matched = implode(",", array_intersect($this->mustExclude, $vals));
$this->result->addError(
"$fullURL is including some settings: {$matched}"
);
}
} | php | private function checkCacheControl(ResponseInterface $response)
{
$cacheControl = $response->getHeaderLine('Cache-Control');
$vals = array_map('trim', explode(',', $cacheControl));
$fullURL = Controller::join_links(Director::absoluteBaseURL(), $this->url);
// All entries from must contain should be present
if ($this->mustInclude == array_intersect($this->mustInclude, $vals)) {
$matched = implode(",", $this->mustInclude);
$this->result->addMessage(
"$fullURL includes all settings: {$matched}",
ValidationResult::TYPE_GOOD
);
} else {
$missing = implode(",", array_diff($this->mustInclude, $vals));
$this->result->addError(
"$fullURL is excluding some settings: {$missing}"
);
}
// All entries from must exclude should not be present
if (empty(array_intersect($this->mustExclude, $vals))) {
$missing = implode(",", $this->mustExclude);
$this->result->addMessage(
"$fullURL excludes all settings: {$missing}",
ValidationResult::TYPE_GOOD
);
} else {
$matched = implode(",", array_intersect($this->mustExclude, $vals));
$this->result->addError(
"$fullURL is including some settings: {$matched}"
);
}
} | [
"private",
"function",
"checkCacheControl",
"(",
"ResponseInterface",
"$",
"response",
")",
"{",
"$",
"cacheControl",
"=",
"$",
"response",
"->",
"getHeaderLine",
"(",
"'Cache-Control'",
")",
";",
"$",
"vals",
"=",
"array_map",
"(",
"'trim'",
",",
"explode",
"... | Check that the correct header settings are either included or excluded.
@param ResponseInterface $response
@return void | [
"Check",
"that",
"the",
"correct",
"header",
"settings",
"are",
"either",
"included",
"or",
"excluded",
"."
] | 6fe0b1889e60678ed374735f037c4e69a87041bb | https://github.com/silverstripe/silverstripe-environmentcheck/blob/6fe0b1889e60678ed374735f037c4e69a87041bb/src/Checks/CacheHeadersCheck.php#L173-L206 | train |
silverstripe/silverstripe-environmentcheck | src/EnvironmentChecker.php | EnvironmentChecker.canAccess | public function canAccess($member = null, $permission = 'ADMIN')
{
if (!$member) {
$member = Security::getCurrentUser();
}
// We allow access to this controller regardless of live-status or ADMIN permission only
// if on CLI. Access to this controller is always allowed in "dev-mode", or of the user is ADMIN.
if (Director::isDev()
|| Director::is_cli()
|| empty($permission)
|| Permission::checkMember($member, $permission)
) {
return true;
}
// Extended access checks.
// "Veto" style, return NULL to abstain vote.
$canExtended = null;
$results = $this->extend('canAccess', $member);
if ($results && is_array($results)) {
if (!min($results)) {
return false;
}
return true;
}
return false;
} | php | public function canAccess($member = null, $permission = 'ADMIN')
{
if (!$member) {
$member = Security::getCurrentUser();
}
// We allow access to this controller regardless of live-status or ADMIN permission only
// if on CLI. Access to this controller is always allowed in "dev-mode", or of the user is ADMIN.
if (Director::isDev()
|| Director::is_cli()
|| empty($permission)
|| Permission::checkMember($member, $permission)
) {
return true;
}
// Extended access checks.
// "Veto" style, return NULL to abstain vote.
$canExtended = null;
$results = $this->extend('canAccess', $member);
if ($results && is_array($results)) {
if (!min($results)) {
return false;
}
return true;
}
return false;
} | [
"public",
"function",
"canAccess",
"(",
"$",
"member",
"=",
"null",
",",
"$",
"permission",
"=",
"'ADMIN'",
")",
"{",
"if",
"(",
"!",
"$",
"member",
")",
"{",
"$",
"member",
"=",
"Security",
"::",
"getCurrentUser",
"(",
")",
";",
"}",
"// We allow acce... | Determine if the current member can access the environment checker
@param null|int|Member $member
@param string $permission
@return bool | [
"Determine",
"if",
"the",
"current",
"member",
"can",
"access",
"the",
"environment",
"checker"
] | 6fe0b1889e60678ed374735f037c4e69a87041bb | https://github.com/silverstripe/silverstripe-environmentcheck/blob/6fe0b1889e60678ed374735f037c4e69a87041bb/src/EnvironmentChecker.php#L133-L161 | train |
silverstripe/silverstripe-environmentcheck | src/EnvironmentChecker.php | EnvironmentChecker.log | public function log($message, $level)
{
Injector::inst()->get(LoggerInterface::class)->log($level, $message);
} | php | public function log($message, $level)
{
Injector::inst()->get(LoggerInterface::class)->log($level, $message);
} | [
"public",
"function",
"log",
"(",
"$",
"message",
",",
"$",
"level",
")",
"{",
"Injector",
"::",
"inst",
"(",
")",
"->",
"get",
"(",
"LoggerInterface",
"::",
"class",
")",
"->",
"log",
"(",
"$",
"level",
",",
"$",
"message",
")",
";",
"}"
] | Sends a log entry to the configured PSR-3 LoggerInterface
@param string $message
@param int $level | [
"Sends",
"a",
"log",
"entry",
"to",
"the",
"configured",
"PSR",
"-",
"3",
"LoggerInterface"
] | 6fe0b1889e60678ed374735f037c4e69a87041bb | https://github.com/silverstripe/silverstripe-environmentcheck/blob/6fe0b1889e60678ed374735f037c4e69a87041bb/src/EnvironmentChecker.php#L227-L230 | train |
silverstripe/silverstripe-environmentcheck | src/EnvironmentCheckSuite.php | EnvironmentCheckSuite.run | public function run()
{
$result = new EnvironmentCheckSuiteResult();
foreach ($this->checkInstances() as $check) {
list($checkClass, $checkTitle) = $check;
try {
list($status, $message) = $checkClass->check();
// If the check fails, register that as an error
} catch (Exception $e) {
$status = EnvironmentCheck::ERROR;
$message = $e->getMessage();
}
$result->addResult($status, $message, $checkTitle);
}
return $result;
} | php | public function run()
{
$result = new EnvironmentCheckSuiteResult();
foreach ($this->checkInstances() as $check) {
list($checkClass, $checkTitle) = $check;
try {
list($status, $message) = $checkClass->check();
// If the check fails, register that as an error
} catch (Exception $e) {
$status = EnvironmentCheck::ERROR;
$message = $e->getMessage();
}
$result->addResult($status, $message, $checkTitle);
}
return $result;
} | [
"public",
"function",
"run",
"(",
")",
"{",
"$",
"result",
"=",
"new",
"EnvironmentCheckSuiteResult",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"checkInstances",
"(",
")",
"as",
"$",
"check",
")",
"{",
"list",
"(",
"$",
"checkClass",
",",
"$",
... | Run this test suite and return the result code of the worst result.
@return EnvironmentCheckSuiteResult | [
"Run",
"this",
"test",
"suite",
"and",
"return",
"the",
"result",
"code",
"of",
"the",
"worst",
"result",
"."
] | 6fe0b1889e60678ed374735f037c4e69a87041bb | https://github.com/silverstripe/silverstripe-environmentcheck/blob/6fe0b1889e60678ed374735f037c4e69a87041bb/src/EnvironmentCheckSuite.php#L106-L123 | train |
silverstripe/silverstripe-environmentcheck | src/EnvironmentCheckSuite.php | EnvironmentCheckSuite.checkInstances | protected function checkInstances()
{
$output = [];
foreach ($this->checks as $check) {
list($checkClass, $checkTitle) = $check;
if (is_string($checkClass)) {
$checkInst = Injector::inst()->create($checkClass);
if ($checkInst instanceof EnvironmentCheck) {
$output[] = [$checkInst, $checkTitle];
} else {
throw new InvalidArgumentException(
"Bad EnvironmentCheck: '$checkClass' - the named class doesn't implement EnvironmentCheck"
);
}
} elseif ($checkClass instanceof EnvironmentCheck) {
$output[] = [$checkClass, $checkTitle];
} else {
throw new InvalidArgumentException("Bad EnvironmentCheck: " . var_export($check, true));
}
}
return $output;
} | php | protected function checkInstances()
{
$output = [];
foreach ($this->checks as $check) {
list($checkClass, $checkTitle) = $check;
if (is_string($checkClass)) {
$checkInst = Injector::inst()->create($checkClass);
if ($checkInst instanceof EnvironmentCheck) {
$output[] = [$checkInst, $checkTitle];
} else {
throw new InvalidArgumentException(
"Bad EnvironmentCheck: '$checkClass' - the named class doesn't implement EnvironmentCheck"
);
}
} elseif ($checkClass instanceof EnvironmentCheck) {
$output[] = [$checkClass, $checkTitle];
} else {
throw new InvalidArgumentException("Bad EnvironmentCheck: " . var_export($check, true));
}
}
return $output;
} | [
"protected",
"function",
"checkInstances",
"(",
")",
"{",
"$",
"output",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"checks",
"as",
"$",
"check",
")",
"{",
"list",
"(",
"$",
"checkClass",
",",
"$",
"checkTitle",
")",
"=",
"$",
"check",
... | Get instances of all the environment checks.
@return EnvironmentChecker[]
@throws InvalidArgumentException | [
"Get",
"instances",
"of",
"all",
"the",
"environment",
"checks",
"."
] | 6fe0b1889e60678ed374735f037c4e69a87041bb | https://github.com/silverstripe/silverstripe-environmentcheck/blob/6fe0b1889e60678ed374735f037c4e69a87041bb/src/EnvironmentCheckSuite.php#L131-L152 | train |
silverstripe/silverstripe-environmentcheck | src/EnvironmentCheckSuite.php | EnvironmentCheckSuite.push | public function push($check, $title = null)
{
if (!$title) {
$title = is_string($check) ? $check : get_class($check);
}
$this->checks[] = [$check, $title];
} | php | public function push($check, $title = null)
{
if (!$title) {
$title = is_string($check) ? $check : get_class($check);
}
$this->checks[] = [$check, $title];
} | [
"public",
"function",
"push",
"(",
"$",
"check",
",",
"$",
"title",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"title",
")",
"{",
"$",
"title",
"=",
"is_string",
"(",
"$",
"check",
")",
"?",
"$",
"check",
":",
"get_class",
"(",
"$",
"check",
"... | Add a check to this suite.
@param mixed $check
@param string $title | [
"Add",
"a",
"check",
"to",
"this",
"suite",
"."
] | 6fe0b1889e60678ed374735f037c4e69a87041bb | https://github.com/silverstripe/silverstripe-environmentcheck/blob/6fe0b1889e60678ed374735f037c4e69a87041bb/src/EnvironmentCheckSuite.php#L160-L166 | train |
silverstripe/silverstripe-environmentcheck | src/EnvironmentCheckSuite.php | EnvironmentCheckSuite.inst | public static function inst($name)
{
if (!isset(self::$instances[$name])) {
self::$instances[$name] = new EnvironmentCheckSuite($name);
}
return self::$instances[$name];
} | php | public static function inst($name)
{
if (!isset(self::$instances[$name])) {
self::$instances[$name] = new EnvironmentCheckSuite($name);
}
return self::$instances[$name];
} | [
"public",
"static",
"function",
"inst",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"instances",
"[",
"$",
"name",
"]",
")",
")",
"{",
"self",
"::",
"$",
"instances",
"[",
"$",
"name",
"]",
"=",
"new",
"Environmen... | Return a named instance of EnvironmentCheckSuite.
@param string $name
@return EnvironmentCheckSuite | [
"Return",
"a",
"named",
"instance",
"of",
"EnvironmentCheckSuite",
"."
] | 6fe0b1889e60678ed374735f037c4e69a87041bb | https://github.com/silverstripe/silverstripe-environmentcheck/blob/6fe0b1889e60678ed374735f037c4e69a87041bb/src/EnvironmentCheckSuite.php#L182-L188 | train |
silverstripe/silverstripe-environmentcheck | src/EnvironmentCheckSuite.php | EnvironmentCheckSuite.register | public static function register($names, $check, $title = null)
{
if (!is_array($names)) {
$names = [$names];
}
foreach ($names as $name) {
self::inst($name)->push($check, $title);
}
} | php | public static function register($names, $check, $title = null)
{
if (!is_array($names)) {
$names = [$names];
}
foreach ($names as $name) {
self::inst($name)->push($check, $title);
}
} | [
"public",
"static",
"function",
"register",
"(",
"$",
"names",
",",
"$",
"check",
",",
"$",
"title",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"names",
")",
")",
"{",
"$",
"names",
"=",
"[",
"$",
"names",
"]",
";",
"}",
"fore... | Register a check against the named check suite.
@param string|array $names
@param EnvironmentCheck $check
@param string|array | [
"Register",
"a",
"check",
"against",
"the",
"named",
"check",
"suite",
"."
] | 6fe0b1889e60678ed374735f037c4e69a87041bb | https://github.com/silverstripe/silverstripe-environmentcheck/blob/6fe0b1889e60678ed374735f037c4e69a87041bb/src/EnvironmentCheckSuite.php#L197-L206 | train |
silverstripe/silverstripe-environmentcheck | src/EnvironmentCheckSuiteResult.php | EnvironmentCheckSuiteResult.toJSON | public function toJSON()
{
$result = [
'Status' => $this->Status(),
'ShouldPass' => $this->ShouldPass(),
'Checks' => []
];
foreach ($this->details as $detail) {
$result['Checks'][] = $detail->toMap();
}
return json_encode($result);
} | php | public function toJSON()
{
$result = [
'Status' => $this->Status(),
'ShouldPass' => $this->ShouldPass(),
'Checks' => []
];
foreach ($this->details as $detail) {
$result['Checks'][] = $detail->toMap();
}
return json_encode($result);
} | [
"public",
"function",
"toJSON",
"(",
")",
"{",
"$",
"result",
"=",
"[",
"'Status'",
"=>",
"$",
"this",
"->",
"Status",
"(",
")",
",",
"'ShouldPass'",
"=>",
"$",
"this",
"->",
"ShouldPass",
"(",
")",
",",
"'Checks'",
"=>",
"[",
"]",
"]",
";",
"forea... | Convert the final result status and details to JSON.
@return string | [
"Convert",
"the",
"final",
"result",
"status",
"and",
"details",
"to",
"JSON",
"."
] | 6fe0b1889e60678ed374735f037c4e69a87041bb | https://github.com/silverstripe/silverstripe-environmentcheck/blob/6fe0b1889e60678ed374735f037c4e69a87041bb/src/EnvironmentCheckSuiteResult.php#L85-L96 | train |
silverstripe/silverstripe-environmentcheck | src/EnvironmentCheckSuiteResult.php | EnvironmentCheckSuiteResult.statusText | protected function statusText($status)
{
switch ($status) {
case EnvironmentCheck::ERROR:
return 'ERROR';
break;
case EnvironmentCheck::WARNING:
return 'WARNING';
break;
case EnvironmentCheck::OK:
return 'OK';
break;
case 0:
return 'NO CHECKS';
break;
default:
throw new InvalidArgumentException("Bad environment check status '$status'");
break;
}
} | php | protected function statusText($status)
{
switch ($status) {
case EnvironmentCheck::ERROR:
return 'ERROR';
break;
case EnvironmentCheck::WARNING:
return 'WARNING';
break;
case EnvironmentCheck::OK:
return 'OK';
break;
case 0:
return 'NO CHECKS';
break;
default:
throw new InvalidArgumentException("Bad environment check status '$status'");
break;
}
} | [
"protected",
"function",
"statusText",
"(",
"$",
"status",
")",
"{",
"switch",
"(",
"$",
"status",
")",
"{",
"case",
"EnvironmentCheck",
"::",
"ERROR",
":",
"return",
"'ERROR'",
";",
"break",
";",
"case",
"EnvironmentCheck",
"::",
"WARNING",
":",
"return",
... | Return a text version of a status code.
@param int $status
@return string
@throws InvalidArgumentException | [
"Return",
"a",
"text",
"version",
"of",
"a",
"status",
"code",
"."
] | 6fe0b1889e60678ed374735f037c4e69a87041bb | https://github.com/silverstripe/silverstripe-environmentcheck/blob/6fe0b1889e60678ed374735f037c4e69a87041bb/src/EnvironmentCheckSuiteResult.php#L105-L124 | train |
silverstripe/silverstripe-environmentcheck | src/Checks/SessionCheck.php | SessionCheck.getCookie | public function getCookie(ResponseInterface $response)
{
$result = null;
$cookies = $response->getHeader('Set-Cookie');
foreach ($cookies as $cookie) {
if (strpos($cookie, 'SESSID') !== false) {
$result = $cookie;
}
}
return $result;
} | php | public function getCookie(ResponseInterface $response)
{
$result = null;
$cookies = $response->getHeader('Set-Cookie');
foreach ($cookies as $cookie) {
if (strpos($cookie, 'SESSID') !== false) {
$result = $cookie;
}
}
return $result;
} | [
"public",
"function",
"getCookie",
"(",
"ResponseInterface",
"$",
"response",
")",
"{",
"$",
"result",
"=",
"null",
";",
"$",
"cookies",
"=",
"$",
"response",
"->",
"getHeader",
"(",
"'Set-Cookie'",
")",
";",
"foreach",
"(",
"$",
"cookies",
"as",
"$",
"c... | Get PHPSESSID or SECSESSID cookie set from the response if it exists.
@param ResponseInterface $response
@return string|null Cookie contents or null if it doesn't exist | [
"Get",
"PHPSESSID",
"or",
"SECSESSID",
"cookie",
"set",
"from",
"the",
"response",
"if",
"it",
"exists",
"."
] | 6fe0b1889e60678ed374735f037c4e69a87041bb | https://github.com/silverstripe/silverstripe-environmentcheck/blob/6fe0b1889e60678ed374735f037c4e69a87041bb/src/Checks/SessionCheck.php#L59-L70 | train |
phalapi/cli | src/Ulrichsg/Getopt/Getopt.php | Getopt.addOptions | public function addOptions($options)
{
if (is_string($options)) {
$this->mergeOptions($this->optionParser->parseString($options));
} elseif (is_array($options)) {
$this->mergeOptions($this->optionParser->parseArray($options));
} else {
throw new \InvalidArgumentException("Getopt(): argument must be string or array");
}
} | php | public function addOptions($options)
{
if (is_string($options)) {
$this->mergeOptions($this->optionParser->parseString($options));
} elseif (is_array($options)) {
$this->mergeOptions($this->optionParser->parseArray($options));
} else {
throw new \InvalidArgumentException("Getopt(): argument must be string or array");
}
} | [
"public",
"function",
"addOptions",
"(",
"$",
"options",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"options",
")",
")",
"{",
"$",
"this",
"->",
"mergeOptions",
"(",
"$",
"this",
"->",
"optionParser",
"->",
"parseString",
"(",
"$",
"options",
")",
")"... | Extends the list of known options. Takes the same argument types as the constructor.
@param mixed $options
@throws \InvalidArgumentException | [
"Extends",
"the",
"list",
"of",
"known",
"options",
".",
"Takes",
"the",
"same",
"argument",
"types",
"as",
"the",
"constructor",
"."
] | c5df41e5fa483ad5990296421cde808a0d29f36f | https://github.com/phalapi/cli/blob/c5df41e5fa483ad5990296421cde808a0d29f36f/src/Ulrichsg/Getopt/Getopt.php#L58-L67 | train |
phalapi/cli | src/Ulrichsg/Getopt/Getopt.php | Getopt.mergeOptions | private function mergeOptions(array $options)
{
/** @var Option[] $mergedList */
$mergedList = array_merge($this->optionList, $options);
$duplicates = array();
foreach ($mergedList as $option) {
foreach ($mergedList as $otherOption) {
if (($option === $otherOption) || in_array($otherOption, $duplicates)) {
continue;
}
if ($this->optionsConflict($option, $otherOption)) {
throw new \InvalidArgumentException('Failed to add options due to conflict');
}
if (($option->short() === $otherOption->short()) && ($option->long() === $otherOption->long())) {
$duplicates[] = $option;
}
}
}
foreach ($mergedList as $index => $option) {
if (in_array($option, $duplicates)) {
unset($mergedList[$index]);
}
}
$this->optionList = array_values($mergedList);
} | php | private function mergeOptions(array $options)
{
/** @var Option[] $mergedList */
$mergedList = array_merge($this->optionList, $options);
$duplicates = array();
foreach ($mergedList as $option) {
foreach ($mergedList as $otherOption) {
if (($option === $otherOption) || in_array($otherOption, $duplicates)) {
continue;
}
if ($this->optionsConflict($option, $otherOption)) {
throw new \InvalidArgumentException('Failed to add options due to conflict');
}
if (($option->short() === $otherOption->short()) && ($option->long() === $otherOption->long())) {
$duplicates[] = $option;
}
}
}
foreach ($mergedList as $index => $option) {
if (in_array($option, $duplicates)) {
unset($mergedList[$index]);
}
}
$this->optionList = array_values($mergedList);
} | [
"private",
"function",
"mergeOptions",
"(",
"array",
"$",
"options",
")",
"{",
"/** @var Option[] $mergedList */",
"$",
"mergedList",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"optionList",
",",
"$",
"options",
")",
";",
"$",
"duplicates",
"=",
"array",
"(",... | Merges new options with the ones already in the Getopt optionList, making sure the resulting list is free of
conflicts.
@param Option[] $options The list of new options
@throws \InvalidArgumentException | [
"Merges",
"new",
"options",
"with",
"the",
"ones",
"already",
"in",
"the",
"Getopt",
"optionList",
"making",
"sure",
"the",
"resulting",
"list",
"is",
"free",
"of",
"conflicts",
"."
] | c5df41e5fa483ad5990296421cde808a0d29f36f | https://github.com/phalapi/cli/blob/c5df41e5fa483ad5990296421cde808a0d29f36f/src/Ulrichsg/Getopt/Getopt.php#L76-L100 | train |
phalapi/cli | src/Ulrichsg/Getopt/Getopt.php | Getopt.parse | public function parse($arguments = null)
{
$this->options = array();
if (!isset($arguments)) {
global $argv;
$arguments = $argv;
$this->scriptName = array_shift($arguments); // $argv[0] is the script's name
} elseif (is_string($arguments)) {
$this->scriptName = $_SERVER['PHP_SELF'];
$arguments = explode(' ', $arguments);
}
$parser = new CommandLineParser($this->optionList);
$parser->parse($arguments);
$this->options = $parser->getOptions();
$this->operands = $parser->getOperands();
} | php | public function parse($arguments = null)
{
$this->options = array();
if (!isset($arguments)) {
global $argv;
$arguments = $argv;
$this->scriptName = array_shift($arguments); // $argv[0] is the script's name
} elseif (is_string($arguments)) {
$this->scriptName = $_SERVER['PHP_SELF'];
$arguments = explode(' ', $arguments);
}
$parser = new CommandLineParser($this->optionList);
$parser->parse($arguments);
$this->options = $parser->getOptions();
$this->operands = $parser->getOperands();
} | [
"public",
"function",
"parse",
"(",
"$",
"arguments",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"options",
"=",
"array",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"arguments",
")",
")",
"{",
"global",
"$",
"argv",
";",
"$",
"arguments",
"... | Evaluate the given arguments. These can be passed either as a string or as an array.
If nothing is passed, the running script's command line arguments are used.
An {@link \UnexpectedValueException} or {@link \InvalidArgumentException} is thrown
when the arguments are not well-formed or do not conform to the options passed by the user.
@param mixed $arguments optional ARGV array or space separated string | [
"Evaluate",
"the",
"given",
"arguments",
".",
"These",
"can",
"be",
"passed",
"either",
"as",
"a",
"string",
"or",
"as",
"an",
"array",
".",
"If",
"nothing",
"is",
"passed",
"the",
"running",
"script",
"s",
"command",
"line",
"arguments",
"are",
"used",
... | c5df41e5fa483ad5990296421cde808a0d29f36f | https://github.com/phalapi/cli/blob/c5df41e5fa483ad5990296421cde808a0d29f36f/src/Ulrichsg/Getopt/Getopt.php#L120-L136 | train |
phalapi/cli | src/Ulrichsg/Getopt/Getopt.php | Getopt.getHelpText | public function getHelpText($padding = 25)
{
$helpText = sprintf($this->getBanner(), $this->scriptName);
$helpText .= "Options:\n";
foreach ($this->optionList as $option) {
$mode = '';
switch ($option->mode()) {
case self::NO_ARGUMENT:
$mode = '';
break;
case self::REQUIRED_ARGUMENT:
$mode = "<".$option->getArgument()->getName().">";
break;
case self::OPTIONAL_ARGUMENT:
$mode = "[<".$option->getArgument()->getName().">]";
break;
}
$short = ($option->short()) ? '-'.$option->short() : '';
$long = ($option->long()) ? '--'.$option->long() : '';
if ($short && $long) {
$options = $short.', '.$long;
} else {
$options = $short ? : $long;
}
$padded = str_pad(sprintf(" %s %s", $options, $mode), $padding);
$helpText .= sprintf("%s %s\n", $padded, $option->getDescription());
}
return $helpText;
} | php | public function getHelpText($padding = 25)
{
$helpText = sprintf($this->getBanner(), $this->scriptName);
$helpText .= "Options:\n";
foreach ($this->optionList as $option) {
$mode = '';
switch ($option->mode()) {
case self::NO_ARGUMENT:
$mode = '';
break;
case self::REQUIRED_ARGUMENT:
$mode = "<".$option->getArgument()->getName().">";
break;
case self::OPTIONAL_ARGUMENT:
$mode = "[<".$option->getArgument()->getName().">]";
break;
}
$short = ($option->short()) ? '-'.$option->short() : '';
$long = ($option->long()) ? '--'.$option->long() : '';
if ($short && $long) {
$options = $short.', '.$long;
} else {
$options = $short ? : $long;
}
$padded = str_pad(sprintf(" %s %s", $options, $mode), $padding);
$helpText .= sprintf("%s %s\n", $padded, $option->getDescription());
}
return $helpText;
} | [
"public",
"function",
"getHelpText",
"(",
"$",
"padding",
"=",
"25",
")",
"{",
"$",
"helpText",
"=",
"sprintf",
"(",
"$",
"this",
"->",
"getBanner",
"(",
")",
",",
"$",
"this",
"->",
"scriptName",
")",
";",
"$",
"helpText",
".=",
"\"Options:\\n\"",
";"... | Returns an usage information text generated from the given options.
@param int $padding Number of characters to pad output of options to
@return string | [
"Returns",
"an",
"usage",
"information",
"text",
"generated",
"from",
"the",
"given",
"options",
"."
] | c5df41e5fa483ad5990296421cde808a0d29f36f | https://github.com/phalapi/cli/blob/c5df41e5fa483ad5990296421cde808a0d29f36f/src/Ulrichsg/Getopt/Getopt.php#L217-L245 | train |
phalapi/cli | src/Ulrichsg/Getopt/OptionParser.php | OptionParser.parseString | public function parseString($string)
{
if (!mb_strlen($string)) {
throw new \InvalidArgumentException('Option string must not be empty');
}
$options = array();
$eol = mb_strlen($string) - 1;
$nextCanBeColon = false;
for ($i = 0; $i <= $eol; ++$i) {
$ch = $string[$i];
if (!preg_match('/^[A-Za-z0-9]$/', $ch)) {
$colon = $nextCanBeColon ? " or ':'" : '';
throw new \InvalidArgumentException("Option string is not well formed: "
."expected a letter$colon, found '$ch' at position ".($i + 1));
}
if ($i == $eol || $string[$i + 1] != ':') {
$options[] = new Option($ch, null, Getopt::NO_ARGUMENT);
$nextCanBeColon = true;
} elseif ($i < $eol - 1 && $string[$i + 2] == ':') {
$options[] = new Option($ch, null, Getopt::OPTIONAL_ARGUMENT);
$i += 2;
$nextCanBeColon = false;
} else {
$options[] = new Option($ch, null, Getopt::REQUIRED_ARGUMENT);
++$i;
$nextCanBeColon = true;
}
}
return $options;
} | php | public function parseString($string)
{
if (!mb_strlen($string)) {
throw new \InvalidArgumentException('Option string must not be empty');
}
$options = array();
$eol = mb_strlen($string) - 1;
$nextCanBeColon = false;
for ($i = 0; $i <= $eol; ++$i) {
$ch = $string[$i];
if (!preg_match('/^[A-Za-z0-9]$/', $ch)) {
$colon = $nextCanBeColon ? " or ':'" : '';
throw new \InvalidArgumentException("Option string is not well formed: "
."expected a letter$colon, found '$ch' at position ".($i + 1));
}
if ($i == $eol || $string[$i + 1] != ':') {
$options[] = new Option($ch, null, Getopt::NO_ARGUMENT);
$nextCanBeColon = true;
} elseif ($i < $eol - 1 && $string[$i + 2] == ':') {
$options[] = new Option($ch, null, Getopt::OPTIONAL_ARGUMENT);
$i += 2;
$nextCanBeColon = false;
} else {
$options[] = new Option($ch, null, Getopt::REQUIRED_ARGUMENT);
++$i;
$nextCanBeColon = true;
}
}
return $options;
} | [
"public",
"function",
"parseString",
"(",
"$",
"string",
")",
"{",
"if",
"(",
"!",
"mb_strlen",
"(",
"$",
"string",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Option string must not be empty'",
")",
";",
"}",
"$",
"options",
"=",... | Parse a GNU-style option string.
@param string $string the option string
@return Option[]
@throws \InvalidArgumentException | [
"Parse",
"a",
"GNU",
"-",
"style",
"option",
"string",
"."
] | c5df41e5fa483ad5990296421cde808a0d29f36f | https://github.com/phalapi/cli/blob/c5df41e5fa483ad5990296421cde808a0d29f36f/src/Ulrichsg/Getopt/OptionParser.php#L28-L57 | train |
phalapi/cli | src/Ulrichsg/Getopt/CommandLineParser.php | CommandLineParser.parse | public function parse($arguments)
{
if (!is_array($arguments)) {
$arguments = explode(' ', $arguments);
}
$operands = array();
$numArgs = count($arguments);
for ($i = 0; $i < $numArgs; ++$i) {
$arg = trim($arguments[$i]);
if (empty($arg)) {
continue;
}
if (($arg === '--') || ($arg === '-') || (mb_substr($arg, 0, 1) !== '-')){
// no more options, treat the remaining arguments as operands
$firstOperandIndex = ($arg == '--') ? $i + 1 : $i;
$operands = array_slice($arguments, $firstOperandIndex);
break;
}
if (mb_substr($arg, 0, 2) == '--') {
$this->addLongOption($arguments, $i);
} else {
$this->addShortOption($arguments, $i);
}
} // endfor
$this->addDefaultValues();
// remove '--' from operands array
foreach ($operands as $operand) {
if ($operand !== '--') {
$this->operands[] = $operand;
}
}
} | php | public function parse($arguments)
{
if (!is_array($arguments)) {
$arguments = explode(' ', $arguments);
}
$operands = array();
$numArgs = count($arguments);
for ($i = 0; $i < $numArgs; ++$i) {
$arg = trim($arguments[$i]);
if (empty($arg)) {
continue;
}
if (($arg === '--') || ($arg === '-') || (mb_substr($arg, 0, 1) !== '-')){
// no more options, treat the remaining arguments as operands
$firstOperandIndex = ($arg == '--') ? $i + 1 : $i;
$operands = array_slice($arguments, $firstOperandIndex);
break;
}
if (mb_substr($arg, 0, 2) == '--') {
$this->addLongOption($arguments, $i);
} else {
$this->addShortOption($arguments, $i);
}
} // endfor
$this->addDefaultValues();
// remove '--' from operands array
foreach ($operands as $operand) {
if ($operand !== '--') {
$this->operands[] = $operand;
}
}
} | [
"public",
"function",
"parse",
"(",
"$",
"arguments",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"arguments",
")",
")",
"{",
"$",
"arguments",
"=",
"explode",
"(",
"' '",
",",
"$",
"arguments",
")",
";",
"}",
"$",
"operands",
"=",
"array",
"("... | Parses the given arguments and converts them into options and operands.
@param mixed $arguments a string or an array with one argument per element | [
"Parses",
"the",
"given",
"arguments",
"and",
"converts",
"them",
"into",
"options",
"and",
"operands",
"."
] | c5df41e5fa483ad5990296421cde808a0d29f36f | https://github.com/phalapi/cli/blob/c5df41e5fa483ad5990296421cde808a0d29f36f/src/Ulrichsg/Getopt/CommandLineParser.php#L31-L64 | train |
phalapi/cli | src/Ulrichsg/Getopt/CommandLineParser.php | CommandLineParser.optionHasArgument | private function optionHasArgument($name)
{
foreach ($this->optionList as $option) {
if ($option->matches($name)) {
return $option->mode() != Getopt::NO_ARGUMENT;
}
}
return false;
} | php | private function optionHasArgument($name)
{
foreach ($this->optionList as $option) {
if ($option->matches($name)) {
return $option->mode() != Getopt::NO_ARGUMENT;
}
}
return false;
} | [
"private",
"function",
"optionHasArgument",
"(",
"$",
"name",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"optionList",
"as",
"$",
"option",
")",
"{",
"if",
"(",
"$",
"option",
"->",
"matches",
"(",
"$",
"name",
")",
")",
"{",
"return",
"$",
"option... | Return true if the given option can take an argument, false if it can't or is unknown.
@param string $name the option's name
@return boolean | [
"Return",
"true",
"if",
"the",
"given",
"option",
"can",
"take",
"an",
"argument",
"false",
"if",
"it",
"can",
"t",
"or",
"is",
"unknown",
"."
] | c5df41e5fa483ad5990296421cde808a0d29f36f | https://github.com/phalapi/cli/blob/c5df41e5fa483ad5990296421cde808a0d29f36f/src/Ulrichsg/Getopt/CommandLineParser.php#L216-L224 | train |
phalapi/cli | src/Ulrichsg/Getopt/CommandLineParser.php | CommandLineParser.splitString | private function splitString($string)
{
$result = array();
for ($i = 0; $i < mb_strlen($string, "UTF-8"); ++$i) {
$result[] = mb_substr($string, $i, 1, "UTF-8");
}
return $result;
} | php | private function splitString($string)
{
$result = array();
for ($i = 0; $i < mb_strlen($string, "UTF-8"); ++$i) {
$result[] = mb_substr($string, $i, 1, "UTF-8");
}
return $result;
} | [
"private",
"function",
"splitString",
"(",
"$",
"string",
")",
"{",
"$",
"result",
"=",
"array",
"(",
")",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"mb_strlen",
"(",
"$",
"string",
",",
"\"UTF-8\"",
")",
";",
"++",
"$",
"i",
")"... | Split the string into individual characters,
@param string $string string to split
@return array | [
"Split",
"the",
"string",
"into",
"individual",
"characters"
] | c5df41e5fa483ad5990296421cde808a0d29f36f | https://github.com/phalapi/cli/blob/c5df41e5fa483ad5990296421cde808a0d29f36f/src/Ulrichsg/Getopt/CommandLineParser.php#L232-L239 | train |
Algatux/influxdb-bundle | src/Form/Type/AbstractInfluxChoiceType.php | AbstractInfluxChoiceType.loadChoicesFromQuery | final protected function loadChoicesFromQuery(string $query, string $columnName, string $connectionName = null)
{
$connection = $connectionName
? $this->connectionRegistry->getHttpConnection($connectionName)
: $this->connectionRegistry->getDefaultHttpConnection()
;
$measurements = array_map(function ($point) use ($columnName) {
return $point[$columnName];
}, $connection->query($query)->getPoints());
return array_combine(array_values($measurements), $measurements);
} | php | final protected function loadChoicesFromQuery(string $query, string $columnName, string $connectionName = null)
{
$connection = $connectionName
? $this->connectionRegistry->getHttpConnection($connectionName)
: $this->connectionRegistry->getDefaultHttpConnection()
;
$measurements = array_map(function ($point) use ($columnName) {
return $point[$columnName];
}, $connection->query($query)->getPoints());
return array_combine(array_values($measurements), $measurements);
} | [
"final",
"protected",
"function",
"loadChoicesFromQuery",
"(",
"string",
"$",
"query",
",",
"string",
"$",
"columnName",
",",
"string",
"$",
"connectionName",
"=",
"null",
")",
"{",
"$",
"connection",
"=",
"$",
"connectionName",
"?",
"$",
"this",
"->",
"conn... | Executes the given query and converts the result to a proper choices list.
@param string $query
@param string $columnName
@param string|null $connectionName
@return array | [
"Executes",
"the",
"given",
"query",
"and",
"converts",
"the",
"result",
"to",
"a",
"proper",
"choices",
"list",
"."
] | 0945dbf0f5345d26897a99ea074e8f656ed49811 | https://github.com/Algatux/influxdb-bundle/blob/0945dbf0f5345d26897a99ea074e8f656ed49811/src/Form/Type/AbstractInfluxChoiceType.php#L65-L76 | train |
snowcap/SnowcapImBundle | Twig/Extension/ImExtension.php | ImExtension.convert | public function convert($html)
{
preg_match_all('|<img ([^>]+)>|', $html, $matches);
foreach($matches[0] as $img)
{
$crawler = new Crawler();
$crawler->addContent($img);
$imgTag = $crawler->filter("img");
$src = $imgTag->attr('src');
$width = $imgTag->attr('width');
$height = $imgTag->attr('height');
if (!empty($width) || !empty($height)) {
$format = $width . "x" . $height;
$updatedTagString = preg_replace("| src=[\"']" . $src . "[\"']|", " src=\"" . $this->imResize($src, $format) . "\"", $img);
$html = str_replace($img, $updatedTagString, $html);
}
}
return $html;
} | php | public function convert($html)
{
preg_match_all('|<img ([^>]+)>|', $html, $matches);
foreach($matches[0] as $img)
{
$crawler = new Crawler();
$crawler->addContent($img);
$imgTag = $crawler->filter("img");
$src = $imgTag->attr('src');
$width = $imgTag->attr('width');
$height = $imgTag->attr('height');
if (!empty($width) || !empty($height)) {
$format = $width . "x" . $height;
$updatedTagString = preg_replace("| src=[\"']" . $src . "[\"']|", " src=\"" . $this->imResize($src, $format) . "\"", $img);
$html = str_replace($img, $updatedTagString, $html);
}
}
return $html;
} | [
"public",
"function",
"convert",
"(",
"$",
"html",
")",
"{",
"preg_match_all",
"(",
"'|<img ([^>]+)>|'",
",",
"$",
"html",
",",
"$",
"matches",
")",
";",
"foreach",
"(",
"$",
"matches",
"[",
"0",
"]",
"as",
"$",
"img",
")",
"{",
"$",
"crawler",
"=",
... | Called by the compile method to replace the image sources with image cache sources
@param string $html
@return string | [
"Called",
"by",
"the",
"compile",
"method",
"to",
"replace",
"the",
"image",
"sources",
"with",
"image",
"cache",
"sources"
] | 2a15913b371e4b7d45d03a79c7decb620cce9c64 | https://github.com/snowcap/SnowcapImBundle/blob/2a15913b371e4b7d45d03a79c7decb620cce9c64/Twig/Extension/ImExtension.php#L78-L100 | train |
snowcap/SnowcapImBundle | Twig/Extension/ImExtension.php | ImExtension.imResize | public function imResize($path, $format)
{
// Remove extra whitespaces
$path = trim($path);
$separator = "";
// Transform absolute url to custom url like : http/ or https/ or simply /
if (strpos($path, "http://") === 0 || strpos($path, "https://") === 0 || strpos($path, "//") === 0) {
$path = str_replace(array("://", "//"), "/", $path);
} elseif (strpos($path, "/") === 0) {
// If the path started with a slash, we will add it at the start of the path result
$separator = "/";
}
// Remove the first slash, as we add it manually
$path = ltrim($path, '/');
return $separator . $this->manager->getCachePath() . '/' . $format . '/' . $path;
} | php | public function imResize($path, $format)
{
// Remove extra whitespaces
$path = trim($path);
$separator = "";
// Transform absolute url to custom url like : http/ or https/ or simply /
if (strpos($path, "http://") === 0 || strpos($path, "https://") === 0 || strpos($path, "//") === 0) {
$path = str_replace(array("://", "//"), "/", $path);
} elseif (strpos($path, "/") === 0) {
// If the path started with a slash, we will add it at the start of the path result
$separator = "/";
}
// Remove the first slash, as we add it manually
$path = ltrim($path, '/');
return $separator . $this->manager->getCachePath() . '/' . $format . '/' . $path;
} | [
"public",
"function",
"imResize",
"(",
"$",
"path",
",",
"$",
"format",
")",
"{",
"// Remove extra whitespaces",
"$",
"path",
"=",
"trim",
"(",
"$",
"path",
")",
";",
"$",
"separator",
"=",
"\"\"",
";",
"// Transform absolute url to custom url like : http/ or http... | Returns the cached path, after executing the asset twig function
@param string $path Path of the source file
@param string $format Imbundle format string
@return mixed | [
"Returns",
"the",
"cached",
"path",
"after",
"executing",
"the",
"asset",
"twig",
"function"
] | 2a15913b371e4b7d45d03a79c7decb620cce9c64 | https://github.com/snowcap/SnowcapImBundle/blob/2a15913b371e4b7d45d03a79c7decb620cce9c64/Twig/Extension/ImExtension.php#L110-L128 | train |
snowcap/SnowcapImBundle | Manager.php | Manager.convert | public function convert($format, $file)
{
$file = ltrim($file, '/');
$this->checkImage($file);
return $this->wrapper->run("convert", $this->getWebDirectory() . '/' . $file, $this->convertFormat($format), $this->getCacheDirectory() . '/' . $this->pathify($format) . '/' . $file);
} | php | public function convert($format, $file)
{
$file = ltrim($file, '/');
$this->checkImage($file);
return $this->wrapper->run("convert", $this->getWebDirectory() . '/' . $file, $this->convertFormat($format), $this->getCacheDirectory() . '/' . $this->pathify($format) . '/' . $file);
} | [
"public",
"function",
"convert",
"(",
"$",
"format",
",",
"$",
"file",
")",
"{",
"$",
"file",
"=",
"ltrim",
"(",
"$",
"file",
",",
"'/'",
")",
";",
"$",
"this",
"->",
"checkImage",
"(",
"$",
"file",
")",
";",
"return",
"$",
"this",
"->",
"wrapper... | Shortcut to run a "convert" command => creates a new image
@param string $format ImBundle format string
@param string $file Source file path
@return string
@codeCoverageIgnore | [
"Shortcut",
"to",
"run",
"a",
"convert",
"command",
"=",
">",
"creates",
"a",
"new",
"image"
] | 2a15913b371e4b7d45d03a79c7decb620cce9c64 | https://github.com/snowcap/SnowcapImBundle/blob/2a15913b371e4b7d45d03a79c7decb620cce9c64/Manager.php#L188-L194 | train |
snowcap/SnowcapImBundle | Manager.php | Manager.mogrify | public function mogrify($format, $file)
{
$this->checkImage($file);
return $this->wrapper->run("mogrify", $file, $this->convertFormat($format));
} | php | public function mogrify($format, $file)
{
$this->checkImage($file);
return $this->wrapper->run("mogrify", $file, $this->convertFormat($format));
} | [
"public",
"function",
"mogrify",
"(",
"$",
"format",
",",
"$",
"file",
")",
"{",
"$",
"this",
"->",
"checkImage",
"(",
"$",
"file",
")",
";",
"return",
"$",
"this",
"->",
"wrapper",
"->",
"run",
"(",
"\"mogrify\"",
",",
"$",
"file",
",",
"$",
"this... | Shortcut to run a "mogrify" command => modifies the image source
@param string $format ImBundle format string
@param string $file Source file path
@return string
@codeCoverageIgnore | [
"Shortcut",
"to",
"run",
"a",
"mogrify",
"command",
"=",
">",
"modifies",
"the",
"image",
"source"
] | 2a15913b371e4b7d45d03a79c7decb620cce9c64 | https://github.com/snowcap/SnowcapImBundle/blob/2a15913b371e4b7d45d03a79c7decb620cce9c64/Manager.php#L205-L210 | train |
snowcap/SnowcapImBundle | Manager.php | Manager.convertFormat | private function convertFormat($format)
{
if (is_array($format)) {
// sounds like the format is already done, let's keep it as it is
return $format;
}
if (array_key_exists($format, $this->formats)) {
// it's a format defined in config, let's use all defined parameters
return $this->formats[$format];
} elseif (preg_match("/^([0-9]*)x([0-9]*)/", $format)) {
// it's a custom [width]x[height] format, let's make a thumb
return array('thumbnail' => $format);
} else {
throw new InvalidArgumentException(sprintf("Unknown IM format: %s", $format));
}
} | php | private function convertFormat($format)
{
if (is_array($format)) {
// sounds like the format is already done, let's keep it as it is
return $format;
}
if (array_key_exists($format, $this->formats)) {
// it's a format defined in config, let's use all defined parameters
return $this->formats[$format];
} elseif (preg_match("/^([0-9]*)x([0-9]*)/", $format)) {
// it's a custom [width]x[height] format, let's make a thumb
return array('thumbnail' => $format);
} else {
throw new InvalidArgumentException(sprintf("Unknown IM format: %s", $format));
}
} | [
"private",
"function",
"convertFormat",
"(",
"$",
"format",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"format",
")",
")",
"{",
"// sounds like the format is already done, let's keep it as it is",
"return",
"$",
"format",
";",
"}",
"if",
"(",
"array_key_exists",
"... | Returns the attributes for converting the image regarding a specific format
@param string $format
@return array
@throws InvalidArgumentException | [
"Returns",
"the",
"attributes",
"for",
"converting",
"the",
"image",
"regarding",
"a",
"specific",
"format"
] | 2a15913b371e4b7d45d03a79c7decb620cce9c64 | https://github.com/snowcap/SnowcapImBundle/blob/2a15913b371e4b7d45d03a79c7decb620cce9c64/Manager.php#L250-L265 | train |
snowcap/SnowcapImBundle | Wrapper.php | Wrapper.run | public function run($command, $inputfile, $attributes = array(), $outputfile = "")
{
$commandString = $this->buildCommand($command, $inputfile, $attributes, $outputfile);
return $this->rawRun($commandString);
} | php | public function run($command, $inputfile, $attributes = array(), $outputfile = "")
{
$commandString = $this->buildCommand($command, $inputfile, $attributes, $outputfile);
return $this->rawRun($commandString);
} | [
"public",
"function",
"run",
"(",
"$",
"command",
",",
"$",
"inputfile",
",",
"$",
"attributes",
"=",
"array",
"(",
")",
",",
"$",
"outputfile",
"=",
"\"\"",
")",
"{",
"$",
"commandString",
"=",
"$",
"this",
"->",
"buildCommand",
"(",
"$",
"command",
... | Shortcut to construct & run an Imagemagick command
@param string $command @see _self::buildCommand
@param string $inputfile @see _self::buildCommand
@param array $attributes @see _self::buildCommand
@param string $outputfile @see _self::buildCommand
@return string
@codeCoverageIgnore | [
"Shortcut",
"to",
"construct",
"&",
"run",
"an",
"Imagemagick",
"command"
] | 2a15913b371e4b7d45d03a79c7decb620cce9c64 | https://github.com/snowcap/SnowcapImBundle/blob/2a15913b371e4b7d45d03a79c7decb620cce9c64/Wrapper.php#L67-L72 | train |
snowcap/SnowcapImBundle | Wrapper.php | Wrapper.prepareAttributes | private function prepareAttributes($attributes = array())
{
if (!is_array($attributes)) {
throw new InvalidArgumentException("[ImBundle] format attributes must be an array, recieved: " . var_export($attributes, true));
}
$result = "";
foreach ($attributes as $key => $value) {
if ($key === null || $key === "") {
$result .= " " . $value;
} else {
$result .= " -" . $key;
if ($value != "") {
$result .= " \"" . $value . "\"";
}
}
}
return $result;
} | php | private function prepareAttributes($attributes = array())
{
if (!is_array($attributes)) {
throw new InvalidArgumentException("[ImBundle] format attributes must be an array, recieved: " . var_export($attributes, true));
}
$result = "";
foreach ($attributes as $key => $value) {
if ($key === null || $key === "") {
$result .= " " . $value;
} else {
$result .= " -" . $key;
if ($value != "") {
$result .= " \"" . $value . "\"";
}
}
}
return $result;
} | [
"private",
"function",
"prepareAttributes",
"(",
"$",
"attributes",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"attributes",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"[ImBundle] format attributes must be an arr... | Takes an array of attributes and formats it as CLI parameters
@param array $attributes
@return string
@throws InvalidArgumentException | [
"Takes",
"an",
"array",
"of",
"attributes",
"and",
"formats",
"it",
"as",
"CLI",
"parameters"
] | 2a15913b371e4b7d45d03a79c7decb620cce9c64 | https://github.com/snowcap/SnowcapImBundle/blob/2a15913b371e4b7d45d03a79c7decb620cce9c64/Wrapper.php#L134-L152 | train |
snowcap/SnowcapImBundle | Wrapper.php | Wrapper.checkDirectory | public function checkDirectory($path)
{
$dir = dirname($path);
if (!is_dir($dir)) {
if (false === @mkdir($dir, 0777, true)) {
throw new RuntimeException(sprintf('Unable to create the "%s" directory', $dir));
}
}
} | php | public function checkDirectory($path)
{
$dir = dirname($path);
if (!is_dir($dir)) {
if (false === @mkdir($dir, 0777, true)) {
throw new RuntimeException(sprintf('Unable to create the "%s" directory', $dir));
}
}
} | [
"public",
"function",
"checkDirectory",
"(",
"$",
"path",
")",
"{",
"$",
"dir",
"=",
"dirname",
"(",
"$",
"path",
")",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"dir",
")",
")",
"{",
"if",
"(",
"false",
"===",
"@",
"mkdir",
"(",
"$",
"dir",
",",... | Creates the given directory if unexistant
@param string $path
@throws RuntimeException | [
"Creates",
"the",
"given",
"directory",
"if",
"unexistant"
] | 2a15913b371e4b7d45d03a79c7decb620cce9c64 | https://github.com/snowcap/SnowcapImBundle/blob/2a15913b371e4b7d45d03a79c7decb620cce9c64/Wrapper.php#L161-L169 | train |
snowcap/SnowcapImBundle | Wrapper.php | Wrapper.validateCommand | private function validateCommand($commandString)
{
$cmdParts = explode(" ", $commandString);
if (count($cmdParts) < 2) {
throw new InvalidArgumentException("This command isn't properly structured : '" . $commandString . "'");
}
$binaryPath = $cmdParts[0];
$binaryPathParts = explode('/', $binaryPath);
$binary = $binaryPathParts[count($binaryPathParts)-1];
if (!in_array($binary, $this->_acceptedBinaries)) {
throw new InvalidArgumentException("This command isn't part of the ImageMagick command line tools : '" . $binary . "'");
}
return true;
} | php | private function validateCommand($commandString)
{
$cmdParts = explode(" ", $commandString);
if (count($cmdParts) < 2) {
throw new InvalidArgumentException("This command isn't properly structured : '" . $commandString . "'");
}
$binaryPath = $cmdParts[0];
$binaryPathParts = explode('/', $binaryPath);
$binary = $binaryPathParts[count($binaryPathParts)-1];
if (!in_array($binary, $this->_acceptedBinaries)) {
throw new InvalidArgumentException("This command isn't part of the ImageMagick command line tools : '" . $binary . "'");
}
return true;
} | [
"private",
"function",
"validateCommand",
"(",
"$",
"commandString",
")",
"{",
"$",
"cmdParts",
"=",
"explode",
"(",
"\" \"",
",",
"$",
"commandString",
")",
";",
"if",
"(",
"count",
"(",
"$",
"cmdParts",
")",
"<",
"2",
")",
"{",
"throw",
"new",
"Inval... | Validates that the command launches a Imagemagick command line tool executable
@param string $commandString
@throws InvalidArgumentException
@return boolean | [
"Validates",
"that",
"the",
"command",
"launches",
"a",
"Imagemagick",
"command",
"line",
"tool",
"executable"
] | 2a15913b371e4b7d45d03a79c7decb620cce9c64 | https://github.com/snowcap/SnowcapImBundle/blob/2a15913b371e4b7d45d03a79c7decb620cce9c64/Wrapper.php#L179-L196 | train |
grrr-amsterdam/garp3 | library/Garp/Auth.php | Garp_Auth.isLoggedIn | public function isLoggedIn() {
$hasUserData = isset($this->_store->userData);
$hasLoginMethod = isset($this->_store->method);
$hasValidToken = isset($this->_store->token) && $this->validateToken();
$isLoggedIn = $hasUserData && $hasLoginMethod && $hasValidToken;
// Don't leave invalid cookies laying around.
// Clear data only when data is present, but it is invalid.
if ($hasUserData && $hasLoginMethod && !$hasValidToken) {
$this->_store->userData = null;
$this->_store->method = null;
}
return $isLoggedIn;
} | php | public function isLoggedIn() {
$hasUserData = isset($this->_store->userData);
$hasLoginMethod = isset($this->_store->method);
$hasValidToken = isset($this->_store->token) && $this->validateToken();
$isLoggedIn = $hasUserData && $hasLoginMethod && $hasValidToken;
// Don't leave invalid cookies laying around.
// Clear data only when data is present, but it is invalid.
if ($hasUserData && $hasLoginMethod && !$hasValidToken) {
$this->_store->userData = null;
$this->_store->method = null;
}
return $isLoggedIn;
} | [
"public",
"function",
"isLoggedIn",
"(",
")",
"{",
"$",
"hasUserData",
"=",
"isset",
"(",
"$",
"this",
"->",
"_store",
"->",
"userData",
")",
";",
"$",
"hasLoginMethod",
"=",
"isset",
"(",
"$",
"this",
"->",
"_store",
"->",
"method",
")",
";",
"$",
"... | Check if a user is logged in
@return Boolean | [
"Check",
"if",
"a",
"user",
"is",
"logged",
"in"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Auth.php#L96-L109 | train |
grrr-amsterdam/garp3 | library/Garp/Auth.php | Garp_Auth.createToken | public function createToken($input) {
$config = $this->getConfigValues();
$salt = $config['salt'];
$token = '';
$token .= !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$token .= md5($input);
$token .= md5($salt);
/**
* Embed an outline of the User table columns in the token. That way, whenever the
* database changes, all current cookies are made invalid and users have to generate a
* new cookie afresh by logging in.
* This ensures the user cookies always contains all the columns.
*/
$columns = '';
try {
$userModel = new Model_User();
$columns = $userModel->info(Zend_Db_Table_Abstract::COLS);
$columns = implode('.', $columns);
} catch (Zend_Db_Adapter_Exception $e) {
Garp_ErrorHandler::handlePrematureException($e);
}
$token .= $columns;
$token = md5($token);
return $token;
} | php | public function createToken($input) {
$config = $this->getConfigValues();
$salt = $config['salt'];
$token = '';
$token .= !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$token .= md5($input);
$token .= md5($salt);
/**
* Embed an outline of the User table columns in the token. That way, whenever the
* database changes, all current cookies are made invalid and users have to generate a
* new cookie afresh by logging in.
* This ensures the user cookies always contains all the columns.
*/
$columns = '';
try {
$userModel = new Model_User();
$columns = $userModel->info(Zend_Db_Table_Abstract::COLS);
$columns = implode('.', $columns);
} catch (Zend_Db_Adapter_Exception $e) {
Garp_ErrorHandler::handlePrematureException($e);
}
$token .= $columns;
$token = md5($token);
return $token;
} | [
"public",
"function",
"createToken",
"(",
"$",
"input",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"getConfigValues",
"(",
")",
";",
"$",
"salt",
"=",
"$",
"config",
"[",
"'salt'",
"]",
";",
"$",
"token",
"=",
"''",
";",
"$",
"token",
".=",
... | Create a unique token for the currently logged in user.
@param String $input Serialized user data
@return String | [
"Create",
"a",
"unique",
"token",
"for",
"the",
"currently",
"logged",
"in",
"user",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Auth.php#L133-L161 | train |
grrr-amsterdam/garp3 | library/Garp/Auth.php | Garp_Auth.validateToken | public function validateToken() {
$userData = $this->_store->userData;
$currToken = $this->_store->token;
$checkToken = $this->createToken(serialize($userData));
return $checkToken === $currToken;
} | php | public function validateToken() {
$userData = $this->_store->userData;
$currToken = $this->_store->token;
$checkToken = $this->createToken(serialize($userData));
return $checkToken === $currToken;
} | [
"public",
"function",
"validateToken",
"(",
")",
"{",
"$",
"userData",
"=",
"$",
"this",
"->",
"_store",
"->",
"userData",
";",
"$",
"currToken",
"=",
"$",
"this",
"->",
"_store",
"->",
"token",
";",
"$",
"checkToken",
"=",
"$",
"this",
"->",
"createTo... | Validate the current token
@return Boolean | [
"Validate",
"the",
"current",
"token"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Auth.php#L167-L172 | train |
grrr-amsterdam/garp3 | library/Garp/Auth.php | Garp_Auth.store | public function store($data, $method = 'db') {
$token = $this->createToken(serialize($data));
$this->_store->userData = $data;
$this->_store->method = $method;
$this->_store->token = $token;
return $this;
} | php | public function store($data, $method = 'db') {
$token = $this->createToken(serialize($data));
$this->_store->userData = $data;
$this->_store->method = $method;
$this->_store->token = $token;
return $this;
} | [
"public",
"function",
"store",
"(",
"$",
"data",
",",
"$",
"method",
"=",
"'db'",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"createToken",
"(",
"serialize",
"(",
"$",
"data",
")",
")",
";",
"$",
"this",
"->",
"_store",
"->",
"userData",
"=",
... | Store user data in session
@param Mixed $data The user data
@param String $method The method used to login
@return Void | [
"Store",
"user",
"data",
"in",
"session"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Auth.php#L180-L186 | train |
grrr-amsterdam/garp3 | library/Garp/Auth.php | Garp_Auth.getConfigValues | public function getConfigValues($subSection = null) {
$config = Zend_Registry::get('config');
// set defaults
$values = $this->_defaultConfigValues;
if ($config->auth) {
$values = array_merge($values, $config->auth->toArray());
}
if ($subSection) {
return array_get($values, $subSection);
}
return $values;
} | php | public function getConfigValues($subSection = null) {
$config = Zend_Registry::get('config');
// set defaults
$values = $this->_defaultConfigValues;
if ($config->auth) {
$values = array_merge($values, $config->auth->toArray());
}
if ($subSection) {
return array_get($values, $subSection);
}
return $values;
} | [
"public",
"function",
"getConfigValues",
"(",
"$",
"subSection",
"=",
"null",
")",
"{",
"$",
"config",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"// set defaults",
"$",
"values",
"=",
"$",
"this",
"->",
"_defaultConfigValues",
";",
"if",
... | Retrieve auth-related config values from application.ini
@return Array | [
"Retrieve",
"auth",
"-",
"related",
"config",
"values",
"from",
"application",
".",
"ini"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Auth.php#L200-L211 | train |
grrr-amsterdam/garp3 | library/Garp/Auth.php | Garp_Auth.getCurrentRole | public function getCurrentRole() {
$role = self::DEFAULT_VISITOR_ROLE;
if ($this->isLoggedIn()) {
$role = self::DEFAULT_USER_ROLE;
$data = $this->getUserData();
if (isset($data[self::ROLE_COLUMN])) {
$role = $data[self::ROLE_COLUMN];
}
}
return $role;
} | php | public function getCurrentRole() {
$role = self::DEFAULT_VISITOR_ROLE;
if ($this->isLoggedIn()) {
$role = self::DEFAULT_USER_ROLE;
$data = $this->getUserData();
if (isset($data[self::ROLE_COLUMN])) {
$role = $data[self::ROLE_COLUMN];
}
}
return $role;
} | [
"public",
"function",
"getCurrentRole",
"(",
")",
"{",
"$",
"role",
"=",
"self",
"::",
"DEFAULT_VISITOR_ROLE",
";",
"if",
"(",
"$",
"this",
"->",
"isLoggedIn",
"(",
")",
")",
"{",
"$",
"role",
"=",
"self",
"::",
"DEFAULT_USER_ROLE",
";",
"$",
"data",
"... | Get the role associated with the current session.
Note that an anonymous session, where nobody is logged in also has a role associated with it.
@return String The role | [
"Get",
"the",
"role",
"associated",
"with",
"the",
"current",
"session",
".",
"Note",
"that",
"an",
"anonymous",
"session",
"where",
"nobody",
"is",
"logged",
"in",
"also",
"has",
"a",
"role",
"associated",
"with",
"it",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Auth.php#L239-L249 | train |
grrr-amsterdam/garp3 | library/Garp/Auth.php | Garp_Auth.getRoles | public function getRoles($verbose = false) {
if (Zend_Registry::isRegistered('Zend_Acl')) {
$acl = Zend_Registry::get('Zend_Acl');
$roles = $acl->getRoles();
// collect parents
if ($verbose) {
$roles = array_fill_keys($roles, array());
foreach (array_keys($roles) as $role) {
$roles[$role]['parents'] = $this->getRoleParents($role);
$roles[$role]['children'] = $this->getRoleChildren($role);
}
}
return $roles;
}
return array();
} | php | public function getRoles($verbose = false) {
if (Zend_Registry::isRegistered('Zend_Acl')) {
$acl = Zend_Registry::get('Zend_Acl');
$roles = $acl->getRoles();
// collect parents
if ($verbose) {
$roles = array_fill_keys($roles, array());
foreach (array_keys($roles) as $role) {
$roles[$role]['parents'] = $this->getRoleParents($role);
$roles[$role]['children'] = $this->getRoleChildren($role);
}
}
return $roles;
}
return array();
} | [
"public",
"function",
"getRoles",
"(",
"$",
"verbose",
"=",
"false",
")",
"{",
"if",
"(",
"Zend_Registry",
"::",
"isRegistered",
"(",
"'Zend_Acl'",
")",
")",
"{",
"$",
"acl",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'Zend_Acl'",
")",
";",
"$",
"roles",
... | Return all available roles from the ACL tree.
@param Boolean $verbose Wether to include a role's parents
@return Array A numeric array consisting of role strings | [
"Return",
"all",
"available",
"roles",
"from",
"the",
"ACL",
"tree",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Auth.php#L256-L272 | train |
grrr-amsterdam/garp3 | library/Garp/Auth.php | Garp_Auth.getRoleParents | public function getRoleParents($role, $onlyParents = true) {
$parents = array();
if (Zend_Registry::isRegistered('Zend_Acl')) {
$acl = Zend_Registry::get('Zend_Acl');
$roles = $acl->getRoles();
foreach ($roles as $potentialParent) {
if ($acl->inheritsRole($role, $potentialParent, $onlyParents)) {
$parents[] = $potentialParent;
}
}
}
return $parents;
} | php | public function getRoleParents($role, $onlyParents = true) {
$parents = array();
if (Zend_Registry::isRegistered('Zend_Acl')) {
$acl = Zend_Registry::get('Zend_Acl');
$roles = $acl->getRoles();
foreach ($roles as $potentialParent) {
if ($acl->inheritsRole($role, $potentialParent, $onlyParents)) {
$parents[] = $potentialParent;
}
}
}
return $parents;
} | [
"public",
"function",
"getRoleParents",
"(",
"$",
"role",
",",
"$",
"onlyParents",
"=",
"true",
")",
"{",
"$",
"parents",
"=",
"array",
"(",
")",
";",
"if",
"(",
"Zend_Registry",
"::",
"isRegistered",
"(",
"'Zend_Acl'",
")",
")",
"{",
"$",
"acl",
"=",
... | Return the parents of a given role
@param String $role
@param Boolean $onlyParents Wether to only return direct parents
@return Array | [
"Return",
"the",
"parents",
"of",
"a",
"given",
"role"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Auth.php#L280-L293 | train |
grrr-amsterdam/garp3 | library/Garp/Auth.php | Garp_Auth.getRoleChildren | public function getRoleChildren($role) {
$children = array();
if (Zend_Registry::isRegistered('Zend_Acl')) {
$acl = Zend_Registry::get('Zend_Acl');
$roles = $acl->getRoles();
foreach ($roles as $potentialChild) {
if ($acl->inheritsRole($potentialChild, $role)) {
$children[] = $potentialChild;
}
}
}
return $children;
} | php | public function getRoleChildren($role) {
$children = array();
if (Zend_Registry::isRegistered('Zend_Acl')) {
$acl = Zend_Registry::get('Zend_Acl');
$roles = $acl->getRoles();
foreach ($roles as $potentialChild) {
if ($acl->inheritsRole($potentialChild, $role)) {
$children[] = $potentialChild;
}
}
}
return $children;
} | [
"public",
"function",
"getRoleChildren",
"(",
"$",
"role",
")",
"{",
"$",
"children",
"=",
"array",
"(",
")",
";",
"if",
"(",
"Zend_Registry",
"::",
"isRegistered",
"(",
"'Zend_Acl'",
")",
")",
"{",
"$",
"acl",
"=",
"Zend_Registry",
"::",
"get",
"(",
"... | Return the children of a given role
@param String $role
@return Array | [
"Return",
"the",
"children",
"of",
"a",
"given",
"role"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Auth.php#L300-L313 | train |
grrr-amsterdam/garp3 | library/Garp/Auth.php | Garp_Auth.getSessionColumns | public function getSessionColumns() {
$ini = Zend_Registry::get('config');
$sessionColumns = Zend_Db_Select::SQL_WILDCARD;
if (!empty($ini->auth->login->sessionColumns)) {
$sessionColumns = $ini->auth->login->sessionColumns;
$sessionColumns = explode(',', $sessionColumns);
}
return $sessionColumns;
} | php | public function getSessionColumns() {
$ini = Zend_Registry::get('config');
$sessionColumns = Zend_Db_Select::SQL_WILDCARD;
if (!empty($ini->auth->login->sessionColumns)) {
$sessionColumns = $ini->auth->login->sessionColumns;
$sessionColumns = explode(',', $sessionColumns);
}
return $sessionColumns;
} | [
"public",
"function",
"getSessionColumns",
"(",
")",
"{",
"$",
"ini",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"$",
"sessionColumns",
"=",
"Zend_Db_Select",
"::",
"SQL_WILDCARD",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"ini",
"->",
"... | Return which columns should be stored in the user session | [
"Return",
"which",
"columns",
"should",
"be",
"stored",
"in",
"the",
"user",
"session"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Auth.php#L318-L326 | train |
grrr-amsterdam/garp3 | library/Garp/Auth.php | Garp_Auth._getSnippetModel | protected function _getSnippetModel() {
$snippetModel = new Model_Snippet();
if ($snippetModel->getObserver('Translatable')) {
$i18nModelFactory = new Garp_I18n_ModelFactory();
$snippetModel = $i18nModelFactory->getModel($snippetModel);
}
return $snippetModel;
} | php | protected function _getSnippetModel() {
$snippetModel = new Model_Snippet();
if ($snippetModel->getObserver('Translatable')) {
$i18nModelFactory = new Garp_I18n_ModelFactory();
$snippetModel = $i18nModelFactory->getModel($snippetModel);
}
return $snippetModel;
} | [
"protected",
"function",
"_getSnippetModel",
"(",
")",
"{",
"$",
"snippetModel",
"=",
"new",
"Model_Snippet",
"(",
")",
";",
"if",
"(",
"$",
"snippetModel",
"->",
"getObserver",
"(",
"'Translatable'",
")",
")",
"{",
"$",
"i18nModelFactory",
"=",
"new",
"Garp... | Retrieve snippet model for system messages. | [
"Retrieve",
"snippet",
"model",
"for",
"system",
"messages",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Auth.php#L393-L400 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Api/Rest.php | Garp_Content_Api_Rest.post | public function post(array $params, array $postData) {
$this->_validatePostParams($params, $postData);
$model = $this->_normalizeModelName($params['datatype']);
$contentManager = $this->_getContentManager($model);
$primaryKey = $contentManager->create($postData);
$record = array_get(
array_get(
$this->get(
array(
'datatype' => $params['datatype'],
'id' => $primaryKey
)
),
'data',
array()
),
'result',
array()
);
$response = array(
'success' => true,
'result' => $record,
'link' => (string)new Garp_Util_FullUrl(
array(array('datatype' => $params['datatype'], 'id' => $primaryKey), 'rest')
)
);
return $this->_formatResponse($response, 201);
} | php | public function post(array $params, array $postData) {
$this->_validatePostParams($params, $postData);
$model = $this->_normalizeModelName($params['datatype']);
$contentManager = $this->_getContentManager($model);
$primaryKey = $contentManager->create($postData);
$record = array_get(
array_get(
$this->get(
array(
'datatype' => $params['datatype'],
'id' => $primaryKey
)
),
'data',
array()
),
'result',
array()
);
$response = array(
'success' => true,
'result' => $record,
'link' => (string)new Garp_Util_FullUrl(
array(array('datatype' => $params['datatype'], 'id' => $primaryKey), 'rest')
)
);
return $this->_formatResponse($response, 201);
} | [
"public",
"function",
"post",
"(",
"array",
"$",
"params",
",",
"array",
"$",
"postData",
")",
"{",
"$",
"this",
"->",
"_validatePostParams",
"(",
"$",
"params",
",",
"$",
"postData",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"_normalizeModelName",... | POST a new record
@param array $params
@param array $postData
@return array | [
"POST",
"a",
"new",
"record"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Api/Rest.php#L53-L80 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Api/Rest.php | Garp_Content_Api_Rest.put | public function put(array $params, array $postData) {
$this->_requireDataType($params);
if (!array_get($params, 'id')) {
throw new Garp_Content_Api_Rest_Exception(
self::EXCEPTION_PUT_WITHOUT_ID
);
}
$model = $this->_normalizeModelName($params['datatype']);
// First, see if the record actually exists
list($record) = $this->_getSingleResult($params);
if (is_null($record['result'])) {
return $this->_formatResponse(array('success' => false), 404);
}
if (!array_get($params, 'relatedType')) {
$this->_updateSingle($params, $postData);
list($response, $httpCode) = $this->_getSingleResult($params);
} else {
$schema = new Garp_Content_Api_Rest_Schema('rest');
// Sanity check if related model exists
list($relatedRecord) = $this->_getSingleResult(
array(
'datatype' => getProperty(
'model',
$schema->getRelation(
$params['datatype'],
$params['relatedType']
)
),
'id' => $params['relatedId']
)
);
if (!$relatedRecord['result']) {
return $this->_formatResponse(array('success' => false), 404);
}
$this->_addRelation($params, $postData);
list($response, $httpCode) = $this->_getRelatedResults($params);
}
return $this->_formatResponse($response, $httpCode);
} | php | public function put(array $params, array $postData) {
$this->_requireDataType($params);
if (!array_get($params, 'id')) {
throw new Garp_Content_Api_Rest_Exception(
self::EXCEPTION_PUT_WITHOUT_ID
);
}
$model = $this->_normalizeModelName($params['datatype']);
// First, see if the record actually exists
list($record) = $this->_getSingleResult($params);
if (is_null($record['result'])) {
return $this->_formatResponse(array('success' => false), 404);
}
if (!array_get($params, 'relatedType')) {
$this->_updateSingle($params, $postData);
list($response, $httpCode) = $this->_getSingleResult($params);
} else {
$schema = new Garp_Content_Api_Rest_Schema('rest');
// Sanity check if related model exists
list($relatedRecord) = $this->_getSingleResult(
array(
'datatype' => getProperty(
'model',
$schema->getRelation(
$params['datatype'],
$params['relatedType']
)
),
'id' => $params['relatedId']
)
);
if (!$relatedRecord['result']) {
return $this->_formatResponse(array('success' => false), 404);
}
$this->_addRelation($params, $postData);
list($response, $httpCode) = $this->_getRelatedResults($params);
}
return $this->_formatResponse($response, $httpCode);
} | [
"public",
"function",
"put",
"(",
"array",
"$",
"params",
",",
"array",
"$",
"postData",
")",
"{",
"$",
"this",
"->",
"_requireDataType",
"(",
"$",
"params",
")",
";",
"if",
"(",
"!",
"array_get",
"(",
"$",
"params",
",",
"'id'",
")",
")",
"{",
"th... | PUT changes into an existing record
@param array $params
@param array $postData
@return array | [
"PUT",
"changes",
"into",
"an",
"existing",
"record"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Api/Rest.php#L89-L130 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Api/Rest.php | Garp_Content_Api_Rest.delete | public function delete(array $params) {
$this->_requireDataType($params);
if (!array_get($params, 'id')) {
throw new Garp_Content_Api_Rest_Exception(
self::EXCEPTION_MISSING_ID
);
}
// First, see if the record actually exists
list($record) = $this->_getSingleResult($params);
if (is_null($record['result'])) {
return $this->_formatResponse(array('success' => false), 404);
}
if (array_get($params, 'relatedType')) {
$this->_removeRelation($params);
return $this->_formatResponse(null, 204, false);
}
$contentManager = $this->_getContentManager($params['datatype']);
$contentManager->destroy(array('id' => $params['id']));
return $this->_formatResponse(null, 204, false);
} | php | public function delete(array $params) {
$this->_requireDataType($params);
if (!array_get($params, 'id')) {
throw new Garp_Content_Api_Rest_Exception(
self::EXCEPTION_MISSING_ID
);
}
// First, see if the record actually exists
list($record) = $this->_getSingleResult($params);
if (is_null($record['result'])) {
return $this->_formatResponse(array('success' => false), 404);
}
if (array_get($params, 'relatedType')) {
$this->_removeRelation($params);
return $this->_formatResponse(null, 204, false);
}
$contentManager = $this->_getContentManager($params['datatype']);
$contentManager->destroy(array('id' => $params['id']));
return $this->_formatResponse(null, 204, false);
} | [
"public",
"function",
"delete",
"(",
"array",
"$",
"params",
")",
"{",
"$",
"this",
"->",
"_requireDataType",
"(",
"$",
"params",
")",
";",
"if",
"(",
"!",
"array_get",
"(",
"$",
"params",
",",
"'id'",
")",
")",
"{",
"throw",
"new",
"Garp_Content_Api_R... | DELETE a record
@param array $params
@return bool | [
"DELETE",
"a",
"record"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Api/Rest.php#L151-L171 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Api/Rest.php | Garp_Content_Api_Rest.getDictionary | public function getDictionary() {
if (!Zend_Registry::isRegistered('Zend_Translate')) {
throw new Garp_Content_Api_Rest_Exception(
self::EXCEPTION_NO_DICTIONARY
);
}
$out = array(
'results' => Zend_Registry::get('Zend_Translate')->getMessages(),
'success' => true
);
return $this->_formatResponse($out, 200);
} | php | public function getDictionary() {
if (!Zend_Registry::isRegistered('Zend_Translate')) {
throw new Garp_Content_Api_Rest_Exception(
self::EXCEPTION_NO_DICTIONARY
);
}
$out = array(
'results' => Zend_Registry::get('Zend_Translate')->getMessages(),
'success' => true
);
return $this->_formatResponse($out, 200);
} | [
"public",
"function",
"getDictionary",
"(",
")",
"{",
"if",
"(",
"!",
"Zend_Registry",
"::",
"isRegistered",
"(",
"'Zend_Translate'",
")",
")",
"{",
"throw",
"new",
"Garp_Content_Api_Rest_Exception",
"(",
"self",
"::",
"EXCEPTION_NO_DICTIONARY",
")",
";",
"}",
"... | Grab the dictionary containing all translatable strings.
@return array | [
"Grab",
"the",
"dictionary",
"containing",
"all",
"translatable",
"strings",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Api/Rest.php#L218-L229 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Api/Rest.php | Garp_Content_Api_Rest._extractOptionsForFetch | protected function _extractOptionsForFetch(array $params) {
if (!isset($params['options'])) {
$params['options'] = array();
}
try {
$options = is_string($params['options']) ?
Zend_Json::decode(urldecode($params['options'])) :
$params['options'];
} catch (Zend_Json_Exception $e) {
throw new Garp_Content_Api_Rest_Exception(
sprintf(self::EXCEPTION_INVALID_JSON, $e->getMessage())
);
}
$options = array_get_subset(
$options,
array(
'sort', 'start', 'limit', 'fields', 'query', 'group', 'with'
)
);
if (!isset($options['limit'])) {
$options['limit'] = self::DEFAULT_PAGE_LIMIT;
}
if (isset($options['with'])) {
// Normalize into an array
$options['with'] = (array)$options['with'];
}
if (array_get($params, 'id')) {
$options['query']['id'] = $params['id'];
}
return $options;
} | php | protected function _extractOptionsForFetch(array $params) {
if (!isset($params['options'])) {
$params['options'] = array();
}
try {
$options = is_string($params['options']) ?
Zend_Json::decode(urldecode($params['options'])) :
$params['options'];
} catch (Zend_Json_Exception $e) {
throw new Garp_Content_Api_Rest_Exception(
sprintf(self::EXCEPTION_INVALID_JSON, $e->getMessage())
);
}
$options = array_get_subset(
$options,
array(
'sort', 'start', 'limit', 'fields', 'query', 'group', 'with'
)
);
if (!isset($options['limit'])) {
$options['limit'] = self::DEFAULT_PAGE_LIMIT;
}
if (isset($options['with'])) {
// Normalize into an array
$options['with'] = (array)$options['with'];
}
if (array_get($params, 'id')) {
$options['query']['id'] = $params['id'];
}
return $options;
} | [
"protected",
"function",
"_extractOptionsForFetch",
"(",
"array",
"$",
"params",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"params",
"[",
"'options'",
"]",
")",
")",
"{",
"$",
"params",
"[",
"'options'",
"]",
"=",
"array",
"(",
")",
";",
"}",
"try... | Remove cruft from HTTP params and provide sensible defaults.
@param array $params The combined URL parameters
@return array | [
"Remove",
"cruft",
"from",
"HTTP",
"params",
"and",
"provide",
"sensible",
"defaults",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Api/Rest.php#L250-L281 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Api/Rest.php | Garp_Content_Api_Rest._getRelatedResults | protected function _getRelatedResults(array $params) {
// Check for existence of the subject record first, in order to return a 404 error
list($subjectRecord, $httpCode) = $this->_getSingleResult($params);
if (!$subjectRecord['success']) {
return array(
array(
'success' => false,
'result' => array()
),
404
);
}
$schema = new Garp_Content_Api_Rest_Schema('rest');
$relation = $schema->getRelation($params['datatype'], $params['relatedType']);
list($rule1, $rule2) = $relation->getRules($params['datatype']);
$contentManager = $this->_getContentManager($relation->model);
$subjectId = $params['id'];
unset($params['id']);
$options = $this->_extractOptionsForFetch($params);
$options['query'][ucfirst($params['datatype']) . '.id'] = $subjectId;
$options['bindingModel'] = $relation->getBindingModel()->id;
$options['rule'] = $rule1;
$options['rule2'] = $rule2;
$options['fields'] = Zend_Db_Select::SQL_WILDCARD;
if ($contentManager->getModel()->isMultilingual()) {
$options['joinMultilingualModel'] = true;
}
$records = $contentManager->fetch($options);
$amount = count($records);
$records = array($params['relatedType'] => $records);
if (isset($options['with'])) {
$records = $this->_combineRecords($params['relatedType'], $records, $options['with']);
}
return array(
array(
'success' => true,
'result' => $records,
'amount' => $amount,
'total' => intval($contentManager->count($options))
),
200
);
} | php | protected function _getRelatedResults(array $params) {
// Check for existence of the subject record first, in order to return a 404 error
list($subjectRecord, $httpCode) = $this->_getSingleResult($params);
if (!$subjectRecord['success']) {
return array(
array(
'success' => false,
'result' => array()
),
404
);
}
$schema = new Garp_Content_Api_Rest_Schema('rest');
$relation = $schema->getRelation($params['datatype'], $params['relatedType']);
list($rule1, $rule2) = $relation->getRules($params['datatype']);
$contentManager = $this->_getContentManager($relation->model);
$subjectId = $params['id'];
unset($params['id']);
$options = $this->_extractOptionsForFetch($params);
$options['query'][ucfirst($params['datatype']) . '.id'] = $subjectId;
$options['bindingModel'] = $relation->getBindingModel()->id;
$options['rule'] = $rule1;
$options['rule2'] = $rule2;
$options['fields'] = Zend_Db_Select::SQL_WILDCARD;
if ($contentManager->getModel()->isMultilingual()) {
$options['joinMultilingualModel'] = true;
}
$records = $contentManager->fetch($options);
$amount = count($records);
$records = array($params['relatedType'] => $records);
if (isset($options['with'])) {
$records = $this->_combineRecords($params['relatedType'], $records, $options['with']);
}
return array(
array(
'success' => true,
'result' => $records,
'amount' => $amount,
'total' => intval($contentManager->count($options))
),
200
);
} | [
"protected",
"function",
"_getRelatedResults",
"(",
"array",
"$",
"params",
")",
"{",
"// Check for existence of the subject record first, in order to return a 404 error",
"list",
"(",
"$",
"subjectRecord",
",",
"$",
"httpCode",
")",
"=",
"$",
"this",
"->",
"_getSingleRes... | Get index of items related to the given id.
@param array $params
@return array | [
"Get",
"index",
"of",
"items",
"related",
"to",
"the",
"given",
"id",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Api/Rest.php#L343-L388 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Api/Rest.php | Garp_Content_Api_Rest._combineRecords | protected function _combineRecords($datatype, array $records, $with) {
$modelName = $this->_normalizeModelName($datatype);
$rootModel = new $modelName;
$schema = instance(new Garp_Content_Api_Rest_Schema('rest'))->getModelDetails($datatype);
$hasOneRelations = array_filter($schema['fields'], propertyEquals('origin', 'relation'));
$hasOneRelations = array_map(array_get('relationAlias'), $hasOneRelations);
// Check validity of 'with'
$unknowns = array_filter($with, callRight(not('in_array'), $hasOneRelations));
if (count($unknowns)) {
$err = sprintf(
Garp_Content_Api_Rest_Schema::EXCEPTION_RELATION_NOT_FOUND, $datatype,
current($unknowns)
);
throw new Garp_Content_Api_Rest_Exception($err);
}
$self = $this;
return array_reduce(
$with,
function ($acc, $cur) use ($datatype, $schema, $self) {
// Grab foreign key names from the relation
$foreignKey = current(
array_filter(
$schema['fields'],
propertyEquals('relationAlias', $cur)
)
);
// Prepare a place for the result
if (!isset($acc[$foreignKey['model']])) {
$acc[$foreignKey['model']] = array();
}
// Grab foreign key values
$foreignKeyValues = array_map(array_get($foreignKey['name']), $acc[$datatype]);
// No values to filter on? Bail.
if (!count(array_filter($foreignKeyValues))) {
return $acc;
}
$foreignKeyValues = array_values(array_unique($foreignKeyValues));
// Construct options object for manager
$options = array(
'options' => array('query' => array('id' => $foreignKeyValues)),
'datatype' => $foreignKey['model']
);
// Fetch with options
$relatedRowset = current($self->_getIndex($options));
$acc[$foreignKey['model']] = array_merge(
$acc[$foreignKey['model']],
$relatedRowset['result'][$foreignKey['model']]
);
return $acc;
},
$records
);
} | php | protected function _combineRecords($datatype, array $records, $with) {
$modelName = $this->_normalizeModelName($datatype);
$rootModel = new $modelName;
$schema = instance(new Garp_Content_Api_Rest_Schema('rest'))->getModelDetails($datatype);
$hasOneRelations = array_filter($schema['fields'], propertyEquals('origin', 'relation'));
$hasOneRelations = array_map(array_get('relationAlias'), $hasOneRelations);
// Check validity of 'with'
$unknowns = array_filter($with, callRight(not('in_array'), $hasOneRelations));
if (count($unknowns)) {
$err = sprintf(
Garp_Content_Api_Rest_Schema::EXCEPTION_RELATION_NOT_FOUND, $datatype,
current($unknowns)
);
throw new Garp_Content_Api_Rest_Exception($err);
}
$self = $this;
return array_reduce(
$with,
function ($acc, $cur) use ($datatype, $schema, $self) {
// Grab foreign key names from the relation
$foreignKey = current(
array_filter(
$schema['fields'],
propertyEquals('relationAlias', $cur)
)
);
// Prepare a place for the result
if (!isset($acc[$foreignKey['model']])) {
$acc[$foreignKey['model']] = array();
}
// Grab foreign key values
$foreignKeyValues = array_map(array_get($foreignKey['name']), $acc[$datatype]);
// No values to filter on? Bail.
if (!count(array_filter($foreignKeyValues))) {
return $acc;
}
$foreignKeyValues = array_values(array_unique($foreignKeyValues));
// Construct options object for manager
$options = array(
'options' => array('query' => array('id' => $foreignKeyValues)),
'datatype' => $foreignKey['model']
);
// Fetch with options
$relatedRowset = current($self->_getIndex($options));
$acc[$foreignKey['model']] = array_merge(
$acc[$foreignKey['model']],
$relatedRowset['result'][$foreignKey['model']]
);
return $acc;
},
$records
);
} | [
"protected",
"function",
"_combineRecords",
"(",
"$",
"datatype",
",",
"array",
"$",
"records",
",",
"$",
"with",
")",
"{",
"$",
"modelName",
"=",
"$",
"this",
"->",
"_normalizeModelName",
"(",
"$",
"datatype",
")",
";",
"$",
"rootModel",
"=",
"new",
"$"... | Get related hasOne records and combine into a single response
@param string $datatype
@param array $records
@param array $with
@return array The combined resultsets | [
"Get",
"related",
"hasOne",
"records",
"and",
"combine",
"into",
"a",
"single",
"response"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Api/Rest.php#L482-L541 | train |
grrr-amsterdam/garp3 | library/Garp/Log.php | Garp_Log.factory | static public function factory($config = array()) {
if (is_string($config)) {
// Assume $config is a filename
$filename = $config;
$config = array(
'timestampFormat' => 'Y-m-d',
array(
'writerName' => 'Stream',
'writerParams' => array(
'stream' => self::_getLoggingDirectory() . DIRECTORY_SEPARATOR . $filename
)
)
);
}
return parent::factory($config);
} | php | static public function factory($config = array()) {
if (is_string($config)) {
// Assume $config is a filename
$filename = $config;
$config = array(
'timestampFormat' => 'Y-m-d',
array(
'writerName' => 'Stream',
'writerParams' => array(
'stream' => self::_getLoggingDirectory() . DIRECTORY_SEPARATOR . $filename
)
)
);
}
return parent::factory($config);
} | [
"static",
"public",
"function",
"factory",
"(",
"$",
"config",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"config",
")",
")",
"{",
"// Assume $config is a filename",
"$",
"filename",
"=",
"$",
"config",
";",
"$",
"config",
"=",
... | Shortcut to fetching a configured logger instance
@param array|Zend_Config $config Array or instance of Zend_Config
@return Zend_Log | [
"Shortcut",
"to",
"fetching",
"a",
"configured",
"logger",
"instance"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Log.php#L16-L31 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Db/AuthOpenId.php | Garp_Model_Db_AuthOpenId.createNew | public function createNew($openid, array $props) {
// first save the new user
$userModel = new Model_User();
$userId = $userModel->insert($props);
$userData = $userModel->find($userId)->current();
$this->insert(array(
'openid' => $openid,
'user_id' => $userId
));
$this->getObserver('Authenticatable')->updateLoginStats($userId);
return $userData;
} | php | public function createNew($openid, array $props) {
// first save the new user
$userModel = new Model_User();
$userId = $userModel->insert($props);
$userData = $userModel->find($userId)->current();
$this->insert(array(
'openid' => $openid,
'user_id' => $userId
));
$this->getObserver('Authenticatable')->updateLoginStats($userId);
return $userData;
} | [
"public",
"function",
"createNew",
"(",
"$",
"openid",
",",
"array",
"$",
"props",
")",
"{",
"// first save the new user",
"$",
"userModel",
"=",
"new",
"Model_User",
"(",
")",
";",
"$",
"userId",
"=",
"$",
"userModel",
"->",
"insert",
"(",
"$",
"props",
... | Store a new user. This creates a new auth_openid record, but also
a new users record.
@param String $openid
@param Array $props Properties fetched thru Sreg
@return Garp_Db_Table_Row The new user data | [
"Store",
"a",
"new",
"user",
".",
"This",
"creates",
"a",
"new",
"auth_openid",
"record",
"but",
"also",
"a",
"new",
"users",
"record",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Db/AuthOpenId.php#L27-L39 | train |
grrr-amsterdam/garp3 | library/Garp/Application/Resource/Router.php | Garp_Application_Resource_Router.getRouter | public function getRouter() {
$routesIni = $this->_getRoutesConfig();
$this->setOptions($routesIni->toArray());
$options = $this->getOptions();
if ($this->_localeIsEnabled()) {
$bootstrap = $this->getBootstrap();
if (!$this->_locale) {
$bootstrap->bootstrap('Locale');
$this->_locale = $bootstrap->getContainer()->locale;
}
$defaultLocale = array_keys($this->_locale->getDefault());
$defaultLocale = $defaultLocale[0];
$locales = $this->_getPossibleLocales();
$routes = $options['routes'];
$localizedRoutes = Garp_I18n::getLocalizedRoutes($routes, $locales);
$options['routes'] = array_merge($routes, $localizedRoutes);
$this->setOptions($options);
}
$router = parent::getRouter();
$router->addDefaultRoutes();
return $router;
} | php | public function getRouter() {
$routesIni = $this->_getRoutesConfig();
$this->setOptions($routesIni->toArray());
$options = $this->getOptions();
if ($this->_localeIsEnabled()) {
$bootstrap = $this->getBootstrap();
if (!$this->_locale) {
$bootstrap->bootstrap('Locale');
$this->_locale = $bootstrap->getContainer()->locale;
}
$defaultLocale = array_keys($this->_locale->getDefault());
$defaultLocale = $defaultLocale[0];
$locales = $this->_getPossibleLocales();
$routes = $options['routes'];
$localizedRoutes = Garp_I18n::getLocalizedRoutes($routes, $locales);
$options['routes'] = array_merge($routes, $localizedRoutes);
$this->setOptions($options);
}
$router = parent::getRouter();
$router->addDefaultRoutes();
return $router;
} | [
"public",
"function",
"getRouter",
"(",
")",
"{",
"$",
"routesIni",
"=",
"$",
"this",
"->",
"_getRoutesConfig",
"(",
")",
";",
"$",
"this",
"->",
"setOptions",
"(",
"$",
"routesIni",
"->",
"toArray",
"(",
")",
")",
";",
"$",
"options",
"=",
"$",
"thi... | Retrieve router object
@return Zend_Controller_Router_Rewrite | [
"Retrieve",
"router",
"object"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Application/Resource/Router.php#L41-L67 | train |
grrr-amsterdam/garp3 | library/Garp/Application/Resource/Router.php | Garp_Application_Resource_Router._getRoutesConfig | protected function _getRoutesConfig() {
$options = $this->getOptions();
if (!isset($options['routesFile'])) {
throw new Exception(self::ERROR_NO_ROUTE_DEFINED);
}
$routes = $options['routesFile'];
if (is_string($routes)) {
$genericRoutes = $this->_loadRoutesConfig($routes);
} else {
$genericRoutes = array_key_exists('generic', $routes) ?
$this->_loadRoutesConfig($routes['generic']) :
array()
;
}
$lang = $this->_getCurrentLanguage();
$territory = Garp_I18n::languageToTerritory($lang);
$utf8_extension = PHP_OS === 'Linux' ? '.utf8' : '.UTF-8';
setlocale(LC_ALL, $territory . $utf8_extension);
/**
* Fix for Turkish language lowercasing issues.
*
* @see: http://www.sobstel.org/blog/php-call-to-undefined-method-on-tr-tr-locale/
* @see: https://bugs.php.net/bug.php?id=18556
*/
if (in_array($territory, array('tr_TR', 'ku', 'az_AZ'))) {
setlocale(LC_CTYPE, 'en_US' . $utf8_extension);
}
if ($this->_localeIsEnabled() && $lang && isset($options['routesFile'][$lang])) {
$langFile = $options['routesFile'][$lang];
$langRoutes = $this->_loadRoutesConfig($langFile);
return $genericRoutes->merge($langRoutes);
}
return $genericRoutes;
} | php | protected function _getRoutesConfig() {
$options = $this->getOptions();
if (!isset($options['routesFile'])) {
throw new Exception(self::ERROR_NO_ROUTE_DEFINED);
}
$routes = $options['routesFile'];
if (is_string($routes)) {
$genericRoutes = $this->_loadRoutesConfig($routes);
} else {
$genericRoutes = array_key_exists('generic', $routes) ?
$this->_loadRoutesConfig($routes['generic']) :
array()
;
}
$lang = $this->_getCurrentLanguage();
$territory = Garp_I18n::languageToTerritory($lang);
$utf8_extension = PHP_OS === 'Linux' ? '.utf8' : '.UTF-8';
setlocale(LC_ALL, $territory . $utf8_extension);
/**
* Fix for Turkish language lowercasing issues.
*
* @see: http://www.sobstel.org/blog/php-call-to-undefined-method-on-tr-tr-locale/
* @see: https://bugs.php.net/bug.php?id=18556
*/
if (in_array($territory, array('tr_TR', 'ku', 'az_AZ'))) {
setlocale(LC_CTYPE, 'en_US' . $utf8_extension);
}
if ($this->_localeIsEnabled() && $lang && isset($options['routesFile'][$lang])) {
$langFile = $options['routesFile'][$lang];
$langRoutes = $this->_loadRoutesConfig($langFile);
return $genericRoutes->merge($langRoutes);
}
return $genericRoutes;
} | [
"protected",
"function",
"_getRoutesConfig",
"(",
")",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"getOptions",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"'routesFile'",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
... | Retrieve a routes.ini file containing routes
@return Zend_Config_Ini | [
"Retrieve",
"a",
"routes",
".",
"ini",
"file",
"containing",
"routes"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Application/Resource/Router.php#L74-L115 | train |
grrr-amsterdam/garp3 | library/Garp/Application/Resource/Router.php | Garp_Application_Resource_Router._getPossibleLocales | protected function _getPossibleLocales() {
$bootstrap = $this->getBootstrap();
$bootstrap->bootstrap('FrontController');
$frontController = $bootstrap->getContainer()->frontcontroller;
$locales = $frontController->getParam('locales');
return $locales;
} | php | protected function _getPossibleLocales() {
$bootstrap = $this->getBootstrap();
$bootstrap->bootstrap('FrontController');
$frontController = $bootstrap->getContainer()->frontcontroller;
$locales = $frontController->getParam('locales');
return $locales;
} | [
"protected",
"function",
"_getPossibleLocales",
"(",
")",
"{",
"$",
"bootstrap",
"=",
"$",
"this",
"->",
"getBootstrap",
"(",
")",
";",
"$",
"bootstrap",
"->",
"bootstrap",
"(",
"'FrontController'",
")",
";",
"$",
"frontController",
"=",
"$",
"bootstrap",
"-... | Fetch all possible locales from the front controller parameters.
@return array | [
"Fetch",
"all",
"possible",
"locales",
"from",
"the",
"front",
"controller",
"parameters",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Application/Resource/Router.php#L126-L132 | train |
grrr-amsterdam/garp3 | library/Garp/Application/Resource/Router.php | Garp_Application_Resource_Router._getCurrentLanguage | protected function _getCurrentLanguage() {
if (!isset($_SERVER['REQUEST_URI'])) {
// Probably CLI context. Return the default locale
return Garp_I18n::getDefaultLocale();
}
$requestUri = $_SERVER['REQUEST_URI'];
$bits = explode('/', $requestUri);
// remove empty values
$bits = array_filter($bits, 'strlen');
// reindex the array
$bits = array_values($bits);
$bits = array_map('strtolower', $bits);
$locales = $this->_getPossibleLocales();
if (array_key_exists(0, $bits) && in_array($bits[0], $locales)) {
return $bits[0];
}
return Garp_I18n::getDefaultLocale();
} | php | protected function _getCurrentLanguage() {
if (!isset($_SERVER['REQUEST_URI'])) {
// Probably CLI context. Return the default locale
return Garp_I18n::getDefaultLocale();
}
$requestUri = $_SERVER['REQUEST_URI'];
$bits = explode('/', $requestUri);
// remove empty values
$bits = array_filter($bits, 'strlen');
// reindex the array
$bits = array_values($bits);
$bits = array_map('strtolower', $bits);
$locales = $this->_getPossibleLocales();
if (array_key_exists(0, $bits) && in_array($bits[0], $locales)) {
return $bits[0];
}
return Garp_I18n::getDefaultLocale();
} | [
"protected",
"function",
"_getCurrentLanguage",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"_SERVER",
"[",
"'REQUEST_URI'",
"]",
")",
")",
"{",
"// Probably CLI context. Return the default locale",
"return",
"Garp_I18n",
"::",
"getDefaultLocale",
"(",
")",
... | Get current language from URL
@return string | [
"Get",
"current",
"language",
"from",
"URL"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Application/Resource/Router.php#L149-L166 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/YouTubeable.php | Garp_Model_Behavior_YouTubeable._fillFields | protected function _fillFields(Array $input) {
if (!array_key_exists($this->_fields['watch_url'], $input)) {
throw new Garp_Model_Behavior_YouTubeable_Exception_MissingField(
sprintf(self::EXCEPTION_MISSING_FIELD, $this->_fields['watch_url'])
);
}
$url = $input[$this->_fields['watch_url']];
if (empty($url)) {
return;
}
$entry = $this->_fetchEntryByUrl($url);
$images = $entry->getSnippet()->getThumbnails();
$duration = $entry->getContentDetails()->getDuration();
$data = array(
'identifier' => $entry->getId(),
'name' => $this->_getVideoName($entry, $input),
'description' => $this->_getVideoDescription($entry, $input),
'flash_player_url' => $this->_getFlashPlayerUrl($entry),
'watch_url' => $url,
'duration' => $this->_getDurationInSeconds($duration),
'image_url' => $images['high']['url'],
'thumbnail_url' => $images['default']['url'],
);
$out = array();
foreach ($data as $ytKey => $value) {
$garpKey = $this->_fields[$ytKey];
$this->_populateOutput($out, $garpKey, $value);
}
return $out;
} | php | protected function _fillFields(Array $input) {
if (!array_key_exists($this->_fields['watch_url'], $input)) {
throw new Garp_Model_Behavior_YouTubeable_Exception_MissingField(
sprintf(self::EXCEPTION_MISSING_FIELD, $this->_fields['watch_url'])
);
}
$url = $input[$this->_fields['watch_url']];
if (empty($url)) {
return;
}
$entry = $this->_fetchEntryByUrl($url);
$images = $entry->getSnippet()->getThumbnails();
$duration = $entry->getContentDetails()->getDuration();
$data = array(
'identifier' => $entry->getId(),
'name' => $this->_getVideoName($entry, $input),
'description' => $this->_getVideoDescription($entry, $input),
'flash_player_url' => $this->_getFlashPlayerUrl($entry),
'watch_url' => $url,
'duration' => $this->_getDurationInSeconds($duration),
'image_url' => $images['high']['url'],
'thumbnail_url' => $images['default']['url'],
);
$out = array();
foreach ($data as $ytKey => $value) {
$garpKey = $this->_fields[$ytKey];
$this->_populateOutput($out, $garpKey, $value);
}
return $out;
} | [
"protected",
"function",
"_fillFields",
"(",
"Array",
"$",
"input",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"this",
"->",
"_fields",
"[",
"'watch_url'",
"]",
",",
"$",
"input",
")",
")",
"{",
"throw",
"new",
"Garp_Model_Behavior_YouTubeable_E... | Retrieves additional data about the video corresponding with given input url from YouTube,
and returns new data structure.
@param array $input
@return array | [
"Retrieves",
"additional",
"data",
"about",
"the",
"video",
"corresponding",
"with",
"given",
"input",
"url",
"from",
"YouTube",
"and",
"returns",
"new",
"data",
"structure",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/YouTubeable.php#L96-L126 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/YouTubeable.php | Garp_Model_Behavior_YouTubeable._populateOutput | protected function _populateOutput(array &$output, $key, $value) {
if (strpos($key, '.') === false) {
$output[$key] = $value;
return;
}
$array = Garp_Util_String::toArray($key, '.', $value);
$output += $array;
} | php | protected function _populateOutput(array &$output, $key, $value) {
if (strpos($key, '.') === false) {
$output[$key] = $value;
return;
}
$array = Garp_Util_String::toArray($key, '.', $value);
$output += $array;
} | [
"protected",
"function",
"_populateOutput",
"(",
"array",
"&",
"$",
"output",
",",
"$",
"key",
",",
"$",
"value",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"key",
",",
"'.'",
")",
"===",
"false",
")",
"{",
"$",
"output",
"[",
"$",
"key",
"]",
"=",... | Populate record with new data
@param array $output
@param string $key
@param string $value
@return void | [
"Populate",
"record",
"with",
"new",
"data"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/YouTubeable.php#L136-L143 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/YouTubeable.php | Garp_Model_Behavior_YouTubeable._getId | protected function _getId($watchUrl) {
$query = array();
if (!$watchUrl) {
throw new Garp_Model_Behavior_YouTubeable_Exception_NoUrl(self::EXCEPTION_NO_URL);
}
$url = parse_url($watchUrl);
if (empty($url['query']) && $url['host'] == 'youtu.be') {
$videoId = substr($url['path'], 1);
} elseif (isset($url['query'])) {
parse_str($url['query'], $query);
if (isset($query['v']) && $query['v']) {
$videoId = $query['v'];
}
}
if (!isset($videoId)) {
throw new Garp_Model_Behavior_YouTubeable_Exception_InvalidUrl(
sprintf(self::EXCEPTION_INVALID_YOUTUBE_URL, $watchUrl)
);
}
return $videoId;
} | php | protected function _getId($watchUrl) {
$query = array();
if (!$watchUrl) {
throw new Garp_Model_Behavior_YouTubeable_Exception_NoUrl(self::EXCEPTION_NO_URL);
}
$url = parse_url($watchUrl);
if (empty($url['query']) && $url['host'] == 'youtu.be') {
$videoId = substr($url['path'], 1);
} elseif (isset($url['query'])) {
parse_str($url['query'], $query);
if (isset($query['v']) && $query['v']) {
$videoId = $query['v'];
}
}
if (!isset($videoId)) {
throw new Garp_Model_Behavior_YouTubeable_Exception_InvalidUrl(
sprintf(self::EXCEPTION_INVALID_YOUTUBE_URL, $watchUrl)
);
}
return $videoId;
} | [
"protected",
"function",
"_getId",
"(",
"$",
"watchUrl",
")",
"{",
"$",
"query",
"=",
"array",
"(",
")",
";",
"if",
"(",
"!",
"$",
"watchUrl",
")",
"{",
"throw",
"new",
"Garp_Model_Behavior_YouTubeable_Exception_NoUrl",
"(",
"self",
"::",
"EXCEPTION_NO_URL",
... | Retrieves the id value of a YouTube url.
@param string $watchUrl
@return string | [
"Retrieves",
"the",
"id",
"value",
"of",
"a",
"YouTube",
"url",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/YouTubeable.php#L172-L194 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Behavior/YouTubeable.php | Garp_Model_Behavior_YouTubeable._getDurationInSeconds | protected function _getDurationInSeconds($duration) {
$interval = new \DateInterval($duration);
return ($interval->d * 24 * 60 * 60) +
($interval->h * 60 * 60) +
($interval->i * 60) +
$interval->s;
} | php | protected function _getDurationInSeconds($duration) {
$interval = new \DateInterval($duration);
return ($interval->d * 24 * 60 * 60) +
($interval->h * 60 * 60) +
($interval->i * 60) +
$interval->s;
} | [
"protected",
"function",
"_getDurationInSeconds",
"(",
"$",
"duration",
")",
"{",
"$",
"interval",
"=",
"new",
"\\",
"DateInterval",
"(",
"$",
"duration",
")",
";",
"return",
"(",
"$",
"interval",
"->",
"d",
"*",
"24",
"*",
"60",
"*",
"60",
")",
"+",
... | Convert ISO 8601 duration to seconds
@param string $duration
@return integer | [
"Convert",
"ISO",
"8601",
"duration",
"to",
"seconds"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Behavior/YouTubeable.php#L216-L222 | train |
grrr-amsterdam/garp3 | library/Garp/Spawn/MySql/View/Abstract.php | Garp_Spawn_MySql_View_Abstract.deleteAllByPostfix | public static function deleteAllByPostfix($postfix) {
$adapter = Zend_Db_Table::getDefaultAdapter();
$config = Zend_Registry::get('config');
$dbName = $config->resources->db->params->dbname;
$queryTpl = "SELECT table_name FROM information_schema.views WHERE table_schema = '%s' and table_name like '%%%s';";
$statement = sprintf($queryTpl, $dbName, $postfix);
$views = $adapter->fetchAll($statement);
foreach ($views as $view) {
$viewName = $view['table_name'];
$dropStatement = "DROP VIEW IF EXISTS `{$viewName}`;";
$adapter->query($dropStatement);
}
} | php | public static function deleteAllByPostfix($postfix) {
$adapter = Zend_Db_Table::getDefaultAdapter();
$config = Zend_Registry::get('config');
$dbName = $config->resources->db->params->dbname;
$queryTpl = "SELECT table_name FROM information_schema.views WHERE table_schema = '%s' and table_name like '%%%s';";
$statement = sprintf($queryTpl, $dbName, $postfix);
$views = $adapter->fetchAll($statement);
foreach ($views as $view) {
$viewName = $view['table_name'];
$dropStatement = "DROP VIEW IF EXISTS `{$viewName}`;";
$adapter->query($dropStatement);
}
} | [
"public",
"static",
"function",
"deleteAllByPostfix",
"(",
"$",
"postfix",
")",
"{",
"$",
"adapter",
"=",
"Zend_Db_Table",
"::",
"getDefaultAdapter",
"(",
")",
";",
"$",
"config",
"=",
"Zend_Registry",
"::",
"get",
"(",
"'config'",
")",
";",
"$",
"dbName",
... | Deletes all views in the database with given postfix.
@param String $postfix The postfix for this type of view, f.i. '_joint' | [
"Deletes",
"all",
"views",
"in",
"the",
"database",
"with",
"given",
"postfix",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Spawn/MySql/View/Abstract.php#L25-L39 | train |
grrr-amsterdam/garp3 | library/Garp/Spawn/MySql/Table/Synchronizer.php | Garp_Spawn_MySql_Table_Synchronizer.sync | public function sync($removeRedundantColumns = true) {
$target = $this->getTarget();
$keysInSync = true;
$configuredKeys = $this->_getConfiguredKeys();
$keySyncer = new Garp_Spawn_MySql_Key_Set_Synchronizer(
$configuredKeys,
$target->keys,
$this->getFeedback()
);
if (!$keySyncer->removeKeys()) {
$keysInSync = false;
}
$colsInSync = $this->_syncColumns($target);
$i18nTableFork = $this->_detectI18nTableFork();
if ($i18nTableFork) {
$dbManager = Garp_Spawn_MySql_Manager::getInstance($this->_feedback);
$dbManager->onI18nTableFork($this->getModel());
}
if ($removeRedundantColumns) {
$this->_deleteRedundantColumns();
}
if (!$keySyncer->addKeys() || !$keySyncer->modifyKeys()) {
$keysInSync = false;
}
return $colsInSync && $keysInSync;
} | php | public function sync($removeRedundantColumns = true) {
$target = $this->getTarget();
$keysInSync = true;
$configuredKeys = $this->_getConfiguredKeys();
$keySyncer = new Garp_Spawn_MySql_Key_Set_Synchronizer(
$configuredKeys,
$target->keys,
$this->getFeedback()
);
if (!$keySyncer->removeKeys()) {
$keysInSync = false;
}
$colsInSync = $this->_syncColumns($target);
$i18nTableFork = $this->_detectI18nTableFork();
if ($i18nTableFork) {
$dbManager = Garp_Spawn_MySql_Manager::getInstance($this->_feedback);
$dbManager->onI18nTableFork($this->getModel());
}
if ($removeRedundantColumns) {
$this->_deleteRedundantColumns();
}
if (!$keySyncer->addKeys() || !$keySyncer->modifyKeys()) {
$keysInSync = false;
}
return $colsInSync && $keysInSync;
} | [
"public",
"function",
"sync",
"(",
"$",
"removeRedundantColumns",
"=",
"true",
")",
"{",
"$",
"target",
"=",
"$",
"this",
"->",
"getTarget",
"(",
")",
";",
"$",
"keysInSync",
"=",
"true",
";",
"$",
"configuredKeys",
"=",
"$",
"this",
"->",
"_getConfigure... | Syncs source and target tables with one another, trying to resolve any conflicts.
@param bool $removeRedundantColumns Whether to remove no longer configured columns. This
can be triggered separately with the cleanUp() method.
@return bool In sync | [
"Syncs",
"source",
"and",
"target",
"tables",
"with",
"one",
"another",
"trying",
"to",
"resolve",
"any",
"conflicts",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Spawn/MySql/Table/Synchronizer.php#L52-L84 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/BrowseboxController.php | G_BrowseboxController.indexAction | public function indexAction() {
$request = $this->getRequest();
if (!$request->getParam('id') || !$request->getParam('chunk')) {
throw new Exception('Not enough parameters: "id" and "chunk" are required.');
}
$bb = $this->_initBrowsebox($request);
$this->view->bb = $bb;
$this->_helper->layout->setLayout('blank');
} | php | public function indexAction() {
$request = $this->getRequest();
if (!$request->getParam('id') || !$request->getParam('chunk')) {
throw new Exception('Not enough parameters: "id" and "chunk" are required.');
}
$bb = $this->_initBrowsebox($request);
$this->view->bb = $bb;
$this->_helper->layout->setLayout('blank');
} | [
"public",
"function",
"indexAction",
"(",
")",
"{",
"$",
"request",
"=",
"$",
"this",
"->",
"getRequest",
"(",
")",
";",
"if",
"(",
"!",
"$",
"request",
"->",
"getParam",
"(",
"'id'",
")",
"||",
"!",
"$",
"request",
"->",
"getParam",
"(",
"'chunk'",
... | Central entry point.
@return void | [
"Central",
"entry",
"point",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/BrowseboxController.php#L15-L23 | train |
grrr-amsterdam/garp3 | application/modules/g/controllers/BrowseboxController.php | G_BrowseboxController._initBrowsebox | protected function _initBrowsebox(Zend_Controller_Request_Abstract $request) {
$bb = Garp_Browsebox::factory($request->getParam('id'));
if ($request->getParam('conditions')) {
$options = unserialize(base64_decode($request->getParam('conditions')));
if (!empty($options['filters'])) {
$conditions = base64_decode($options['filters']);
$conditions = explode(
Garp_Browsebox::BROWSEBOX_QUERY_FILTER_SEPARATOR,
$conditions
);
foreach ($conditions as $condition) {
$parts = explode(':', $condition);
if (count($parts) < 2) {
continue;
}
$filterId = $parts[0];
$params = explode(
Garp_Browsebox::BROWSEBOX_QUERY_FILTER_PROP_SEPARATOR,
$parts[1]
);
$bb->setFilter($filterId, $params);
}
}
unset($options['filters']);
foreach ($options as $key => $value) {
$bb->setOption($key, $value);
}
}
$chunk = $request->getParam('chunk');
if ($chunk < 1) {
$chunk = 1;
}
$bb->init($chunk);
return $bb;
} | php | protected function _initBrowsebox(Zend_Controller_Request_Abstract $request) {
$bb = Garp_Browsebox::factory($request->getParam('id'));
if ($request->getParam('conditions')) {
$options = unserialize(base64_decode($request->getParam('conditions')));
if (!empty($options['filters'])) {
$conditions = base64_decode($options['filters']);
$conditions = explode(
Garp_Browsebox::BROWSEBOX_QUERY_FILTER_SEPARATOR,
$conditions
);
foreach ($conditions as $condition) {
$parts = explode(':', $condition);
if (count($parts) < 2) {
continue;
}
$filterId = $parts[0];
$params = explode(
Garp_Browsebox::BROWSEBOX_QUERY_FILTER_PROP_SEPARATOR,
$parts[1]
);
$bb->setFilter($filterId, $params);
}
}
unset($options['filters']);
foreach ($options as $key => $value) {
$bb->setOption($key, $value);
}
}
$chunk = $request->getParam('chunk');
if ($chunk < 1) {
$chunk = 1;
}
$bb->init($chunk);
return $bb;
} | [
"protected",
"function",
"_initBrowsebox",
"(",
"Zend_Controller_Request_Abstract",
"$",
"request",
")",
"{",
"$",
"bb",
"=",
"Garp_Browsebox",
"::",
"factory",
"(",
"$",
"request",
"->",
"getParam",
"(",
"'id'",
")",
")",
";",
"if",
"(",
"$",
"request",
"->... | Fetch a Browsebox object configured based on parameters found in the request.
@param Zend_Controller_Request_Abstract $request The current request
@return Garp_Browsebox | [
"Fetch",
"a",
"Browsebox",
"object",
"configured",
"based",
"on",
"parameters",
"found",
"in",
"the",
"request",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/application/modules/g/controllers/BrowseboxController.php#L32-L69 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Export/Abstract.php | Garp_Content_Export_Abstract.getFilename | public function getFilename(Garp_Util_Configuration $params) {
$className = Garp_Content_Api::modelAliasToClass($params['model']);
$model = new $className();
$filename = 'export_';
$filename .= $model->getName();
$filename .= '_' . date('Y_m_d');
$filename .= '.';
$filename .= $this->_extension;
return $filename;
} | php | public function getFilename(Garp_Util_Configuration $params) {
$className = Garp_Content_Api::modelAliasToClass($params['model']);
$model = new $className();
$filename = 'export_';
$filename .= $model->getName();
$filename .= '_' . date('Y_m_d');
$filename .= '.';
$filename .= $this->_extension;
return $filename;
} | [
"public",
"function",
"getFilename",
"(",
"Garp_Util_Configuration",
"$",
"params",
")",
"{",
"$",
"className",
"=",
"Garp_Content_Api",
"::",
"modelAliasToClass",
"(",
"$",
"params",
"[",
"'model'",
"]",
")",
";",
"$",
"model",
"=",
"new",
"$",
"className",
... | Generate a filename for the exported text file
@param Garp_Util_Configuration $params
@return string | [
"Generate",
"a",
"filename",
"for",
"the",
"exported",
"text",
"file"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Export/Abstract.php#L111-L120 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Export/Abstract.php | Garp_Content_Export_Abstract._humanizeData | protected function _humanizeData($data, Garp_Model_Db $model) {
$humanizedData = array();
foreach ($data as $i => $datum) {
if (!is_array($datum)) {
$humanizedData[$i] = $datum;
continue;
}
foreach ($datum as $column => $value) {
$field = $model->getFieldConfiguration($column);
if ($field['type'] === 'checkbox') {
$value = $value ? __('yes') : __('no');
}
$alias = $column;
if ($field) {
$alias = $field['label'];
}
$alias = ucfirst(__($alias));
if (is_array($value) && $this->_isMultilingualArray($value)) {
// special case: we convert the language keys to new columns in the output
foreach ($value as $key => $data) {
$i18n_alias = "$alias ($key)";
$humanizedData[$i][$i18n_alias] = $data;
}
// Continue so we don't add duplicate data
continue;
} elseif (is_array($value)) {
// OMG recursion!
$value = $this->_humanizeData($value, $model);
}
$humanizedData[$i][$alias] = $value;
}
}
return $humanizedData;
} | php | protected function _humanizeData($data, Garp_Model_Db $model) {
$humanizedData = array();
foreach ($data as $i => $datum) {
if (!is_array($datum)) {
$humanizedData[$i] = $datum;
continue;
}
foreach ($datum as $column => $value) {
$field = $model->getFieldConfiguration($column);
if ($field['type'] === 'checkbox') {
$value = $value ? __('yes') : __('no');
}
$alias = $column;
if ($field) {
$alias = $field['label'];
}
$alias = ucfirst(__($alias));
if (is_array($value) && $this->_isMultilingualArray($value)) {
// special case: we convert the language keys to new columns in the output
foreach ($value as $key => $data) {
$i18n_alias = "$alias ($key)";
$humanizedData[$i][$i18n_alias] = $data;
}
// Continue so we don't add duplicate data
continue;
} elseif (is_array($value)) {
// OMG recursion!
$value = $this->_humanizeData($value, $model);
}
$humanizedData[$i][$alias] = $value;
}
}
return $humanizedData;
} | [
"protected",
"function",
"_humanizeData",
"(",
"$",
"data",
",",
"Garp_Model_Db",
"$",
"model",
")",
"{",
"$",
"humanizedData",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"i",
"=>",
"$",
"datum",
")",
"{",
"if",
"(",
"!",
... | Translate the columns of a record into the human-friendly versions used
in the CMS
@param array $data
@param Garp_Model_Db $model
@return array | [
"Translate",
"the",
"columns",
"of",
"a",
"record",
"into",
"the",
"human",
"-",
"friendly",
"versions",
"used",
"in",
"the",
"CMS"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Export/Abstract.php#L141-L175 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Export/Abstract.php | Garp_Content_Export_Abstract._humanizeMultilingualData | protected function _humanizeMultilingualData(array $value) {
$out = array();
foreach ($value as $key => $data) {
$out[] = "[$key]: $data";
}
return implode(" - ", $out);
} | php | protected function _humanizeMultilingualData(array $value) {
$out = array();
foreach ($value as $key => $data) {
$out[] = "[$key]: $data";
}
return implode(" - ", $out);
} | [
"protected",
"function",
"_humanizeMultilingualData",
"(",
"array",
"$",
"value",
")",
"{",
"$",
"out",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"value",
"as",
"$",
"key",
"=>",
"$",
"data",
")",
"{",
"$",
"out",
"[",
"]",
"=",
"\"[$key]: $d... | Humanize a multilingual data array
@param array $value
@return string | [
"Humanize",
"a",
"multilingual",
"data",
"array"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Export/Abstract.php#L183-L189 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Export/Abstract.php | Garp_Content_Export_Abstract._isMultilingualArray | protected function _isMultilingualArray($value) {
if (!is_array($value)) {
return false;
}
$locales = Garp_I18n::getLocales();
$keys = array_keys($value);
sort($locales);
sort($keys);
return $locales === $keys;
} | php | protected function _isMultilingualArray($value) {
if (!is_array($value)) {
return false;
}
$locales = Garp_I18n::getLocales();
$keys = array_keys($value);
sort($locales);
sort($keys);
return $locales === $keys;
} | [
"protected",
"function",
"_isMultilingualArray",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"locales",
"=",
"Garp_I18n",
"::",
"getLocales",
"(",
")",
";",
"$",
"keys",
... | Check if value is a multilingual array.
@param mixed $value
@return bool | [
"Check",
"if",
"value",
"is",
"a",
"multilingual",
"array",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Export/Abstract.php#L197-L207 | train |
grrr-amsterdam/garp3 | library/Garp/Content/Export/Abstract.php | Garp_Content_Export_Abstract._bindModels | protected function _bindModels(Garp_Model_Db $model) {
// Add HABTM related records
$relations = $model->getConfiguration('relations');
foreach ($relations as $key => $config) {
if ($config['type'] !== 'hasAndBelongsToMany' && $config['type'] !== 'hasMany') {
continue;
}
$otherModelName = 'Model_' . $config['model'];
$otherModel = new $otherModelName();
$multilingual = false;
$modelFactory = new Garp_I18n_ModelFactory();
if ($otherModel->getObserver('Translatable')) {
$otherModel = $modelFactory->getModel($otherModel);
$multilingual = true;
}
$otherModelAlias = $otherModel->getName();
$bindingModel = null;
if ($config['type'] === 'hasAndBelongsToMany') {
$bindingModelName = 'Model_' . $config['bindingModel'];
$bindingModel = new $bindingModelName;
if ($multilingual) {
$refmapLocaliser = new Garp_Model_ReferenceMapLocalizer($bindingModel);
$refmapLocaliser->populate($otherModelName);
}
$otherModelAlias = 'm';
}
$labelFields = $otherModel->getListFields();
$prefixedLabelFields = array();
foreach ($labelFields as $labelField) {
$prefixedLabelFields[] = "$otherModelAlias.$labelField";
}
$labelFields = 'CONCAT_WS(", ", ' . implode(', ', $prefixedLabelFields) . ')';
// If the Translatable behavior would be effective,
// the output would be in a localized array, which is overkill for this
// purpose.
$otherModel->unregisterObserver('Translatable');
$options = array(
'bindingModel' => $bindingModel,
'modelClass' => $otherModel,
'conditions' => $otherModel->select()
->setIntegrityCheck(false)
->from(
array($otherModelAlias => $otherModel->getName()),
array($config['label'] => $labelFields)
)
->order("$otherModelAlias.id")
);
$model->bindModel($config['label'], $options);
}
} | php | protected function _bindModels(Garp_Model_Db $model) {
// Add HABTM related records
$relations = $model->getConfiguration('relations');
foreach ($relations as $key => $config) {
if ($config['type'] !== 'hasAndBelongsToMany' && $config['type'] !== 'hasMany') {
continue;
}
$otherModelName = 'Model_' . $config['model'];
$otherModel = new $otherModelName();
$multilingual = false;
$modelFactory = new Garp_I18n_ModelFactory();
if ($otherModel->getObserver('Translatable')) {
$otherModel = $modelFactory->getModel($otherModel);
$multilingual = true;
}
$otherModelAlias = $otherModel->getName();
$bindingModel = null;
if ($config['type'] === 'hasAndBelongsToMany') {
$bindingModelName = 'Model_' . $config['bindingModel'];
$bindingModel = new $bindingModelName;
if ($multilingual) {
$refmapLocaliser = new Garp_Model_ReferenceMapLocalizer($bindingModel);
$refmapLocaliser->populate($otherModelName);
}
$otherModelAlias = 'm';
}
$labelFields = $otherModel->getListFields();
$prefixedLabelFields = array();
foreach ($labelFields as $labelField) {
$prefixedLabelFields[] = "$otherModelAlias.$labelField";
}
$labelFields = 'CONCAT_WS(", ", ' . implode(', ', $prefixedLabelFields) . ')';
// If the Translatable behavior would be effective,
// the output would be in a localized array, which is overkill for this
// purpose.
$otherModel->unregisterObserver('Translatable');
$options = array(
'bindingModel' => $bindingModel,
'modelClass' => $otherModel,
'conditions' => $otherModel->select()
->setIntegrityCheck(false)
->from(
array($otherModelAlias => $otherModel->getName()),
array($config['label'] => $labelFields)
)
->order("$otherModelAlias.id")
);
$model->bindModel($config['label'], $options);
}
} | [
"protected",
"function",
"_bindModels",
"(",
"Garp_Model_Db",
"$",
"model",
")",
"{",
"// Add HABTM related records",
"$",
"relations",
"=",
"$",
"model",
"->",
"getConfiguration",
"(",
"'relations'",
")",
";",
"foreach",
"(",
"$",
"relations",
"as",
"$",
"key",... | Bind all HABTM related models so they, too, get exported
@param Garp_Model_Db $model
@return void | [
"Bind",
"all",
"HABTM",
"related",
"models",
"so",
"they",
"too",
"get",
"exported"
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Content/Export/Abstract.php#L215-L269 | train |
grrr-amsterdam/garp3 | library/Garp/Model/Db/AuthFacebook.php | Garp_Model_Db_AuthFacebook.createNew | public function createNew(array $authData, array $userData) {
// first save the new user
$userModel = new Model_User();
$userId = $userModel->insert($userData);
$userData = $userModel->find($userId)->current();
$authData['user_id'] = $userId;
$this->insert($authData);
$this->getObserver('Authenticatable')->updateLoginStats($userId);
return $userData;
} | php | public function createNew(array $authData, array $userData) {
// first save the new user
$userModel = new Model_User();
$userId = $userModel->insert($userData);
$userData = $userModel->find($userId)->current();
$authData['user_id'] = $userId;
$this->insert($authData);
$this->getObserver('Authenticatable')->updateLoginStats($userId);
return $userData;
} | [
"public",
"function",
"createNew",
"(",
"array",
"$",
"authData",
",",
"array",
"$",
"userData",
")",
"{",
"// first save the new user",
"$",
"userModel",
"=",
"new",
"Model_User",
"(",
")",
";",
"$",
"userId",
"=",
"$",
"userModel",
"->",
"insert",
"(",
"... | Store a new user. This creates a new auth_facebook record, but also
a new user record.
@param Array $authData Data for the new Auth record
@param Array $userData Data for the new User record
@return Garp_Db_Table_Row The new user data | [
"Store",
"a",
"new",
"user",
".",
"This",
"creates",
"a",
"new",
"auth_facebook",
"record",
"but",
"also",
"a",
"new",
"user",
"record",
"."
] | ee6fa716406047568bc5227670748d3b1dd7290d | https://github.com/grrr-amsterdam/garp3/blob/ee6fa716406047568bc5227670748d3b1dd7290d/library/Garp/Model/Db/AuthFacebook.php#L27-L37 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.