_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q263300 | GestPayCryptWS.getDecParams | test | private function getDecParams()
{
// Parametri obbligatori
$params = array(
'shopLogin' => $this->getShopLogin(),
'CryptedString' => $this->getEncryptedString(),
);
return array_merge($params, $this->getOptParams());
} | php | {
"resource": ""
} |
q263301 | UpdateProcess.saveDynamicData | test | private function saveDynamicData($entity, $data)
{
$fields = new DynamicFields($entity);
$fields->init($data);
$fields->save();
} | php | {
"resource": ""
} |
q263302 | File.valid | test | public function valid()
{
$bResult = false;
if ($this->getOption('required') == 'true') {
$value = $this->getValue();
if (empty($value)) {
$this->isValid = false;
} else {
$bResult = true;
}
} else {
$bResult = true;
}
return $bResult;
} | php | {
"resource": ""
} |
q263303 | File.save | test | public function save()
{
if (isset($this->file)) {
$fileName = $this->entityId . '_' . $this->fieldId . '.' . $this->file->getClientOriginalExtension();
$this->value = $fileName;
$this->file->move(public_path() . config('asgard.dynamicfield.config.files-path'), $fileName);
}
parent::save();
} | php | {
"resource": ""
} |
q263304 | DynamicFields.init | test | public function init($default = null)
{
$this->request = $default;
$locale = $this->locale;
$entityItem = $this->entity;
$type = $this->type;
if (isset($locale)) {
$entity = new Entity($entityItem->id, $entityItem->template, $locale, $type);
$entity->init($default);
$this->entities[$locale] = $entity;
} else {
$languages = LaravelLocalization::getSupportedLocales();
foreach ($languages as $locale => $code) {
$entity = new Entity(@$entityItem->id, @$entityItem->template, $locale, $type);
$entity->init($default);
$this->entities[$locale] = $entity;
}
}
} | php | {
"resource": ""
} |
q263305 | DynamicFields.renderFields | test | public function renderFields($locale)
{
$entity = $this->entities[$locale];
if (isset($this->request)) {
$entity->valid();
}
$html = $entity->render();
return $html;
} | php | {
"resource": ""
} |
q263306 | DynamicFields.getFieldValue | test | public function getFieldValue($fieldName, $locale = 'en')
{
$strValue = '';
$entity = $this->entities[$locale];
$values = $entity->values();
if (count($values)) {
$keys = array_keys($values);
if (in_array($fieldName, $keys)) {
$strValue = $values[$fieldName];
}
}
return $strValue;
} | php | {
"resource": ""
} |
q263307 | DynamicFields.getFieldValues | test | public function getFieldValues($locale = 'en')
{
$entity = $this->entities[$locale];
$values = $entity->values();
return $values;
} | php | {
"resource": ""
} |
q263308 | DynamicFields.valid | test | public function valid()
{
$isValid = true;
foreach ($this->entities as $entity) {
$isValid = $entity->valid();
if (!$isValid) {
break;
}
}
return $isValid;
} | php | {
"resource": ""
} |
q263309 | DynamicFields.save | test | public function save()
{
$isSave = true;
foreach ($this->entities as $entity) {
$isSave = $entity->save();
if (!$isSave) {
break;
}
}
return $isSave;
} | php | {
"resource": ""
} |
q263310 | DynamicfieldViewComposer.assignDynamicFieldsToPageObject | test | private function assignDynamicFieldsToPageObject($view)
{
$entityDynamic = null;
$data = $view->getData();
//TODO Fix with event
if (count($data)) {
$arrType = config('asgard.dynamicfield.config.entity-type');
$arrType = array_keys($arrType);
// edit entity
foreach ($data as $item) {
if (is_object($item)) {
$className = get_class($item);
if (in_array($className, $arrType)) {
$entityDynamic = $item;
break;
}
}
}
}
// initial model data for create new;
if (is_null($entityDynamic)) {
$router = \Request::route()->getName();
$arrCreateRouter = config('asgard.dynamicfield.config.router');
if (array_key_exists($router, $arrCreateRouter)) {
$entityDynamic = new $arrCreateRouter[$router];
}
}
$view->with('entityDynamic', $entityDynamic);
return $view;
} | php | {
"resource": ""
} |
q263311 | Entity.getFieldByLocale | test | public function getFieldByLocale($locale = 'en')
{
$fields = $this->fields()->where('locale', $locale)->get();
if ($fields->count()) {
$object = $fields[0];
} else {
$object = new FieldTranslation();
}
return $object;
} | php | {
"resource": ""
} |
q263312 | Entity.getRepeatersByLocale | test | public function getRepeatersByLocale($locale)
{
$repeaters = $this->repeaters()
->where('locale', $locale)
->orderBy('order')
->get();
return $repeaters;
} | php | {
"resource": ""
} |
q263313 | Entity.getEntitiesByFieldId | test | public function getEntitiesByFieldId($fieldId)
{
$values = $this->where('field_id', $fieldId)->get();
if ($values->count()) {
$object = $values[0];
} else {
$object = new self();
}
return $object;
} | php | {
"resource": ""
} |
q263314 | Entity.scopeGetEntity | test | public function scopeGetEntity($query, $entityId, $entityType, $fieldId)
{
$entities = $query->where('entity_id', $entityId)
->where('entity_type', $entityType)
->where('field_id', $fieldId)->get();
if ($entities->count()) {
$object = $entities[0];
} else {
$object = new self();
}
return $object;
} | php | {
"resource": ""
} |
q263315 | Entity.duplicate | test | public function duplicate($pageId = 0)
{
$entity = $this->replicate();
$entity->entity_id = $pageId;
$entity->save();
$type = $this->getFieldType();
if ($type != 'repeater') {
$fields = $this->Fields;
foreach ($fields as $translation) {
$tranReplicate = $translation->replicate();
$tranReplicate->entity_field_id = $entity->id;
$tranReplicate->save();
}
} else {
$repeaters = $this->Repeaters;
foreach ($repeaters as $repeater) {
$fields = $repeater->FieldValues;
$repeaterReplicate = $repeater->replicate();
$repeaterReplicate->entity_repeater_id = $entity->id;
$repeaterReplicate->save();
foreach ($fields as $translation) {
$tranReplicate = $translation->replicate();
$tranReplicate->translation_id = $repeaterReplicate->id;
$tranReplicate->save();
}
}
}
return $entity;
} | php | {
"resource": ""
} |
q263316 | Entity.init | test | public function init($default = null)
{
//getGroupByRule
$options['type'] = $this->type;
$options['template'] = $this->template;
$groups = $this->getGroupByRule($options);
if (count($groups)) {
foreach ($groups as $groupId) {
$group = Group::find($groupId);
$this->initGroup($group, $default);
}
}
} | php | {
"resource": ""
} |
q263317 | Entity.valid | test | public function valid()
{
$isValid = true;
if (count($this->groupFields)) {
foreach ($this->groupFields as $group) {
$fields = $group['fields'];
foreach ($fields as $field) {
$isValid = $field->valid();
if (!$isValid) {
break;
}
}
}
}
return $isValid;
} | php | {
"resource": ""
} |
q263318 | Entity.render | test | public function render()
{
$html = '';
if (count($this->groupFields)) {
foreach ($this->groupFields as $group) {
$htmlControl = '';
$fields = $group['fields'];
foreach ($fields as $field) {
$htmlControl .= $field->render();
}
$label = $group['name'];
$html .= sprintf($this->htmlItemTemplate, $label, $htmlControl);
}
}
return $html;
} | php | {
"resource": ""
} |
q263319 | Entity.save | test | public function save()
{
$bResult = false;
try {
if (count($this->groupFields)) {
foreach ($this->groupFields as $group) {
$fields = $group['fields'];
foreach ($fields as $field) {
$field->save();
}
}
}
$bResult = true;
} catch (\Exception $e) {
//exception handling
}
return $bResult;
} | php | {
"resource": ""
} |
q263320 | Entity.getGroupByRule | test | public function getGroupByRule($options)
{
$arrResult = array();
$rules = Rule::all();
foreach ($rules as $rule) {
$params = (array) json_decode($rule->rule);
$defaultMatch = true;
foreach ($params as $item) {
$match = $this->matchRule((array) $item, $options);
$defaultMatch = $defaultMatch && $match;
}
if ($defaultMatch) {
$arrResult[$rule->group_id] = $rule->group_id;
}
}
return $arrResult;
} | php | {
"resource": ""
} |
q263321 | Entity.matchRule | test | private function matchRule($rule, $options)
{
$match = false;
$type = array_get($rule, 'parameter', 'type');
$operator = array_get($rule, 'operator', 'equal');
$value = array_get($rule, 'value', 'default');
if ($operator == 'equal') {
$match = ($value === $options[$type]);
} elseif ($operator == 'notequal') {
$match = ($value !== $options[$type]);
}
return $match;
} | php | {
"resource": ""
} |
q263322 | Entity.initGroup | test | private function initGroup($group, $default = null)
{
$groupId = $group->id;
$groupName = $group->name;
$fields = $group->getListFields();
$fieldData = $this->getFieldPostData($default);
$controls = array();
if ($fields->count()) {
$this->fieldInDB = EntityModel::getAllDataFields($this->entityId, $this->type);
$controls['name'] = $groupName;
foreach ($fields as $field) {
$fieldValue = @$fieldData['fields'][$field->id];
$fieldControl = null;
$dbData = $this->getFieldDataInDB($field->id, $this->locale);
switch ($field->type) {
case 'text':
$fieldControl = new Text($field, $this->entityId, $this->locale, $dbData);
break;
case 'number':
$fieldControl = new Number($field, $this->entityId, $this->locale, $dbData);
break;
case 'textarea':
$fieldControl = new Textarea($field, $this->entityId, $this->locale, $dbData);
break;
case 'wysiwyg':
$fieldControl = new Wysiwyg($field, $this->entityId, $this->locale, $dbData);
break;
case 'file':
$fieldControl = new File($field, $this->entityId, $this->locale, $dbData);
break;
case 'image':
$fieldControl = new Image($field, $this->entityId, $this->locale, $dbData);
break;
case 'repeater':
$fieldControl = new Repeater($field, $this->entityId, $this->locale, $dbData);
break;
}
// assign entity type class to field to use for save data;
$fieldControl->setEntityType($this->type);
$fieldControl->init($fieldValue);
$controls['fields'][$field->id] = $fieldControl;
$this->fieldValues[$field->name] = $fieldControl->getDisplayValue();
}
$this->groupFields[$groupId] = $controls;
}
} | php | {
"resource": ""
} |
q263323 | Entity.getFieldPostData | test | private function getFieldPostData($data)
{
$arrData = array();
if (isset($data)) {
$arrData = @$data[$this->locale];
}
return $arrData;
} | php | {
"resource": ""
} |
q263324 | Canvas.set | test | public function set($x, $y) {
list($x, $y, $px, $py) = $this->prime($x, $y);
$this->chars[$py][$px] |= $this->getDotFromMap($x, $y);
} | php | {
"resource": ""
} |
q263325 | Canvas.get | test | public function get($x, $y) {
list($x, $y, , , $char) = $this->prime($x, $y);
return (bool) ($char & $this->getDotFromMap($x, $y));
} | php | {
"resource": ""
} |
q263326 | Canvas.row | test | public function row($y, array $options = []) {
$row = isset($this->chars[$y]) ? $this->chars[$y] : [];
if (!isset($options['min_x']) || !isset($options['max_x'])) {
if (!($keys = array_keys($row))) {
return '';
}
}
$min = isset($options['min_x']) ? $options['min_x'] : min($keys);
$max = isset($options['max_x']) ? $options['max_x'] : max($keys);
return array_reduce(range($min, $max), function ($carry, $item) use ($row) {
return $carry .= $this->toBraille(isset($row[$item]) ? $row[$item] : 0);
}, '');
} | php | {
"resource": ""
} |
q263327 | Canvas.rows | test | public function rows(array $options = []) {
if (!isset($options['min_y']) || !isset($options['max_y'])) {
if (!($keys = array_keys($this->chars))) {
return [];
}
}
$min = isset($options['min_y']) ? $options['min_y'] : min($keys);
$max = isset($options['max_y']) ? $options['max_y'] : max($keys);
if (!isset($options['min_x']) || !isset($options['max_x'])) {
$flattened = array();
foreach ($this->chars as $key => $char) {
$flattened = array_merge($flattened, array_keys($char));
}
}
$options['min_x'] = isset($options['min_x']) ? $options['min_x'] : min($flattened);
$options['max_x'] = isset($options['max_x']) ? $options['max_x'] : max($flattened);
return array_map(function ($i) use ($options) {
return $this->row($i, $options);
}, range($min, $max));
} | php | {
"resource": ""
} |
q263328 | Canvas.getDotFromMap | test | private function getDotFromMap($x, $y) {
$y = $y % 4;
$x = $x % 2;
return self::$pixel_map[$y < 0 ? 4 + $y : $y][$x < 0 ? 2 + $x : $x];
} | php | {
"resource": ""
} |
q263329 | Canvas.prime | test | private function prime($x, $y) {
$x = round($x);
$y = round($y);
$px = floor($x / 2);
$py = floor($y / 4);
if (!isset($this->chars[$py][$px])) {
$this->chars[$py][$px] = 0;
}
return [$x, $y, $px, $py, $this->chars[$py][$px]];
} | php | {
"resource": ""
} |
q263330 | Repeater.initRepeatFields | test | private function initRepeatFields($fieldInfo, $default = null)
{
$controls = array();
$repeaterId = $fieldInfo->id;
$entity = Entity::getEntity($this->entityId, $this->entityType, $repeaterId);
$repeaters = Entity::getAllDataTranactionRepeater($this->entityId, $this->entityType, $repeaterId, $this->locale);
$this->repeaterFieldData = Entity::getAllDataTranactionRepeaterFields($this->entityId, $this->entityType, $repeaterId, $this->locale);
$post_data = @$default['value'];
$this->defaultOrder = @$default['order'];
$repeater_field = $this->field;
$fieldOfRepeater = $repeater_field->getListFields();
if (isset($post_data)) {
unset($post_data['clone']);
$this->deleteItems = $default['delete'];
foreach ($post_data as $k => $control) {
$listDefault = $post_data[$k];
$controls[$k]['fields'] = $this->createListControlAfterPostData($k, $listDefault, $fieldOfRepeater);
$controls[$k]['order'] = -1;
}
} else {
if (count($repeaters)) {
$i = 1;
foreach ($repeaters as $repeater) {
$controls[$repeater->id]['fields'] = $this->createListControl($repeater, $fieldOfRepeater);
$controls[$repeater->id]['order'] = $i;
++$i;
}
}
}
$this->groupFields = $controls;
$this->repeaterHeaders = $this->createHeaderRepeater($fieldOfRepeater);
} | php | {
"resource": ""
} |
q263331 | Repeater.createListControlAfterPostData | test | private function createListControlAfterPostData($repeaterId, $default = null, $fieldOfRepeater)
{
$controls = array();
$nameFormat = '%s[fields]' . sprintf('[%s][value][%s]', $this->getFieldId(), $repeaterId) . '[%s][value]';
$idFormat = '%s_' . sprintf('%s_%s_', $this->getFieldId(), $repeaterId) . '_%s_value';
if ($fieldOfRepeater->count()) {
foreach ($fieldOfRepeater as $field) {
$listDefault = $default[$field->id];
$fieldControl = $this->createFieldControl($field, $repeaterId, $listDefault);
$fieldControl->setHtmlNameFormat($nameFormat);
$fieldControl->setHtmlIdFormat($idFormat);
$controls[$field->id] = $fieldControl;
}
}
return $controls;
} | php | {
"resource": ""
} |
q263332 | Repeater.createListControl | test | private function createListControl($repeater, $fieldOfRepeater)
{
$nameFormat = '%s[fields]' . sprintf('[%s][value][%s]', $this->getFieldId(), $repeater->id) . '[%s][value]';
$idFormat = '%s_' . sprintf('%s_%s_', $this->getFieldId(), $repeater->id) . '_%s_value';
if ($fieldOfRepeater->count()) {
foreach ($fieldOfRepeater as $field) {
$dbData = $this->getFieldDataInDB($field->id, $repeater->id);
$fieldControl = $this->createFieldControl($field, $repeater->id);
$fieldControl->setHtmlItemTemplate('%s');
$fieldControl->setHtmlNameFormat($nameFormat);
$fieldControl->setHtmlIdFormat($idFormat);
// $value = $repeater->getFieldValue($field->id);
$fieldControl->setValue($dbData);
$controls[$field->id] = $fieldControl;
}
}
return $controls;
} | php | {
"resource": ""
} |
q263333 | Repeater.createFieldControl | test | private function createFieldControl($field, $translateId, $default = null)
{
$fieldControl = null;
$fieldValue = $default;
switch ($field->type) {
case 'text':
$fieldControl = new Text($field, $this->entityId, $this->locale);
break;
case 'number':
$fieldControl = new Number($field, $this->entityId, $this->locale);
break;
case 'textarea':
$fieldControl = new Textarea($field, $this->entityId, $this->locale);
break;
case 'wysiwyg':
$fieldControl = new Wysiwyg($field, $this->entityId, $this->locale);
break;
case 'file':
$fieldControl = new File($field, $this->entityId, $this->locale);
break;
case 'image':
$fieldControl = new Image($field, $this->entityId, $this->locale);
break;
}
// assign entity type class to field to use for save data;
$fieldControl->setEntityType($this->entityType);
$fieldControl->setRepeaterId($this->fieldId);
$fieldControl->setTranslateId($translateId);
$fieldControl->init($fieldValue);
return $fieldControl;
} | php | {
"resource": ""
} |
q263334 | Repeater.createHeaderRepeater | test | private function createHeaderRepeater($fieldOfRepeater)
{
$repeater = new RepeaterTranslation();
//TODO Here was ='clone'
$repeater->id = 'clone';
$controls = $this->createListControl($repeater, $fieldOfRepeater);
return $controls;
} | php | {
"resource": ""
} |
q263335 | Repeater.save | test | public function save()
{
$bResult = false;
try {
if (!empty($this->deleteItems)) {
$items = explode(',', $this->deleteItems);
RepeaterTranslation::destroy($items);
}
if (count($this->groupFields)) {
foreach ($this->groupFields as $groupId => $group) {
$fields = $group['fields'];
$order = $this->defaultOrder[$groupId];
$translate_id = 0;
foreach ($fields as $field) {
if ($translate_id) {
$field->setTranslateId($translate_id);
}
$field->save();
$translate_id = $field->getTranslateId();
}
// update order
$translate = RepeaterTranslation::find($translate_id);
$translate->order = $order;
$translate->save();
}
}
$bResult = true;
} catch (\Exception $e) {
//exception handling
}
return $bResult;
} | php | {
"resource": ""
} |
q263336 | Repeater.getDisplayValue | test | public function getDisplayValue()
{
$values = array();
if (count($this->groupFields)) {
$i = 0;
foreach ($this->groupFields as $key => $group) {
$fields = $group['fields'];
$item = array();
foreach ($fields as $field) {
$item[$field->getFieldName()] = $field->getDisplayValue();
}
$item['id'] = $key;
$values[$i] = $item;
++$i;
}
}
return $values;
} | php | {
"resource": ""
} |
q263337 | RepeaterTranslation.getFieldValue | test | public function getFieldValue($fieldId)
{
$object = new RepeaterValue();
if (is_numeric($this->id)) {
$repeatValues = $this->fieldValues()->where('field_id', $fieldId)->get();
if ($repeatValues->count()) {
$object = $repeatValues[0];
}
}
return $object;
} | php | {
"resource": ""
} |
q263338 | Template.getTemplateName | test | private function getTemplateName($template)
{
preg_match('/{{-- Template: (.*) --}}/', $template->getContents(), $templateName);
if (count($templateName) > 1) {
return $templateName[1];
}
return $this->getDefaultTemplateName($template);
} | php | {
"resource": ""
} |
q263339 | Template.getDefaultTemplateName | test | private function getDefaultTemplateName($template)
{
$relativePath = $template->getRelativePath();
$fileName = $this->removeExtensionsFromFilename($template);
return $this->hasSubdirectory($relativePath) ? $relativePath . '/' . $fileName : $fileName;
} | php | {
"resource": ""
} |
q263340 | FieldBase.init | test | public function init($default = null)
{
//$this->model = $this->getModel();
if (!isset($default)) {
//$this->value = $this->model->value;
if (empty($this->dataInDB)) {
$this->value = $this->getOption('default');
} else {
$this->value = $this->dataInDB;
}
} else {
$this->value = $default['value'];
}
} | php | {
"resource": ""
} |
q263341 | FieldBase.getModel | test | public function getModel()
{
if (is_a($this->field, 'Modules\Dynamicfield\Entities\Field')) {
$entity = Entity::getEntity($this->entityId, $this->entityType, $this->fieldId);
$model = $entity->getFieldByLocale($this->locale);
} else {
$model = new RepeaterValue();
if (is_numeric($this->translationId)) {
$repeaterTranslate = RepeaterTranslation::firstOrNew(array('id' => $this->translationId));
$model = $repeaterTranslate->getFieldValue($this->fieldId);
}
}
return $model;
} | php | {
"resource": ""
} |
q263342 | FieldBase.getHtmlId | test | public function getHtmlId()
{
$strHtmlId = sprintf($this->htmlIdFormat, $this->locale, $this->fieldId);
return $strHtmlId;
} | php | {
"resource": ""
} |
q263343 | FieldBase.getHtmlName | test | public function getHtmlName()
{
$strHtmlName = sprintf($this->htmlNameFormat, $this->locale, $this->fieldId);
return $strHtmlName;
} | php | {
"resource": ""
} |
q263344 | FieldBase.save | test | public function save()
{
$this->model = $this->getModel();
if (is_a($this->model, 'Modules\Dynamicfield\Entities\FieldTranslation')) {
$this->saveField();
} else {
// save sub control of repeater
$this->saveRepeaterField();
}
} | php | {
"resource": ""
} |
q263345 | FieldBase.saveField | test | public function saveField()
{
$entity = Entity::getEntity($this->entityId, $this->entityType, $this->fieldId);
if (!$entity->id) {
$entity->entity_id = $this->entityId;
$entity->field_id = $this->fieldId;
$entity->entity_type = $this->entityType;
$entity->save();
}
$this->model->entity_field_id = $entity->id;
$this->model->locale = $this->locale;
$this->model->value = $this->getValue();
$this->model->save();
} | php | {
"resource": ""
} |
q263346 | FieldBase.saveRepeaterField | test | public function saveRepeaterField()
{
$repeaterId = $this->repeaterId;
$repeaterTranslate = RepeaterTranslation::firstOrNew(array('id' => $this->translationId));
if (!$repeaterTranslate->id) {
$entity = Entity::getEntity($this->entityId, $this->entityType, $repeaterId);
if (!$entity->id) {
$entity->entity_id = $this->entityId;
$entity->entity_type = $this->entityType;
$entity->field_id = $repeaterId;
$entity->save();
}
$repeaterTranslate->entity_repeater_id = $entity->id;
$repeaterTranslate->locale = $this->locale;
$repeaterTranslate->save();
}
$this->model->translation_id = $repeaterTranslate->id;
$this->model->field_id = $this->fieldId;
$this->model->value = $this->getValue();
$this->model->save();
// assign translate_id to same group;
$this->translationId = $this->model->translation_id;
} | php | {
"resource": ""
} |
q263347 | FieldBase.getOption | test | public function getOption($key)
{
$value = '';
try {
$value = $this->options[$key];
} catch (\Exception $e) {
}
return $value;
} | php | {
"resource": ""
} |
q263348 | Turtle.forward | test | public function forward($length) {
$theta = $this->rotation / 180.0 * M_PI;
$x = $this->x + $length * cos($theta);
$y = $this->y + $length * sin($theta);
$this->move($x, $y);
} | php | {
"resource": ""
} |
q263349 | Turtle.move | test | public function move($x, $y) {
if (!$this->up) {
$x1 = round($this->x);
$y1 = round($this->y);
$x2 = $x;
$y2 = $y;
$xdiff = max($x1, $x2) - min($x1, $x2);
$ydiff = max($y1, $y2) - min($y1, $y2);
$xdir = $x1 <= $x2 ? 1 : -1;
$ydir = $y1 <= $y2 ? 1 : -1;
$r = max($xdiff, $ydiff);
for ($i = 0; $i <= $r; $i++) {
$x = $x1;
$y = $y1;
if ($ydiff > 0) {
$y += ((float)$i * $ydiff) / $r * $ydir;
}
if ($xdiff > 0) {
$x += ((float)$i * $xdiff) / $r * $xdir;
}
$this->set($x, $y);
}
}
$this->x = $x;
$this->y = $y;
} | php | {
"resource": ""
} |
q263350 | TaskConfiguration.hasAncestor | test | public function hasAncestor(TaskConfiguration $taskConfig)
{
foreach ($this->getPreviousTasksConfigurations() as $previousTaskConfig) {
// Avoid errors for direct ancestors
if ($this->getCode() === $previousTaskConfig->getCode()) {
continue;
}
if ($previousTaskConfig->getCode() === $taskConfig->getCode()) {
return true;
}
if ($previousTaskConfig->hasAncestor($taskConfig)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q263351 | TaskConfiguration.hasDescendant | test | public function hasDescendant(TaskConfiguration $taskConfig, $checkErrors = true)
{
foreach ($this->getNextTasksConfigurations() as $nextTaskConfig) {
// Avoid errors for direct descendant
if ($this->getCode() === $nextTaskConfig->getCode()) {
continue;
}
if ($nextTaskConfig->getCode() === $taskConfig->getCode()) {
return true;
}
if ($nextTaskConfig->hasDescendant($taskConfig, $checkErrors)) {
return true;
}
}
if ($checkErrors) {
foreach ($this->getErrorTasksConfigurations() as $errorTasksConfig) {
// Avoid errors for direct error descendant
if ($this->getCode() === $errorTasksConfig->getCode()) {
continue;
}
if ($errorTasksConfig->getCode() === $taskConfig->getCode()) {
return true;
}
if ($errorTasksConfig->hasDescendant($taskConfig, $checkErrors)) {
return true;
}
}
}
return false;
} | php | {
"resource": ""
} |
q263352 | ProcessState.reset | test | public function reset($cleanInput)
{
$this->setOutput(null);
$this->setSkipped(false);
$this->setException(null);
$this->setErrorOutput(null);
if($cleanInput) {
$this->setInput(null);
$this->setPreviousState(null);
}
} | php | {
"resource": ""
} |
q263353 | ConditionTrait.checkCondition | test | protected function checkCondition($input, $conditions)
{
foreach ($conditions['match'] as $key => $value) {
if (!$this->checkValue($input, $key, $value)) {
return false;
}
}
foreach ($conditions['empty'] as $key => $value) {
if (!$this->checkEmpty($input, $key)) {
return false;
}
}
foreach ($conditions['match_regexp'] as $key => $value) {
if (!$this->checkValue($input, $key, $value, true, true)) {
return false;
}
}
foreach ($conditions['not_match'] as $key => $value) {
if (!$this->checkValue($input, $key, $value, false)) {
return false;
}
}
foreach ($conditions['not_empty'] as $key => $value) {
if ($this->checkEmpty($input, $key)) {
return false;
}
}
foreach ($conditions['not_match_regexp'] as $key => $value) {
if (!$this->checkValue($input, $key, $value, false, true)) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q263354 | ConditionTrait.configureWrappedConditionOptions | test | protected function configureWrappedConditionOptions(string $wrapperKey, OptionsResolver $resolver)
{
$resolver->setDefault($wrapperKey, []);
$resolver->setAllowedTypes($wrapperKey, ['array']);
$resolver->setNormalizer($wrapperKey, function (OptionsResolver $options, $value) {
$conditionResolver = new OptionsResolver();
$this->configureConditionOptions($conditionResolver);
return $conditionResolver->resolve($value);
});
} | php | {
"resource": ""
} |
q263355 | ConditionTrait.configureConditionOptions | test | protected function configureConditionOptions(OptionsResolver $resolver)
{
$resolver->setDefault('not_match', []);
$resolver->setDefault('match', []);
$resolver->setDefault('not_empty', []);
$resolver->setDefault('empty', []);
$resolver->setDefault('not_match_regexp', []);
$resolver->setDefault('match_regexp', []);
$resolver->setAllowedTypes('not_match', 'array');
$resolver->setAllowedTypes('match', 'array');
$resolver->setAllowedTypes('not_match_regexp', 'array');
$resolver->setAllowedTypes('match_regexp', 'array');
} | php | {
"resource": ""
} |
q263356 | ConditionTrait.checkValue | test | protected function checkValue($input, $key, $value, $shouldMatch = true, $regexpMode = false)
{
$currentValue = $this->getValue($input, $key);
/** @noinspection TypeUnsafeComparisonInspection */
if ($shouldMatch && !$regexpMode && $currentValue != $value) {
return false;
}
/** @noinspection TypeUnsafeComparisonInspection */
if (!$shouldMatch && !$regexpMode && $currentValue == $value) {
return false;
}
if ($regexpMode) {
$pregMatch = preg_match($value, $currentValue);
if ($shouldMatch && (false === $pregMatch || 0 === $pregMatch)) {
return false;
}
if (!$shouldMatch && (false === $pregMatch || $pregMatch > 0)) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q263357 | ConditionTrait.checkEmpty | test | protected function checkEmpty($input, $key)
{
$currentValue = $this->getValue($input, $key);
return empty($currentValue);
} | php | {
"resource": ""
} |
q263358 | ProcessHistory.getDuration | test | public function getDuration()
{
if ($this->getEndDate()) {
return $this->getEndDate()->getTimestamp() - $this->getStartDate()->getTimestamp();
}
return null;
} | php | {
"resource": ""
} |
q263359 | ContextualOptionResolver.contextualizeOptions | test | public function contextualizeOptions(array $options, array $context): array
{
$contextualizedOptions = [];
foreach ($options as $key => $value) {
$contextualizedKey = $this->contextualizeOption($key, $context);
$contextualizedValue = $this->contextualizeOption($value, $context);
$contextualizedOptions[$contextualizedKey] = $contextualizedValue;
}
return $contextualizedOptions;
} | php | {
"resource": ""
} |
q263360 | ProcessHelpCommand.findBestNextTask | test | protected function findBestNextTask($branches, $taskList, ProcessConfiguration $process)
{
// Get resolvable tasks
$taskCandidates = [];
foreach ($taskList as $taskCode) {
$task = $process->getTaskConfiguration($taskCode);
if (empty($task->getPreviousTasksConfigurations())) {
return $taskCode;
}
// Check if task has all necessary ancestors in branches
$hasAllAncestors = array_reduce($task->getPreviousTasksConfigurations(), function ($result, TaskConfiguration $prevTask) use ($branches) {
return $result && \in_array($prevTask->getCode(), $branches);
}, true);
if ($hasAllAncestors) {
$taskCandidates[] = $taskCode;
}
}
if (empty($taskCandidates)) {
throw new \UnexpectedValueException('Cannot find a task to output');
}
// Try to find the task the most on the right
$taskWeights = [];
foreach ($taskCandidates as $taskCandidate) {
$weight = 0;
$task = $process->getTaskConfiguration($taskCandidate);
foreach ($task->getPreviousTasksConfigurations() as $prevTask) {
$key = array_search($prevTask->getCode(), $branches);
// Should never be non-numeric...
if (!is_numeric($key)) {
throw new \UnexpectedValueException('Invalid key type');
}
$weight += $key;
}
if (!empty($task->getPreviousTasksConfigurations())) {
$weight = $weight / \count($task->getPreviousTasksConfigurations());
}
$taskWeights[$taskCandidate] = $weight;
}
arsort($taskWeights);
$bestCandidate = key($taskWeights);
$bestWeight = $taskWeights[$bestCandidate];
$equalWeights = array_filter($taskWeights, function ($item) use ($bestWeight) {
return $item == $bestWeight;
});
if (count($equalWeights) == 1) {
return $bestCandidate;
}
// If a few tasks have the same weight, return the tasks with the lowest number of children
$childCounts = [];
foreach ($equalWeights as $taskCode => $weight) {
$task = $process->getTaskConfiguration($taskCode);
$childCounts[$taskCode] = $this->getTaskChildrenCount($task);
}
asort($childCounts);
return key($childCounts);
} | php | {
"resource": ""
} |
q263361 | InputAggregatorTask.getInputCode | test | protected function getInputCode(ProcessState $state)
{
$previousState = $state->getPreviousState();
$previousTaskCode = $previousState->getTaskConfiguration()->getCode();
$inputCodes = $this->getOption($state, 'input_codes');
if (!array_key_exists($previousTaskCode, $inputCodes)) {
throw new \UnexpectedValueException("Task '{$previousTaskCode}' is not mapped in the input_codes option");
}
return $inputCodes[$previousTaskCode];
} | php | {
"resource": ""
} |
q263362 | InputAggregatorTask.isResolved | test | protected function isResolved(ProcessState $state)
{
$inputCodes = $this->getOption($state, 'input_codes');
foreach ($inputCodes as $inputCode) {
if (!array_key_exists($inputCode, $this->inputs)) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q263363 | InputCsvReaderTask.getFilePath | test | protected function getFilePath(array $options, string $input)
{
$basePath = $options['base_path'];
if (\strlen($basePath) > 0) {
$basePath = rtrim($options['base_path'], '/').'/';
}
return $basePath.$input;
} | php | {
"resource": ""
} |
q263364 | ListProcessCommand.processSorter | test | public function processSorter(ProcessConfiguration $a, ProcessConfiguration $b)
{
if ($a->getCode() === $b->getCode()) {
return 0;
}
return ($a->getCode() < $b->getCode()) ? -1 : 1;
} | php | {
"resource": ""
} |
q263365 | InputIteratorTask.handleIteratorFromInput | test | protected function handleIteratorFromInput(ProcessState $state)
{
if ($this->iterator instanceof \Iterator) {
if ($this->iterator->valid()) {
// No action needed, execution is in progress
return;
}
// Cleanup invalid iterator => prepare for new iteration cycle
$this->iterator = null;
}
// This should never be reached
if (null !== $this->iterator) {
throw new \UnexpectedValueException(
"At this point iterator should have been null, maybe it's a wrong type..."
);
}
// Create iterator
if ($state->getInput() instanceof \Iterator) {
$this->iterator = $state->getInput();
} elseif (\is_array($state->getInput())) {
$this->iterator = new \ArrayIterator($state->getInput());
}
// Assert iterator is OK
if (!$this->iterator instanceof \Iterator) {
throw new \UnexpectedValueException('Cannot create iterator from input');
}
} | php | {
"resource": ""
} |
q263366 | CounterTask.flush | test | public function flush(ProcessState $state): void
{
$modulo = $this->getOption($state, 'flush_every');
if (0 === $this->counter % $modulo) {
$state->setSkipped(true);
} else {
$state->setOutput($this->counter);
}
} | php | {
"resource": ""
} |
q263367 | CsvResource.getLineCount | test | public function getLineCount(): int
{
if (null === $this->lineCount) {
$this->rewind();
$line = 0;
while (!$this->isEndOfFile()) {
++$line;
$this->readRaw();
}
$this->rewind();
$this->lineCount = $line;
}
return $this->lineCount;
} | php | {
"resource": ""
} |
q263368 | CsvResource.rewind | test | public function rewind(): void
{
$this->assertOpened();
if (!rewind($this->handler)) {
throw new \RuntimeException("Unable to rewind '{$this->getResourceName()}'");
}
$this->currentLine = 0;
if (!$this->manualHeaders) {
$this->readRaw(); // skip headers
}
} | php | {
"resource": ""
} |
q263369 | TransformerTrait.getCleanedTransfomerCode | test | protected function getCleanedTransfomerCode(string $transformerCode)
{
$match = preg_match('/([^#]+)(#[\d]+)?/', $transformerCode, $parts);
if (1 === $match && $this->transformerRegistry->hasTransformer($parts[1])) {
return $parts[1];
}
return $transformerCode;
} | php | {
"resource": ""
} |
q263370 | ProcessConfiguration.getDependencyGroups | test | public function getDependencyGroups(): array
{
if (null === $this->dependencyGroups) {
$this->dependencyGroups = [];
foreach ($this->getTaskConfigurations() as $taskConfiguration) {
$isInBranch = false;
foreach ($this->dependencyGroups as $branch) {
if (\in_array($taskConfiguration->getCode(), $branch, true)) {
$isInBranch = true;
break;
}
}
if (!$isInBranch) {
$dependencies = $this->buildDependencies($taskConfiguration);
$dependencies = $this->sortDependencies($dependencies);
$this->dependencyGroups[] = $dependencies;
}
}
}
return $this->dependencyGroups;
} | php | {
"resource": ""
} |
q263371 | ProcessConfiguration.getMainTaskGroup | test | public function getMainTaskGroup(): array
{
if (null === $this->mainTaskGroup) {
$mainTask = $this->getMainTask();
foreach ($this->getDependencyGroups() as $branch) {
if (\in_array($mainTask->getCode(), $branch, true)) {
$this->mainTaskGroup = $branch;
break;
}
}
}
return $this->mainTaskGroup;
} | php | {
"resource": ""
} |
q263372 | ProcessConfiguration.checkCircularDependencies | test | public function checkCircularDependencies()
{
$taskConfigurations = $this->getTaskConfigurations();
foreach ($taskConfigurations as $taskConfiguration) {
foreach ($taskConfiguration->getPreviousTasksConfigurations() as $previousTaskConfig) {
if ($taskConfiguration->getCode() === $previousTaskConfig->getCode()) {
throw CircularProcessException::create($this->getCode(), $taskConfiguration->getCode());
}
}
if ($taskConfiguration->hasAncestor($taskConfiguration)) {
throw CircularProcessException::create($this->getCode(), $taskConfiguration->getCode());
}
}
} | php | {
"resource": ""
} |
q263373 | ProcessConfiguration.buildDependencies | test | protected function buildDependencies(TaskConfiguration $taskConfig, array &$dependencies = [])
{
$code = $taskConfig->getCode();
// May have been added by previous task
if (!\in_array($code, $dependencies, true)) {
$dependencies[] = $code;
foreach ($taskConfig->getPreviousTasksConfigurations() as $previousTasksConfig) {
$this->buildDependencies($previousTasksConfig, $dependencies);
}
foreach ($taskConfig->getNextTasksConfigurations() as $nextTasksConfig) {
$this->buildDependencies($nextTasksConfig, $dependencies);
}
foreach ($taskConfig->getErrorTasksConfigurations() as $errorTasksConfig) {
$this->buildDependencies($errorTasksConfig, $dependencies);
}
}
return $dependencies;
} | php | {
"resource": ""
} |
q263374 | ProcessConfiguration.sortDependencies | test | protected function sortDependencies(array $dependencies)
{
if (\count($dependencies) <= 1) {
return $dependencies;
}
try {
$this->checkCircularDependencies();
} catch (CircularProcessException $e) {
// Skipping the sort phase, it will throw later, on runtime
return $dependencies;
}
/** @var int $midOffset */
$midOffset = \count($dependencies) / 2;
$midTaskCode = $dependencies[$midOffset];
$midTask = $this->getTaskConfiguration($midTaskCode);
$previousTasks = [];
$independentTasks = [];
$nextTasks = [];
foreach ($dependencies as $taskCode) {
if ($taskCode !== $midTaskCode) {
$task = $this->getTaskConfiguration($taskCode);
if ($midTask->hasAncestor($task)) {
$previousTasks[] = $taskCode;
} elseif ($midTask->hasDescendant($task)) {
$nextTasks[] = $taskCode;
} else {
$independentTasks[] = $taskCode;
}
}
}
$previousTasks = $this->sortDependencies($previousTasks);
$independentTasks = $this->sortDependencies($independentTasks);
$nextTasks = $this->sortDependencies($nextTasks);
return array_merge($previousTasks, [$midTaskCode], $independentTasks, $nextTasks);
} | php | {
"resource": ""
} |
q263375 | ProcessManager.resolve | test | protected function resolve(TaskConfiguration $taskConfiguration): bool
{
$state = $taskConfiguration->getState();
if ($state->isResolved()) {
return true;
}
$state->setStatus(ProcessState::STATUS_PENDING);
// Resolve parents first
$allParentsResolved = true;
foreach ($taskConfiguration->getPreviousTasksConfigurations() as $previousTasksConfiguration) {
if (!$previousTasksConfiguration->getState()->isResolved()) {
$isResolved = $this->resolve($previousTasksConfiguration);
$allParentsResolved = $allParentsResolved && $isResolved;
}
}
if (!$allParentsResolved) {
throw new \UnexpectedValueException('Cannot resolve all parents');
}
$state->setStatus(ProcessState::STATUS_PROCESSING);
// Start processing only roots that are not in error branch
if ($taskConfiguration->isRoot()) {
$this->process($taskConfiguration);
}
// Then we can proceed with BlockingTask only if they have been processed normally and where never "proceeded"
if ($taskConfiguration->getTask() instanceof BlockingTaskInterface
&& $this->hasProcessedBlocking($taskConfiguration)
) {
$this->process($taskConfiguration, self::EXECUTE_PROCEED);
}
// This task is now finished, we may flush it to test if there is anything lasting
$this->flush($taskConfiguration);
$state->setStatus(ProcessState::STATUS_RESOLVED);
return $state->isResolved();
} | php | {
"resource": ""
} |
q263376 | ProcessManager.initialize | test | protected function initialize(TaskConfiguration $taskConfiguration): void
{
$this->taskConfiguration = $taskConfiguration;
if ($taskConfiguration->getErrorStrategy() === TaskConfiguration::STRATEGY_STOP
&& \count($taskConfiguration->getErrorOutputs()) > 0) {
$m = "Task configuration {$taskConfiguration->getCode()} has error outputs ";
$m .= "but it's error strategy 'stop' implies they will never be reached.";
$this->taskLogger->error($m);
}
// @todo Refactor this using a Registry with this feature:
// https://symfony.com/doc/current/service_container/service_subscribers_locators.html
$serviceReference = $taskConfiguration->getServiceReference();
if (0 === strpos($serviceReference, '@')) {
$task = $this->container->get(ltrim($serviceReference, '@'));
} elseif ($this->container->has($serviceReference)) {
$task = $this->container->get($serviceReference);
} else {
throw new \UnexpectedValueException(
"Unable to resolve service reference for Task '{$taskConfiguration->getCode()}'"
);
}
if (!$task instanceof TaskInterface) {
throw new \UnexpectedValueException(
"Service defined in Task '{$taskConfiguration->getCode()}' is not a TaskInterface"
);
}
$taskConfiguration->setTask($task);
if ($task instanceof InitializableTaskInterface) {
$state = $taskConfiguration->getState();
try {
$task->initialize($state);
} catch (\Throwable $e) {
$logContext = ['exception' => $e];
$this->taskLogger->critical($e->getMessage(), $logContext);
$state->stop($e);
}
}
$this->handleState($taskConfiguration->getState());
$this->taskConfiguration = null;
} | php | {
"resource": ""
} |
q263377 | ProcessManager.flush | test | protected function flush(TaskConfiguration $taskConfiguration): void
{
$task = $taskConfiguration->getTask();
if ($task instanceof BlockingTaskInterface) {
return;
}
if ($task instanceof FlushableTaskInterface) {
$this->process($taskConfiguration, self::EXECUTE_FLUSH);
if ($taskConfiguration->getState()->isStopped()) {
return;
}
}
// Check outputs
foreach ($taskConfiguration->getNextTasksConfigurations() as $nextTaskConfiguration) {
$this->flush($nextTaskConfiguration);
}
// Check errors
foreach ($taskConfiguration->getErrorTasksConfigurations() as $errorTasksConfiguration) {
$this->flush($errorTasksConfiguration);
}
} | php | {
"resource": ""
} |
q263378 | ProcessManager.handleState | test | protected function handleState(ProcessState $state): void
{
$processHistory = $state->getProcessHistory();
if ($state->getException() && $state->isStopped()) {
$processHistory->setFailed();
throw new \RuntimeException(
"Process {$state->getProcessConfiguration()->getCode()} has failed",
-1,
$state->getException()
);
}
} | php | {
"resource": ""
} |
q263379 | ProcessManager.checkProcess | test | protected function checkProcess(ProcessConfiguration $processConfiguration): void
{
$processConfiguration->checkCircularDependencies();
$taskConfigurations = $processConfiguration->getTaskConfigurations();
$mainTaskList = $processConfiguration->getMainTaskGroup();
$entryPoint = $processConfiguration->getEntryPoint();
$endPoint = $processConfiguration->getEndPoint();
// Check multi-branch processes
foreach ($taskConfigurations as $taskConfiguration) {
if (!\in_array($taskConfiguration->getCode(), $mainTaskList, true)) {
// We won't throw an error to ease development... but there must be some kind of warning
$state = $taskConfiguration->getState();
$logContext = ['main_task_list' => $mainTaskList];
$this->processLogger->warning("Task '{$taskConfiguration->getCode()}' is unreachable", $logContext);
$this->handleState($state);
}
}
// Check coherence for entry/end points
$processConfiguration->getEndPoint();
if ($entryPoint && !\in_array($entryPoint->getCode(), $mainTaskList, true)) {
throw InvalidProcessConfigurationException::createNotInMain($entryPoint, $mainTaskList);
}
if ($endPoint && !\in_array($endPoint->getCode(), $mainTaskList, true)) {
throw InvalidProcessConfigurationException::createNotInMain($endPoint, $mainTaskList);
}
} | php | {
"resource": ""
} |
q263380 | Model._validateModel | test | protected static function _validateModel()
{
// check if model is already validate
if (!isset(self::$_validationStatus[static::$_databaseName . static::$_tableName])) {
// grab actual class name from late state binding
$subClassName = get_class(new static());
// check model OOP static structure is OK
if (static::$_tableName === null) {
throw new Exception($subClassName . '::$_tableName must be implemented');
}
if (static::$_primaryKey === null) {
throw new Exception($subClassName . '::$_primaryKey must be implemented');
}
if (static::$_tableFields === null) {
throw new Exception($subClassName . '::$_tableFields must be implemented');
}
if(in_array(static::$_primaryKey,static::$_tableFields)) {
throw new Exception($subClassName . '::$_tableFields must not contain $_primaryKey');
}
// if user has implemented $_relations for this model, call the defineRelations() method
if (static::$_relations !== null) {
static::defineRelations();
}
// store model validation status
self::$_validationStatus[static::$_databaseName . static::$_tableName] = true;
}
} | php | {
"resource": ""
} |
q263381 | Model.toArray | test | public function toArray($includePrimary = true)
{
if ($includePrimary) {
$array = array(static::$_primaryKey => $this->{static::$_primaryKey});
} else {
$array = array();
}
foreach (static::$_tableFields as $unChamp) {
$array[$unChamp] = $this->{$unChamp};
}
return $array;
} | php | {
"resource": ""
} |
q263382 | Model.getModelFields | test | public static function getModelFields($includePrimary = true)
{
$fields = array();
if ($includePrimary) {
$fields[] = static::$_primaryKey;
}
foreach (static::$_tableFields as $unChamp) {
$fields[] = $unChamp;
}
return $fields;
} | php | {
"resource": ""
} |
q263383 | Model._unsetRelation | test | private function _unsetRelation(array $configRelation, $callArgs)
{
$isDeleted = false;
switch ($configRelation['typeRelation']) {
case self::MANY_TO_MANY:
// assure that we provide an array of relation to unset
if (!is_array($callArgs[0])) {
$callArgs[0] = array($callArgs[0]);
}
foreach ($callArgs[0] as $oneRelationModel) {
// build delete query for this relationship
$query = new InternalQueryHelper();
$query->delete($configRelation['relationTable'])
->where($configRelation['sourceField'], '=', '?')
->where($configRelation['targetField'], '=', '?');
$query = static::$_dataSource->prepare($query->buildQuery());
$query->execute(
array(
$this->{$configRelation['sourceField']},
$oneRelationModel->{$configRelation['targetField']}
)
);
}
$isDeleted = true;
break;
}
return $isDeleted;
} | php | {
"resource": ""
} |
q263384 | Model.formatClassnameToRelationName | test | protected static function formatClassnameToRelationName($fullClassName)
{
// test if namespace present and remove them
if (strpos($fullClassName, '\\') !== false) {
$fullClassName = explode('\\', $fullClassName);
$fullClassName = array_pop($fullClassName);
}
return strtolower($fullClassName);
} | php | {
"resource": ""
} |
q263385 | Model.addRelationOneToOne | test | protected static function addRelationOneToOne(
$sourceField,
$classRelation,
$targetField,
$autoGetFields = array(),
$aliasRelation = ''
)
{
if (!is_string($sourceField)) {
throw new Exception('$sourceField have to be a string');
}
if (!is_string($classRelation)) {
throw new Exception('$classRelation have to be a string');
}
if (!is_string($targetField)) {
throw new Exception('$targetField have to be a string');
}
// test is related class is a PicORM model
if (!class_exists($classRelation) || !new $classRelation() instanceof Model) {
throw new Exception("Class " . $classRelation . " doesn't exists or is not subclass of \PicORM\Model");
}
// test if its needed to autoget all fields
if ($autoGetFields === true) {
$autoGetFields = $classRelation::getModelFields();
}
// store autogetfields as an array
if (!is_array($autoGetFields)) {
$autoGetFields = array($autoGetFields);
}
// create relation id with normalized classRelation name
$idRelation = self :: formatClassnameToRelationName($classRelation);
// override the relation's id if an alias is present
if (!empty($aliasRelation)) {
$idRelation = strtolower($aliasRelation);
}
// store new relation in model
static::$_relations[$idRelation] = array(
'typeRelation' => self::ONE_TO_ONE,
'classRelation' => $classRelation,
'sourceField' => $sourceField,
'targetField' => $targetField,
'autoGetFields' => $autoGetFields
);
} | php | {
"resource": ""
} |
q263386 | Model.addRelationOneToMany | test | protected static function addRelationOneToMany($sourceField, $classRelation, $targetField, $aliasRelation = '')
{
// test is related class is a PicORM model
if (!class_exists($classRelation) || !new $classRelation() instanceof Model) {
throw new Exception("Class " . $classRelation . " doesn't exists or is not subclass of PicORM\Model");
}
// create relation id with normalized classRelation name
$idRelation = self :: formatClassnameToRelationName($classRelation);
// override the relation's id if an alias is present
if (!empty($aliasRelation)) {
$idRelation = strtolower($aliasRelation);
}
// store new relation in model
static::$_relations[$idRelation] = array(
'typeRelation' => self::ONE_TO_MANY,
'classRelation' => $classRelation,
'sourceField' => $sourceField,
'targetField' => $targetField,
);
} | php | {
"resource": ""
} |
q263387 | Model.addRelationManyToMany | test | protected static function addRelationManyToMany(
$sourceField,
$classRelation,
$targetField,
$relationTable,
$aliasRelation = ''
)
{
// test is related class is a PicORM model
if (!class_exists($classRelation) || !new $classRelation() instanceof Model) {
throw new Exception("Class " . $classRelation . " doesn't exists or is not subclass of PicORM\Model");
}
// create relation id with normalized classRelation name
$idRelation = self :: formatClassnameToRelationName($classRelation);
// override the relation's id if an alias is present
if (!empty($aliasRelation)) {
$idRelation = strtolower($aliasRelation);
}
// store new relation in model
static::$_relations[$idRelation] = array(
'typeRelation' => self::MANY_TO_MANY,
'classRelation' => $classRelation,
'sourceField' => $sourceField,
'targetField' => $targetField,
'relationTable' => $relationTable,
);
} | php | {
"resource": ""
} |
q263388 | Model.findQuery | test | public static function findQuery($query, $params)
{
$query = static::$_dataSource->prepare($query);
$query->execute($params);
$fetch = $query->fetchAll(\PDO::FETCH_ASSOC);
$collection = array();
foreach ($fetch as $unRes) {
$object = new static();
$object->hydrate($unRes);
$collection[] = $object;
}
return $collection;
} | php | {
"resource": ""
} |
q263389 | Model.find | test | public static function find($where = array(), $order = array(), $limitStart = null, $limitEnd = null)
{
// validate model PHP structure if necessary
self :: _validateModel();
// build a query helper with parameters
$queryHelper = static::buildSelectQuery(array("*"), $where, $order, $limitStart, $limitEnd);
// create a collection instance for called model with model datasource and custom created queryhelper
return new Collection(static::$_dataSource, $queryHelper, get_called_class());
} | php | {
"resource": ""
} |
q263390 | Model.findOne | test | public static function findOne($where = array(), $order = array())
{
// try to fetch a model from database
if ($dataModel = self::select(array('*'), $where, $order, 1)) {
// hydrate new model instance with fetched data
$model = new static();
$model->hydrate($dataModel);
return $model;
} else {
return null;
}
} | php | {
"resource": ""
} |
q263391 | Model.count | test | public static function count($where = array())
{
// fetch the count with $where parameters
$rawSqlFetch = self::select(array("count(*) as nb"), $where);
return isset($rawSqlFetch[0]) && isset($rawSqlFetch[0]['nb']) ? (int)$rawSqlFetch[0]['nb'] : null;
} | php | {
"resource": ""
} |
q263392 | Model.buildSelectQuery | test | protected static function buildSelectQuery(
$fields = array('*'),
$where = array(),
$order = array(),
$limitStart = null,
$limitEnd = null
)
{
// get the formatted model mysql table name with database name
$modelTableName = static::formatTableNameMySQL();
// be sure that "*" is prefixed with model table name
foreach ($fields as &$oneField) {
if ($oneField == "*") {
$oneField = $modelTableName . ".*";
break;
}
}
// create and helper to build a sql query
$helper = new InternalQueryHelper();
// prefix columns with model table name
$where = $helper->prefixWhereWithTable($where, $modelTableName);
$orders = $helper->prefixOrderWithTable($order, $modelTableName);
// starting build select
$helper->select($fields)
->from($modelTableName);
// check one to one relation with auto get fields
// and append necessary fields to select
$nbRelation = 0;
foreach (static::$_relations as $uneRelation) {
if ($uneRelation['typeRelation'] == self::ONE_TO_ONE && count($uneRelation['autoGetFields']) > 0) {
// prefix fields
foreach ($uneRelation['autoGetFields'] as &$oneField) {
$oneField = 'rel' . $nbRelation . "." . $oneField;
}
// add fields to select
$helper->select($uneRelation['autoGetFields']);
// add query join corresponding to the relation
$helper->leftJoin(
$uneRelation['classRelation']::formatTableNameMySQL() . ' rel' . $nbRelation,
'rel' . $nbRelation . '.`' . $uneRelation['targetField'] . '` = ' . $modelTableName . '.`' . $uneRelation['sourceField'] . '`'
);
// increment relation count used in prefix
$nbRelation++;
}
}
// build where clause
$helper->buildWhereFromArray($where);
// build order clause
foreach ($orders as $orderField => $orderVal) {
$helper->orderBy($orderField, $orderVal);
}
// build limit clause
$helper->limit($limitStart, $limitEnd);
return $helper;
} | php | {
"resource": ""
} |
q263393 | Model.select | test | public static function select(
$fields = array('*'),
$where = array(),
$order = array(),
$limitStart = null,
$limitEnd = null,
$pdoFetchMode = null
)
{
// validate model PHP structure if necessary
static::_validateModel();
// build and execute query
$mysqlQuery = static::buildSelectQuery($fields, $where, $order, $limitStart, $limitEnd);
$query = static::$_dataSource->prepare($mysqlQuery->buildQuery());
$query->execute($mysqlQuery->getWhereParamsValues());
// check for mysql error
$errorcode = $query->errorInfo();
if ($errorcode[0] != "00000") {
throw new Exception($errorcode[2]);
}
// if no fetch mode specified fallback to FETCH_ASSOC
if ($pdoFetchMode === null) {
$pdoFetchMode = \PDO::FETCH_ASSOC;
}
// if limit say its a findOne only fetch
if ($limitStart == 1 && ($limitEnd === null || $limitEnd === 1)) {
return $query->fetch($pdoFetchMode);
}
// fetch and return data from database
return $query->fetchAll($pdoFetchMode);
} | php | {
"resource": ""
} |
q263394 | Model.hydrate | test | public function hydrate($data, $strictLoad = true)
{
// using reflection to check if property exist
$reflection = new \ReflectionObject($this);
foreach ($data as $k => $v) {
// if strictLoad is disabled, all properties are allowed to be hydrated
if (!$strictLoad) {
$this->{$k} = $v;
continue;
}
// check if property really exists in class
if ($reflection->hasProperty($k)) {
$this->{$k} = $v;
continue;
}
// test relation auto get fields
foreach (static::$_relations as $uneRelation) {
// check if this field is in auto get from relation
if ($uneRelation['typeRelation'] == self::ONE_TO_ONE && in_array($k, $uneRelation['autoGetFields'])) {
$this->{$k} = $v;
break;
}
}
}
// model is not new anymore
$this->_isNew = false;
} | php | {
"resource": ""
} |
q263395 | Model.delete | test | public function delete()
{
// validate model PHP structure if necessary
static::_validateModel();
// build delete query helper for this model
$query = new InternalQueryHelper();
$query->delete(self::formatTableNameMySQL())
->where(static::$_primaryKey, "=", "?");
// delete model from database
$query = static::$_dataSource->prepare($query->buildQuery());
$query->execute(array($this->{static::$_primaryKey}));
// check for mysql error
$errorcode = $query->errorInfo();
if ($errorcode[0] != "00000") {
throw new Exception($errorcode[2]);
}
// model is not stored anymore in database
$this->_isNew = true;
return true;
} | php | {
"resource": ""
} |
q263396 | Model.update | test | private function update()
{
// validate model PHP structure if necessary
static::_validateModel();
// build update query on model table
$helper = new InternalQueryHelper();
$helper->update(self::formatTableNameMySQL());
// setting model fields value
$params = array();
foreach (static::$_tableFields as $unChamp) {
// array is for raw SQL value
if (is_array($this->$unChamp) && isset($this->{$unChamp}[0])) {
$helper->set($unChamp, $this->{$unChamp}[0]);
} else {
// Mysql prepared value
$helper->set($unChamp, '?');
$params[] = $this->{$unChamp};
}
}
// restrict with model primary key
$helper->where(self::formatTableNameMySQL() . ".`" . static::$_primaryKey . "`", "=", "?");
$params[] = $this->{static::$_primaryKey};
// update model in database
$query = static::$_dataSource->prepare($helper->buildQuery());
$query->execute($params);
// check for mysql error
$errorcode = $query->errorInfo();
if ($errorcode[0] != "00000") {
throw new Exception($errorcode[2]);
}
return true;
} | php | {
"resource": ""
} |
q263397 | Model.insert | test | private function insert()
{
// validate model PHP structure if necessary
static::_validateModel();
// create insert query for this model
$queryHelp = new InternalQueryHelper();
$queryHelp->insertInto(self::formatTableNameMySQL());
// if primary key has forced value and is not present in tableField array
if (!empty($this->{static::$_primaryKey}) && !in_array(static::$_primaryKey, static::$_tableFields)) {
array_unshift(static::$_tableFields, static::$_primaryKey);
} else {
// use autoincrement for primary key
$queryHelp->values(static::$_primaryKey, 'NULL');
}
// save model fields
$params = array();
foreach (static::$_tableFields as $unChamp) {
// array is for raw SQL value
if (is_array($this->$unChamp) && isset($this->{$unChamp}[0])) {
$val = $this->{$unChamp}[0];
} else {
// mysql prepared value
$val = '?';
$params[] = $this->$unChamp;
}
$queryHelp->values($unChamp, $val);
}
// execute insert query
$query = static::$_dataSource->prepare($queryHelp->buildQuery());
$query->execute($params);
// check for mysql error
$errorcode = $query->errorInfo();
if ($errorcode[0] != "00000") {
throw new Exception($errorcode[2]);
}
// model is saved, not new anymore
$this->_isNew = false;
// if empty PK grab the last insert ID for auto_increment fields
if (empty($this->{static::$_primaryKey})) {
$this->{static::$_primaryKey} = static::$_dataSource->lastInsertId();
}
return true;
} | php | {
"resource": ""
} |
q263398 | Collection.keep_memory | test | public function keep_memory( $keep_memory = true ) {
$prev = $this->keep_memory;
$this->keep_memory = $keep_memory;
return $prev;
} | php | {
"resource": ""
} |
q263399 | Collection.dont_remember | test | public function dont_remember( Closure $callback ) {
$prev = $this->keep_memory( false );
$callback( $this );
$this->keep_memory( $prev );
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.