repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
silverstripe/silverstripe-userforms | code/Model/EditableFormField/EditableDateField.php | EditableDateField.getFormField | public function getFormField()
{
$defaultValue = $this->DefaultToToday
? DBDatetime::now()->Format('yyyy-MM-dd')
: $this->Default;
$field = FormField::create($this->Name, $this->Title ?: false, $defaultValue)
->setFieldHolderTemplate(EditableFormField::class . '_holder')
->setTemplate(EditableFormField::class);
$this->doUpdateFormField($field);
return $field;
} | php | public function getFormField()
{
$defaultValue = $this->DefaultToToday
? DBDatetime::now()->Format('yyyy-MM-dd')
: $this->Default;
$field = FormField::create($this->Name, $this->Title ?: false, $defaultValue)
->setFieldHolderTemplate(EditableFormField::class . '_holder')
->setTemplate(EditableFormField::class);
$this->doUpdateFormField($field);
return $field;
} | [
"public",
"function",
"getFormField",
"(",
")",
"{",
"$",
"defaultValue",
"=",
"$",
"this",
"->",
"DefaultToToday",
"?",
"DBDatetime",
"::",
"now",
"(",
")",
"->",
"Format",
"(",
"'yyyy-MM-dd'",
")",
":",
"$",
"this",
"->",
"Default",
";",
"$",
"field",
... | Return the form field | [
"Return",
"the",
"form",
"field"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Model/EditableFormField/EditableDateField.php#L55-L68 |
silverstripe/silverstripe-userforms | code/FormField/UserFormsCheckboxSetField.php | UserFormsCheckboxSetField.getOptions | public function getOptions()
{
$options = parent::getOptions();
foreach ($options as $option) {
$option->Name = "{$this->name}[]";
}
return $options;
} | php | public function getOptions()
{
$options = parent::getOptions();
foreach ($options as $option) {
$option->Name = "{$this->name}[]";
}
return $options;
} | [
"public",
"function",
"getOptions",
"(",
")",
"{",
"$",
"options",
"=",
"parent",
"::",
"getOptions",
"(",
")",
";",
"foreach",
"(",
"$",
"options",
"as",
"$",
"option",
")",
"{",
"$",
"option",
"->",
"Name",
"=",
"\"{$this->name}[]\"",
";",
"}",
"retu... | jQuery validate requires that the value of the option does not contain
the actual value of the input.
@return ArrayList | [
"jQuery",
"validate",
"requires",
"that",
"the",
"value",
"of",
"the",
"option",
"does",
"not",
"contain",
"the",
"actual",
"value",
"of",
"the",
"input",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/FormField/UserFormsCheckboxSetField.php#L19-L28 |
silverstripe/silverstripe-userforms | code/FormField/UserFormsCheckboxSetField.php | UserFormsCheckboxSetField.validate | public function validate($validator)
{
// get the previous values (could contain comma-delimited list)
$previous = $value = $this->Value();
if (is_string($value) && strstr($value, ",")) {
$value = explode(",", $value);
}
// set the value as an array for parent validation
$this->setValue($value);
$validated = parent::validate($validator);
// restore previous value after validation
$this->setValue($previous);
return $validated;
} | php | public function validate($validator)
{
// get the previous values (could contain comma-delimited list)
$previous = $value = $this->Value();
if (is_string($value) && strstr($value, ",")) {
$value = explode(",", $value);
}
// set the value as an array for parent validation
$this->setValue($value);
$validated = parent::validate($validator);
// restore previous value after validation
$this->setValue($previous);
return $validated;
} | [
"public",
"function",
"validate",
"(",
"$",
"validator",
")",
"{",
"// get the previous values (could contain comma-delimited list)",
"$",
"previous",
"=",
"$",
"value",
"=",
"$",
"this",
"->",
"Value",
"(",
")",
";",
"if",
"(",
"is_string",
"(",
"$",
"value",
... | @inheritdoc
@param Validator $validator
@return bool | [
"@inheritdoc"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/FormField/UserFormsCheckboxSetField.php#L37-L58 |
silverstripe/silverstripe-userforms | code/Form/GridFieldAddClassesButton.php | GridFieldAddClassesButton.getClassesCreate | public function getClassesCreate($grid)
{
// Get explicit or fallback class list
$classes = $this->getClasses();
if (empty($classes) && $grid) {
$classes = array($grid->getModelClass());
}
// Filter out classes without permission
return array_filter($classes, function ($class) {
return singleton($class)->canCreate();
});
} | php | public function getClassesCreate($grid)
{
// Get explicit or fallback class list
$classes = $this->getClasses();
if (empty($classes) && $grid) {
$classes = array($grid->getModelClass());
}
// Filter out classes without permission
return array_filter($classes, function ($class) {
return singleton($class)->canCreate();
});
} | [
"public",
"function",
"getClassesCreate",
"(",
"$",
"grid",
")",
"{",
"// Get explicit or fallback class list",
"$",
"classes",
"=",
"$",
"this",
"->",
"getClasses",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"classes",
")",
"&&",
"$",
"grid",
")",
"{",
... | Gets the list of classes which can be created, with checks for permissions.
Will fallback to the default model class for the given DataGrid
@param DataGrid $grid
@return array | [
"Gets",
"the",
"list",
"of",
"classes",
"which",
"can",
"be",
"created",
"with",
"checks",
"for",
"permissions",
".",
"Will",
"fallback",
"to",
"the",
"default",
"model",
"class",
"for",
"the",
"given",
"DataGrid"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Form/GridFieldAddClassesButton.php#L139-L151 |
silverstripe/silverstripe-userforms | code/Form/GridFieldAddClassesButton.php | GridFieldAddClassesButton.setClasses | public function setClasses($classes)
{
if (!is_array($classes)) {
$classes = $classes ? array($classes) : array();
}
$this->modelClasses = $classes;
} | php | public function setClasses($classes)
{
if (!is_array($classes)) {
$classes = $classes ? array($classes) : array();
}
$this->modelClasses = $classes;
} | [
"public",
"function",
"setClasses",
"(",
"$",
"classes",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"classes",
")",
")",
"{",
"$",
"classes",
"=",
"$",
"classes",
"?",
"array",
"(",
"$",
"classes",
")",
":",
"array",
"(",
")",
";",
"}",
"$",... | Specify the classes to create
@param array $classes | [
"Specify",
"the",
"classes",
"to",
"create"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Form/GridFieldAddClassesButton.php#L158-L164 |
silverstripe/silverstripe-userforms | code/Form/GridFieldAddClassesButton.php | GridFieldAddClassesButton.handleAdd | public function handleAdd($grid)
{
$classes = $this->getClassesCreate($grid);
if (empty($classes)) {
throw new HTTPResponse_Exception(400);
}
// Add item to gridfield
$list = $grid->getList();
foreach ($classes as $class) {
$item = $class::create();
$item->write();
$list->add($item);
}
// Should trigger a simple reload
return null;
} | php | public function handleAdd($grid)
{
$classes = $this->getClassesCreate($grid);
if (empty($classes)) {
throw new HTTPResponse_Exception(400);
}
// Add item to gridfield
$list = $grid->getList();
foreach ($classes as $class) {
$item = $class::create();
$item->write();
$list->add($item);
}
// Should trigger a simple reload
return null;
} | [
"public",
"function",
"handleAdd",
"(",
"$",
"grid",
")",
"{",
"$",
"classes",
"=",
"$",
"this",
"->",
"getClassesCreate",
"(",
"$",
"grid",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"classes",
")",
")",
"{",
"throw",
"new",
"HTTPResponse_Exception",
"("... | Handles adding a new instance of a selected class.
@param GridField $grid
@return null | [
"Handles",
"adding",
"a",
"new",
"instance",
"of",
"a",
"selected",
"class",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Form/GridFieldAddClassesButton.php#L236-L253 |
silverstripe/silverstripe-userforms | code/Task/UserFormsColumnCleanTask.php | UserFormsColumnCleanTask.run | public function run($request)
{
/** @var \SilverStripe\ORM\DataObjectSchema $schema */
$schema = DataObject::getSchema();
foreach ($this->tables as $db) {
$columns = $schema->databaseFields($db);
$query = "SHOW COLUMNS FROM $db";
$liveColumns = DB::query($query)->column();
$backedUp = 0;
$query = "SHOW TABLES LIKE 'Backup_$db'";
$tableExists = DB::query($query)->value();
if ($tableExists != null) {
echo "Tasks run already on $db exiting";
return;
}
$backedUp = 0;
foreach ($liveColumns as $index => $column) {
if ($backedUp == 0) {
echo "Backing up $db <br />";
echo "Creating Backup_$db <br />";
// backup table
$query = "CREATE TABLE Backup_$db LIKE $db";
DB::query($query);
echo "Populating Backup_$db <br />";
$query = "INSERT Backup_$db SELECT * FROM $db";
DB::query($query);
$backedUp = 1;
}
if (!isset($columns[$column]) && !in_array($column, $this->keepColumns)) {
echo "Dropping $column from $db <br />";
$query = "ALTER TABLE $db DROP COLUMN $column";
DB::query($query);
}
}
}
} | php | public function run($request)
{
/** @var \SilverStripe\ORM\DataObjectSchema $schema */
$schema = DataObject::getSchema();
foreach ($this->tables as $db) {
$columns = $schema->databaseFields($db);
$query = "SHOW COLUMNS FROM $db";
$liveColumns = DB::query($query)->column();
$backedUp = 0;
$query = "SHOW TABLES LIKE 'Backup_$db'";
$tableExists = DB::query($query)->value();
if ($tableExists != null) {
echo "Tasks run already on $db exiting";
return;
}
$backedUp = 0;
foreach ($liveColumns as $index => $column) {
if ($backedUp == 0) {
echo "Backing up $db <br />";
echo "Creating Backup_$db <br />";
// backup table
$query = "CREATE TABLE Backup_$db LIKE $db";
DB::query($query);
echo "Populating Backup_$db <br />";
$query = "INSERT Backup_$db SELECT * FROM $db";
DB::query($query);
$backedUp = 1;
}
if (!isset($columns[$column]) && !in_array($column, $this->keepColumns)) {
echo "Dropping $column from $db <br />";
$query = "ALTER TABLE $db DROP COLUMN $column";
DB::query($query);
}
}
}
} | [
"public",
"function",
"run",
"(",
"$",
"request",
")",
"{",
"/** @var \\SilverStripe\\ORM\\DataObjectSchema $schema */",
"$",
"schema",
"=",
"DataObject",
"::",
"getSchema",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"tables",
"as",
"$",
"db",
")",
"{",... | Publish the existing forms. | [
"Publish",
"the",
"existing",
"forms",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Task/UserFormsColumnCleanTask.php#L31-L67 |
silverstripe/silverstripe-userforms | code/Model/Submission/SubmittedForm.php | SubmittedForm.relField | public function relField($fieldName)
{
// default case
if ($value = parent::relField($fieldName)) {
return $value;
}
// check values for a form field with the matching name.
$formField = SubmittedFormField::get()->filter(array(
'ParentID' => $this->ID,
'Name' => $fieldName
))->first();
if ($formField) {
return $formField->getFormattedValue();
}
} | php | public function relField($fieldName)
{
// default case
if ($value = parent::relField($fieldName)) {
return $value;
}
// check values for a form field with the matching name.
$formField = SubmittedFormField::get()->filter(array(
'ParentID' => $this->ID,
'Name' => $fieldName
))->first();
if ($formField) {
return $formField->getFormattedValue();
}
} | [
"public",
"function",
"relField",
"(",
"$",
"fieldName",
")",
"{",
"// default case",
"if",
"(",
"$",
"value",
"=",
"parent",
"::",
"relField",
"(",
"$",
"fieldName",
")",
")",
"{",
"return",
"$",
"value",
";",
"}",
"// check values for a form field with the m... | Returns the value of a relation or, in the case of this form, the value
of a given child {@link SubmittedFormField}
@param string
@return mixed | [
"Returns",
"the",
"value",
"of",
"a",
"relation",
"or",
"in",
"the",
"case",
"of",
"this",
"form",
"the",
"value",
"of",
"a",
"given",
"child",
"{",
"@link",
"SubmittedFormField",
"}"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Model/Submission/SubmittedForm.php#L56-L72 |
silverstripe/silverstripe-userforms | code/Model/Submission/SubmittedForm.php | SubmittedForm.canCreate | public function canCreate($member = null, $context = [])
{
$extended = $this->extendedCan(__FUNCTION__, $member);
if ($extended !== null) {
return $extended;
}
return $this->Parent()->canCreate();
} | php | public function canCreate($member = null, $context = [])
{
$extended = $this->extendedCan(__FUNCTION__, $member);
if ($extended !== null) {
return $extended;
}
return $this->Parent()->canCreate();
} | [
"public",
"function",
"canCreate",
"(",
"$",
"member",
"=",
"null",
",",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"$",
"extended",
"=",
"$",
"this",
"->",
"extendedCan",
"(",
"__FUNCTION__",
",",
"$",
"member",
")",
";",
"if",
"(",
"$",
"extended",
... | @param Member
@return boolean | [
"@param",
"Member"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Model/Submission/SubmittedForm.php#L127-L134 |
silverstripe/silverstripe-userforms | code/Model/Submission/SubmittedForm.php | SubmittedForm.canView | public function canView($member = null)
{
$extended = $this->extendedCan(__FUNCTION__, $member);
if ($extended !== null) {
return $extended;
}
if ($this->Parent()) {
return $this->Parent()->canView($member);
}
return parent::canView($member);
} | php | public function canView($member = null)
{
$extended = $this->extendedCan(__FUNCTION__, $member);
if ($extended !== null) {
return $extended;
}
if ($this->Parent()) {
return $this->Parent()->canView($member);
}
return parent::canView($member);
} | [
"public",
"function",
"canView",
"(",
"$",
"member",
"=",
"null",
")",
"{",
"$",
"extended",
"=",
"$",
"this",
"->",
"extendedCan",
"(",
"__FUNCTION__",
",",
"$",
"member",
")",
";",
"if",
"(",
"$",
"extended",
"!==",
"null",
")",
"{",
"return",
"$",... | @param Member
@return boolean | [
"@param",
"Member"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Model/Submission/SubmittedForm.php#L141-L154 |
silverstripe/silverstripe-userforms | code/Model/Submission/SubmittedForm.php | SubmittedForm.onBeforeDelete | protected function onBeforeDelete()
{
if ($this->Values()) {
foreach ($this->Values() as $value) {
$value->delete();
}
}
parent::onBeforeDelete();
} | php | protected function onBeforeDelete()
{
if ($this->Values()) {
foreach ($this->Values() as $value) {
$value->delete();
}
}
parent::onBeforeDelete();
} | [
"protected",
"function",
"onBeforeDelete",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"Values",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"Values",
"(",
")",
"as",
"$",
"value",
")",
"{",
"$",
"value",
"->",
"delete",
"(",
")",
";"... | Before we delete this form make sure we delete all the field values so
that we don't leave old data round.
@return void | [
"Before",
"we",
"delete",
"this",
"form",
"make",
"sure",
"we",
"delete",
"all",
"the",
"field",
"values",
"so",
"that",
"we",
"don",
"t",
"leave",
"old",
"data",
"round",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Model/Submission/SubmittedForm.php#L202-L211 |
silverstripe/silverstripe-userforms | code/UserForm.php | UserForm.FilteredEmailRecipients | public function FilteredEmailRecipients($data = null, $form = null)
{
$recipients = ArrayList::create($this->EmailRecipients()->toArray());
// Filter by rules
$recipients = $recipients->filterByCallback(function ($recipient) use ($data, $form) {
/** @var EmailRecipient $recipient */
return $recipient->canSend($data, $form);
});
$this->extend('updateFilteredEmailRecipients', $recipients, $data, $form);
return $recipients;
} | php | public function FilteredEmailRecipients($data = null, $form = null)
{
$recipients = ArrayList::create($this->EmailRecipients()->toArray());
// Filter by rules
$recipients = $recipients->filterByCallback(function ($recipient) use ($data, $form) {
/** @var EmailRecipient $recipient */
return $recipient->canSend($data, $form);
});
$this->extend('updateFilteredEmailRecipients', $recipients, $data, $form);
return $recipients;
} | [
"public",
"function",
"FilteredEmailRecipients",
"(",
"$",
"data",
"=",
"null",
",",
"$",
"form",
"=",
"null",
")",
"{",
"$",
"recipients",
"=",
"ArrayList",
"::",
"create",
"(",
"$",
"this",
"->",
"EmailRecipients",
"(",
")",
"->",
"toArray",
"(",
")",
... | Allow overriding the EmailRecipients on a {@link DataExtension}
so you can customise who receives an email.
Converts the RelationList to an ArrayList so that manipulation
of the original source data isn't possible.
@return ArrayList | [
"Allow",
"overriding",
"the",
"EmailRecipients",
"on",
"a",
"{",
"@link",
"DataExtension",
"}",
"so",
"you",
"can",
"customise",
"who",
"receives",
"an",
"email",
".",
"Converts",
"the",
"RelationList",
"to",
"an",
"ArrayList",
"so",
"that",
"manipulation",
"o... | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/UserForm.php#L346-L359 |
silverstripe/silverstripe-userforms | code/UserForm.php | UserForm.getFormOptions | public function getFormOptions()
{
$submit = ($this->SubmitButtonText) ? $this->SubmitButtonText : _t(__CLASS__.'.SUBMITBUTTON', 'Submit');
$clear = ($this->ClearButtonText) ? $this->ClearButtonText : _t(__CLASS__.'.CLEARBUTTON', 'Clear');
$options = FieldList::create(
TextField::create('SubmitButtonText', _t(__CLASS__.'.TEXTONSUBMIT', 'Text on submit button:'), $submit),
TextField::create('ClearButtonText', _t(__CLASS__.'.TEXTONCLEAR', 'Text on clear button:'), $clear),
CheckboxField::create('ShowClearButton', _t(__CLASS__.'.SHOWCLEARFORM', 'Show Clear Form Button'), $this->ShowClearButton),
CheckboxField::create('EnableLiveValidation', _t(__CLASS__.'.ENABLELIVEVALIDATION', 'Enable live validation')),
CheckboxField::create('DisplayErrorMessagesAtTop', _t(__CLASS__.'.DISPLAYERRORMESSAGESATTOP', 'Display error messages above the form?')),
CheckboxField::create('DisableCsrfSecurityToken', _t(__CLASS__.'.DISABLECSRFSECURITYTOKEN', 'Disable CSRF Token')),
CheckboxField::create('DisableAuthenicatedFinishAction', _t(__CLASS__.'.DISABLEAUTHENICATEDFINISHACTION', 'Disable Authentication on finish action'))
);
$this->extend('updateFormOptions', $options);
return $options;
} | php | public function getFormOptions()
{
$submit = ($this->SubmitButtonText) ? $this->SubmitButtonText : _t(__CLASS__.'.SUBMITBUTTON', 'Submit');
$clear = ($this->ClearButtonText) ? $this->ClearButtonText : _t(__CLASS__.'.CLEARBUTTON', 'Clear');
$options = FieldList::create(
TextField::create('SubmitButtonText', _t(__CLASS__.'.TEXTONSUBMIT', 'Text on submit button:'), $submit),
TextField::create('ClearButtonText', _t(__CLASS__.'.TEXTONCLEAR', 'Text on clear button:'), $clear),
CheckboxField::create('ShowClearButton', _t(__CLASS__.'.SHOWCLEARFORM', 'Show Clear Form Button'), $this->ShowClearButton),
CheckboxField::create('EnableLiveValidation', _t(__CLASS__.'.ENABLELIVEVALIDATION', 'Enable live validation')),
CheckboxField::create('DisplayErrorMessagesAtTop', _t(__CLASS__.'.DISPLAYERRORMESSAGESATTOP', 'Display error messages above the form?')),
CheckboxField::create('DisableCsrfSecurityToken', _t(__CLASS__.'.DISABLECSRFSECURITYTOKEN', 'Disable CSRF Token')),
CheckboxField::create('DisableAuthenicatedFinishAction', _t(__CLASS__.'.DISABLEAUTHENICATEDFINISHACTION', 'Disable Authentication on finish action'))
);
$this->extend('updateFormOptions', $options);
return $options;
} | [
"public",
"function",
"getFormOptions",
"(",
")",
"{",
"$",
"submit",
"=",
"(",
"$",
"this",
"->",
"SubmitButtonText",
")",
"?",
"$",
"this",
"->",
"SubmitButtonText",
":",
"_t",
"(",
"__CLASS__",
".",
"'.SUBMITBUTTON'",
",",
"'Submit'",
")",
";",
"$",
"... | Custom options for the form. You can extend the built in options by
using {@link updateFormOptions()}
@return FieldList | [
"Custom",
"options",
"for",
"the",
"form",
".",
"You",
"can",
"extend",
"the",
"built",
"in",
"options",
"by",
"using",
"{",
"@link",
"updateFormOptions",
"()",
"}"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/UserForm.php#L367-L385 |
silverstripe/silverstripe-userforms | code/Model/EditableFormField/EditableOption.php | EditableOption.getValue | public function getValue()
{
$value = $this->getField('Value');
if (empty($value) && !self::allow_empty_values()) {
return $this->Title;
}
return $value;
} | php | public function getValue()
{
$value = $this->getField('Value');
if (empty($value) && !self::allow_empty_values()) {
return $this->Title;
}
return $value;
} | [
"public",
"function",
"getValue",
"(",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"getField",
"(",
"'Value'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"value",
")",
"&&",
"!",
"self",
"::",
"allow_empty_values",
"(",
")",
")",
"{",
"return",
"$... | Fetches a value for $this->Value. If empty values are not allowed,
then this will return the title in the case of an empty value.
@return string | [
"Fetches",
"a",
"value",
"for",
"$this",
"-",
">",
"Value",
".",
"If",
"empty",
"values",
"are",
"not",
"allowed",
"then",
"this",
"will",
"return",
"the",
"title",
"in",
"the",
"case",
"of",
"an",
"empty",
"value",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Model/EditableFormField/EditableOption.php#L81-L88 |
silverstripe/silverstripe-userforms | code/Model/EditableFormField/EditableOption.php | EditableOption.canCreate | public function canCreate($member = null, $context = [])
{
// Check parent object
$parent = $this->Parent();
if ($parent) {
return $parent->canCreate($member);
}
// Fall back to secure admin permissions
return parent::canCreate($member);
} | php | public function canCreate($member = null, $context = [])
{
// Check parent object
$parent = $this->Parent();
if ($parent) {
return $parent->canCreate($member);
}
// Fall back to secure admin permissions
return parent::canCreate($member);
} | [
"public",
"function",
"canCreate",
"(",
"$",
"member",
"=",
"null",
",",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"// Check parent object",
"$",
"parent",
"=",
"$",
"this",
"->",
"Parent",
"(",
")",
";",
"if",
"(",
"$",
"parent",
")",
"{",
"return",
... | Return whether a user can create an object of this type
@param Member $member
@param array $context Virtual parameter to allow context to be passed in to check
@return bool | [
"Return",
"whether",
"a",
"user",
"can",
"create",
"an",
"object",
"of",
"this",
"type"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Model/EditableFormField/EditableOption.php#L134-L144 |
silverstripe/silverstripe-userforms | code/Extension/UserFormFieldEditorExtension.php | UserFormFieldEditorExtension.updateCMSFields | public function updateCMSFields(FieldList $fields)
{
$fieldEditor = $this->getFieldEditorGrid();
$fields->insertAfter(new Tab('FormFields', _t(__CLASS__.'.FORMFIELDS', 'Form Fields')), 'Main');
$fields->addFieldToTab('Root.FormFields', $fieldEditor);
return $fields;
} | php | public function updateCMSFields(FieldList $fields)
{
$fieldEditor = $this->getFieldEditorGrid();
$fields->insertAfter(new Tab('FormFields', _t(__CLASS__.'.FORMFIELDS', 'Form Fields')), 'Main');
$fields->addFieldToTab('Root.FormFields', $fieldEditor);
return $fields;
} | [
"public",
"function",
"updateCMSFields",
"(",
"FieldList",
"$",
"fields",
")",
"{",
"$",
"fieldEditor",
"=",
"$",
"this",
"->",
"getFieldEditorGrid",
"(",
")",
";",
"$",
"fields",
"->",
"insertAfter",
"(",
"new",
"Tab",
"(",
"'FormFields'",
",",
"_t",
"(",... | Adds the field editor to the page.
@return FieldList | [
"Adds",
"the",
"field",
"editor",
"to",
"the",
"page",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Extension/UserFormFieldEditorExtension.php#L51-L59 |
silverstripe/silverstripe-userforms | code/Extension/UserFormFieldEditorExtension.php | UserFormFieldEditorExtension.getFieldEditorGrid | public function getFieldEditorGrid()
{
Requirements::javascript('silverstripe/userforms:client/dist/js/userforms-cms.js');
$fields = $this->owner->Fields();
$this->createInitialFormStep(true);
$editableColumns = new GridFieldEditableColumns();
$fieldClasses = singleton(EditableFormField::class)->getEditableFieldClasses();
$editableColumns->setDisplayFields([
'ClassName' => function ($record, $column, $grid) use ($fieldClasses) {
if ($record instanceof EditableFormField) {
return $record->getInlineClassnameField($column, $fieldClasses);
}
},
'Title' => function ($record, $column, $grid) {
if ($record instanceof EditableFormField) {
return $record->getInlineTitleField($column);
}
}
]);
$config = GridFieldConfig::create()
->addComponents(
$editableColumns,
new GridFieldButtonRow(),
(new GridFieldAddClassesButton(EditableTextField::class))
->setButtonName(_t(__CLASS__.'.ADD_FIELD', 'Add Field'))
->setButtonClass('btn-primary'),
(new GridFieldAddClassesButton(EditableFormStep::class))
->setButtonName(_t(__CLASS__.'.ADD_PAGE_BREAK', 'Add Page Break'))
->setButtonClass('btn-secondary'),
(new GridFieldAddClassesButton([EditableFieldGroup::class, EditableFieldGroupEnd::class]))
->setButtonName(_t(__CLASS__.'.ADD_FIELD_GROUP', 'Add Field Group'))
->setButtonClass('btn-secondary'),
$editButton = new GridFieldEditButton(),
new GridFieldDeleteAction(),
new GridFieldToolbarHeader(),
new GridFieldOrderableRows('Sort'),
new GridFieldDetailForm()
);
$editButton->removeExtraClass('grid-field__icon-action--hidden-on-hover');
$fieldEditor = GridField::create(
'Fields',
'',
$fields,
$config
)->addExtraClass('uf-field-editor');
return $fieldEditor;
} | php | public function getFieldEditorGrid()
{
Requirements::javascript('silverstripe/userforms:client/dist/js/userforms-cms.js');
$fields = $this->owner->Fields();
$this->createInitialFormStep(true);
$editableColumns = new GridFieldEditableColumns();
$fieldClasses = singleton(EditableFormField::class)->getEditableFieldClasses();
$editableColumns->setDisplayFields([
'ClassName' => function ($record, $column, $grid) use ($fieldClasses) {
if ($record instanceof EditableFormField) {
return $record->getInlineClassnameField($column, $fieldClasses);
}
},
'Title' => function ($record, $column, $grid) {
if ($record instanceof EditableFormField) {
return $record->getInlineTitleField($column);
}
}
]);
$config = GridFieldConfig::create()
->addComponents(
$editableColumns,
new GridFieldButtonRow(),
(new GridFieldAddClassesButton(EditableTextField::class))
->setButtonName(_t(__CLASS__.'.ADD_FIELD', 'Add Field'))
->setButtonClass('btn-primary'),
(new GridFieldAddClassesButton(EditableFormStep::class))
->setButtonName(_t(__CLASS__.'.ADD_PAGE_BREAK', 'Add Page Break'))
->setButtonClass('btn-secondary'),
(new GridFieldAddClassesButton([EditableFieldGroup::class, EditableFieldGroupEnd::class]))
->setButtonName(_t(__CLASS__.'.ADD_FIELD_GROUP', 'Add Field Group'))
->setButtonClass('btn-secondary'),
$editButton = new GridFieldEditButton(),
new GridFieldDeleteAction(),
new GridFieldToolbarHeader(),
new GridFieldOrderableRows('Sort'),
new GridFieldDetailForm()
);
$editButton->removeExtraClass('grid-field__icon-action--hidden-on-hover');
$fieldEditor = GridField::create(
'Fields',
'',
$fields,
$config
)->addExtraClass('uf-field-editor');
return $fieldEditor;
} | [
"public",
"function",
"getFieldEditorGrid",
"(",
")",
"{",
"Requirements",
"::",
"javascript",
"(",
"'silverstripe/userforms:client/dist/js/userforms-cms.js'",
")",
";",
"$",
"fields",
"=",
"$",
"this",
"->",
"owner",
"->",
"Fields",
"(",
")",
";",
"$",
"this",
... | Gets the field editor, for adding and removing EditableFormFields.
@return GridField | [
"Gets",
"the",
"field",
"editor",
"for",
"adding",
"and",
"removing",
"EditableFormFields",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Extension/UserFormFieldEditorExtension.php#L66-L119 |
silverstripe/silverstripe-userforms | code/Extension/UserFormFieldEditorExtension.php | UserFormFieldEditorExtension.createInitialFormStep | public function createInitialFormStep($force = false)
{
// Only invoke once saved
if (!$this->owner->exists()) {
return;
}
// Check if first field is a step
$fields = $this->owner->Fields();
$firstField = $fields->first();
if ($firstField instanceof EditableFormStep) {
return;
}
// Don't create steps on write if there are no formfields, as this
// can create duplicate first steps during publish of new records
if (!$force && !$firstField) {
return;
}
// Re-apply sort to each field starting at 2
$next = 2;
foreach ($fields as $field) {
$field->Sort = $next++;
$field->write();
}
// Add step
$step = EditableFormStep::create();
$step->Title = _t('SilverStripe\\UserForms\\Model\\EditableFormField\\EditableFormStep.TITLE_FIRST', 'First Page');
$step->Sort = 1;
$step->write();
$fields->add($step);
} | php | public function createInitialFormStep($force = false)
{
// Only invoke once saved
if (!$this->owner->exists()) {
return;
}
// Check if first field is a step
$fields = $this->owner->Fields();
$firstField = $fields->first();
if ($firstField instanceof EditableFormStep) {
return;
}
// Don't create steps on write if there are no formfields, as this
// can create duplicate first steps during publish of new records
if (!$force && !$firstField) {
return;
}
// Re-apply sort to each field starting at 2
$next = 2;
foreach ($fields as $field) {
$field->Sort = $next++;
$field->write();
}
// Add step
$step = EditableFormStep::create();
$step->Title = _t('SilverStripe\\UserForms\\Model\\EditableFormField\\EditableFormStep.TITLE_FIRST', 'First Page');
$step->Sort = 1;
$step->write();
$fields->add($step);
} | [
"public",
"function",
"createInitialFormStep",
"(",
"$",
"force",
"=",
"false",
")",
"{",
"// Only invoke once saved",
"if",
"(",
"!",
"$",
"this",
"->",
"owner",
"->",
"exists",
"(",
")",
")",
"{",
"return",
";",
"}",
"// Check if first field is a step",
"$",... | A UserForm must have at least one step.
If no steps exist, create an initial step, and put all fields inside it.
@param bool $force
@return void | [
"A",
"UserForm",
"must",
"have",
"at",
"least",
"one",
"step",
".",
"If",
"no",
"steps",
"exist",
"create",
"an",
"initial",
"step",
"and",
"put",
"all",
"fields",
"inside",
"it",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Extension/UserFormFieldEditorExtension.php#L128-L161 |
silverstripe/silverstripe-userforms | code/Extension/UserFormFieldEditorExtension.php | UserFormFieldEditorExtension.onAfterPublish | public function onAfterPublish()
{
// store IDs of fields we've published
$seenIDs = [];
foreach ($this->owner->Fields() as $field) {
// store any IDs of fields we publish so we don't unpublish them
$seenIDs[] = $field->ID;
$field->doPublish(Versioned::DRAFT, Versioned::LIVE);
$field->destroy();
}
// fetch any orphaned live records
$live = Versioned::get_by_stage(EditableFormField::class, Versioned::LIVE)
->filter([
'ParentID' => $this->owner->ID,
]);
if (!empty($seenIDs)) {
$live = $live->exclude([
'ID' => $seenIDs,
]);
}
// delete orphaned records
foreach ($live as $field) {
$field->deleteFromStage(Versioned::LIVE);
$field->destroy();
}
} | php | public function onAfterPublish()
{
// store IDs of fields we've published
$seenIDs = [];
foreach ($this->owner->Fields() as $field) {
// store any IDs of fields we publish so we don't unpublish them
$seenIDs[] = $field->ID;
$field->doPublish(Versioned::DRAFT, Versioned::LIVE);
$field->destroy();
}
// fetch any orphaned live records
$live = Versioned::get_by_stage(EditableFormField::class, Versioned::LIVE)
->filter([
'ParentID' => $this->owner->ID,
]);
if (!empty($seenIDs)) {
$live = $live->exclude([
'ID' => $seenIDs,
]);
}
// delete orphaned records
foreach ($live as $field) {
$field->deleteFromStage(Versioned::LIVE);
$field->destroy();
}
} | [
"public",
"function",
"onAfterPublish",
"(",
")",
"{",
"// store IDs of fields we've published",
"$",
"seenIDs",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"owner",
"->",
"Fields",
"(",
")",
"as",
"$",
"field",
")",
"{",
"// store any IDs of fields... | Remove any orphaned child records on publish | [
"Remove",
"any",
"orphaned",
"child",
"records",
"on",
"publish"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Extension/UserFormFieldEditorExtension.php#L174-L202 |
silverstripe/silverstripe-userforms | code/Extension/UserFormFieldEditorExtension.php | UserFormFieldEditorExtension.onAfterUnpublish | public function onAfterUnpublish()
{
foreach ($this->owner->Fields() as $field) {
$field->deleteFromStage(Versioned::LIVE);
}
} | php | public function onAfterUnpublish()
{
foreach ($this->owner->Fields() as $field) {
$field->deleteFromStage(Versioned::LIVE);
}
} | [
"public",
"function",
"onAfterUnpublish",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"owner",
"->",
"Fields",
"(",
")",
"as",
"$",
"field",
")",
"{",
"$",
"field",
"->",
"deleteFromStage",
"(",
"Versioned",
"::",
"LIVE",
")",
";",
"}",
"}"
] | Remove all fields from the live stage when unpublishing the page | [
"Remove",
"all",
"fields",
"from",
"the",
"live",
"stage",
"when",
"unpublishing",
"the",
"page"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Extension/UserFormFieldEditorExtension.php#L207-L212 |
silverstripe/silverstripe-userforms | code/Extension/UserFormFieldEditorExtension.php | UserFormFieldEditorExtension.onAfterDuplicate | public function onAfterDuplicate($oldPage, $doWrite, $manyMany)
{
// List of EditableFieldGroups, where the key of the array is the ID of the old end group
$fieldGroups = [];
foreach ($oldPage->Fields() as $field) {
/** @var EditableFormField $newField */
$newField = $field->duplicate(false);
$newField->ParentID = $this->owner->ID;
$newField->ParentClass = $this->owner->ClassName;
$newField->Version = 0;
$newField->write();
// If we encounter a group start, record it for later use
if ($field instanceof EditableFieldGroup) {
$fieldGroups[$field->EndID] = $newField;
}
// If we encounter an end group, link it back to the group start
if ($field instanceof EditableFieldGroupEnd && isset($fieldGroups[$field->ID])) {
$groupStart = $fieldGroups[$field->ID];
$groupStart->EndID = $newField->ID;
$groupStart->write();
}
foreach ($field->DisplayRules() as $customRule) {
$newRule = $customRule->duplicate(false);
$newRule->ParentID = $newField->ID;
$newRule->Version = 0;
$newRule->write();
}
}
} | php | public function onAfterDuplicate($oldPage, $doWrite, $manyMany)
{
// List of EditableFieldGroups, where the key of the array is the ID of the old end group
$fieldGroups = [];
foreach ($oldPage->Fields() as $field) {
/** @var EditableFormField $newField */
$newField = $field->duplicate(false);
$newField->ParentID = $this->owner->ID;
$newField->ParentClass = $this->owner->ClassName;
$newField->Version = 0;
$newField->write();
// If we encounter a group start, record it for later use
if ($field instanceof EditableFieldGroup) {
$fieldGroups[$field->EndID] = $newField;
}
// If we encounter an end group, link it back to the group start
if ($field instanceof EditableFieldGroupEnd && isset($fieldGroups[$field->ID])) {
$groupStart = $fieldGroups[$field->ID];
$groupStart->EndID = $newField->ID;
$groupStart->write();
}
foreach ($field->DisplayRules() as $customRule) {
$newRule = $customRule->duplicate(false);
$newRule->ParentID = $newField->ID;
$newRule->Version = 0;
$newRule->write();
}
}
} | [
"public",
"function",
"onAfterDuplicate",
"(",
"$",
"oldPage",
",",
"$",
"doWrite",
",",
"$",
"manyMany",
")",
"{",
"// List of EditableFieldGroups, where the key of the array is the ID of the old end group",
"$",
"fieldGroups",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
... | When duplicating a UserDefinedForm, duplicate all of its fields and display rules
@see \SilverStripe\ORM\DataObject::duplicate
@param \SilverStripe\ORM\DataObject $oldPage
@param bool $doWrite
@param string $manyMany
@return \SilverStripe\ORM\DataObject | [
"When",
"duplicating",
"a",
"UserDefinedForm",
"duplicate",
"all",
"of",
"its",
"fields",
"and",
"display",
"rules"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Extension/UserFormFieldEditorExtension.php#L223-L254 |
silverstripe/silverstripe-userforms | code/Control/UserDefinedFormController.php | UserDefinedFormController.addUserFormsValidatei18n | protected function addUserFormsValidatei18n()
{
$module = ModuleLoader::getModule('silverstripe/userforms');
$candidates = [
i18n::getData()->langFromLocale(i18n::config()->get('default_locale')),
i18n::config()->get('default_locale'),
i18n::getData()->langFromLocale(i18n::get_locale()),
i18n::get_locale(),
];
foreach ($candidates as $candidate) {
foreach (['messages', 'methods'] as $candidateType) {
$localisationCandidate = "client/thirdparty/jquery-validate/localization/{$candidateType}_{$candidate}.min.js";
$resource = $module->getResource($localisationCandidate);
if ($resource->exists()) {
Requirements::javascript($resource->getRelativePath());
}
}
}
} | php | protected function addUserFormsValidatei18n()
{
$module = ModuleLoader::getModule('silverstripe/userforms');
$candidates = [
i18n::getData()->langFromLocale(i18n::config()->get('default_locale')),
i18n::config()->get('default_locale'),
i18n::getData()->langFromLocale(i18n::get_locale()),
i18n::get_locale(),
];
foreach ($candidates as $candidate) {
foreach (['messages', 'methods'] as $candidateType) {
$localisationCandidate = "client/thirdparty/jquery-validate/localization/{$candidateType}_{$candidate}.min.js";
$resource = $module->getResource($localisationCandidate);
if ($resource->exists()) {
Requirements::javascript($resource->getRelativePath());
}
}
}
} | [
"protected",
"function",
"addUserFormsValidatei18n",
"(",
")",
"{",
"$",
"module",
"=",
"ModuleLoader",
"::",
"getModule",
"(",
"'silverstripe/userforms'",
")",
";",
"$",
"candidates",
"=",
"[",
"i18n",
"::",
"getData",
"(",
")",
"->",
"langFromLocale",
"(",
"... | Add the necessary jQuery validate i18n translation files, either by locale or by langauge,
e.g. 'en_NZ' or 'en'. This adds "methods_abc.min.js" as well as "messages_abc.min.js" from the
jQuery validate thirdparty library. | [
"Add",
"the",
"necessary",
"jQuery",
"validate",
"i18n",
"translation",
"files",
"either",
"by",
"locale",
"or",
"by",
"langauge",
"e",
".",
"g",
".",
"en_NZ",
"or",
"en",
".",
"This",
"adds",
"methods_abc",
".",
"min",
".",
"js",
"as",
"well",
"as",
"... | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Control/UserDefinedFormController.php#L80-L101 |
silverstripe/silverstripe-userforms | code/Control/UserDefinedFormController.php | UserDefinedFormController.index | public function index(HTTPRequest $request = null)
{
$form = $this->Form();
if ($this->Content && $form && !$this->config()->disable_form_content_shortcode) {
$hasLocation = stristr($this->Content, '$UserDefinedForm');
if ($hasLocation) {
/** @see Requirements_Backend::escapeReplacement */
$formEscapedForRegex = addcslashes($form->forTemplate(), '\\$');
$content = preg_replace(
'/(<p[^>]*>)?\\$UserDefinedForm(<\\/p>)?/i',
$formEscapedForRegex,
$this->Content
);
return [
'Content' => DBField::create_field('HTMLText', $content),
'Form' => ''
];
}
}
return [
'Content' => DBField::create_field('HTMLText', $this->Content),
'Form' => $this->Form()
];
} | php | public function index(HTTPRequest $request = null)
{
$form = $this->Form();
if ($this->Content && $form && !$this->config()->disable_form_content_shortcode) {
$hasLocation = stristr($this->Content, '$UserDefinedForm');
if ($hasLocation) {
/** @see Requirements_Backend::escapeReplacement */
$formEscapedForRegex = addcslashes($form->forTemplate(), '\\$');
$content = preg_replace(
'/(<p[^>]*>)?\\$UserDefinedForm(<\\/p>)?/i',
$formEscapedForRegex,
$this->Content
);
return [
'Content' => DBField::create_field('HTMLText', $content),
'Form' => ''
];
}
}
return [
'Content' => DBField::create_field('HTMLText', $this->Content),
'Form' => $this->Form()
];
} | [
"public",
"function",
"index",
"(",
"HTTPRequest",
"$",
"request",
"=",
"null",
")",
"{",
"$",
"form",
"=",
"$",
"this",
"->",
"Form",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"Content",
"&&",
"$",
"form",
"&&",
"!",
"$",
"this",
"->",
"confi... | Using $UserDefinedForm in the Content area of the page shows
where the form should be rendered into. If it does not exist
then default back to $Form.
@return array | [
"Using",
"$UserDefinedForm",
"in",
"the",
"Content",
"area",
"of",
"the",
"page",
"shows",
"where",
"the",
"form",
"should",
"be",
"rendered",
"into",
".",
"If",
"it",
"does",
"not",
"exist",
"then",
"default",
"back",
"to",
"$Form",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Control/UserDefinedFormController.php#L110-L134 |
silverstripe/silverstripe-userforms | code/Control/UserDefinedFormController.php | UserDefinedFormController.Form | public function Form()
{
$form = UserForm::create($this, 'Form_' . $this->ID);
/** @skipUpgrade */
$form->setFormAction(Controller::join_links($this->Link(), 'Form'));
$this->generateConditionalJavascript();
return $form;
} | php | public function Form()
{
$form = UserForm::create($this, 'Form_' . $this->ID);
/** @skipUpgrade */
$form->setFormAction(Controller::join_links($this->Link(), 'Form'));
$this->generateConditionalJavascript();
return $form;
} | [
"public",
"function",
"Form",
"(",
")",
"{",
"$",
"form",
"=",
"UserForm",
"::",
"create",
"(",
"$",
"this",
",",
"'Form_'",
".",
"$",
"this",
"->",
"ID",
")",
";",
"/** @skipUpgrade */",
"$",
"form",
"->",
"setFormAction",
"(",
"Controller",
"::",
"jo... | Get the form for the page. Form can be modified by calling {@link updateForm()}
on a UserDefinedForm extension.
@return Form | [
"Get",
"the",
"form",
"for",
"the",
"page",
".",
"Form",
"can",
"be",
"modified",
"by",
"calling",
"{",
"@link",
"updateForm",
"()",
"}",
"on",
"a",
"UserDefinedForm",
"extension",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Control/UserDefinedFormController.php#L152-L159 |
silverstripe/silverstripe-userforms | code/Control/UserDefinedFormController.php | UserDefinedFormController.generateConditionalJavascript | public function generateConditionalJavascript()
{
$rules = '';
$form = $this->data();
if (!$form) {
return;
}
$formFields = $form->Fields();
$watch = [];
if ($formFields) {
/** @var EditableFormField $field */
foreach ($formFields as $field) {
if ($result = $field->formatDisplayRules()) {
$watch[] = $result;
}
}
}
if ($watch) {
$rules .= $this->buildWatchJS($watch);
}
// Only add customScript if $default or $rules is defined
if ($rules) {
Requirements::customScript(<<<JS
(function($) {
$(document).ready(function() {
{$rules}
});
})(jQuery);
JS
, 'UserFormsConditional-' . $form->ID);
}
} | php | public function generateConditionalJavascript()
{
$rules = '';
$form = $this->data();
if (!$form) {
return;
}
$formFields = $form->Fields();
$watch = [];
if ($formFields) {
/** @var EditableFormField $field */
foreach ($formFields as $field) {
if ($result = $field->formatDisplayRules()) {
$watch[] = $result;
}
}
}
if ($watch) {
$rules .= $this->buildWatchJS($watch);
}
// Only add customScript if $default or $rules is defined
if ($rules) {
Requirements::customScript(<<<JS
(function($) {
$(document).ready(function() {
{$rules}
});
})(jQuery);
JS
, 'UserFormsConditional-' . $form->ID);
}
} | [
"public",
"function",
"generateConditionalJavascript",
"(",
")",
"{",
"$",
"rules",
"=",
"''",
";",
"$",
"form",
"=",
"$",
"this",
"->",
"data",
"(",
")",
";",
"if",
"(",
"!",
"$",
"form",
")",
"{",
"return",
";",
"}",
"$",
"formFields",
"=",
"$",
... | Generate the javascript for the conditional field show / hiding logic.
@return void | [
"Generate",
"the",
"javascript",
"for",
"the",
"conditional",
"field",
"show",
"/",
"hiding",
"logic",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Control/UserDefinedFormController.php#L166-L200 |
silverstripe/silverstripe-userforms | code/Control/UserDefinedFormController.php | UserDefinedFormController.process | public function process($data, $form)
{
$submittedForm = SubmittedForm::create();
$submittedForm->SubmittedByID = Security::getCurrentUser() ? Security::getCurrentUser()->ID : 0;
$submittedForm->ParentClass = get_class($this->data());
$submittedForm->ParentID = $this->ID;
// if saving is not disabled save now to generate the ID
if (!$this->DisableSaveSubmissions) {
$submittedForm->write();
}
$attachments = [];
$submittedFields = ArrayList::create();
foreach ($this->data()->Fields() as $field) {
if (!$field->showInReports()) {
continue;
}
$submittedField = $field->getSubmittedFormField();
$submittedField->ParentID = $submittedForm->ID;
$submittedField->Name = $field->Name;
$submittedField->Title = $field->getField('Title');
// save the value from the data
if ($field->hasMethod('getValueFromData')) {
$submittedField->Value = $field->getValueFromData($data);
} else {
if (isset($data[$field->Name])) {
$submittedField->Value = $data[$field->Name];
}
}
if (!empty($data[$field->Name])) {
if (in_array(EditableFileField::class, $field->getClassAncestry())) {
if (!empty($_FILES[$field->Name]['name'])) {
$foldername = $field->getFormField()->getFolderName();
// create the file from post data
$upload = Upload::create();
$file = File::create();
$file->ShowInSearch = 0;
try {
$upload->loadIntoFile($_FILES[$field->Name], $file, $foldername);
} catch (ValidationException $e) {
$validationResult = $e->getResult();
foreach ($validationResult->getMessages() as $message) {
$form->sessionMessage($message['message'], ValidationResult::TYPE_ERROR);
}
Controller::curr()->redirectBack();
return;
}
// write file to form field
$submittedField->UploadedFileID = $file->ID;
// attach a file only if lower than 1MB
if ($file->getAbsoluteSize() < 1024 * 1024 * 1) {
$attachments[] = $file;
}
}
}
}
$submittedField->extend('onPopulationFromField', $field);
if (!$this->DisableSaveSubmissions) {
$submittedField->write();
}
$submittedFields->push($submittedField);
}
$emailData = [
'Sender' => Security::getCurrentUser(),
'HideFormData' => false,
'Fields' => $submittedFields,
'Body' => '',
];
$this->extend('updateEmailData', $emailData, $attachments);
// email users on submit.
if ($recipients = $this->FilteredEmailRecipients($data, $form)) {
foreach ($recipients as $recipient) {
$email = Email::create()
->setHTMLTemplate('email/SubmittedFormEmail')
->setPlainTemplate('email/SubmittedFormEmailPlain');
// Merge fields are used for CMS authors to reference specific form fields in email content
$mergeFields = $this->getMergeFieldsMap($emailData['Fields']);
if ($attachments) {
foreach ($attachments as $file) {
/** @var File $file */
if ((int) $file->ID === 0) {
continue;
}
$email->addAttachmentFromData(
$file->getString(),
$file->getFilename(),
$file->getMimeType()
);
}
}
if (!$recipient->SendPlain && $recipient->emailTemplateExists()) {
$email->setHTMLTemplate($recipient->EmailTemplate);
}
// Add specific template data for the current recipient
$emailData['HideFormData'] = (bool) $recipient->HideFormData;
// Include any parsed merge field references from the CMS editor - this is already escaped
$emailData['Body'] = SSViewer::execute_string($recipient->getEmailBodyContent(), $mergeFields);
// Push the template data to the Email's data
foreach ($emailData as $key => $value) {
$email->addData($key, $value);
}
// check to see if they are a dynamic reply to. eg based on a email field a user selected
$emailFrom = $recipient->SendEmailFromField();
if ($emailFrom && $emailFrom->exists()) {
$submittedFormField = $submittedFields->find('Name', $recipient->SendEmailFromField()->Name);
if ($submittedFormField && is_string($submittedFormField->Value)) {
$email->setReplyTo(explode(',', $submittedFormField->Value));
}
} elseif ($recipient->EmailReplyTo) {
$email->setReplyTo(explode(',', $recipient->EmailReplyTo));
}
// check for a specified from; otherwise fall back to server defaults
if ($recipient->EmailFrom) {
$email->setFrom(explode(',', $recipient->EmailFrom));
}
// check to see if they are a dynamic reciever eg based on a dropdown field a user selected
$emailTo = $recipient->SendEmailToField();
if ($emailTo && $emailTo->exists()) {
$submittedFormField = $submittedFields->find('Name', $recipient->SendEmailToField()->Name);
if ($submittedFormField && is_string($submittedFormField->Value)) {
$email->setTo(explode(',', $submittedFormField->Value));
} else {
$email->setTo(explode(',', $recipient->EmailAddress));
}
} else {
$email->setTo(explode(',', $recipient->EmailAddress));
}
// check to see if there is a dynamic subject
$emailSubject = $recipient->SendEmailSubjectField();
if ($emailSubject && $emailSubject->exists()) {
$submittedFormField = $submittedFields->find('Name', $recipient->SendEmailSubjectField()->Name);
if ($submittedFormField && trim($submittedFormField->Value)) {
$email->setSubject($submittedFormField->Value);
} else {
$email->setSubject(SSViewer::execute_string($recipient->EmailSubject, $mergeFields));
}
} else {
$email->setSubject(SSViewer::execute_string($recipient->EmailSubject, $mergeFields));
}
$this->extend('updateEmail', $email, $recipient, $emailData);
if ((bool)$recipient->SendPlain) {
$body = strip_tags($recipient->getEmailBodyContent()) . "\n";
if (isset($emailData['Fields']) && !$emailData['HideFormData']) {
foreach ($emailData['Fields'] as $field) {
$body .= $field->Title . ': ' . $field->Value . " \n";
}
}
$email->setBody($body);
$email->sendPlain();
} else {
$email->send();
}
}
}
$submittedForm->extend('updateAfterProcess');
$session = $this->getRequest()->getSession();
$session->clear("FormInfo.{$form->FormName()}.errors");
$session->clear("FormInfo.{$form->FormName()}.data");
$referrer = (isset($data['Referrer'])) ? '?referrer=' . urlencode($data['Referrer']) : "";
// set a session variable from the security ID to stop people accessing
// the finished method directly.
if (!$this->DisableAuthenicatedFinishAction) {
if (isset($data['SecurityID'])) {
$session->set('FormProcessed', $data['SecurityID']);
} else {
// if the form has had tokens disabled we still need to set FormProcessed
// to allow us to get through the finshed method
if (!$this->Form()->getSecurityToken()->isEnabled()) {
$randNum = rand(1, 1000);
$randHash = md5($randNum);
$session->set('FormProcessed', $randHash);
$session->set('FormProcessedNum', $randNum);
}
}
}
if (!$this->DisableSaveSubmissions) {
$session->set('userformssubmission'. $this->ID, $submittedForm->ID);
}
return $this->redirect($this->Link('finished') . $referrer . $this->config()->get('finished_anchor'));
} | php | public function process($data, $form)
{
$submittedForm = SubmittedForm::create();
$submittedForm->SubmittedByID = Security::getCurrentUser() ? Security::getCurrentUser()->ID : 0;
$submittedForm->ParentClass = get_class($this->data());
$submittedForm->ParentID = $this->ID;
// if saving is not disabled save now to generate the ID
if (!$this->DisableSaveSubmissions) {
$submittedForm->write();
}
$attachments = [];
$submittedFields = ArrayList::create();
foreach ($this->data()->Fields() as $field) {
if (!$field->showInReports()) {
continue;
}
$submittedField = $field->getSubmittedFormField();
$submittedField->ParentID = $submittedForm->ID;
$submittedField->Name = $field->Name;
$submittedField->Title = $field->getField('Title');
// save the value from the data
if ($field->hasMethod('getValueFromData')) {
$submittedField->Value = $field->getValueFromData($data);
} else {
if (isset($data[$field->Name])) {
$submittedField->Value = $data[$field->Name];
}
}
if (!empty($data[$field->Name])) {
if (in_array(EditableFileField::class, $field->getClassAncestry())) {
if (!empty($_FILES[$field->Name]['name'])) {
$foldername = $field->getFormField()->getFolderName();
// create the file from post data
$upload = Upload::create();
$file = File::create();
$file->ShowInSearch = 0;
try {
$upload->loadIntoFile($_FILES[$field->Name], $file, $foldername);
} catch (ValidationException $e) {
$validationResult = $e->getResult();
foreach ($validationResult->getMessages() as $message) {
$form->sessionMessage($message['message'], ValidationResult::TYPE_ERROR);
}
Controller::curr()->redirectBack();
return;
}
// write file to form field
$submittedField->UploadedFileID = $file->ID;
// attach a file only if lower than 1MB
if ($file->getAbsoluteSize() < 1024 * 1024 * 1) {
$attachments[] = $file;
}
}
}
}
$submittedField->extend('onPopulationFromField', $field);
if (!$this->DisableSaveSubmissions) {
$submittedField->write();
}
$submittedFields->push($submittedField);
}
$emailData = [
'Sender' => Security::getCurrentUser(),
'HideFormData' => false,
'Fields' => $submittedFields,
'Body' => '',
];
$this->extend('updateEmailData', $emailData, $attachments);
// email users on submit.
if ($recipients = $this->FilteredEmailRecipients($data, $form)) {
foreach ($recipients as $recipient) {
$email = Email::create()
->setHTMLTemplate('email/SubmittedFormEmail')
->setPlainTemplate('email/SubmittedFormEmailPlain');
// Merge fields are used for CMS authors to reference specific form fields in email content
$mergeFields = $this->getMergeFieldsMap($emailData['Fields']);
if ($attachments) {
foreach ($attachments as $file) {
/** @var File $file */
if ((int) $file->ID === 0) {
continue;
}
$email->addAttachmentFromData(
$file->getString(),
$file->getFilename(),
$file->getMimeType()
);
}
}
if (!$recipient->SendPlain && $recipient->emailTemplateExists()) {
$email->setHTMLTemplate($recipient->EmailTemplate);
}
// Add specific template data for the current recipient
$emailData['HideFormData'] = (bool) $recipient->HideFormData;
// Include any parsed merge field references from the CMS editor - this is already escaped
$emailData['Body'] = SSViewer::execute_string($recipient->getEmailBodyContent(), $mergeFields);
// Push the template data to the Email's data
foreach ($emailData as $key => $value) {
$email->addData($key, $value);
}
// check to see if they are a dynamic reply to. eg based on a email field a user selected
$emailFrom = $recipient->SendEmailFromField();
if ($emailFrom && $emailFrom->exists()) {
$submittedFormField = $submittedFields->find('Name', $recipient->SendEmailFromField()->Name);
if ($submittedFormField && is_string($submittedFormField->Value)) {
$email->setReplyTo(explode(',', $submittedFormField->Value));
}
} elseif ($recipient->EmailReplyTo) {
$email->setReplyTo(explode(',', $recipient->EmailReplyTo));
}
// check for a specified from; otherwise fall back to server defaults
if ($recipient->EmailFrom) {
$email->setFrom(explode(',', $recipient->EmailFrom));
}
// check to see if they are a dynamic reciever eg based on a dropdown field a user selected
$emailTo = $recipient->SendEmailToField();
if ($emailTo && $emailTo->exists()) {
$submittedFormField = $submittedFields->find('Name', $recipient->SendEmailToField()->Name);
if ($submittedFormField && is_string($submittedFormField->Value)) {
$email->setTo(explode(',', $submittedFormField->Value));
} else {
$email->setTo(explode(',', $recipient->EmailAddress));
}
} else {
$email->setTo(explode(',', $recipient->EmailAddress));
}
// check to see if there is a dynamic subject
$emailSubject = $recipient->SendEmailSubjectField();
if ($emailSubject && $emailSubject->exists()) {
$submittedFormField = $submittedFields->find('Name', $recipient->SendEmailSubjectField()->Name);
if ($submittedFormField && trim($submittedFormField->Value)) {
$email->setSubject($submittedFormField->Value);
} else {
$email->setSubject(SSViewer::execute_string($recipient->EmailSubject, $mergeFields));
}
} else {
$email->setSubject(SSViewer::execute_string($recipient->EmailSubject, $mergeFields));
}
$this->extend('updateEmail', $email, $recipient, $emailData);
if ((bool)$recipient->SendPlain) {
$body = strip_tags($recipient->getEmailBodyContent()) . "\n";
if (isset($emailData['Fields']) && !$emailData['HideFormData']) {
foreach ($emailData['Fields'] as $field) {
$body .= $field->Title . ': ' . $field->Value . " \n";
}
}
$email->setBody($body);
$email->sendPlain();
} else {
$email->send();
}
}
}
$submittedForm->extend('updateAfterProcess');
$session = $this->getRequest()->getSession();
$session->clear("FormInfo.{$form->FormName()}.errors");
$session->clear("FormInfo.{$form->FormName()}.data");
$referrer = (isset($data['Referrer'])) ? '?referrer=' . urlencode($data['Referrer']) : "";
// set a session variable from the security ID to stop people accessing
// the finished method directly.
if (!$this->DisableAuthenicatedFinishAction) {
if (isset($data['SecurityID'])) {
$session->set('FormProcessed', $data['SecurityID']);
} else {
// if the form has had tokens disabled we still need to set FormProcessed
// to allow us to get through the finshed method
if (!$this->Form()->getSecurityToken()->isEnabled()) {
$randNum = rand(1, 1000);
$randHash = md5($randNum);
$session->set('FormProcessed', $randHash);
$session->set('FormProcessedNum', $randNum);
}
}
}
if (!$this->DisableSaveSubmissions) {
$session->set('userformssubmission'. $this->ID, $submittedForm->ID);
}
return $this->redirect($this->Link('finished') . $referrer . $this->config()->get('finished_anchor'));
} | [
"public",
"function",
"process",
"(",
"$",
"data",
",",
"$",
"form",
")",
"{",
"$",
"submittedForm",
"=",
"SubmittedForm",
"::",
"create",
"(",
")",
";",
"$",
"submittedForm",
"->",
"SubmittedByID",
"=",
"Security",
"::",
"getCurrentUser",
"(",
")",
"?",
... | Process the form that is submitted through the site
{@see UserForm::validate()} for validation step prior to processing
@param array $data
@param Form $form
@return HTTPResponse | [
"Process",
"the",
"form",
"that",
"is",
"submitted",
"through",
"the",
"site"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Control/UserDefinedFormController.php#L212-L427 |
silverstripe/silverstripe-userforms | code/Control/UserDefinedFormController.php | UserDefinedFormController.getMergeFieldsMap | protected function getMergeFieldsMap($fields = [])
{
$data = ArrayData::create([]);
foreach ($fields as $field) {
$data->setField($field->Name, DBField::create_field('Text', $field->Value));
}
return $data;
} | php | protected function getMergeFieldsMap($fields = [])
{
$data = ArrayData::create([]);
foreach ($fields as $field) {
$data->setField($field->Name, DBField::create_field('Text', $field->Value));
}
return $data;
} | [
"protected",
"function",
"getMergeFieldsMap",
"(",
"$",
"fields",
"=",
"[",
"]",
")",
"{",
"$",
"data",
"=",
"ArrayData",
"::",
"create",
"(",
"[",
"]",
")",
";",
"foreach",
"(",
"$",
"fields",
"as",
"$",
"field",
")",
"{",
"$",
"data",
"->",
"setF... | Allows the use of field values in email body.
@param ArrayList $fields
@return ArrayData | [
"Allows",
"the",
"use",
"of",
"field",
"values",
"in",
"email",
"body",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Control/UserDefinedFormController.php#L435-L444 |
silverstripe/silverstripe-userforms | code/Control/UserDefinedFormController.php | UserDefinedFormController.finished | public function finished()
{
$submission = $this->getRequest()->getSession()->get('userformssubmission'. $this->ID);
if ($submission) {
$submission = SubmittedForm::get()->byId($submission);
}
$referrer = isset($_GET['referrer']) ? urldecode($_GET['referrer']) : null;
if (!$this->DisableAuthenicatedFinishAction) {
$formProcessed = $this->getRequest()->getSession()->get('FormProcessed');
if (!isset($formProcessed)) {
return $this->redirect($this->Link() . $referrer);
} else {
$securityID = $this->getRequest()->getSession()->get('SecurityID');
// make sure the session matches the SecurityID and is not left over from another form
if ($formProcessed != $securityID) {
// they may have disabled tokens on the form
$securityID = md5($this->getRequest()->getSession()->get('FormProcessedNum'));
if ($formProcessed != $securityID) {
return $this->redirect($this->Link() . $referrer);
}
}
}
$this->getRequest()->getSession()->clear('FormProcessed');
}
$data = [
'Submission' => $submission,
'Link' => $referrer
];
$this->extend('updateReceivedFormSubmissionData', $data);
return $this->customise([
'Content' => $this->customise($data)->renderWith(__CLASS__ . '_ReceivedFormSubmission'),
'Form' => '',
]);
} | php | public function finished()
{
$submission = $this->getRequest()->getSession()->get('userformssubmission'. $this->ID);
if ($submission) {
$submission = SubmittedForm::get()->byId($submission);
}
$referrer = isset($_GET['referrer']) ? urldecode($_GET['referrer']) : null;
if (!$this->DisableAuthenicatedFinishAction) {
$formProcessed = $this->getRequest()->getSession()->get('FormProcessed');
if (!isset($formProcessed)) {
return $this->redirect($this->Link() . $referrer);
} else {
$securityID = $this->getRequest()->getSession()->get('SecurityID');
// make sure the session matches the SecurityID and is not left over from another form
if ($formProcessed != $securityID) {
// they may have disabled tokens on the form
$securityID = md5($this->getRequest()->getSession()->get('FormProcessedNum'));
if ($formProcessed != $securityID) {
return $this->redirect($this->Link() . $referrer);
}
}
}
$this->getRequest()->getSession()->clear('FormProcessed');
}
$data = [
'Submission' => $submission,
'Link' => $referrer
];
$this->extend('updateReceivedFormSubmissionData', $data);
return $this->customise([
'Content' => $this->customise($data)->renderWith(__CLASS__ . '_ReceivedFormSubmission'),
'Form' => '',
]);
} | [
"public",
"function",
"finished",
"(",
")",
"{",
"$",
"submission",
"=",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"getSession",
"(",
")",
"->",
"get",
"(",
"'userformssubmission'",
".",
"$",
"this",
"->",
"ID",
")",
";",
"if",
"(",
"$",
"subm... | This action handles rendering the "finished" message, which is
customizable by editing the ReceivedFormSubmission template.
@return ViewableData | [
"This",
"action",
"handles",
"rendering",
"the",
"finished",
"message",
"which",
"is",
"customizable",
"by",
"editing",
"the",
"ReceivedFormSubmission",
"template",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Control/UserDefinedFormController.php#L452-L493 |
silverstripe/silverstripe-userforms | code/Control/UserDefinedFormController.php | UserDefinedFormController.buildWatchJS | protected function buildWatchJS($watch)
{
$result = '';
foreach ($watch as $key => $rule) {
$events = implode(' ', $rule['events']);
$selectors = implode(', ', $rule['selectors']);
$conjunction = $rule['conjunction'];
$operations = implode(" {$conjunction} ", $rule['operations']);
$target = $rule['targetFieldID'];
$holder = $rule['holder'];
$result .= <<<EOS
\n
$('.userform').on('{$events}',
"{$selectors}",
function (){
if ({$operations}) {
$('{$target}').{$rule['view']};
{$holder}.{$rule['view']}.trigger('{$rule['holder_event']}');
} else {
$('{$target}').{$rule['opposite']};
{$holder}.{$rule['opposite']}.trigger('{$rule['holder_event_opposite']}');
}
});
$("{$target}").find('.hide').removeClass('hide');
EOS;
}
return $result;
} | php | protected function buildWatchJS($watch)
{
$result = '';
foreach ($watch as $key => $rule) {
$events = implode(' ', $rule['events']);
$selectors = implode(', ', $rule['selectors']);
$conjunction = $rule['conjunction'];
$operations = implode(" {$conjunction} ", $rule['operations']);
$target = $rule['targetFieldID'];
$holder = $rule['holder'];
$result .= <<<EOS
\n
$('.userform').on('{$events}',
"{$selectors}",
function (){
if ({$operations}) {
$('{$target}').{$rule['view']};
{$holder}.{$rule['view']}.trigger('{$rule['holder_event']}');
} else {
$('{$target}').{$rule['opposite']};
{$holder}.{$rule['opposite']}.trigger('{$rule['holder_event_opposite']}');
}
});
$("{$target}").find('.hide').removeClass('hide');
EOS;
}
return $result;
} | [
"protected",
"function",
"buildWatchJS",
"(",
"$",
"watch",
")",
"{",
"$",
"result",
"=",
"''",
";",
"foreach",
"(",
"$",
"watch",
"as",
"$",
"key",
"=>",
"$",
"rule",
")",
"{",
"$",
"events",
"=",
"implode",
"(",
"' '",
",",
"$",
"rule",
"[",
"'... | Outputs the required JS from the $watch input
@param array $watch
@return string | [
"Outputs",
"the",
"required",
"JS",
"from",
"the",
"$watch",
"input"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Control/UserDefinedFormController.php#L502-L531 |
silverstripe/silverstripe-userforms | code/Model/Recipient/UserFormRecipientItemRequest.php | UserFormRecipientItemRequest.preview | public function preview()
{
// Enable theme for preview (may be needed for Shortcodes)
Config::nest();
Config::modify()->set(SSViewer::class, 'theme_enabled', true);
$content = $this->customise([
'Body' => $this->record->getEmailBodyContent(),
'HideFormData' => (bool) $this->record->HideFormData,
'Fields' => $this->getPreviewFieldData()
])->renderWith($this->record->EmailTemplate);
Config::unnest();
return $content;
} | php | public function preview()
{
// Enable theme for preview (may be needed for Shortcodes)
Config::nest();
Config::modify()->set(SSViewer::class, 'theme_enabled', true);
$content = $this->customise([
'Body' => $this->record->getEmailBodyContent(),
'HideFormData' => (bool) $this->record->HideFormData,
'Fields' => $this->getPreviewFieldData()
])->renderWith($this->record->EmailTemplate);
Config::unnest();
return $content;
} | [
"public",
"function",
"preview",
"(",
")",
"{",
"// Enable theme for preview (may be needed for Shortcodes)",
"Config",
"::",
"nest",
"(",
")",
";",
"Config",
"::",
"modify",
"(",
")",
"->",
"set",
"(",
"SSViewer",
"::",
"class",
",",
"'theme_enabled'",
",",
"tr... | Renders a preview of the recipient email. | [
"Renders",
"a",
"preview",
"of",
"the",
"recipient",
"email",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Model/Recipient/UserFormRecipientItemRequest.php#L31-L46 |
silverstripe/silverstripe-userforms | code/Model/Recipient/UserFormRecipientItemRequest.php | UserFormRecipientItemRequest.getPreviewFieldData | protected function getPreviewFieldData()
{
$data = ArrayList::create();
$fields = $this->record->Form()->Fields()->filter(
'ClassName:not',
[
EditableLiteralField::class,
EditableFormHeading::class,
]
);
foreach ($fields as $field) {
$data->push(ArrayData::create([
'Name' => $field->dbObject('Name'),
'Title' => $field->dbObject('Title'),
'Value' => DBField::create_field('Varchar', '$' . $field->Name),
'FormattedValue' => DBField::create_field('Varchar', '$' . $field->Name)
]));
}
return $data;
} | php | protected function getPreviewFieldData()
{
$data = ArrayList::create();
$fields = $this->record->Form()->Fields()->filter(
'ClassName:not',
[
EditableLiteralField::class,
EditableFormHeading::class,
]
);
foreach ($fields as $field) {
$data->push(ArrayData::create([
'Name' => $field->dbObject('Name'),
'Title' => $field->dbObject('Title'),
'Value' => DBField::create_field('Varchar', '$' . $field->Name),
'FormattedValue' => DBField::create_field('Varchar', '$' . $field->Name)
]));
}
return $data;
} | [
"protected",
"function",
"getPreviewFieldData",
"(",
")",
"{",
"$",
"data",
"=",
"ArrayList",
"::",
"create",
"(",
")",
";",
"$",
"fields",
"=",
"$",
"this",
"->",
"record",
"->",
"Form",
"(",
")",
"->",
"Fields",
"(",
")",
"->",
"filter",
"(",
"'Cla... | Get some placeholder field values to display in the preview
@return ArrayList | [
"Get",
"some",
"placeholder",
"field",
"values",
"to",
"display",
"in",
"the",
"preview"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Model/Recipient/UserFormRecipientItemRequest.php#L53-L75 |
silverstripe/silverstripe-userforms | code/Model/EditableCustomRule.php | EditableCustomRule.buildExpression | public function buildExpression()
{
/** @var EditableFormField $formFieldWatch */
$formFieldWatch = $this->ConditionField();
//Encapsulated the action to the object
$action = $formFieldWatch->getJsEventHandler();
// is this field a special option field
$checkboxField = $formFieldWatch->isCheckBoxField();
$radioField = $formFieldWatch->isRadioField();
$target = sprintf('$("%s")', $formFieldWatch->getSelectorFieldOnly());
$fieldValue = Convert::raw2js($this->FieldValue);
$conditionOptions = [
'ValueLessThan' => '<',
'ValueLessThanEqual' => '<=',
'ValueGreaterThan' => '>',
'ValueGreaterThanEqual' => '>='
];
// and what should we evaluate
switch ($this->ConditionOption) {
case 'IsNotBlank':
case 'IsBlank':
$expression = ($checkboxField || $radioField) ? "!{$target}.is(\":checked\")" : "{$target}.val() == ''";
if ((string) $this->ConditionOption === 'IsNotBlank') {
//Negate
$expression = "!({$expression})";
}
break;
case 'HasValue':
case 'ValueNot':
if ($checkboxField) {
if ($formFieldWatch->isCheckBoxGroupField()) {
$expression = sprintf(
"$.inArray('%s', %s.filter(':checked').map(function(){ return $(this).val();}).get()) > -1",
$fieldValue,
$target
);
} else {
$expression = "{$target}.prop('checked')";
}
} elseif ($radioField) {
// We cannot simply get the value of the radio group, we need to find the checked option first.
$expression = sprintf(
'%s.closest(".field, .control-group").find("input:checked").val() == "%s"',
$target,
$fieldValue
);
} else {
$expression = sprintf('%s.val() == "%s"', $target, $fieldValue);
}
if ((string) $this->ConditionOption === 'ValueNot') {
//Negate
$expression = "!({$expression})";
}
break;
case 'ValueLessThan':
case 'ValueLessThanEqual':
case 'ValueGreaterThan':
case 'ValueGreaterThanEqual':
$expression = sprintf(
'%s.val() %s parseFloat("%s")',
$target,
$conditionOptions[$this->ConditionOption],
$fieldValue
);
break;
default:
throw new LogicException("Unhandled rule {$this->ConditionOption}");
break;
}
$result = [
'operation' => $expression,
'event' => $action,
];
return $result;
} | php | public function buildExpression()
{
/** @var EditableFormField $formFieldWatch */
$formFieldWatch = $this->ConditionField();
//Encapsulated the action to the object
$action = $formFieldWatch->getJsEventHandler();
// is this field a special option field
$checkboxField = $formFieldWatch->isCheckBoxField();
$radioField = $formFieldWatch->isRadioField();
$target = sprintf('$("%s")', $formFieldWatch->getSelectorFieldOnly());
$fieldValue = Convert::raw2js($this->FieldValue);
$conditionOptions = [
'ValueLessThan' => '<',
'ValueLessThanEqual' => '<=',
'ValueGreaterThan' => '>',
'ValueGreaterThanEqual' => '>='
];
// and what should we evaluate
switch ($this->ConditionOption) {
case 'IsNotBlank':
case 'IsBlank':
$expression = ($checkboxField || $radioField) ? "!{$target}.is(\":checked\")" : "{$target}.val() == ''";
if ((string) $this->ConditionOption === 'IsNotBlank') {
//Negate
$expression = "!({$expression})";
}
break;
case 'HasValue':
case 'ValueNot':
if ($checkboxField) {
if ($formFieldWatch->isCheckBoxGroupField()) {
$expression = sprintf(
"$.inArray('%s', %s.filter(':checked').map(function(){ return $(this).val();}).get()) > -1",
$fieldValue,
$target
);
} else {
$expression = "{$target}.prop('checked')";
}
} elseif ($radioField) {
// We cannot simply get the value of the radio group, we need to find the checked option first.
$expression = sprintf(
'%s.closest(".field, .control-group").find("input:checked").val() == "%s"',
$target,
$fieldValue
);
} else {
$expression = sprintf('%s.val() == "%s"', $target, $fieldValue);
}
if ((string) $this->ConditionOption === 'ValueNot') {
//Negate
$expression = "!({$expression})";
}
break;
case 'ValueLessThan':
case 'ValueLessThanEqual':
case 'ValueGreaterThan':
case 'ValueGreaterThanEqual':
$expression = sprintf(
'%s.val() %s parseFloat("%s")',
$target,
$conditionOptions[$this->ConditionOption],
$fieldValue
);
break;
default:
throw new LogicException("Unhandled rule {$this->ConditionOption}");
break;
}
$result = [
'operation' => $expression,
'event' => $action,
];
return $result;
} | [
"public",
"function",
"buildExpression",
"(",
")",
"{",
"/** @var EditableFormField $formFieldWatch */",
"$",
"formFieldWatch",
"=",
"$",
"this",
"->",
"ConditionField",
"(",
")",
";",
"//Encapsulated the action to the object",
"$",
"action",
"=",
"$",
"formFieldWatch",
... | Substitutes configured rule logic with it's JS equivalents and returns them as array elements
@return array
@throws LogicException If the provided condition option was not able to be handled | [
"Substitutes",
"configured",
"rule",
"logic",
"with",
"it",
"s",
"JS",
"equivalents",
"and",
"returns",
"them",
"as",
"array",
"elements"
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Model/EditableCustomRule.php#L151-L231 |
silverstripe/silverstripe-userforms | code/Model/EditableCustomRule.php | EditableCustomRule.toggleDisplayText | public function toggleDisplayText($initialState, $invert = false)
{
$action = strtolower($initialState) === 'hide' ? 'removeClass' : 'addClass';
if ($invert) {
$action = $action === 'removeClass' ? 'addClass' : 'removeClass';
}
return sprintf('%s("hide")', $action);
} | php | public function toggleDisplayText($initialState, $invert = false)
{
$action = strtolower($initialState) === 'hide' ? 'removeClass' : 'addClass';
if ($invert) {
$action = $action === 'removeClass' ? 'addClass' : 'removeClass';
}
return sprintf('%s("hide")', $action);
} | [
"public",
"function",
"toggleDisplayText",
"(",
"$",
"initialState",
",",
"$",
"invert",
"=",
"false",
")",
"{",
"$",
"action",
"=",
"strtolower",
"(",
"$",
"initialState",
")",
"===",
"'hide'",
"?",
"'removeClass'",
":",
"'addClass'",
";",
"if",
"(",
"$",... | Returns the opposite visibility function for the value of the initial visibility field, e.g. show/hide. This
will toggle the "hide" class either way, which is handled by CSS.
@param string $initialState
@param boolean $invert
@return string | [
"Returns",
"the",
"opposite",
"visibility",
"function",
"for",
"the",
"value",
"of",
"the",
"initial",
"visibility",
"field",
"e",
".",
"g",
".",
"show",
"/",
"hide",
".",
"This",
"will",
"toggle",
"the",
"hide",
"class",
"either",
"way",
"which",
"is",
... | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Model/EditableCustomRule.php#L241-L248 |
silverstripe/silverstripe-userforms | code/Model/EditableCustomRule.php | EditableCustomRule.toggleDisplayEvent | public function toggleDisplayEvent($initialState, $invert = false)
{
$action = strtolower($initialState) === 'hide' ? 'show' : 'hide';
if ($invert) {
$action = $action === 'hide' ? 'show' : 'hide';
}
return sprintf('userform.field.%s', $action);
} | php | public function toggleDisplayEvent($initialState, $invert = false)
{
$action = strtolower($initialState) === 'hide' ? 'show' : 'hide';
if ($invert) {
$action = $action === 'hide' ? 'show' : 'hide';
}
return sprintf('userform.field.%s', $action);
} | [
"public",
"function",
"toggleDisplayEvent",
"(",
"$",
"initialState",
",",
"$",
"invert",
"=",
"false",
")",
"{",
"$",
"action",
"=",
"strtolower",
"(",
"$",
"initialState",
")",
"===",
"'hide'",
"?",
"'show'",
":",
"'hide'",
";",
"if",
"(",
"$",
"invert... | Returns an event name to be dispatched when the field is changed. Matches up with the visibility classes
added or removed in `toggleDisplayText()`.
@param string $initialState
@param bool $invert
@return string | [
"Returns",
"an",
"event",
"name",
"to",
"be",
"dispatched",
"when",
"the",
"field",
"is",
"changed",
".",
"Matches",
"up",
"with",
"the",
"visibility",
"classes",
"added",
"or",
"removed",
"in",
"toggleDisplayText",
"()",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Model/EditableCustomRule.php#L258-L265 |
silverstripe/silverstripe-userforms | code/Model/Submission/SubmittedFileField.php | SubmittedFileField.getFormattedValue | public function getFormattedValue()
{
$name = $this->getFileName();
$link = $this->getLink();
$title = _t(__CLASS__.'.DOWNLOADFILE', 'Download File');
if ($link) {
return DBField::create_field('HTMLText', sprintf(
'%s - <a href="%s" target="_blank">%s</a>',
$name,
$link,
$title
));
}
return false;
} | php | public function getFormattedValue()
{
$name = $this->getFileName();
$link = $this->getLink();
$title = _t(__CLASS__.'.DOWNLOADFILE', 'Download File');
if ($link) {
return DBField::create_field('HTMLText', sprintf(
'%s - <a href="%s" target="_blank">%s</a>',
$name,
$link,
$title
));
}
return false;
} | [
"public",
"function",
"getFormattedValue",
"(",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"getFileName",
"(",
")",
";",
"$",
"link",
"=",
"$",
"this",
"->",
"getLink",
"(",
")",
";",
"$",
"title",
"=",
"_t",
"(",
"__CLASS__",
".",
"'.DOWNLOADFIL... | Return the value of this field for inclusion into things such as
reports.
@return string | [
"Return",
"the",
"value",
"of",
"this",
"field",
"for",
"inclusion",
"into",
"things",
"such",
"as",
"reports",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Model/Submission/SubmittedFileField.php#L29-L45 |
silverstripe/silverstripe-userforms | code/Model/Submission/SubmittedFileField.php | SubmittedFileField.getLink | public function getLink()
{
if ($file = $this->UploadedFile()) {
if (trim($file->getFilename(), '/') != trim(ASSETS_DIR, '/')) {
return $this->UploadedFile()->AbsoluteLink();
}
}
} | php | public function getLink()
{
if ($file = $this->UploadedFile()) {
if (trim($file->getFilename(), '/') != trim(ASSETS_DIR, '/')) {
return $this->UploadedFile()->AbsoluteLink();
}
}
} | [
"public",
"function",
"getLink",
"(",
")",
"{",
"if",
"(",
"$",
"file",
"=",
"$",
"this",
"->",
"UploadedFile",
"(",
")",
")",
"{",
"if",
"(",
"trim",
"(",
"$",
"file",
"->",
"getFilename",
"(",
")",
",",
"'/'",
")",
"!=",
"trim",
"(",
"ASSETS_DI... | Return the link for the file attached to this submitted form field.
@return string | [
"Return",
"the",
"link",
"for",
"the",
"file",
"attached",
"to",
"this",
"submitted",
"form",
"field",
"."
] | train | https://github.com/silverstripe/silverstripe-userforms/blob/6eb661fedf5f1cb70a814a1c2354e627b28273e3/code/Model/Submission/SubmittedFileField.php#L62-L69 |
core23/DompdfBundle | src/Wrapper/DompdfWrapper.php | DompdfWrapper.streamHtml | public function streamHtml(string $html, string $filename, array $options = []): void
{
$pdf = $this->dompdfFactory->create($options);
$pdf->loadHtml($html);
$pdf->render();
if ($this->eventDispatcher instanceof EventDispatcherInterface) {
$event = new StreamEvent($pdf, $filename, $html);
$this->eventDispatcher->dispatch(DompdfEvents::STREAM, $event);
}
$pdf->stream($filename, $options);
} | php | public function streamHtml(string $html, string $filename, array $options = []): void
{
$pdf = $this->dompdfFactory->create($options);
$pdf->loadHtml($html);
$pdf->render();
if ($this->eventDispatcher instanceof EventDispatcherInterface) {
$event = new StreamEvent($pdf, $filename, $html);
$this->eventDispatcher->dispatch(DompdfEvents::STREAM, $event);
}
$pdf->stream($filename, $options);
} | [
"public",
"function",
"streamHtml",
"(",
"string",
"$",
"html",
",",
"string",
"$",
"filename",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"void",
"{",
"$",
"pdf",
"=",
"$",
"this",
"->",
"dompdfFactory",
"->",
"create",
"(",
"$",
"option... | {@inheritdoc} | [
"{"
] | train | https://github.com/core23/DompdfBundle/blob/d24afba1351c807ddff35df53500ec81c9cae5cf/src/Wrapper/DompdfWrapper.php#L47-L59 |
core23/DompdfBundle | src/Wrapper/DompdfWrapper.php | DompdfWrapper.getStreamResponse | public function getStreamResponse(string $html, string $filename, array $options = []): StreamedResponse
{
$response = new StreamedResponse();
$response->setCallback(function () use ($html, $filename, $options): void {
$this->streamHtml($html, $filename, $options);
});
return $response;
} | php | public function getStreamResponse(string $html, string $filename, array $options = []): StreamedResponse
{
$response = new StreamedResponse();
$response->setCallback(function () use ($html, $filename, $options): void {
$this->streamHtml($html, $filename, $options);
});
return $response;
} | [
"public",
"function",
"getStreamResponse",
"(",
"string",
"$",
"html",
",",
"string",
"$",
"filename",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"StreamedResponse",
"{",
"$",
"response",
"=",
"new",
"StreamedResponse",
"(",
")",
";",
"$",
"r... | @param string $html
@param string $filename
@param array $options
@return StreamedResponse | [
"@param",
"string",
"$html",
"@param",
"string",
"$filename",
"@param",
"array",
"$options"
] | train | https://github.com/core23/DompdfBundle/blob/d24afba1351c807ddff35df53500ec81c9cae5cf/src/Wrapper/DompdfWrapper.php#L68-L76 |
core23/DompdfBundle | src/Wrapper/DompdfWrapper.php | DompdfWrapper.getPdf | public function getPdf(string $html, array $options = []): string
{
$pdf = $this->dompdfFactory->create($options);
$pdf->loadHtml($html);
$pdf->render();
if ($this->eventDispatcher instanceof EventDispatcherInterface) {
$event = new OutputEvent($pdf, $html);
$this->eventDispatcher->dispatch(DompdfEvents::OUTPUT, $event);
}
$out = $pdf->output();
if (null === $out) {
throw new PdfException('Error creating PDF document');
}
return $out;
} | php | public function getPdf(string $html, array $options = []): string
{
$pdf = $this->dompdfFactory->create($options);
$pdf->loadHtml($html);
$pdf->render();
if ($this->eventDispatcher instanceof EventDispatcherInterface) {
$event = new OutputEvent($pdf, $html);
$this->eventDispatcher->dispatch(DompdfEvents::OUTPUT, $event);
}
$out = $pdf->output();
if (null === $out) {
throw new PdfException('Error creating PDF document');
}
return $out;
} | [
"public",
"function",
"getPdf",
"(",
"string",
"$",
"html",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"string",
"{",
"$",
"pdf",
"=",
"$",
"this",
"->",
"dompdfFactory",
"->",
"create",
"(",
"$",
"options",
")",
";",
"$",
"pdf",
"->",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/core23/DompdfBundle/blob/d24afba1351c807ddff35df53500ec81c9cae5cf/src/Wrapper/DompdfWrapper.php#L81-L99 |
core23/DompdfBundle | src/DependencyInjection/Configuration.php | Configuration.getConfigTreeBuilder | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('core23_dompdf');
// Keep compatibility with symfony/config < 4.2
if (!method_exists($treeBuilder, 'getRootNode')) {
$rootNode = $treeBuilder->root('core23_dompdf');
} else {
$rootNode = $treeBuilder->getRootNode();
}
\assert($rootNode instanceof ArrayNodeDefinition);
$rootNode
->children()
->arrayNode('defaults')
->useAttributeAsKey('name')
->prototype('scalar')->end()
->defaultValue([
'fontCache' => '%kernel.cache_dir%',
])
->end()
->end()
;
return $treeBuilder;
} | php | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('core23_dompdf');
// Keep compatibility with symfony/config < 4.2
if (!method_exists($treeBuilder, 'getRootNode')) {
$rootNode = $treeBuilder->root('core23_dompdf');
} else {
$rootNode = $treeBuilder->getRootNode();
}
\assert($rootNode instanceof ArrayNodeDefinition);
$rootNode
->children()
->arrayNode('defaults')
->useAttributeAsKey('name')
->prototype('scalar')->end()
->defaultValue([
'fontCache' => '%kernel.cache_dir%',
])
->end()
->end()
;
return $treeBuilder;
} | [
"public",
"function",
"getConfigTreeBuilder",
"(",
")",
"{",
"$",
"treeBuilder",
"=",
"new",
"TreeBuilder",
"(",
"'core23_dompdf'",
")",
";",
"// Keep compatibility with symfony/config < 4.2",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"treeBuilder",
",",
"'getRootNod... | {@inheritdoc} | [
"{"
] | train | https://github.com/core23/DompdfBundle/blob/d24afba1351c807ddff35df53500ec81c9cae5cf/src/DependencyInjection/Configuration.php#L23-L48 |
evias/nem-php | src/Models/Transaction/MosaicSupplyChange.php | MosaicSupplyChange.extend | public function extend()
{
// supply type validation
$type = $this->getAttribute("supplyType");
$validTypes = [self::TYPE_INCREASE, self::TYPE_DECREASE];
if (! $type || ! in_array($type, $validTypes)) {
$type = self::TYPE_INCREASE;
$this->setAttribute("supplyType", $type);
}
// always positive delta
$delta = abs($this->delta ?: 0);
return [
"mosaicId" => $this->mosaicId()->toDTO(),
"supplyType" => $type,
"delta" => $delta,
// transaction type specialization
"type" => TransactionType::MOSAIC_SUPPLY_CHANGE,
];
} | php | public function extend()
{
// supply type validation
$type = $this->getAttribute("supplyType");
$validTypes = [self::TYPE_INCREASE, self::TYPE_DECREASE];
if (! $type || ! in_array($type, $validTypes)) {
$type = self::TYPE_INCREASE;
$this->setAttribute("supplyType", $type);
}
// always positive delta
$delta = abs($this->delta ?: 0);
return [
"mosaicId" => $this->mosaicId()->toDTO(),
"supplyType" => $type,
"delta" => $delta,
// transaction type specialization
"type" => TransactionType::MOSAIC_SUPPLY_CHANGE,
];
} | [
"public",
"function",
"extend",
"(",
")",
"{",
"// supply type validation",
"$",
"type",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"\"supplyType\"",
")",
";",
"$",
"validTypes",
"=",
"[",
"self",
"::",
"TYPE_INCREASE",
",",
"self",
"::",
"TYPE_DECREASE",
... | The Signature transaction type does not need to add an offset to
the transaction base DTO.
@return array | [
"The",
"Signature",
"transaction",
"type",
"does",
"not",
"need",
"to",
"add",
"an",
"offset",
"to",
"the",
"transaction",
"base",
"DTO",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/MosaicSupplyChange.php#L64-L84 |
evias/nem-php | src/Models/Transaction/MosaicSupplyChange.php | MosaicSupplyChange.serialize | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->extend();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_mosaic = $this->mosaicId()->serialize();
$uint8_supType = $serializer->serializeInt($nisData["supplyType"]);
$uint8_delta = $serializer->serializeLong($nisData["delta"]);
// concatenate the UInt8 representation
$output = array_merge(
$uint8_mosaic,
$uint8_supType,
$uint8_delta);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | php | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->extend();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_mosaic = $this->mosaicId()->serialize();
$uint8_supType = $serializer->serializeInt($nisData["supplyType"]);
$uint8_delta = $serializer->serializeLong($nisData["delta"]);
// concatenate the UInt8 representation
$output = array_merge(
$uint8_mosaic,
$uint8_supType,
$uint8_delta);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"$",
"baseTx",
"=",
"parent",
"::",
"serialize",
"(",
"$",
"parameters",
")",
";",
"$",
"nisData",
"=",
"$",
"this",
"->",
"extend",
"(",
")",
";",
"// shortcuts",
"$",
... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *MosaicSupplyChange* serialization.
@see \NEM\Contracts\Serializable
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"MosaicSupplyChange",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/MosaicSupplyChange.php#L105-L127 |
evias/nem-php | src/Models/Mutators/CollectionMutator.php | CollectionMutator.mutate | public function mutate($name, $items)
{
// snake_case to camelCase
$modelClass = "\\NEM\\Models\\" . Str::studly($name);
if (!class_exists($modelClass)) {
throw new BadMethodCallException("Model class '" . $modelClass . "' could not be found in \\NEM\\Model namespace.");
}
if ($items instanceof ModelCollection)
// collection already provided
return $items;
$mutator = new ModelMutator();
$collection = new ModelCollection;
$reflection = new $modelClass;
if ($reflection instanceof ModelCollection) {
// mutating Collection object, the model class is the singular
// representation of the passed `$name`.
$collection = $reflection; // specialize collection
$name = Str::singular($name); // attachments=attachment, properties=property, etc..
}
for ($i = 0, $m = count($items); $i < $m; $i++) {
if (!isset($items[$i]))
$data = $items;
elseif ($items[$i] instanceof DataTransferObject)
$data = $items[$i]->toDTO();
else
$data = $items[$i];
// load Model instance with item data
$collection->push($mutator->mutate($name, $data));
}
return $collection;
} | php | public function mutate($name, $items)
{
// snake_case to camelCase
$modelClass = "\\NEM\\Models\\" . Str::studly($name);
if (!class_exists($modelClass)) {
throw new BadMethodCallException("Model class '" . $modelClass . "' could not be found in \\NEM\\Model namespace.");
}
if ($items instanceof ModelCollection)
// collection already provided
return $items;
$mutator = new ModelMutator();
$collection = new ModelCollection;
$reflection = new $modelClass;
if ($reflection instanceof ModelCollection) {
// mutating Collection object, the model class is the singular
// representation of the passed `$name`.
$collection = $reflection; // specialize collection
$name = Str::singular($name); // attachments=attachment, properties=property, etc..
}
for ($i = 0, $m = count($items); $i < $m; $i++) {
if (!isset($items[$i]))
$data = $items;
elseif ($items[$i] instanceof DataTransferObject)
$data = $items[$i]->toDTO();
else
$data = $items[$i];
// load Model instance with item data
$collection->push($mutator->mutate($name, $data));
}
return $collection;
} | [
"public",
"function",
"mutate",
"(",
"$",
"name",
",",
"$",
"items",
")",
"{",
"// snake_case to camelCase",
"$",
"modelClass",
"=",
"\"\\\\NEM\\\\Models\\\\\"",
".",
"Str",
"::",
"studly",
"(",
"$",
"name",
")",
";",
"if",
"(",
"!",
"class_exists",
"(",
"... | Collect several items into a Collection of Models.
The \NEM\Models\ModelMutator will be used internally to craft singular
model objects for each item you pass to this method.
@internal
@param string $name The model name you would like to store in the collection.
@param array $items The collection's items data.
@return \Illuminate\Support\Collection | [
"Collect",
"several",
"items",
"into",
"a",
"Collection",
"of",
"Models",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Mutators/CollectionMutator.php#L50-L88 |
evias/nem-php | src/Models/Transaction/NamespaceProvision.php | NamespaceProvision.extend | public function extend()
{
return [
"rentalFeeSink" => $this->rentalFeeSink()->address()->toClean(),
"rentalFee" => empty($this->parent) ? Fee::ROOT_PROVISION_NAMESPACE : Fee::SUB_PROVISION_NAMESPACE,
"parent" => $this->parent,
"newPart" => $this->newPart,
// transaction type specialization
"type" => TransactionType::PROVISION_NAMESPACE,
];
} | php | public function extend()
{
return [
"rentalFeeSink" => $this->rentalFeeSink()->address()->toClean(),
"rentalFee" => empty($this->parent) ? Fee::ROOT_PROVISION_NAMESPACE : Fee::SUB_PROVISION_NAMESPACE,
"parent" => $this->parent,
"newPart" => $this->newPart,
// transaction type specialization
"type" => TransactionType::PROVISION_NAMESPACE,
];
} | [
"public",
"function",
"extend",
"(",
")",
"{",
"return",
"[",
"\"rentalFeeSink\"",
"=>",
"$",
"this",
"->",
"rentalFeeSink",
"(",
")",
"->",
"address",
"(",
")",
"->",
"toClean",
"(",
")",
",",
"\"rentalFee\"",
"=>",
"empty",
"(",
"$",
"this",
"->",
"p... | Return specialized fields array for Namespace Provision Transactions.
@return array | [
"Return",
"specialized",
"fields",
"array",
"for",
"Namespace",
"Provision",
"Transactions",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/NamespaceProvision.php#L56-L66 |
evias/nem-php | src/Models/Transaction/NamespaceProvision.php | NamespaceProvision.serialize | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->extend();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_sink = $serializer->serializeString($nisData["rentalFeeSink"]);
$uint8_rental = $serializer->serializeLong($nisData["rentalFee"]);
$uint8_newPart = $serializer->serializeString($nisData["newPart"]);
// empty parent is *null* on-chain
$uint8_parent = $serializer->serializeInt(null);
if (!empty($nisData["parent"])) {
$uint8_parent = $serializer->serializeString($nisData["parent"]);
}
// concatenate the UInt8 representation
$output = array_merge(
$uint8_sink,
$uint8_rental,
$uint8_newPart,
$uint8_parent);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | php | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->extend();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_sink = $serializer->serializeString($nisData["rentalFeeSink"]);
$uint8_rental = $serializer->serializeLong($nisData["rentalFee"]);
$uint8_newPart = $serializer->serializeString($nisData["newPart"]);
// empty parent is *null* on-chain
$uint8_parent = $serializer->serializeInt(null);
if (!empty($nisData["parent"])) {
$uint8_parent = $serializer->serializeString($nisData["parent"]);
}
// concatenate the UInt8 representation
$output = array_merge(
$uint8_sink,
$uint8_rental,
$uint8_newPart,
$uint8_parent);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"$",
"baseTx",
"=",
"parent",
"::",
"serialize",
"(",
"$",
"parameters",
")",
";",
"$",
"nisData",
"=",
"$",
"this",
"->",
"extend",
"(",
")",
";",
"// shortcuts",
"$",
... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *NamespaceProvision* serialization.
@see \NEM\Contracts\Serializable
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"NamespaceProvision",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/NamespaceProvision.php#L87-L116 |
evias/nem-php | src/Handlers/AbstractRequestHandler.php | AbstractRequestHandler.normalizeHeaders | protected function normalizeHeaders(array $headers)
{
if (empty($headers["User-Agent"]))
$headers["User-Agent"] = "evias NEM Blockchain Wrapper";
if (empty($headers["Accept"]))
$headers["Accept"] = "application/json";
if (empty($headers["Content-Type"]))
$headers["Content-Type"] = "application/json";
return $headers;
} | php | protected function normalizeHeaders(array $headers)
{
if (empty($headers["User-Agent"]))
$headers["User-Agent"] = "evias NEM Blockchain Wrapper";
if (empty($headers["Accept"]))
$headers["Accept"] = "application/json";
if (empty($headers["Content-Type"]))
$headers["Content-Type"] = "application/json";
return $headers;
} | [
"protected",
"function",
"normalizeHeaders",
"(",
"array",
"$",
"headers",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"headers",
"[",
"\"User-Agent\"",
"]",
")",
")",
"$",
"headers",
"[",
"\"User-Agent\"",
"]",
"=",
"\"evias NEM Blockchain Wrapper\"",
";",
"if",
... | This method makes sure mandatory headers are
added in case they are not present.
@param array $headers [description]
@return [type] [description] | [
"This",
"method",
"makes",
"sure",
"mandatory",
"headers",
"are",
"added",
"in",
"case",
"they",
"are",
"not",
"present",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Handlers/AbstractRequestHandler.php#L45-L57 |
evias/nem-php | src/Models/Mosaic.php | Mosaic.create | static public function create(string $namespace, string $mosaic = null)
{
if (empty($mosaic)) {
// `namespace` should contain `FQN`
$fullyQualifiedName = $namespace;
$splitRegexp = "/([^:]+):([^:]+)/";
// split with format: `namespace:mosaic`
$namespace = preg_replace($splitRegexp, "$1", $fullyQualifiedName);
$mosaic = preg_replace($splitRegexp, "$2", $fullyQualifiedName);
}
if (empty($namespace) || empty($mosaic)) {
throw new RuntimeException("Missing namespace or mosaic name for \\NEM\\Models\\Mosaic instance.");
}
return new static([
"namespaceId" => $namespace,
"name" => $mosaic
]);
} | php | static public function create(string $namespace, string $mosaic = null)
{
if (empty($mosaic)) {
// `namespace` should contain `FQN`
$fullyQualifiedName = $namespace;
$splitRegexp = "/([^:]+):([^:]+)/";
// split with format: `namespace:mosaic`
$namespace = preg_replace($splitRegexp, "$1", $fullyQualifiedName);
$mosaic = preg_replace($splitRegexp, "$2", $fullyQualifiedName);
}
if (empty($namespace) || empty($mosaic)) {
throw new RuntimeException("Missing namespace or mosaic name for \\NEM\\Models\\Mosaic instance.");
}
return new static([
"namespaceId" => $namespace,
"name" => $mosaic
]);
} | [
"static",
"public",
"function",
"create",
"(",
"string",
"$",
"namespace",
",",
"string",
"$",
"mosaic",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"mosaic",
")",
")",
"{",
"// `namespace` should contain `FQN`",
"$",
"fullyQualifiedName",
"=",
"$",... | Class method to create a new `Mosaic` object from `namespace`
name and `mosaic` mosaic name.
@param string $namespace
@param string $mosaic
@return \NEM\Models\Mosaic | [
"Class",
"method",
"to",
"create",
"a",
"new",
"Mosaic",
"object",
"from",
"namespace",
"name",
"and",
"mosaic",
"mosaic",
"name",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Mosaic.php#L52-L72 |
evias/nem-php | src/Models/Mosaic.php | Mosaic.serialize | public function serialize($parameters = null)
{
$nisData = $this->toDTO();
// shortcuts
$serializer = $this->getSerializer();
$namespace = $nisData["namespaceId"];
$mosaicName = $nisData["name"];
$serializedNS = $serializer->serializeString($namespace);
$serializedMos = $serializer->serializeString($mosaicName);
return $serializer->aggregate($serializedNS, $serializedMos);
} | php | public function serialize($parameters = null)
{
$nisData = $this->toDTO();
// shortcuts
$serializer = $this->getSerializer();
$namespace = $nisData["namespaceId"];
$mosaicName = $nisData["name"];
$serializedNS = $serializer->serializeString($namespace);
$serializedMos = $serializer->serializeString($mosaicName);
return $serializer->aggregate($serializedNS, $serializedMos);
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"$",
"nisData",
"=",
"$",
"this",
"->",
"toDTO",
"(",
")",
";",
"// shortcuts",
"$",
"serializer",
"=",
"$",
"this",
"->",
"getSerializer",
"(",
")",
";",
"$",
"namespace... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *mosaicId* serialization.
@see \NEM\Contracts\Serializable
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"mosaicId",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Mosaic.php#L96-L109 |
evias/nem-php | src/Models/Mosaic.php | Mosaic.getFQN | public function getFQN()
{
if (empty($this->namespaceId) || empty($this->name))
return "";
return sprintf("%s:%s", $this->namespaceId, $this->name);
} | php | public function getFQN()
{
if (empty($this->namespaceId) || empty($this->name))
return "";
return sprintf("%s:%s", $this->namespaceId, $this->name);
} | [
"public",
"function",
"getFQN",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"namespaceId",
")",
"||",
"empty",
"(",
"$",
"this",
"->",
"name",
")",
")",
"return",
"\"\"",
";",
"return",
"sprintf",
"(",
"\"%s:%s\"",
",",
"$",
"this",
... | Getter for the *fully qualified name* of the Mosaic.
@return string | [
"Getter",
"for",
"the",
"*",
"fully",
"qualified",
"name",
"*",
"of",
"the",
"Mosaic",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Mosaic.php#L116-L122 |
evias/nem-php | src/Mosaics/Pacnem/Cheese.php | Cheese.levy | public function levy(array $levy = null)
{
$xem = new Mosaic(["namespaceId" => "nem", "name" => "xem"]);
$data = $levy ?: [
"type" => MosaicLevy::TYPE_PERCENTILE,
"fee" => 100,
"recipient" => "NDHGYUVXKUWYFNO6THLUKAF6ZH2WIDCC6XD5UPC4",
"mosaicId" => $xem->toDTO(),
];
return new MosaicLevy($data);
} | php | public function levy(array $levy = null)
{
$xem = new Mosaic(["namespaceId" => "nem", "name" => "xem"]);
$data = $levy ?: [
"type" => MosaicLevy::TYPE_PERCENTILE,
"fee" => 100,
"recipient" => "NDHGYUVXKUWYFNO6THLUKAF6ZH2WIDCC6XD5UPC4",
"mosaicId" => $xem->toDTO(),
];
return new MosaicLevy($data);
} | [
"public",
"function",
"levy",
"(",
"array",
"$",
"levy",
"=",
"null",
")",
"{",
"$",
"xem",
"=",
"new",
"Mosaic",
"(",
"[",
"\"namespaceId\"",
"=>",
"\"nem\"",
",",
"\"name\"",
"=>",
"\"xem\"",
"]",
")",
";",
"$",
"data",
"=",
"$",
"levy",
"?",
":"... | Mutator for `levy` relation.
This will return a NIS compliant [MosaicLevy](https://bob.nem.ninja/docs/#mosaicLevy) object.
@param array $mosaidId Array should contain offsets `type`, `recipient`, `mosaicId` and `fee`.
@return \NEM\Models\MosaicLevy | [
"Mutator",
"for",
"levy",
"relation",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Mosaics/Pacnem/Cheese.php#L80-L91 |
evias/nem-php | src/Models/Address.php | Address.fromPublicKey | static public function fromPublicKey($publicKey, $networkId = 104) // 104=mainnet
{
// discover public key content
if ($publicKey instanceof Buffer) {
$pubKeyBuf = $publicKey; // Buffer to public key
}
elseif ($publicKey instanceof KeyPair) {
$pubKeyBuf = $publicKey->getPublicKey(null); // Keypair to public key
}
elseif (is_string($publicKey) && ctype_xdigit($publicKey)) {
$pubKeyBuf = Buffer::fromHex($publicKey, 32); // Hexadecimal to public key
}
elseif (is_string($publicKey) && mb_strlen($publicKey) === 32) {
$pubKeyBuf = new Buffer($publicKey, 32); // Binary to public key
}
else {
throw new NISInvalidPublicKeyFormat("Could not identify public key format: " . var_export($publicKey, true));
}
// discover network name / version byte
if (is_string($networkId) && !is_numeric($networkId)
&& in_array(strtolower($networkId), ["mainnet", "testnet", "mijin"])) {
// network name provided, read version byte from SDK
$networkId = Network::$networkInfos[strtolower($networkId)]["id"];
}
elseif (is_numeric($networkId) && !in_array($networkId, [104, -104, 96])) {
throw new NISInvalidNetworkId("Invalid netword ID '" . $networkId . "'");
}
// network name / version byte is important for address creation
elseif (is_string($networkId)) {
throw new NISInvalidNetworkName("Invalid network name '" . $networkId . "'");
}
// step 1: keccak-256 hash of the public key
$pubKeyHash = Encryption::hash("keccak-256", $pubKeyBuf->getBinary(), true); // raw=true
// step 2: ripemd160 hash of (1)
$pubKeyRiped = new Buffer(hash("ripemd160", $pubKeyHash, true), 20);
// step 3: add version byte in front of (2)
$networkPrefix = Network::getPrefixFromId($networkId);
$versionPrefixedPubKey = Buffer::fromHex($networkPrefix . $pubKeyRiped->getHex());
// step 4: get the checksum of (3)
$checksum = Encryption::checksum("keccak-256", $versionPrefixedPubKey, 4); // checksumLen=4
// step 5: concatenate (3) and (4)
$addressHash = $versionPrefixedPubKey->getHex() . $checksum->getHex();
$hashBuf = Buffer::fromHex($addressHash);
$encodedAddress = hex2bin($addressHash);
// step 6: base32 encode (5)
$encodedBase32 = new Buffer(Base32::encode($encodedAddress), Address::BYTES);
return new Address([
"address" => $encodedBase32->getBinary(),
"publicKey" => $pubKeyBuf->getHex(),
]);
} | php | static public function fromPublicKey($publicKey, $networkId = 104) // 104=mainnet
{
// discover public key content
if ($publicKey instanceof Buffer) {
$pubKeyBuf = $publicKey; // Buffer to public key
}
elseif ($publicKey instanceof KeyPair) {
$pubKeyBuf = $publicKey->getPublicKey(null); // Keypair to public key
}
elseif (is_string($publicKey) && ctype_xdigit($publicKey)) {
$pubKeyBuf = Buffer::fromHex($publicKey, 32); // Hexadecimal to public key
}
elseif (is_string($publicKey) && mb_strlen($publicKey) === 32) {
$pubKeyBuf = new Buffer($publicKey, 32); // Binary to public key
}
else {
throw new NISInvalidPublicKeyFormat("Could not identify public key format: " . var_export($publicKey, true));
}
// discover network name / version byte
if (is_string($networkId) && !is_numeric($networkId)
&& in_array(strtolower($networkId), ["mainnet", "testnet", "mijin"])) {
// network name provided, read version byte from SDK
$networkId = Network::$networkInfos[strtolower($networkId)]["id"];
}
elseif (is_numeric($networkId) && !in_array($networkId, [104, -104, 96])) {
throw new NISInvalidNetworkId("Invalid netword ID '" . $networkId . "'");
}
// network name / version byte is important for address creation
elseif (is_string($networkId)) {
throw new NISInvalidNetworkName("Invalid network name '" . $networkId . "'");
}
// step 1: keccak-256 hash of the public key
$pubKeyHash = Encryption::hash("keccak-256", $pubKeyBuf->getBinary(), true); // raw=true
// step 2: ripemd160 hash of (1)
$pubKeyRiped = new Buffer(hash("ripemd160", $pubKeyHash, true), 20);
// step 3: add version byte in front of (2)
$networkPrefix = Network::getPrefixFromId($networkId);
$versionPrefixedPubKey = Buffer::fromHex($networkPrefix . $pubKeyRiped->getHex());
// step 4: get the checksum of (3)
$checksum = Encryption::checksum("keccak-256", $versionPrefixedPubKey, 4); // checksumLen=4
// step 5: concatenate (3) and (4)
$addressHash = $versionPrefixedPubKey->getHex() . $checksum->getHex();
$hashBuf = Buffer::fromHex($addressHash);
$encodedAddress = hex2bin($addressHash);
// step 6: base32 encode (5)
$encodedBase32 = new Buffer(Base32::encode($encodedAddress), Address::BYTES);
return new Address([
"address" => $encodedBase32->getBinary(),
"publicKey" => $pubKeyBuf->getHex(),
]);
} | [
"static",
"public",
"function",
"fromPublicKey",
"(",
"$",
"publicKey",
",",
"$",
"networkId",
"=",
"104",
")",
"// 104=mainnet",
"{",
"// discover public key content",
"if",
"(",
"$",
"publicKey",
"instanceof",
"Buffer",
")",
"{",
"$",
"pubKeyBuf",
"=",
"$",
... | Generate an address corresponding to a `publicKey`
public key.
The `publicKey` parameter can be either a hexadecimal
public key representation, a byte level representation
of the public key, a Buffer object or a KeyPair object.
@param mixed $publicKey
@param string|integer $networkId A network ID OR a network name. (default mainnet)
@return \NEM\Models\Address
@throws \NEM\Errors\NISInvalidPublicKeyFormat On unidentifiable public key format.
@throws \NEM\Errors\NISInvalidNetworkName On invalid network name provided in `version` (when string).
@throws \NEM\Errors\NISInvalidVersionByte On invalid network byte provided in `version` (when integer). | [
"Generate",
"an",
"address",
"corresponding",
"to",
"a",
"publicKey",
"public",
"key",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Address.php#L78-L136 |
evias/nem-php | src/Models/Address.php | Address.getAttribute | public function getAttribute($alias, $doCast = true)
{
if ($alias === 'address')
return $this->toClean();
return parent::getAttribute($alias, $doCast);
} | php | public function getAttribute($alias, $doCast = true)
{
if ($alias === 'address')
return $this->toClean();
return parent::getAttribute($alias, $doCast);
} | [
"public",
"function",
"getAttribute",
"(",
"$",
"alias",
",",
"$",
"doCast",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"alias",
"===",
"'address'",
")",
"return",
"$",
"this",
"->",
"toClean",
"(",
")",
";",
"return",
"parent",
"::",
"getAttribute",
"(",
... | Getter for singular attribute values by name.
Overloaded to provide with specific CLEAN FORMATTING
always when trying to read address attributes.
@param string $alias The attribute field alias.
@return mixed | [
"Getter",
"for",
"singular",
"attribute",
"values",
"by",
"name",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Address.php#L147-L153 |
evias/nem-php | src/Models/Address.php | Address.toDTO | public function toDTO($filterByKey = null)
{
$toDTO = ["address" => $this->toClean()];
// KeyPair's public key/private key not always set
// because \NEM\Models\Address is used for simple Address formatting
if (!empty($this->publicKey))
$toDTO["publicKey"] = $this->publicKey;
if (!empty($this->privateKey))
$toDTO["privateKey"] = $this->privateKey;
if ($filterByKey && isset($toDTO[$filterByKey]))
return $toDTO[$filterByKey];
return $toDTO;
} | php | public function toDTO($filterByKey = null)
{
$toDTO = ["address" => $this->toClean()];
// KeyPair's public key/private key not always set
// because \NEM\Models\Address is used for simple Address formatting
if (!empty($this->publicKey))
$toDTO["publicKey"] = $this->publicKey;
if (!empty($this->privateKey))
$toDTO["privateKey"] = $this->privateKey;
if ($filterByKey && isset($toDTO[$filterByKey]))
return $toDTO[$filterByKey];
return $toDTO;
} | [
"public",
"function",
"toDTO",
"(",
"$",
"filterByKey",
"=",
"null",
")",
"{",
"$",
"toDTO",
"=",
"[",
"\"address\"",
"=>",
"$",
"this",
"->",
"toClean",
"(",
")",
"]",
";",
"// KeyPair's public key/private key not always set",
"// because \\NEM\\Models\\Address is ... | Address DTO automatically cleans address representation.
@see [KeyPairViewModel](https://nemproject.github.io/#keyPairViewModel)
@return array Associative array with key `address` containing a NIS *compliable* address representation. | [
"Address",
"DTO",
"automatically",
"cleans",
"address",
"representation",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Address.php#L161-L177 |
evias/nem-php | src/Models/Address.php | Address.toClean | public function toClean($string = null)
{
$attrib = $string;
if (! $attrib && isset($this->attributes["address"]))
$attrib = $this->attributes["address"];
return strtoupper(preg_replace("/[^a-zA-Z0-9]+/", "", $attrib));
} | php | public function toClean($string = null)
{
$attrib = $string;
if (! $attrib && isset($this->attributes["address"]))
$attrib = $this->attributes["address"];
return strtoupper(preg_replace("/[^a-zA-Z0-9]+/", "", $attrib));
} | [
"public",
"function",
"toClean",
"(",
"$",
"string",
"=",
"null",
")",
"{",
"$",
"attrib",
"=",
"$",
"string",
";",
"if",
"(",
"!",
"$",
"attrib",
"&&",
"isset",
"(",
"$",
"this",
"->",
"attributes",
"[",
"\"address\"",
"]",
")",
")",
"$",
"attrib"... | Helper to clean an address of any non alpha-numeric characters
back to the actual Base32 representation of the address.
@return string | [
"Helper",
"to",
"clean",
"an",
"address",
"of",
"any",
"non",
"alpha",
"-",
"numeric",
"characters",
"back",
"to",
"the",
"actual",
"Base32",
"representation",
"of",
"the",
"address",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Address.php#L185-L192 |
evias/nem-php | src/Models/Transaction/Multisig.php | Multisig.serialize | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->extend();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_tx = $this->otherTrans()->serialize($parameters);
$uint8_len = $serializer->serializeInt(count($uint8_tx));
// concatenate the UInt8 representation
$output = array_merge($uint8_len, $uint8_tx);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | php | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->extend();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_tx = $this->otherTrans()->serialize($parameters);
$uint8_len = $serializer->serializeInt(count($uint8_tx));
// concatenate the UInt8 representation
$output = array_merge($uint8_len, $uint8_tx);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"$",
"baseTx",
"=",
"parent",
"::",
"serialize",
"(",
"$",
"parameters",
")",
";",
"$",
"nisData",
"=",
"$",
"this",
"->",
"extend",
"(",
")",
";",
"// shortcuts",
"$",
... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *Multisig transaction* serialization.
@see \NEM\Contracts\Serializable
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"Multisig",
"transaction",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/Multisig.php#L68-L86 |
evias/nem-php | src/Models/Transaction/Multisig.php | Multisig.extend | public function extend()
{
// The Multisig Wrapper transaction should have VERSION_1
$version = $this->getAttribute("version");
$oneByOld = [
Transaction::VERSION_2 => Transaction::VERSION_1,
Transaction::VERSION_2_TEST => Transaction::VERSION_1_TEST,
Transaction::VERSION_2_MIJIN => Transaction::VERSION_1_MIJIN,
];
// Multisig always use *VERSION 1 TRANSACTIONS* (for the wrapper).
// this small block will make sure to stay on the correct
// network in case a version was set before.
if (in_array($version, array_keys($oneByOld))) {
// switch to v1
$version = $oneByOld[$version];
}
elseif (!$version || !in_array($version, array_values($oneByOld))) {
// invalid version provided, set default
$version = Transaction::VERSION_1_TEST;
}
return [
"otherTrans" => $this->otherTrans()->toDTO("transaction"),
"signatures" => $this->signatures()->toDTO(),
// transaction type specialization
"type" => TransactionType::MULTISIG,
"version" => $version,
];
} | php | public function extend()
{
// The Multisig Wrapper transaction should have VERSION_1
$version = $this->getAttribute("version");
$oneByOld = [
Transaction::VERSION_2 => Transaction::VERSION_1,
Transaction::VERSION_2_TEST => Transaction::VERSION_1_TEST,
Transaction::VERSION_2_MIJIN => Transaction::VERSION_1_MIJIN,
];
// Multisig always use *VERSION 1 TRANSACTIONS* (for the wrapper).
// this small block will make sure to stay on the correct
// network in case a version was set before.
if (in_array($version, array_keys($oneByOld))) {
// switch to v1
$version = $oneByOld[$version];
}
elseif (!$version || !in_array($version, array_values($oneByOld))) {
// invalid version provided, set default
$version = Transaction::VERSION_1_TEST;
}
return [
"otherTrans" => $this->otherTrans()->toDTO("transaction"),
"signatures" => $this->signatures()->toDTO(),
// transaction type specialization
"type" => TransactionType::MULTISIG,
"version" => $version,
];
} | [
"public",
"function",
"extend",
"(",
")",
"{",
"// The Multisig Wrapper transaction should have VERSION_1",
"$",
"version",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"\"version\"",
")",
";",
"$",
"oneByOld",
"=",
"[",
"Transaction",
"::",
"VERSION_2",
"=>",
"Tr... | The Multisig transaction type adds offsets `otherTrans` and
`signatures`.
The `otherTrans` in the DTO is used to store transaction details.
The Multisig Transaction Type only acts as a wrapper! It will contain
a subordinate Transaction object in the `otherTrans` attribute and a
collection of subordinate Transaction\Signature transactions in the
`signatures` attribute.
@return array | [
"The",
"Multisig",
"transaction",
"type",
"adds",
"offsets",
"otherTrans",
"and",
"signatures",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/Multisig.php#L101-L131 |
evias/nem-php | src/Models/Transaction/Multisig.php | Multisig.setOtherTrans | public function setOtherTrans(Transaction $otherTrans)
{
$this->setAttribute("otherTrans", $otherTrans->toDTO("transaction"));
return $this->otherTrans($otherTrans->toDTO("transaction"));
} | php | public function setOtherTrans(Transaction $otherTrans)
{
$this->setAttribute("otherTrans", $otherTrans->toDTO("transaction"));
return $this->otherTrans($otherTrans->toDTO("transaction"));
} | [
"public",
"function",
"setOtherTrans",
"(",
"Transaction",
"$",
"otherTrans",
")",
"{",
"$",
"this",
"->",
"setAttribute",
"(",
"\"otherTrans\"",
",",
"$",
"otherTrans",
"->",
"toDTO",
"(",
"\"transaction\"",
")",
")",
";",
"return",
"$",
"this",
"->",
"othe... | Setter for the `otherTrans` DTO property.
This is used to include non-multisig transaction data in
the multisig transaction package.
@param \NEM\Models\Transaction $otherTrans Transaction to include in the multisig DTO's `otherTrans` attribute.
@return \NEM\Models\Transaction\Multisig | [
"Setter",
"for",
"the",
"otherTrans",
"DTO",
"property",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/Multisig.php#L172-L176 |
evias/nem-php | src/Models/Transaction/Multisig.php | Multisig.otherTrans | public function otherTrans(array $transaction = null)
{
// morph Transaction extension - will read the type of transaction
// and instantiate the correct class extending Transaction.
$morphed = Transaction::create($transaction ?: $this->getAttribute("otherTrans"));
if ($morphed->type === TransactionType::MULTISIG) {
// cannot nest multisig in another multisig.
throw new InvalidArgumentException("It is forbidden to nest a Multisig transaction in another Multisig transaction.");
}
elseif ($morphed->type === TransactionType::MULTISIG_SIGNATURE) {
// cannot nest multisig in another multisig.
throw new InvalidArgumentException("It is forbidden to nest a Signature transaction in the inner transaction of a Multisig transaction.");
}
return $morphed;
} | php | public function otherTrans(array $transaction = null)
{
// morph Transaction extension - will read the type of transaction
// and instantiate the correct class extending Transaction.
$morphed = Transaction::create($transaction ?: $this->getAttribute("otherTrans"));
if ($morphed->type === TransactionType::MULTISIG) {
// cannot nest multisig in another multisig.
throw new InvalidArgumentException("It is forbidden to nest a Multisig transaction in another Multisig transaction.");
}
elseif ($morphed->type === TransactionType::MULTISIG_SIGNATURE) {
// cannot nest multisig in another multisig.
throw new InvalidArgumentException("It is forbidden to nest a Signature transaction in the inner transaction of a Multisig transaction.");
}
return $morphed;
} | [
"public",
"function",
"otherTrans",
"(",
"array",
"$",
"transaction",
"=",
"null",
")",
"{",
"// morph Transaction extension - will read the type of transaction",
"// and instantiate the correct class extending Transaction.",
"$",
"morphed",
"=",
"Transaction",
"::",
"create",
... | Mutator for the `otherTrans` sub DTO.
@param array $transaction
@return \NEM\Models\Transaction | [
"Mutator",
"for",
"the",
"otherTrans",
"sub",
"DTO",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/Multisig.php#L184-L200 |
evias/nem-php | src/Core/KeyGenerator.php | KeyGenerator.derivePublicKey | public function derivePublicKey(KeyPair $keyPair)
{
$buffer = new Buffer;
// hash the secret key with Keccak SHA3 variation with 512-bit output (64 bytes)
$hashedSecret = Encryption::hash("keccak-512", $keyPair->getSecretKey()->getBinary(), true); // raw=true
// clamp bits of the scalar *before* scalar multiplication
$safeSecret = Buffer::clampBits($hashedSecret);
// do scalar multiplication for: `basePoint` * `safeSecret`
// the result of this multiplication is the `publicKey`.
// sk_to_pk() does scalarmult_base() and ge_p3_tobytes()
$publicKey = ParagonIE_Sodium_Core_Ed25519::sk_to_pk($safeSecret);
$publicBuf = new Buffer($publicKey, SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES);
assert(SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES === $publicBuf->getSize());
return $publicBuf;
} | php | public function derivePublicKey(KeyPair $keyPair)
{
$buffer = new Buffer;
// hash the secret key with Keccak SHA3 variation with 512-bit output (64 bytes)
$hashedSecret = Encryption::hash("keccak-512", $keyPair->getSecretKey()->getBinary(), true); // raw=true
// clamp bits of the scalar *before* scalar multiplication
$safeSecret = Buffer::clampBits($hashedSecret);
// do scalar multiplication for: `basePoint` * `safeSecret`
// the result of this multiplication is the `publicKey`.
// sk_to_pk() does scalarmult_base() and ge_p3_tobytes()
$publicKey = ParagonIE_Sodium_Core_Ed25519::sk_to_pk($safeSecret);
$publicBuf = new Buffer($publicKey, SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES);
assert(SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES === $publicBuf->getSize());
return $publicBuf;
} | [
"public",
"function",
"derivePublicKey",
"(",
"KeyPair",
"$",
"keyPair",
")",
"{",
"$",
"buffer",
"=",
"new",
"Buffer",
";",
"// hash the secret key with Keccak SHA3 variation with 512-bit output (64 bytes)",
"$",
"hashedSecret",
"=",
"Encryption",
"::",
"hash",
"(",
"\... | Derive the public key from the KeyPair's secret.
This method uses Keccak 64 bytes (512 bits) hashing on
the provided `keyPair`'s secret key.
@param \NEM\Core\KeyPair $keyPair The initialized key pair from which to derive the public key.
@return \NEM\Core\Buffer | [
"Derive",
"the",
"public",
"key",
"from",
"the",
"KeyPair",
"s",
"secret",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Core/KeyGenerator.php#L49-L67 |
evias/nem-php | src/Models/Amount.php | Amount.fromMicro | static public function fromMicro($amount, $divisibility = 6)
{
$amt = new Amount(["amount" => $amount]);
$amt->setDivisibility($divisibility);
return $amt;
} | php | static public function fromMicro($amount, $divisibility = 6)
{
$amt = new Amount(["amount" => $amount]);
$amt->setDivisibility($divisibility);
return $amt;
} | [
"static",
"public",
"function",
"fromMicro",
"(",
"$",
"amount",
",",
"$",
"divisibility",
"=",
"6",
")",
"{",
"$",
"amt",
"=",
"new",
"Amount",
"(",
"[",
"\"amount\"",
"=>",
"$",
"amount",
"]",
")",
";",
"$",
"amt",
"->",
"setDivisibility",
"(",
"$"... | Factory for Amount models with MICRO amounts and provided
`divisibility`.
@param integer $amount
@param integer $divisibility
@return \NEM\Models\Amount | [
"Factory",
"for",
"Amount",
"models",
"with",
"MICRO",
"amounts",
"and",
"provided",
"divisibility",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Amount.php#L93-L99 |
evias/nem-php | src/Models/Amount.php | Amount.setAttribute | public function setAttribute($name, $data)
{
if ($name === 'amount') {
$this->attributes["amount"] = $data;
// parse provided data and check for overflow
$micro = $this->toMicro();
if ($micro >= Amount::MAX_AMOUNT)
throw new NISAmountOverflowException("Amounts cannot exceed " . Amount::MAX_AMOUNT . ".");
}
return parent::setAttribute($name, $data);
} | php | public function setAttribute($name, $data)
{
if ($name === 'amount') {
$this->attributes["amount"] = $data;
// parse provided data and check for overflow
$micro = $this->toMicro();
if ($micro >= Amount::MAX_AMOUNT)
throw new NISAmountOverflowException("Amounts cannot exceed " . Amount::MAX_AMOUNT . ".");
}
return parent::setAttribute($name, $data);
} | [
"public",
"function",
"setAttribute",
"(",
"$",
"name",
",",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"name",
"===",
"'amount'",
")",
"{",
"$",
"this",
"->",
"attributes",
"[",
"\"amount\"",
"]",
"=",
"$",
"data",
";",
"// parse provided data and check for o... | Setter for singular attribute values by name.
Overload takes care of TOO BIG amounts.
@param string $name The attribute name.
@param mixed $data The attribute data.
@return mixed
@throws \NEM\Errors\NISAmountOverflowException | [
"Setter",
"for",
"singular",
"attribute",
"values",
"by",
"name",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Amount.php#L111-L123 |
evias/nem-php | src/Models/Amount.php | Amount.toDTO | public function toDTO($filterByKey = null)
{
$toDTO = ["amount" => $this->toMicro()];
if ($filterByKey && isset($toDTO[$filterByKey]))
return $toDTO[$filterByKey];
return $toDTO;
} | php | public function toDTO($filterByKey = null)
{
$toDTO = ["amount" => $this->toMicro()];
if ($filterByKey && isset($toDTO[$filterByKey]))
return $toDTO[$filterByKey];
return $toDTO;
} | [
"public",
"function",
"toDTO",
"(",
"$",
"filterByKey",
"=",
"null",
")",
"{",
"$",
"toDTO",
"=",
"[",
"\"amount\"",
"=>",
"$",
"this",
"->",
"toMicro",
"(",
")",
"]",
";",
"if",
"(",
"$",
"filterByKey",
"&&",
"isset",
"(",
"$",
"toDTO",
"[",
"$",
... | Amount DTO automatically returns MICRO amount.
@return array Associative array with key `address` containing a NIS *compliable* address representation. | [
"Amount",
"DTO",
"automatically",
"returns",
"MICRO",
"amount",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Amount.php#L130-L138 |
evias/nem-php | src/Models/Amount.php | Amount.toMicro | public function toMicro()
{
$inner = $this->getAttribute("amount", false); //cast=false
$decimals = $this->getDivisibility();
if (is_integer($inner)) {
$attrib = $inner;
}
elseif (is_float($inner)) {
// we want only integer!
$attrib = $inner * pow(10, $decimals);
}
elseif (is_string($inner)) {
// parse number string representation. Parsing to float.
$isFloat = false !== strpos($inner, ".");
$number = $isFloat ? (float) $inner : (int) $inner;
$multi = $isFloat ? pow(10, $decimals) : 1;
$attrib = $number * $multi;
}
elseif (is_array($inner)) {
// try to read first value of array
$attrib = array_shift($inner);
}
else {
$attrib = (int) $inner;
}
$this->micro = (int) $attrib;
if ($this->micro < 0)
// not allowed: 0 in micro XEM is the minimum possible value!
$this->micro = 0;
return $this->micro;
} | php | public function toMicro()
{
$inner = $this->getAttribute("amount", false); //cast=false
$decimals = $this->getDivisibility();
if (is_integer($inner)) {
$attrib = $inner;
}
elseif (is_float($inner)) {
// we want only integer!
$attrib = $inner * pow(10, $decimals);
}
elseif (is_string($inner)) {
// parse number string representation. Parsing to float.
$isFloat = false !== strpos($inner, ".");
$number = $isFloat ? (float) $inner : (int) $inner;
$multi = $isFloat ? pow(10, $decimals) : 1;
$attrib = $number * $multi;
}
elseif (is_array($inner)) {
// try to read first value of array
$attrib = array_shift($inner);
}
else {
$attrib = (int) $inner;
}
$this->micro = (int) $attrib;
if ($this->micro < 0)
// not allowed: 0 in micro XEM is the minimum possible value!
$this->micro = 0;
return $this->micro;
} | [
"public",
"function",
"toMicro",
"(",
")",
"{",
"$",
"inner",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"\"amount\"",
",",
"false",
")",
";",
"//cast=false",
"$",
"decimals",
"=",
"$",
"this",
"->",
"getDivisibility",
"(",
")",
";",
"if",
"(",
"is_i... | Helper to return a MICRO amount. This means to get the smallest unit
of an Amount on the NEM Blockchain. Maximum Divisibility is up to 6
decimal places.
@return integer | [
"Helper",
"to",
"return",
"a",
"MICRO",
"amount",
".",
"This",
"means",
"to",
"get",
"the",
"smallest",
"unit",
"of",
"an",
"Amount",
"on",
"the",
"NEM",
"Blockchain",
".",
"Maximum",
"Divisibility",
"is",
"up",
"to",
"6",
"decimal",
"places",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Amount.php#L147-L180 |
evias/nem-php | src/Models/Amount.php | Amount.toUnit | public function toUnit()
{
if ($this->divisibility <= 0)
return $this->toMicro();
$div = pow(10, $this->getDivisibility());
return ($this->toMicro() / $div);
} | php | public function toUnit()
{
if ($this->divisibility <= 0)
return $this->toMicro();
$div = pow(10, $this->getDivisibility());
return ($this->toMicro() / $div);
} | [
"public",
"function",
"toUnit",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"divisibility",
"<=",
"0",
")",
"return",
"$",
"this",
"->",
"toMicro",
"(",
")",
";",
"$",
"div",
"=",
"pow",
"(",
"10",
",",
"$",
"this",
"->",
"getDivisibility",
"(",
... | Helper to return UNITs amounts. This method will return floating
point numbers. The divisibility can be set using `setDivisibility`
in case of different mosaics.
@return float | [
"Helper",
"to",
"return",
"UNITs",
"amounts",
".",
"This",
"method",
"will",
"return",
"floating",
"point",
"numbers",
".",
"The",
"divisibility",
"can",
"be",
"set",
"using",
"setDivisibility",
"in",
"case",
"of",
"different",
"mosaics",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Amount.php#L189-L196 |
evias/nem-php | src/Models/Amount.php | Amount.setDivisibility | public function setDivisibility($divisibility)
{
if (!is_integer($divisibility) || $divisibility < 0)
$divisibility = 6; // default 6
$this->divisibility = $divisibility;
return $this;
} | php | public function setDivisibility($divisibility)
{
if (!is_integer($divisibility) || $divisibility < 0)
$divisibility = 6; // default 6
$this->divisibility = $divisibility;
return $this;
} | [
"public",
"function",
"setDivisibility",
"(",
"$",
"divisibility",
")",
"{",
"if",
"(",
"!",
"is_integer",
"(",
"$",
"divisibility",
")",
"||",
"$",
"divisibility",
"<",
"0",
")",
"$",
"divisibility",
"=",
"6",
";",
"// default 6",
"$",
"this",
"->",
"di... | Setter for the `divisibility` property.
@param integer $divisibility
@return \NEM\Models\Amount | [
"Setter",
"for",
"the",
"divisibility",
"property",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Amount.php#L204-L211 |
evias/nem-php | src/Models/Amount.php | Amount.mosaicQuantityToXEM | static public function mosaicQuantityToXEM($divisibility, $supply, $quantity, $multiplier = Amount::XEM)
{
if ((int) $supply <= 0) return 0;
if ((int) $divisibility <= 0) $divisibility = 0;
return self::XEM_SUPPLY * $quantity * $multiplier / $supply / pow(10, $divisibility + 6);
} | php | static public function mosaicQuantityToXEM($divisibility, $supply, $quantity, $multiplier = Amount::XEM)
{
if ((int) $supply <= 0) return 0;
if ((int) $divisibility <= 0) $divisibility = 0;
return self::XEM_SUPPLY * $quantity * $multiplier / $supply / pow(10, $divisibility + 6);
} | [
"static",
"public",
"function",
"mosaicQuantityToXEM",
"(",
"$",
"divisibility",
",",
"$",
"supply",
",",
"$",
"quantity",
",",
"$",
"multiplier",
"=",
"Amount",
"::",
"XEM",
")",
"{",
"if",
"(",
"(",
"int",
")",
"$",
"supply",
"<=",
"0",
")",
"return"... | Helper to get the XEM equivalent for a given mosaic definition
`definition` and attachment quantity `quantity`.
This method is used internally to calculate the equivalent XEM
amounts of a given mosaic quantity for *fees calculation*.
@internal
@param \NEM\Models\MosaicDefinition $definition
@param integer $quantity
@return integer | [
"Helper",
"to",
"get",
"the",
"XEM",
"equivalent",
"for",
"a",
"given",
"mosaic",
"definition",
"definition",
"and",
"attachment",
"quantity",
"quantity",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Amount.php#L235-L241 |
evias/nem-php | src/Traits/Serializable.php | Serializable.getSerializer | public function getSerializer()
{
if (! $this->serializer || ! ($this->serializer instanceof Serializer)) {
$this->serializer = Serializer::getInstance();
}
return $this->serializer;
} | php | public function getSerializer()
{
if (! $this->serializer || ! ($this->serializer instanceof Serializer)) {
$this->serializer = Serializer::getInstance();
}
return $this->serializer;
} | [
"public",
"function",
"getSerializer",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"serializer",
"||",
"!",
"(",
"$",
"this",
"->",
"serializer",
"instanceof",
"Serializer",
")",
")",
"{",
"$",
"this",
"->",
"serializer",
"=",
"Serializer",
"::",
... | Getter for the `serializer` property.
@return \NEM\Core\Serializer | [
"Getter",
"for",
"the",
"serializer",
"property",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Traits/Serializable.php#L44-L51 |
evias/nem-php | src/Mosaics/Nemether/Nemether.php | Nemether.levy | public function levy(array $levy = null)
{
$xem = new Mosaic(["namespaceId" => "nem", "name" => "xem"]);
$data = $levy ?: [
"type" => MosaicLevy::TYPE_ABSOLUTE,
"fee" => 10,
"recipient" => "NC56RYVRUPG3WRNGMVNRKODJZJNZKZYS76UAPO7K",
"mosaicId" => $xem->toDTO(),
];
return new MosaicLevy($data);
} | php | public function levy(array $levy = null)
{
$xem = new Mosaic(["namespaceId" => "nem", "name" => "xem"]);
$data = $levy ?: [
"type" => MosaicLevy::TYPE_ABSOLUTE,
"fee" => 10,
"recipient" => "NC56RYVRUPG3WRNGMVNRKODJZJNZKZYS76UAPO7K",
"mosaicId" => $xem->toDTO(),
];
return new MosaicLevy($data);
} | [
"public",
"function",
"levy",
"(",
"array",
"$",
"levy",
"=",
"null",
")",
"{",
"$",
"xem",
"=",
"new",
"Mosaic",
"(",
"[",
"\"namespaceId\"",
"=>",
"\"nem\"",
",",
"\"name\"",
"=>",
"\"xem\"",
"]",
")",
";",
"$",
"data",
"=",
"$",
"levy",
"?",
":"... | Mutator for `levy` relation.
This will return a NIS compliant [MosaicLevy](https://bob.nem.ninja/docs/#mosaicLevy) object.
@param array $mosaidId Array should contain offsets `type`, `recipient`, `mosaicId` and `fee`.
@return \NEM\Models\MosaicLevy | [
"Mutator",
"for",
"levy",
"relation",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Mosaics/Nemether/Nemether.php#L73-L84 |
evias/nem-php | src/Mosaics/Nemether/Nemether.php | Nemether.properties | public function properties(array $properties = null)
{
$data = [
new MosaicProperty(["name" => "divisibility", "value" => 6]),
new MosaicProperty(["name" => "initialSupply", "value" => 95100000]),
new MosaicProperty(["name" => "supplyMutable", "value" => true]),
new MosaicProperty(["name" => "transferable", "value" => true]),
];
return new MosaicProperties($data);
} | php | public function properties(array $properties = null)
{
$data = [
new MosaicProperty(["name" => "divisibility", "value" => 6]),
new MosaicProperty(["name" => "initialSupply", "value" => 95100000]),
new MosaicProperty(["name" => "supplyMutable", "value" => true]),
new MosaicProperty(["name" => "transferable", "value" => true]),
];
return new MosaicProperties($data);
} | [
"public",
"function",
"properties",
"(",
"array",
"$",
"properties",
"=",
"null",
")",
"{",
"$",
"data",
"=",
"[",
"new",
"MosaicProperty",
"(",
"[",
"\"name\"",
"=>",
"\"divisibility\"",
",",
"\"value\"",
"=>",
"6",
"]",
")",
",",
"new",
"MosaicProperty",... | Mutator for `properties` relation.
This will return a NIS compliant collection of [MosaicProperties](https://bob.nem.ninja/docs/#mosaicProperties) object.
@param array $properties Array of MosaicProperty instances
@return \NEM\Models\MosaicProperties | [
"Mutator",
"for",
"properties",
"relation",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Mosaics/Nemether/Nemether.php#L94-L104 |
evias/nem-php | src/Models/Fee.php | Fee.calculateForTransaction | static public function calculateForTransaction(Transaction $transaction)
{
// generate each content fee accordingly
$msgFee = self::calculateForMessage($transaction->message());
// default content fee is XEM amount transfer fee
$contentFee = Fee::FEE_FACTOR * self::calculateForXEM($transaction->amount()->toMicro() / Amount::XEM);
// get the Transaction extension fee
$extensionFee = $transaction->extendFee();
if ($extensionFee > 0) {
$contentFee = (int) $extensionFee;
}
return $msgFee + $contentFee;
} | php | static public function calculateForTransaction(Transaction $transaction)
{
// generate each content fee accordingly
$msgFee = self::calculateForMessage($transaction->message());
// default content fee is XEM amount transfer fee
$contentFee = Fee::FEE_FACTOR * self::calculateForXEM($transaction->amount()->toMicro() / Amount::XEM);
// get the Transaction extension fee
$extensionFee = $transaction->extendFee();
if ($extensionFee > 0) {
$contentFee = (int) $extensionFee;
}
return $msgFee + $contentFee;
} | [
"static",
"public",
"function",
"calculateForTransaction",
"(",
"Transaction",
"$",
"transaction",
")",
"{",
"// generate each content fee accordingly",
"$",
"msgFee",
"=",
"self",
"::",
"calculateForMessage",
"(",
"$",
"transaction",
"->",
"message",
"(",
")",
")",
... | Calculate the needed fee for a provided `$transaction` NEM transaction
object.
This method can be used to calculate all needed fees for a given
`transaction` object.
@param \NEM\Models\Transaction $transaction
@return \NEM\Models\Fee | [
"Calculate",
"the",
"needed",
"fee",
"for",
"a",
"provided",
"$transaction",
"NEM",
"transaction",
"object",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Fee.php#L147-L163 |
evias/nem-php | src/Models/Fee.php | Fee.calculateForMessage | static public function calculateForMessage(Message $message)
{
$dto = $message->toDTO();
if (empty($dto["payload"]))
return 0;
// message fee is 0.05 (current fee factor) multiplied
// by the count of *started* 31 characters chunks.
$chunks = floor((strlen($dto["payload"]) / 2) / 32);
return Fee::FEE_FACTOR * ($chunks + 1);
} | php | static public function calculateForMessage(Message $message)
{
$dto = $message->toDTO();
if (empty($dto["payload"]))
return 0;
// message fee is 0.05 (current fee factor) multiplied
// by the count of *started* 31 characters chunks.
$chunks = floor((strlen($dto["payload"]) / 2) / 32);
return Fee::FEE_FACTOR * ($chunks + 1);
} | [
"static",
"public",
"function",
"calculateForMessage",
"(",
"Message",
"$",
"message",
")",
"{",
"$",
"dto",
"=",
"$",
"message",
"->",
"toDTO",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"dto",
"[",
"\"payload\"",
"]",
")",
")",
"return",
"0",
";"... | Calculate the needed fee for a provided `$message` message.
Messages are more expensive when they are encrypted.
This method is used internally to calculate a transactions's
message fees.
@internal
@param Message $message
@return \NEM\Models\Fee | [
"Calculate",
"the",
"needed",
"fee",
"for",
"a",
"provided",
"$message",
"message",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Fee.php#L177-L188 |
evias/nem-php | src/Models/Fee.php | Fee.calculateForMosaics | static public function calculateForMosaics(MosaicDefinitions $definitions,
MosaicAttachments $attachments,
$multiplier = Amount::XEM)
{
if ($attachments->isEmpty())
return 0;
$totalFee = 0;
foreach ($attachments as $attachment) {
if (is_array($attachment)) {
// collection contains arrays instead of MosaicAttachment objects
$attachment = new MosaicAttachment($attachment);
}
$mosaicFQN = $attachment->mosaicId()->getFQN();
// in case user didnt provide the definition, try to
// to find it with the registry of preconfigured Mosaics classes.
$definition = $definitions->getDefinition($attachment->mosaicId())
?: Registry::getDefinition($mosaicFQN);
if ($definition === false) {
throw new RuntimeException("Missing MosaicDefinition for Mosaic: `" . $mosaicFQN . "`.");
}
// read properties for calculations
$divisibility = $definition->getProperty("divisibility") ?: 0;
$supply = $definition->getTotalSupply() ?: Amount::XEM_SUPPLY;
$quantity = $attachment->quantity;
$supplyAdjust = 0;
// small business mosaic fee
if ($supply <= 10000 && $divisibility === 0) {
$fee = Fee::FEE_FACTOR; // 0.05
}
// all other mosaics are first converted to XEM amounts
else {
$maxQuantity = Amount::MAX_AMOUNT; // 9_000_000_000_000_000
$totalQuantity = $supply * pow(10, $divisibility);
$supplyAdjust = floor(0.8 * log($maxQuantity / $totalQuantity));
$xemAmount = Amount::mosaicQuantityToXEM($divisibility,
$supply,
$quantity,
$multiplier);
// mosaic fee is calculate the same a XEM amounts after being converted.
$fee = self::calculateForXEM(ceil($xemAmount));
}
// add current mosaic attachment's fee
$totalFee += Fee::FEE_FACTOR * max([1, $fee - $supplyAdjust]);
}
return $totalFee;
} | php | static public function calculateForMosaics(MosaicDefinitions $definitions,
MosaicAttachments $attachments,
$multiplier = Amount::XEM)
{
if ($attachments->isEmpty())
return 0;
$totalFee = 0;
foreach ($attachments as $attachment) {
if (is_array($attachment)) {
// collection contains arrays instead of MosaicAttachment objects
$attachment = new MosaicAttachment($attachment);
}
$mosaicFQN = $attachment->mosaicId()->getFQN();
// in case user didnt provide the definition, try to
// to find it with the registry of preconfigured Mosaics classes.
$definition = $definitions->getDefinition($attachment->mosaicId())
?: Registry::getDefinition($mosaicFQN);
if ($definition === false) {
throw new RuntimeException("Missing MosaicDefinition for Mosaic: `" . $mosaicFQN . "`.");
}
// read properties for calculations
$divisibility = $definition->getProperty("divisibility") ?: 0;
$supply = $definition->getTotalSupply() ?: Amount::XEM_SUPPLY;
$quantity = $attachment->quantity;
$supplyAdjust = 0;
// small business mosaic fee
if ($supply <= 10000 && $divisibility === 0) {
$fee = Fee::FEE_FACTOR; // 0.05
}
// all other mosaics are first converted to XEM amounts
else {
$maxQuantity = Amount::MAX_AMOUNT; // 9_000_000_000_000_000
$totalQuantity = $supply * pow(10, $divisibility);
$supplyAdjust = floor(0.8 * log($maxQuantity / $totalQuantity));
$xemAmount = Amount::mosaicQuantityToXEM($divisibility,
$supply,
$quantity,
$multiplier);
// mosaic fee is calculate the same a XEM amounts after being converted.
$fee = self::calculateForXEM(ceil($xemAmount));
}
// add current mosaic attachment's fee
$totalFee += Fee::FEE_FACTOR * max([1, $fee - $supplyAdjust]);
}
return $totalFee;
} | [
"static",
"public",
"function",
"calculateForMosaics",
"(",
"MosaicDefinitions",
"$",
"definitions",
",",
"MosaicAttachments",
"$",
"attachments",
",",
"$",
"multiplier",
"=",
"Amount",
"::",
"XEM",
")",
"{",
"if",
"(",
"$",
"attachments",
"->",
"isEmpty",
"(",
... | Calculate the needed fee for a provided `$mosaics` mosaics
attachments array.
This method is used internally to calculate a mosaic transfer
transaction's needed fees.
The `definitions` argument should contain definitions of attached
mosaics.
@internal
@param \NEM\Models\MosaicDefinitions $definitions Collection of MosaicDefinition objects.
@param \NEM\Models\MosaicAttachments $attachments Collection of MosaicAttachment objects.
@param integer $multiplier
@return \NEM\Models\Fee
@throws RuntimeException On missing MosaicDefinition in `definitions` argument. | [
"Calculate",
"the",
"needed",
"fee",
"for",
"a",
"provided",
"$mosaics",
"mosaics",
"attachments",
"array",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Fee.php#L207-L262 |
evias/nem-php | src/Models/Fee.php | Fee.calculateForXEM | static public function calculateForXEM($amountXEM = 1)
{
$fee = floor(max([1, $amountXEM / 10000]));
return $fee > self::MAX_AMOUNT_FEE ? self::MAX_AMOUNT_FEE : $fee;
} | php | static public function calculateForXEM($amountXEM = 1)
{
$fee = floor(max([1, $amountXEM / 10000]));
return $fee > self::MAX_AMOUNT_FEE ? self::MAX_AMOUNT_FEE : $fee;
} | [
"static",
"public",
"function",
"calculateForXEM",
"(",
"$",
"amountXEM",
"=",
"1",
")",
"{",
"$",
"fee",
"=",
"floor",
"(",
"max",
"(",
"[",
"1",
",",
"$",
"amountXEM",
"/",
"10000",
"]",
")",
")",
";",
"return",
"$",
"fee",
">",
"self",
"::",
"... | Calculate the minimum needed fee for a provided `$amountXEM` amount
of XEM to transfer.
This method is used internally to calculate a transaction's base fee.
@internal
@param string $message
@return \NEM\Models\Fee | [
"Calculate",
"the",
"minimum",
"needed",
"fee",
"for",
"a",
"provided",
"$amountXEM",
"amount",
"of",
"XEM",
"to",
"transfer",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Fee.php#L274-L278 |
evias/nem-php | src/Models/Transaction/Transfer.php | Transfer.extend | public function extend()
{
return [
"amount" => $this->amount()->toMicro(),
"recipient" => $this->recipient()->address()->toClean(),
"message" => $this->message()->toDTO(),
// transaction type specialization
"type" => TransactionType::TRANSFER,
];
} | php | public function extend()
{
return [
"amount" => $this->amount()->toMicro(),
"recipient" => $this->recipient()->address()->toClean(),
"message" => $this->message()->toDTO(),
// transaction type specialization
"type" => TransactionType::TRANSFER,
];
} | [
"public",
"function",
"extend",
"(",
")",
"{",
"return",
"[",
"\"amount\"",
"=>",
"$",
"this",
"->",
"amount",
"(",
")",
"->",
"toMicro",
"(",
")",
",",
"\"recipient\"",
"=>",
"$",
"this",
"->",
"recipient",
"(",
")",
"->",
"address",
"(",
")",
"->",... | The extend() method must be overloaded by any Transaction Type
which needs to extend the base DTO structure.
@return array | [
"The",
"extend",
"()",
"method",
"must",
"be",
"overloaded",
"by",
"any",
"Transaction",
"Type",
"which",
"needs",
"to",
"extend",
"the",
"base",
"DTO",
"structure",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/Transfer.php#L44-L53 |
evias/nem-php | src/Models/Transaction/Transfer.php | Transfer.serialize | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->toDTO("transaction");
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_acct = $serializer->serializeString($nisData["recipient"]);
$uint8_amt = $serializer->serializeLong($nisData["amount"]);
$messagePayload = $nisData["message"]["payload"];
$messageType = $nisData["message"]["type"];
// message payload is optional
$uint8_msg = [];
if (!empty($messagePayload)) {
$uint8_len = $serializer->serializeInt(8 + strlen(hex2bin($messagePayload)));
$uint8_type = $serializer->serializeInt($messageType);
$uint8_hex = $serializer->serializeString(hex2bin($messagePayload));
$uint8_msg = array_merge($uint8_len, $uint8_type, $uint8_hex);
}
else { // empty message is 0 on-chain
$uint8_msg = $serializer->serializeInt(0);
}
// concatenate the UInt8 representation
$output = array_merge(
$uint8_acct,
$uint8_amt,
$uint8_msg);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | php | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->toDTO("transaction");
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_acct = $serializer->serializeString($nisData["recipient"]);
$uint8_amt = $serializer->serializeLong($nisData["amount"]);
$messagePayload = $nisData["message"]["payload"];
$messageType = $nisData["message"]["type"];
// message payload is optional
$uint8_msg = [];
if (!empty($messagePayload)) {
$uint8_len = $serializer->serializeInt(8 + strlen(hex2bin($messagePayload)));
$uint8_type = $serializer->serializeInt($messageType);
$uint8_hex = $serializer->serializeString(hex2bin($messagePayload));
$uint8_msg = array_merge($uint8_len, $uint8_type, $uint8_hex);
}
else { // empty message is 0 on-chain
$uint8_msg = $serializer->serializeInt(0);
}
// concatenate the UInt8 representation
$output = array_merge(
$uint8_acct,
$uint8_amt,
$uint8_msg);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"$",
"baseTx",
"=",
"parent",
"::",
"serialize",
"(",
"$",
"parameters",
")",
";",
"$",
"nisData",
"=",
"$",
"this",
"->",
"toDTO",
"(",
"\"transaction\"",
")",
";",
"// ... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *Transfer* serialization.
@see \NEM\Contracts\Serializable
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"Transfer",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/Transfer.php#L89-L126 |
evias/nem-php | src/Models/MosaicAttachments.php | MosaicAttachments.serialize | public function serialize($parameters = null)
{
// shortcuts
$serializer = $this->getSerializer();
$mapped = $this->map(function(&$attach) {
return new MosaicAttachment($attach);
});
// sort attachments lexicographically
$sorted = $mapped->sort(function($attach1, $attach2)
{
$lexic1 = $attach1->mosaicId()->getFQN() . " : " . $attach1->quantity;
$lexic2 = $attach2->mosaicId()->getFQN() . " : " . $attach2->quantity;
return $lexic1 < $lexic2 ? -1 : $lexic1 > $lexic2;
})->values();
// serialize attachments
// prepend size on 4 bytes
$prependSize = $serializer->serializeInt($sorted->count());
// serialize each attachment
$stateUInt8 = $prependSize;
for ($i = 0, $len = $sorted->count(); $i < $len; $i++) {
$attachment = $sorted->get($i);
// use MosaicAttachment::serialize() specialization
$uint8_attach = $attachment->serialize();
// use merge here, no aggregator
$stateUInt8 = array_merge($stateUInt8, $uint8_attach);
}
// no need to use the aggregator, we dynamically aggregated
// our collection data and prepended the size on 4 bytes.
return $stateUInt8;
} | php | public function serialize($parameters = null)
{
// shortcuts
$serializer = $this->getSerializer();
$mapped = $this->map(function(&$attach) {
return new MosaicAttachment($attach);
});
// sort attachments lexicographically
$sorted = $mapped->sort(function($attach1, $attach2)
{
$lexic1 = $attach1->mosaicId()->getFQN() . " : " . $attach1->quantity;
$lexic2 = $attach2->mosaicId()->getFQN() . " : " . $attach2->quantity;
return $lexic1 < $lexic2 ? -1 : $lexic1 > $lexic2;
})->values();
// serialize attachments
// prepend size on 4 bytes
$prependSize = $serializer->serializeInt($sorted->count());
// serialize each attachment
$stateUInt8 = $prependSize;
for ($i = 0, $len = $sorted->count(); $i < $len; $i++) {
$attachment = $sorted->get($i);
// use MosaicAttachment::serialize() specialization
$uint8_attach = $attachment->serialize();
// use merge here, no aggregator
$stateUInt8 = array_merge($stateUInt8, $uint8_attach);
}
// no need to use the aggregator, we dynamically aggregated
// our collection data and prepended the size on 4 bytes.
return $stateUInt8;
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"// shortcuts",
"$",
"serializer",
"=",
"$",
"this",
"->",
"getSerializer",
"(",
")",
";",
"$",
"mapped",
"=",
"$",
"this",
"->",
"map",
"(",
"function",
"(",
"&",
"$",
... | Overload of the \NEM\Core\ModelCollection::serialize() method to provide
with a specialization for *MosaicAttachments Arrays* serialization.
@see \NEM\Contracts\Serializable
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"ModelCollection",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"MosaicAttachments",
"Arrays",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MosaicAttachments.php#L44-L82 |
evias/nem-php | src/Models/Mutators/ModelMutator.php | ModelMutator.mutate | public function mutate($name, $attributes)
{
// snake_case to camelCase
$modelClass = "\\NEM\\Models\\" . Str::studly($name);
if (!class_exists($modelClass)) {
throw new BadMethodCallException("Model class '" . $modelClass . "' could not be found in \\NEM\\Model namespace.");
}
//XXX add fields list to Models
$instance = new $modelClass($attributes);
return $instance;
} | php | public function mutate($name, $attributes)
{
// snake_case to camelCase
$modelClass = "\\NEM\\Models\\" . Str::studly($name);
if (!class_exists($modelClass)) {
throw new BadMethodCallException("Model class '" . $modelClass . "' could not be found in \\NEM\\Model namespace.");
}
//XXX add fields list to Models
$instance = new $modelClass($attributes);
return $instance;
} | [
"public",
"function",
"mutate",
"(",
"$",
"name",
",",
"$",
"attributes",
")",
"{",
"// snake_case to camelCase",
"$",
"modelClass",
"=",
"\"\\\\NEM\\\\Models\\\\\"",
".",
"Str",
"::",
"studly",
"(",
"$",
"name",
")",
";",
"if",
"(",
"!",
"class_exists",
"("... | Mutate a Model object.
This method takes a *snake_case* model name and converts it
to a class name in the namespace \NEM\Models.
@internal
@param string $name The model name you would like to create.
@param array $attributes The model's attribute values.
@return \NEM\Models\ModelInterface | [
"Mutate",
"a",
"Model",
"object",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Mutators/ModelMutator.php#L46-L58 |
evias/nem-php | src/Models/Model.php | Model.toDTO | public function toDTO($filterByKey = null)
{
$dtos = [];
foreach ($this->getAttributes() as $attrib => $data) {
$attribDTO = $data; // default (unparsed or scalar)
// we may need to parse the attribute relation or use
// the model to get the subordinated Data Transfer Object.
if ($data instanceof DataTransferObject || $data instanceof ModelCollection) {
// sub DTO convert to array
$attribDTO = $data->toDTO();
}
elseif (in_array($attrib, $this->relations) || method_exists($this, $attrib)) {
// unparsed sub DTO passed - parse the DTO to make sure
// we are working with NEM *NIS compliant* objects *always*.
$related = $this->resolveRelationship($attrib, $data);
$attribDTO = $related->toDTO();
}
$dtos[$attrib] = $attribDTO;
}
if ($filterByKey && isset($dtos[$filterByKey]))
return $dtos[$filterByKey];
return $dtos;
} | php | public function toDTO($filterByKey = null)
{
$dtos = [];
foreach ($this->getAttributes() as $attrib => $data) {
$attribDTO = $data; // default (unparsed or scalar)
// we may need to parse the attribute relation or use
// the model to get the subordinated Data Transfer Object.
if ($data instanceof DataTransferObject || $data instanceof ModelCollection) {
// sub DTO convert to array
$attribDTO = $data->toDTO();
}
elseif (in_array($attrib, $this->relations) || method_exists($this, $attrib)) {
// unparsed sub DTO passed - parse the DTO to make sure
// we are working with NEM *NIS compliant* objects *always*.
$related = $this->resolveRelationship($attrib, $data);
$attribDTO = $related->toDTO();
}
$dtos[$attrib] = $attribDTO;
}
if ($filterByKey && isset($dtos[$filterByKey]))
return $dtos[$filterByKey];
return $dtos;
} | [
"public",
"function",
"toDTO",
"(",
"$",
"filterByKey",
"=",
"null",
")",
"{",
"$",
"dtos",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getAttributes",
"(",
")",
"as",
"$",
"attrib",
"=>",
"$",
"data",
")",
"{",
"$",
"attribDTO",
"=",
... | Generic helper to convert a Model instance to a Data Transfer Object.
This will make it easy to bridge implemented models to NEM *NIS compliant*
objects.
More complicated objects may overload this method to provide with finer
grained data transfer objects.
@see http://bob.nem.ninja/docs/ NIS API Documentation
@param null|string $filterByKey non-null will return only the named sub-dtos.
@return array Associative array representation of the object *compliable* with NIS definition. | [
"Generic",
"helper",
"to",
"convert",
"a",
"Model",
"instance",
"to",
"a",
"Data",
"Transfer",
"Object",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Model.php#L222-L249 |
evias/nem-php | src/Models/Model.php | Model.getFields | public function getFields()
{
$fields = array_keys($this->fillable);
if (!empty($fields) && is_integer($fields[0]))
// only alias provided
$fields = array_values($this->fillable);
return array_merge($fields, $this->appends, array_keys($this->attributes));
} | php | public function getFields()
{
$fields = array_keys($this->fillable);
if (!empty($fields) && is_integer($fields[0]))
// only alias provided
$fields = array_values($this->fillable);
return array_merge($fields, $this->appends, array_keys($this->attributes));
} | [
"public",
"function",
"getFields",
"(",
")",
"{",
"$",
"fields",
"=",
"array_keys",
"(",
"$",
"this",
"->",
"fillable",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"fields",
")",
"&&",
"is_integer",
"(",
"$",
"fields",
"[",
"0",
"]",
")",
")",
"... | Getter for the model's field names.
This method will merge the `fillable` property and the `appends`
properties into one array of field names.
@param array $fieldNames An array of field names
@return \NEM\Models\ModelInterface | [
"Getter",
"for",
"the",
"model",
"s",
"field",
"names",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Model.php#L295-L303 |
evias/nem-php | src/Models/Model.php | Model.setAttributes | public function setAttributes(array $attributes)
{
$flattened = array_dot($attributes);
$fields = $this->getFields();
if (empty($fields))
$fields = array_keys($attributes);
foreach ($fields as $field) :
// make sure we have an aliased fields list
$fillableKeys = array_keys($this->fillable);
$aliasedFields = !empty($fillableKeys) && !is_integer($fillableKeys[0]);
// read full path to attribute (get dot notation if available).
$attribFullPath = isset($this->fillable[$field]) ? $this->fillable[$field] : $field;
$hasByPath = array_has($flattened, $attribFullPath);
$hasByAlias = array_has($attributes, $field);
if (! $hasByPath && ! $hasByAlias) {
// try deep find and continue
// browse attributes array in depth.
$attrib = $attributes;
foreach (explode(".", $attribFullPath) as $key) {
if (! isset($attrib[$key]))
$attrib[$key] = null;
$attrib = $attrib[$key];
}
$this->setAttribute($field, $attrib);
continue;
}
// use attribute path or alias
$attribValue = $hasByPath ? array_get($flattened, $attribFullPath)
: array_get($attributes, $field);
$this->setAttribute($field, $attribValue);
endforeach ;
return $this;
} | php | public function setAttributes(array $attributes)
{
$flattened = array_dot($attributes);
$fields = $this->getFields();
if (empty($fields))
$fields = array_keys($attributes);
foreach ($fields as $field) :
// make sure we have an aliased fields list
$fillableKeys = array_keys($this->fillable);
$aliasedFields = !empty($fillableKeys) && !is_integer($fillableKeys[0]);
// read full path to attribute (get dot notation if available).
$attribFullPath = isset($this->fillable[$field]) ? $this->fillable[$field] : $field;
$hasByPath = array_has($flattened, $attribFullPath);
$hasByAlias = array_has($attributes, $field);
if (! $hasByPath && ! $hasByAlias) {
// try deep find and continue
// browse attributes array in depth.
$attrib = $attributes;
foreach (explode(".", $attribFullPath) as $key) {
if (! isset($attrib[$key]))
$attrib[$key] = null;
$attrib = $attrib[$key];
}
$this->setAttribute($field, $attrib);
continue;
}
// use attribute path or alias
$attribValue = $hasByPath ? array_get($flattened, $attribFullPath)
: array_get($attributes, $field);
$this->setAttribute($field, $attribValue);
endforeach ;
return $this;
} | [
"public",
"function",
"setAttributes",
"(",
"array",
"$",
"attributes",
")",
"{",
"$",
"flattened",
"=",
"array_dot",
"(",
"$",
"attributes",
")",
";",
"$",
"fields",
"=",
"$",
"this",
"->",
"getFields",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"... | Setter for the `attributes` property.
This method uses a *dot notation* for attributes and resolves
relationships automatically when needed.
@internal
@return \NEM\Contracts\DataTransferObject | [
"Setter",
"for",
"the",
"attributes",
"property",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Model.php#L314-L358 |
evias/nem-php | src/Models/Model.php | Model.getAttributes | public function getAttributes()
{
// prevent order of fields from changing
$sortedAttribs = [];
foreach ($this->sortedFields as $ix => $attribute) {
$sortedAttribs[$attribute] = $this->attributes[$attribute];
}
return $sortedAttribs;
} | php | public function getAttributes()
{
// prevent order of fields from changing
$sortedAttribs = [];
foreach ($this->sortedFields as $ix => $attribute) {
$sortedAttribs[$attribute] = $this->attributes[$attribute];
}
return $sortedAttribs;
} | [
"public",
"function",
"getAttributes",
"(",
")",
"{",
"// prevent order of fields from changing",
"$",
"sortedAttribs",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"sortedFields",
"as",
"$",
"ix",
"=>",
"$",
"attribute",
")",
"{",
"$",
"sortedAttrib... | Getter for the `attributes` property.
The `attributes` property holds an array with key values representing
the Data of this Model instance.
@return array | [
"Getter",
"for",
"the",
"attributes",
"property",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Model.php#L368-L377 |
evias/nem-php | src/Models/Model.php | Model.getAttribute | public function getAttribute($alias, $doCast = true)
{
if (property_exists($this, $alias))
return $this->$alias;
if (array_key_exists($alias, $this->attributes))
// value available
return $this->castValue($alias, $this->attributes[$alias], $doCast);
// check whether we have an aliased fillable fields list.
$fillableKeys = array_keys($this->fillable);
$aliasedFields = !empty($fillableKeys) && !is_integer($fillableKeys[0]);
if ($aliasedFields) {
// get the dot notation for the said `alias` alias (the dot notation is the full path).
$dotNotation = isset($this->fillable[$alias]) ? $this->fillable[$alias] : $alias;
if (array_key_exists($dotNotation, $this->dotAttributes))
return $this->castValue($alias, $this->dotAttributes[$dotNotation], $doCast);
}
if (! $this->hasRelation($alias) || ! isset($this->related[$alias]))
// no value available + no relation
return isset($this->dotAttributes[$alias]) ? $this->castValue($alias, $this->dotAttributes[$alias], $doCast) : null;
if ($this->related[$alias] instanceof Model) {
// getAttribute should return DTO data (not the object).
return $this->attributes[$alias];
}
elseif ($this->related[$alias] instanceof ModelCollection) {
// getAttribute should return DTO data (not the collection).
return $this->related[$alias]->toDTO();
}
return $this->related[$alias];
} | php | public function getAttribute($alias, $doCast = true)
{
if (property_exists($this, $alias))
return $this->$alias;
if (array_key_exists($alias, $this->attributes))
// value available
return $this->castValue($alias, $this->attributes[$alias], $doCast);
// check whether we have an aliased fillable fields list.
$fillableKeys = array_keys($this->fillable);
$aliasedFields = !empty($fillableKeys) && !is_integer($fillableKeys[0]);
if ($aliasedFields) {
// get the dot notation for the said `alias` alias (the dot notation is the full path).
$dotNotation = isset($this->fillable[$alias]) ? $this->fillable[$alias] : $alias;
if (array_key_exists($dotNotation, $this->dotAttributes))
return $this->castValue($alias, $this->dotAttributes[$dotNotation], $doCast);
}
if (! $this->hasRelation($alias) || ! isset($this->related[$alias]))
// no value available + no relation
return isset($this->dotAttributes[$alias]) ? $this->castValue($alias, $this->dotAttributes[$alias], $doCast) : null;
if ($this->related[$alias] instanceof Model) {
// getAttribute should return DTO data (not the object).
return $this->attributes[$alias];
}
elseif ($this->related[$alias] instanceof ModelCollection) {
// getAttribute should return DTO data (not the collection).
return $this->related[$alias]->toDTO();
}
return $this->related[$alias];
} | [
"public",
"function",
"getAttribute",
"(",
"$",
"alias",
",",
"$",
"doCast",
"=",
"true",
")",
"{",
"if",
"(",
"property_exists",
"(",
"$",
"this",
",",
"$",
"alias",
")",
")",
"return",
"$",
"this",
"->",
"$",
"alias",
";",
"if",
"(",
"array_key_exi... | Getter for singular attribute values by name.
@param string $alias The attribute field alias.
@return mixed | [
"Getter",
"for",
"singular",
"attribute",
"values",
"by",
"name",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Model.php#L385-L419 |
evias/nem-php | src/Models/Model.php | Model.setAttribute | public function setAttribute($name, $data)
{
// new fields are detected to *prevent the order of fields*
// from changing during data processes.
$attributes = array_keys($this->attributes);
$cntAttribs = count($attributes);
if (! in_array($name, $attributes)) {
// new field detected, store index for correct order
$this->sortedFields[$cntAttribs-1] = $name;
}
if (in_array($name, $this->relations) || method_exists($this, $name)) {
// subordinate DTO data passed (one-to-one, one-to-many, etc.)
// build the linked Model using Relationship configuration.
$this->related[$name] = $this->resolveRelationship($name, $data);
$this->attributes[$name] = $data; // attributes property contains scalar data
}
elseif (empty($this->fillable) || in_array($name, $this->getFields())) {
// attribute is fillable or any attribute is fillable.
$this->attributes[$name] = $data;
}
// get the dot notation for the said `name` alias (the dot notation is the full path).
$dotNotation = isset($this->fillable[$name]) ? $this->fillable[$name] : $name;
$this->dotAttributes[$dotNotation] = $data;
return $this;
} | php | public function setAttribute($name, $data)
{
// new fields are detected to *prevent the order of fields*
// from changing during data processes.
$attributes = array_keys($this->attributes);
$cntAttribs = count($attributes);
if (! in_array($name, $attributes)) {
// new field detected, store index for correct order
$this->sortedFields[$cntAttribs-1] = $name;
}
if (in_array($name, $this->relations) || method_exists($this, $name)) {
// subordinate DTO data passed (one-to-one, one-to-many, etc.)
// build the linked Model using Relationship configuration.
$this->related[$name] = $this->resolveRelationship($name, $data);
$this->attributes[$name] = $data; // attributes property contains scalar data
}
elseif (empty($this->fillable) || in_array($name, $this->getFields())) {
// attribute is fillable or any attribute is fillable.
$this->attributes[$name] = $data;
}
// get the dot notation for the said `name` alias (the dot notation is the full path).
$dotNotation = isset($this->fillable[$name]) ? $this->fillable[$name] : $name;
$this->dotAttributes[$dotNotation] = $data;
return $this;
} | [
"public",
"function",
"setAttribute",
"(",
"$",
"name",
",",
"$",
"data",
")",
"{",
"// new fields are detected to *prevent the order of fields*",
"// from changing during data processes.",
"$",
"attributes",
"=",
"array_keys",
"(",
"$",
"this",
"->",
"attributes",
")",
... | Setter for singular attribute values by name.
@param string $name The attribute name.
@param mixed $data The attribute data.
@return mixed | [
"Setter",
"for",
"singular",
"attribute",
"values",
"by",
"name",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Model.php#L428-L456 |
evias/nem-php | src/Models/Model.php | Model.castValue | public function castValue($field, $value, $cast = true)
{
if (! array_key_exists($field, $this->casts) || ! $cast)
// no cast configured for said field. Nothing done.
return $value;
$types = [
"boolean", "bool", "integer", "int", "float", "double",
"string", "array", "object", "null"
];
// validate type cast is valid
$type = $this->casts[$field];
if (! in_array($type, $types)) {
throw new RuntimeException("Cast of field '" . $field . "' to type '" . $type . "' not possible. Please define only scalar type casts.");
}
$output = $value;
$result = settype($output, $type);
if ($result === true)
return $output;
return $value;
} | php | public function castValue($field, $value, $cast = true)
{
if (! array_key_exists($field, $this->casts) || ! $cast)
// no cast configured for said field. Nothing done.
return $value;
$types = [
"boolean", "bool", "integer", "int", "float", "double",
"string", "array", "object", "null"
];
// validate type cast is valid
$type = $this->casts[$field];
if (! in_array($type, $types)) {
throw new RuntimeException("Cast of field '" . $field . "' to type '" . $type . "' not possible. Please define only scalar type casts.");
}
$output = $value;
$result = settype($output, $type);
if ($result === true)
return $output;
return $value;
} | [
"public",
"function",
"castValue",
"(",
"$",
"field",
",",
"$",
"value",
",",
"$",
"cast",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"field",
",",
"$",
"this",
"->",
"casts",
")",
"||",
"!",
"$",
"cast",
")",
"// no cast ... | This method will read the `casts` instance property and
automatically cast the `value` provided in the set cast
type.
@see http://php.net/manual/en/function.settype.php
@param string $field
@param mixed $value
@return mixed | [
"This",
"method",
"will",
"read",
"the",
"casts",
"instance",
"property",
"and",
"automatically",
"cast",
"the",
"value",
"provided",
"in",
"the",
"set",
"cast",
"type",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Model.php#L606-L630 |
evias/nem-php | src/Models/Model.php | Model.resolveRelationship | public function resolveRelationship($alias, $data)
{
if (! in_array($alias, $this->relations) && ! method_exists($this, $alias)) {
throw new BadMethodCallException("Relationship for field '" . $alias . "' not configured in " . get_class($this));
}
if (method_exists($this, $alias)) {
// Use relationship *method* (prevail)
$related = $this->$alias($data);
return $related;
}
// try to craft relationship with simple snake_case to camelCase
$relation = "\\NEM\\Models\\" . Str::studly($alias);
if (! class_exists($relation)) {
throw new BadMethodCallException("Relationship method for field '" . $alias . "' not implemented in " . get_class($this));
}
$related = new $relation($data);
return $related;
} | php | public function resolveRelationship($alias, $data)
{
if (! in_array($alias, $this->relations) && ! method_exists($this, $alias)) {
throw new BadMethodCallException("Relationship for field '" . $alias . "' not configured in " . get_class($this));
}
if (method_exists($this, $alias)) {
// Use relationship *method* (prevail)
$related = $this->$alias($data);
return $related;
}
// try to craft relationship with simple snake_case to camelCase
$relation = "\\NEM\\Models\\" . Str::studly($alias);
if (! class_exists($relation)) {
throw new BadMethodCallException("Relationship method for field '" . $alias . "' not implemented in " . get_class($this));
}
$related = new $relation($data);
return $related;
} | [
"public",
"function",
"resolveRelationship",
"(",
"$",
"alias",
",",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"alias",
",",
"$",
"this",
"->",
"relations",
")",
"&&",
"!",
"method_exists",
"(",
"$",
"this",
",",
"$",
"alias",
")",... | Build a Model Relationship between \NEM\Contracts\DataTransferObject objects.
Relation can be defined with the `$relations` property on extending classes.
Relationships for which there is no method implementation, will automatically
try to instantiate using the uppercased CamelCase representation of the relation
alias.
@param string $alias Relation alias name.
@param array $data The relationship data.
@return DataTransferObject|ModelCollection | [
"Build",
"a",
"Model",
"Relationship",
"between",
"\\",
"NEM",
"\\",
"Contracts",
"\\",
"DataTransferObject",
"objects",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Model.php#L645-L666 |
evias/nem-php | src/Models/MosaicDefinition.php | MosaicDefinition.toDTO | public function toDTO($filterByKey = null)
{
$isHexDescription = $filterByKey === true ? true : false;
return [
"creator" => $this->creator()->publicKey,
"id" => $this->id()->toDTO(),
"description" => $isHexDescription ? $this->description()->toHex()
: $this->description()->getPlain(),
"properties" => $this->properties()->toDTO(),
"levy" => $this->levy()->toDTO(),
];
} | php | public function toDTO($filterByKey = null)
{
$isHexDescription = $filterByKey === true ? true : false;
return [
"creator" => $this->creator()->publicKey,
"id" => $this->id()->toDTO(),
"description" => $isHexDescription ? $this->description()->toHex()
: $this->description()->getPlain(),
"properties" => $this->properties()->toDTO(),
"levy" => $this->levy()->toDTO(),
];
} | [
"public",
"function",
"toDTO",
"(",
"$",
"filterByKey",
"=",
"null",
")",
"{",
"$",
"isHexDescription",
"=",
"$",
"filterByKey",
"===",
"true",
"?",
"true",
":",
"false",
";",
"return",
"[",
"\"creator\"",
"=>",
"$",
"this",
"->",
"creator",
"(",
")",
... | Address DTO automatically cleans address representation.
@param boolean $filterByKey When set to `true`, the method will return the description field in hexadecimal format.
@return array Associative array with key `address` containing a NIS *compliable* address representation. | [
"Address",
"DTO",
"automatically",
"cleans",
"address",
"representation",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MosaicDefinition.php#L66-L77 |
evias/nem-php | src/Models/MosaicDefinition.php | MosaicDefinition.serialize | public function serialize($parameters = null)
{
$nisData = $this->toDTO(true); // true=hexadecimal description
// shortcuts
$serializer = $this->getSerializer();
$publicKey = hex2bin($nisData["creator"]);
// bundle with length of pub key and public key in UInt8
$publicKey = $serializer->serializeString($publicKey);
// serialize content
$desc = $serializer->serializeString(hex2bin($nisData["description"]));
$mosaic = $this->id()->serialize();
$props = $this->properties()->serialize();
$levy = $this->levy()->serialize();
// concatenate UInt8
$output = array_merge($publicKey, $mosaic, $desc, $props, $levy);
// do not use aggregator because MosaicDefinition's first byte
// contains a public key size, not a DTO size.
return $output;
} | php | public function serialize($parameters = null)
{
$nisData = $this->toDTO(true); // true=hexadecimal description
// shortcuts
$serializer = $this->getSerializer();
$publicKey = hex2bin($nisData["creator"]);
// bundle with length of pub key and public key in UInt8
$publicKey = $serializer->serializeString($publicKey);
// serialize content
$desc = $serializer->serializeString(hex2bin($nisData["description"]));
$mosaic = $this->id()->serialize();
$props = $this->properties()->serialize();
$levy = $this->levy()->serialize();
// concatenate UInt8
$output = array_merge($publicKey, $mosaic, $desc, $props, $levy);
// do not use aggregator because MosaicDefinition's first byte
// contains a public key size, not a DTO size.
return $output;
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"$",
"nisData",
"=",
"$",
"this",
"->",
"toDTO",
"(",
"true",
")",
";",
"// true=hexadecimal description",
"// shortcuts",
"$",
"serializer",
"=",
"$",
"this",
"->",
"getSerial... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *Mosaic Definition* serialization.
@see \NEM\Contracts\Serializable
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"Mosaic",
"Definition",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MosaicDefinition.php#L87-L110 |
evias/nem-php | src/Models/MultisigModification.php | MultisigModification.toDTO | public function toDTO($filterByKey = null)
{
if (! in_array($this->modificationType, [self::TYPE_ADD, self::TYPE_REMOVE]))
$this->modificationType = self::TYPE_ADD;
return [
"modificationType" => (int) $this->modificationType,
"cosignatoryAccount" => $this->cosignatoryAccount()->publicKey,
];
} | php | public function toDTO($filterByKey = null)
{
if (! in_array($this->modificationType, [self::TYPE_ADD, self::TYPE_REMOVE]))
$this->modificationType = self::TYPE_ADD;
return [
"modificationType" => (int) $this->modificationType,
"cosignatoryAccount" => $this->cosignatoryAccount()->publicKey,
];
} | [
"public",
"function",
"toDTO",
"(",
"$",
"filterByKey",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"this",
"->",
"modificationType",
",",
"[",
"self",
"::",
"TYPE_ADD",
",",
"self",
"::",
"TYPE_REMOVE",
"]",
")",
")",
"$",
"this",
"... | MultisigModification DTO automatically builds a *NIS compliant*
[MultisigCosignatoryModification](https://bob.nem.ninja/docs/#multisigCosignatoryModification)
@return array Associative array with key `modificationType` integer and `cosignatoryAccount` public key. | [
"MultisigModification",
"DTO",
"automatically",
"builds",
"a",
"*",
"NIS",
"compliant",
"*",
"[",
"MultisigCosignatoryModification",
"]",
"(",
"https",
":",
"//",
"bob",
".",
"nem",
".",
"ninja",
"/",
"docs",
"/",
"#multisigCosignatoryModification",
")"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MultisigModification.php#L78-L87 |
evias/nem-php | src/Models/MultisigModification.php | MultisigModification.serialize | public function serialize($parameters = null)
{
$nisData = $this->toDTO();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_struct = $serializer->serializeInt(40); // length of structure
$uint8_type = $serializer->serializeInt($nisData["modificationType"]);
$uint8_acct = $serializer->serializeString(hex2bin($nisData["cosignatoryAccount"]));
// concatenate uint8 representations
$output = array_merge($uint8_struct, $uint8_type, $uint8_acct);
return $output;
} | php | public function serialize($parameters = null)
{
$nisData = $this->toDTO();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_struct = $serializer->serializeInt(40); // length of structure
$uint8_type = $serializer->serializeInt($nisData["modificationType"]);
$uint8_acct = $serializer->serializeString(hex2bin($nisData["cosignatoryAccount"]));
// concatenate uint8 representations
$output = array_merge($uint8_struct, $uint8_type, $uint8_acct);
return $output;
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"$",
"nisData",
"=",
"$",
"this",
"->",
"toDTO",
"(",
")",
";",
"// shortcuts",
"$",
"serializer",
"=",
"$",
"this",
"->",
"getSerializer",
"(",
")",
";",
"$",
"output",
... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *mosaicId* serialization.
@see \NEM\Contracts\Serializable
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"mosaicId",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MultisigModification.php#L97-L113 |
evias/nem-php | src/Models/MosaicAttachment.php | MosaicAttachment.serialize | public function serialize($parameters = null)
{
$nisData = $this->toDTO();
// shortcuts
$mosaicS = $this->mosaicId()->serialize();
$quantity = $this->getSerializer()->serializeLong($nisData["quantity"]);
return $this->getSerializer()->aggregate($mosaicS, $quantity);
} | php | public function serialize($parameters = null)
{
$nisData = $this->toDTO();
// shortcuts
$mosaicS = $this->mosaicId()->serialize();
$quantity = $this->getSerializer()->serializeLong($nisData["quantity"]);
return $this->getSerializer()->aggregate($mosaicS, $quantity);
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"$",
"nisData",
"=",
"$",
"this",
"->",
"toDTO",
"(",
")",
";",
"// shortcuts",
"$",
"mosaicS",
"=",
"$",
"this",
"->",
"mosaicId",
"(",
")",
"->",
"serialize",
"(",
")... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *mosaicId and Quantity* serialization.
@see \NEM\Contracts\Serializable
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"mosaicId",
"and",
"Quantity",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MosaicAttachment.php#L83-L92 |
evias/nem-php | src/Models/Transaction.php | Transaction.create | static public function create(array $data = null)
{
if (empty($data["type"]) && isset($data["transaction"])) {
$type = $data["transaction"]["type"];
}
elseif (! $data || empty($data["type"])) {
return new static($data);
}
else {
$type = $data["type"];
}
// valid transaction type input
$validTypes = array_keys(self::$typesClassMap);
if (! $type || ! in_array($type, $validTypes)) {
$type = TransactionType::TRANSFER;
}
// mutate transaction (morph specialized class)
$classTx = self::$typesClassMap[$type];
if ($type === TransactionType::TRANSFER
&& in_array($data["version"], [self::VERSION_2, self::VERSION_2_TEST, self::VERSION_2_MIJIN])) {
$classTx = "\\NEM\\Models\\Transaction\\MosaicTransfer";
}
return new $classTx($data);
} | php | static public function create(array $data = null)
{
if (empty($data["type"]) && isset($data["transaction"])) {
$type = $data["transaction"]["type"];
}
elseif (! $data || empty($data["type"])) {
return new static($data);
}
else {
$type = $data["type"];
}
// valid transaction type input
$validTypes = array_keys(self::$typesClassMap);
if (! $type || ! in_array($type, $validTypes)) {
$type = TransactionType::TRANSFER;
}
// mutate transaction (morph specialized class)
$classTx = self::$typesClassMap[$type];
if ($type === TransactionType::TRANSFER
&& in_array($data["version"], [self::VERSION_2, self::VERSION_2_TEST, self::VERSION_2_MIJIN])) {
$classTx = "\\NEM\\Models\\Transaction\\MosaicTransfer";
}
return new $classTx($data);
} | [
"static",
"public",
"function",
"create",
"(",
"array",
"$",
"data",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"data",
"[",
"\"type\"",
"]",
")",
"&&",
"isset",
"(",
"$",
"data",
"[",
"\"transaction\"",
"]",
")",
")",
"{",
"$",
"type",
... | Class method to create a Transaction object out of
a DTO data set.
The `type` field is used to determine which class
must be loaded, see the static `typeClassMap` property
for details. | [
"Class",
"method",
"to",
"create",
"a",
"Transaction",
"object",
"out",
"of",
"a",
"DTO",
"data",
"set",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction.php#L162-L190 |
evias/nem-php | src/Models/Transaction.php | Transaction.meta | public function meta()
{
$meta = [];
// look for basic parameters of transactions, only unconfirmed
// transactions will have those fields empty.
if (isset($this->attributes["id"]))
$meta["id"] = (int) $this->attributes["id"];
if (isset($this->attributes["height"]))
$meta["height"] = (int) $this->attributes["height"];
if (isset($this->attributes["hash"]))
$meta["hash"] = ["data" => $this->attributes["hash"]];
return $meta;
} | php | public function meta()
{
$meta = [];
// look for basic parameters of transactions, only unconfirmed
// transactions will have those fields empty.
if (isset($this->attributes["id"]))
$meta["id"] = (int) $this->attributes["id"];
if (isset($this->attributes["height"]))
$meta["height"] = (int) $this->attributes["height"];
if (isset($this->attributes["hash"]))
$meta["hash"] = ["data" => $this->attributes["hash"]];
return $meta;
} | [
"public",
"function",
"meta",
"(",
")",
"{",
"$",
"meta",
"=",
"[",
"]",
";",
"// look for basic parameters of transactions, only unconfirmed",
"// transactions will have those fields empty.",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"attributes",
"[",
"\"id\"",
"]... | The meta() method must be overloaded by any Transaction Type
which needs to extend the base META structure.
@return array | [
"The",
"meta",
"()",
"method",
"must",
"be",
"overloaded",
"by",
"any",
"Transaction",
"Type",
"which",
"needs",
"to",
"extend",
"the",
"base",
"META",
"structure",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction.php#L251-L268 |
evias/nem-php | src/Models/Transaction.php | Transaction.toDTO | public function toDTO($filterByKey = null)
{
$baseMeta = $this->meta();
$baseEntity = [
"timeStamp" => $this->timeStamp()->toDTO(),
"fee" => $this->fee()->toMicro(),
];
// extend entity data in sub class
// @see \NEM\Models\Transaction\MosaicTransfer
$meta = array_merge($baseMeta, $this->extendMeta());
$entity = array_merge($baseEntity, $this->extend());
// mosaics field is used to determine the version
$versionByContent = !isset($entity["mosaics"]) ? self::VERSION_1
: self::VERSION_2;
// validate version field, should always reflect valid NIS tx version
$version = isset($entity["version"]) ? $entity["version"] : $this->getAttribute("version");
$versions = [
self::VERSION_1, self::VERSION_2,
self::VERSION_1_TEST, self::VERSION_2_TEST,
self::VERSION_1_MIJIN, self::VERSION_2_MIJIN
];
if (! $version || !in_array($version, $versions)) {
$version = $versionByContent;
}
// validate transaction type, should always be a valid type
$type = isset($entity["type"]) ? $entity["type"] : $this->getAttribute("type");
$validTypes = array_keys(self::$typesClassMap);
if (! $type || ! in_array($type, $validTypes)) {
$type = TransactionType::TRANSFER;
$this->setAttribute("type", $type);
}
// deadline set to +1 hour if none set
$deadline = $this->deadline()->toDTO();
if (! $deadline || $deadline <= 0) {
$txTime = $entity["timeStamp"];
$deadline = $txTime + 3600;
$this->setAttribute("deadline", $deadline);
}
// do we have optional fields
$optionals = ["signer", "signature"];
foreach ($optionals as $field) {
$data = $this->getAttribute($field);
if (null !== $data) {
$entity[$field] = $data;
}
}
// push validated input
$entity["type"] = $type;
$entity["version"] = $version;
$entity["deadline"] = $deadline;
$toDTO = [
"meta" => $meta,
"transaction" => $entity,
];
if ($filterByKey && isset($toDTO[$filterByKey]))
return $toDTO[$filterByKey];
return $toDTO;
} | php | public function toDTO($filterByKey = null)
{
$baseMeta = $this->meta();
$baseEntity = [
"timeStamp" => $this->timeStamp()->toDTO(),
"fee" => $this->fee()->toMicro(),
];
// extend entity data in sub class
// @see \NEM\Models\Transaction\MosaicTransfer
$meta = array_merge($baseMeta, $this->extendMeta());
$entity = array_merge($baseEntity, $this->extend());
// mosaics field is used to determine the version
$versionByContent = !isset($entity["mosaics"]) ? self::VERSION_1
: self::VERSION_2;
// validate version field, should always reflect valid NIS tx version
$version = isset($entity["version"]) ? $entity["version"] : $this->getAttribute("version");
$versions = [
self::VERSION_1, self::VERSION_2,
self::VERSION_1_TEST, self::VERSION_2_TEST,
self::VERSION_1_MIJIN, self::VERSION_2_MIJIN
];
if (! $version || !in_array($version, $versions)) {
$version = $versionByContent;
}
// validate transaction type, should always be a valid type
$type = isset($entity["type"]) ? $entity["type"] : $this->getAttribute("type");
$validTypes = array_keys(self::$typesClassMap);
if (! $type || ! in_array($type, $validTypes)) {
$type = TransactionType::TRANSFER;
$this->setAttribute("type", $type);
}
// deadline set to +1 hour if none set
$deadline = $this->deadline()->toDTO();
if (! $deadline || $deadline <= 0) {
$txTime = $entity["timeStamp"];
$deadline = $txTime + 3600;
$this->setAttribute("deadline", $deadline);
}
// do we have optional fields
$optionals = ["signer", "signature"];
foreach ($optionals as $field) {
$data = $this->getAttribute($field);
if (null !== $data) {
$entity[$field] = $data;
}
}
// push validated input
$entity["type"] = $type;
$entity["version"] = $version;
$entity["deadline"] = $deadline;
$toDTO = [
"meta" => $meta,
"transaction" => $entity,
];
if ($filterByKey && isset($toDTO[$filterByKey]))
return $toDTO[$filterByKey];
return $toDTO;
} | [
"public",
"function",
"toDTO",
"(",
"$",
"filterByKey",
"=",
"null",
")",
"{",
"$",
"baseMeta",
"=",
"$",
"this",
"->",
"meta",
"(",
")",
";",
"$",
"baseEntity",
"=",
"[",
"\"timeStamp\"",
"=>",
"$",
"this",
"->",
"timeStamp",
"(",
")",
"->",
"toDTO"... | Account DTO represents NIS API's [AccountMetaDataPair](https://bob.nem.ninja/docs/#accountMetaDataPair).
@see [AccountMetaDataPair](https://bob.nem.ninja/docs/#accountMetaDataPair)
@return array Associative array containing a NIS *compliable* account representation. | [
"Account",
"DTO",
"represents",
"NIS",
"API",
"s",
"[",
"AccountMetaDataPair",
"]",
"(",
"https",
":",
"//",
"bob",
".",
"nem",
".",
"ninja",
"/",
"docs",
"/",
"#accountMetaDataPair",
")",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction.php#L276-L344 |
evias/nem-php | src/Models/Transaction.php | Transaction.serialize | public function serialize($parameters = null)
{
$nisData = $this->toDTO("transaction");
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize all the base data
$uint8_type = $serializer->serializeInt($nisData["type"]);
$uint8_version = $serializer->serializeInt($nisData["version"]);
$uint8_timestamp = $serializer->serializeInt($nisData["timeStamp"]);
$uint8_signer = $serializer->serializeString(hex2bin($nisData["signer"]));
$uint8_fee = $serializer->serializeLong($nisData["fee"]);
$uint8_deadline = $serializer->serializeInt($nisData["deadline"]);
// step 1: meta data at the beginning
$output = array_merge(
$uint8_type,
$uint8_version,
$uint8_timestamp,
$uint8_signer);
// step 2: serialize fee and deadline
$output = array_merge($output,
$uint8_fee,
$uint8_deadline);
// done with `base transaction data` serialization.
return ($this->serialized = $output);
} | php | public function serialize($parameters = null)
{
$nisData = $this->toDTO("transaction");
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize all the base data
$uint8_type = $serializer->serializeInt($nisData["type"]);
$uint8_version = $serializer->serializeInt($nisData["version"]);
$uint8_timestamp = $serializer->serializeInt($nisData["timeStamp"]);
$uint8_signer = $serializer->serializeString(hex2bin($nisData["signer"]));
$uint8_fee = $serializer->serializeLong($nisData["fee"]);
$uint8_deadline = $serializer->serializeInt($nisData["deadline"]);
// step 1: meta data at the beginning
$output = array_merge(
$uint8_type,
$uint8_version,
$uint8_timestamp,
$uint8_signer);
// step 2: serialize fee and deadline
$output = array_merge($output,
$uint8_fee,
$uint8_deadline);
// done with `base transaction data` serialization.
return ($this->serialized = $output);
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"$",
"nisData",
"=",
"$",
"this",
"->",
"toDTO",
"(",
"\"transaction\"",
")",
";",
"// shortcuts",
"$",
"serializer",
"=",
"$",
"this",
"->",
"getSerializer",
"(",
")",
";"... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *Transaction* serialization.
@see \NEM\Contracts\Serializable
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"Transaction",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction.php#L354-L384 |
evias/nem-php | src/Models/Transaction.php | Transaction.timeStamp | public function timeStamp($timestamp = null)
{
$ts = $timestamp ?: $this->getAttribute("timeStamp");
if (is_integer($ts) || $ts instanceof TimeWindow) {
return new TimeWindow(["timeStamp" => $ts]);
}
return new TimeWindow();
} | php | public function timeStamp($timestamp = null)
{
$ts = $timestamp ?: $this->getAttribute("timeStamp");
if (is_integer($ts) || $ts instanceof TimeWindow) {
return new TimeWindow(["timeStamp" => $ts]);
}
return new TimeWindow();
} | [
"public",
"function",
"timeStamp",
"(",
"$",
"timestamp",
"=",
"null",
")",
"{",
"$",
"ts",
"=",
"$",
"timestamp",
"?",
":",
"$",
"this",
"->",
"getAttribute",
"(",
"\"timeStamp\"",
")",
";",
"if",
"(",
"is_integer",
"(",
"$",
"ts",
")",
"||",
"$",
... | Returns timestamp of the transaction.
@return int | [
"Returns",
"timestamp",
"of",
"the",
"transaction",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction.php#L391-L399 |
evias/nem-php | src/Models/Transaction.php | Transaction.deadline | public function deadline($deadline = null)
{
$ts = $deadline ?: $this->getAttribute("deadline");
if (is_integer($ts) || $ts instanceof TimeWindow) {
return new TimeWindow(["timeStamp" => $ts]);
}
return new TimeWindow();
} | php | public function deadline($deadline = null)
{
$ts = $deadline ?: $this->getAttribute("deadline");
if (is_integer($ts) || $ts instanceof TimeWindow) {
return new TimeWindow(["timeStamp" => $ts]);
}
return new TimeWindow();
} | [
"public",
"function",
"deadline",
"(",
"$",
"deadline",
"=",
"null",
")",
"{",
"$",
"ts",
"=",
"$",
"deadline",
"?",
":",
"$",
"this",
"->",
"getAttribute",
"(",
"\"deadline\"",
")",
";",
"if",
"(",
"is_integer",
"(",
"$",
"ts",
")",
"||",
"$",
"ts... | Returns deadline associated with the transaction
@return int | [
"Returns",
"deadline",
"associated",
"with",
"the",
"transaction"
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction.php#L406-L414 |
evias/nem-php | src/Models/Transaction.php | Transaction.fee | public function fee($fee = null)
{
$amount = $fee ?: $this->getAttribute("fee");
if (!$amount)
$amount = (int) Fee::calculateForTransaction($this);
return new Fee(["amount" => $amount]);
} | php | public function fee($fee = null)
{
$amount = $fee ?: $this->getAttribute("fee");
if (!$amount)
$amount = (int) Fee::calculateForTransaction($this);
return new Fee(["amount" => $amount]);
} | [
"public",
"function",
"fee",
"(",
"$",
"fee",
"=",
"null",
")",
"{",
"$",
"amount",
"=",
"$",
"fee",
"?",
":",
"$",
"this",
"->",
"getAttribute",
"(",
"\"fee\"",
")",
";",
"if",
"(",
"!",
"$",
"amount",
")",
"$",
"amount",
"=",
"(",
"int",
")",... | Mutator for the fee amount object.
@return \NEM\Models\Fee | [
"Mutator",
"for",
"the",
"fee",
"amount",
"object",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction.php#L441-L448 |
evias/nem-php | src/Models/Transaction/MosaicDefinition.php | MosaicDefinition.extend | public function extend()
{
return [
"creationFeeSink" => $this->creationFeeSink()->address()->toClean(),
"creationFee" => Fee::MOSAIC_DEFINITION,
"mosaicDefinition" => $this->mosaicDefinition()->toDTO(),
// transaction type specialization
"type" => TransactionType::MOSAIC_DEFINITION,
];
} | php | public function extend()
{
return [
"creationFeeSink" => $this->creationFeeSink()->address()->toClean(),
"creationFee" => Fee::MOSAIC_DEFINITION,
"mosaicDefinition" => $this->mosaicDefinition()->toDTO(),
// transaction type specialization
"type" => TransactionType::MOSAIC_DEFINITION,
];
} | [
"public",
"function",
"extend",
"(",
")",
"{",
"return",
"[",
"\"creationFeeSink\"",
"=>",
"$",
"this",
"->",
"creationFeeSink",
"(",
")",
"->",
"address",
"(",
")",
"->",
"toClean",
"(",
")",
",",
"\"creationFee\"",
"=>",
"Fee",
"::",
"MOSAIC_DEFINITION",
... | The extend() method must be overloaded by any Transaction Type
which needs to extend the base DTO structure.
@return array | [
"The",
"extend",
"()",
"method",
"must",
"be",
"overloaded",
"by",
"any",
"Transaction",
"Type",
"which",
"needs",
"to",
"extend",
"the",
"base",
"DTO",
"structure",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/MosaicDefinition.php#L67-L76 |
evias/nem-php | src/Models/Transaction/MosaicDefinition.php | MosaicDefinition.serialize | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->extend();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_def = $this->mosaicDefinition()->serialize();
$uint8_len = $serializer->serializeInt(count($uint8_def));
$uint8_sink = $serializer->serializeString($nisData["creationFeeSink"]);
$uint8_fee = $serializer->serializeLong($nisData["creationFee"]);
// concatenate the UInt8 representation
$output = array_merge(
$uint8_len,
$uint8_def,
$uint8_sink,
$uint8_fee);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | php | public function serialize($parameters = null)
{
$baseTx = parent::serialize($parameters);
$nisData = $this->extend();
// shortcuts
$serializer = $this->getSerializer();
$output = [];
// serialize specialized fields
$uint8_def = $this->mosaicDefinition()->serialize();
$uint8_len = $serializer->serializeInt(count($uint8_def));
$uint8_sink = $serializer->serializeString($nisData["creationFeeSink"]);
$uint8_fee = $serializer->serializeLong($nisData["creationFee"]);
// concatenate the UInt8 representation
$output = array_merge(
$uint8_len,
$uint8_def,
$uint8_sink,
$uint8_fee);
// specialized data is concatenated to `base transaction data`.
return ($this->serialized = array_merge($baseTx, $output));
} | [
"public",
"function",
"serialize",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"$",
"baseTx",
"=",
"parent",
"::",
"serialize",
"(",
"$",
"parameters",
")",
";",
"$",
"nisData",
"=",
"$",
"this",
"->",
"extend",
"(",
")",
";",
"// shortcuts",
"$",
... | Overload of the \NEM\Core\Model::serialize() method to provide
with a specialization for *MosaicDefinition transaction* serialization.
@see \NEM\Contracts\Serializable
@param null|string $parameters non-null will return only the named sub-dtos.
@return array Returns a byte-array with values in UInt8 representation. | [
"Overload",
"of",
"the",
"\\",
"NEM",
"\\",
"Core",
"\\",
"Model",
"::",
"serialize",
"()",
"method",
"to",
"provide",
"with",
"a",
"specialization",
"for",
"*",
"MosaicDefinition",
"transaction",
"*",
"serialization",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/Transaction/MosaicDefinition.php#L99-L123 |
evias/nem-php | src/Models/MosaicLevy.php | MosaicLevy.toDTO | public function toDTO($filterByKey = null)
{
if (! $this->getAttribute("recipient") || ! $this->getAttribute("mosaicId"))
return [];
return [
"type" => $this->type,
"recipient" => $this->recipient()->address()->toClean(),
"mosaicId" => $this->mosaicId()->toDTO(),
"fee" => $this->fee,
];
} | php | public function toDTO($filterByKey = null)
{
if (! $this->getAttribute("recipient") || ! $this->getAttribute("mosaicId"))
return [];
return [
"type" => $this->type,
"recipient" => $this->recipient()->address()->toClean(),
"mosaicId" => $this->mosaicId()->toDTO(),
"fee" => $this->fee,
];
} | [
"public",
"function",
"toDTO",
"(",
"$",
"filterByKey",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getAttribute",
"(",
"\"recipient\"",
")",
"||",
"!",
"$",
"this",
"->",
"getAttribute",
"(",
"\"mosaicId\"",
")",
")",
"return",
"[",
"]"... | Mosaic Levy DTO builds a package with offsets `type`,
`recipient`, `mosaicId` and `fee`.
Those fields are required by NIS for the mosaic levy identification.
@return array Associative array with fields present in `$fillable` property. | [
"Mosaic",
"Levy",
"DTO",
"builds",
"a",
"package",
"with",
"offsets",
"type",
"recipient",
"mosaicId",
"and",
"fee",
"."
] | train | https://github.com/evias/nem-php/blob/88cf1674077ed1146b85521db25c09e60c3634bb/src/Models/MosaicLevy.php#L77-L88 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.