sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function beforeRenderIndexType()
{
if (!($this->_action() instanceof IndexAction)) {
return;
}
$controller = $this->_controller();
$controller->set('indexFinderScopes', $this->_getIndexFinderScopes());
$controller->set('indexFormats', $this->_getIndexFormats());
$controller->set('indexType', $this->_getIndexType());
$controller->set('indexTitleField', $this->_getIndexTitleField());
$controller->set('indexBodyField', $this->_getIndexBodyField());
$controller->set('indexImageField', $this->_getIndexImageField());
$controller->set('indexGalleryCssClasses', $this->_getIndexGalleryCssClasses());
}
|
beforeRender event
@return void
|
entailment
|
protected function _getIndexType()
{
$action = $this->_action();
$indexType = $action->getConfig('scaffold.index_type');
if (empty($indexType)) {
$indexType = 'table';
}
return $indexType;
}
|
Returns the index type to show on scaffolded view
@return string
|
entailment
|
protected function _getIndexTitleField()
{
$action = $this->_action();
$field = $action->getConfig('scaffold.index_title_field');
if ($field === null) {
$field = $this->_table()->getDisplayField();
}
return $field;
}
|
Returns the title field to show on scaffolded view
@return string
|
entailment
|
protected function _getIndexBodyField()
{
$action = $this->_action();
$field = $action->getConfig('scaffold.index_body_field');
if ($field === null) {
$field = 'body';
}
return $field;
}
|
Returns the body field to show on scaffolded view
@return string
|
entailment
|
protected function _getIndexImageField()
{
$action = $this->_action();
$field = $action->getConfig('scaffold.index_image_field');
if (empty($field)) {
$field = 'image';
}
return $field;
}
|
Returns the image field to show on scaffolded view
@return string
|
entailment
|
protected function _getIndexGalleryCssClasses()
{
$action = $this->_action();
$field = $action->getConfig('scaffold.index_gallery_css_classes');
if (empty($field)) {
$field = 'col-sm-6 col-md-3';
}
return $field;
}
|
Returns the css classes to use for each gallery entry
@return string
|
entailment
|
protected function _setOptions($options)
{
if (empty($options)) {
$options = [];
}
$url = $this->get('url');
if (!is_array($url)) {
$isHttp = substr($url, 0, 7) === 'http://';
$isHttps = substr($url, 0, 8) === 'https://';
if ($isHttp || $isHttps) {
$options += ['target' => '_blank'];
}
}
return $options;
}
|
options property setter
@param array $options Array of options and HTML attributes.
@return string|array
|
entailment
|
public function display($title, array $links = [])
{
if (is_array($title)) {
$links = $title;
$title = '';
}
$this->set('title', $title);
if (!empty($links)) {
$this->set('links', $links);
}
}
|
Default display method.
If the first argument is an array, it will replace the second
`$links` argument and `$title` will be set to an empty string.
@param string|array $title A title to display
@param array $links A array of LinkItem objects
@return void
|
entailment
|
protected function deprecatedScaffoldKeyNotice($deprecatedKey, $newKey)
{
$template = 'The configuration key %s has been deprecated. Use %s instead.';
$message = sprintf($template, $deprecatedKey, $newKey);
trigger_error($message, E_USER_DEPRECATED);
}
|
Emit a deprecation notice for deprecated configuration key use
@param string $deprecatedKey Name of key that is deprecated
@param string $newKey Name of key that should be used instead of the deprecated key
@return void
|
entailment
|
public function valid()
{
$allowed_values = $this->getInputAllowableValues();
if (!in_array($this->container['input'], $allowed_values)) {
return false;
}
return true;
}
|
validate all the properties in the model
return true if all passed
@return bool True if all properties are valid
|
entailment
|
public function setInput($input)
{
$allowed_values = $this->getInputAllowableValues();
if (!is_null($input) && !in_array($input, $allowed_values)) {
throw new \InvalidArgumentException(
sprintf(
"Invalid value for 'input', must be one of '%s'",
implode("', '", $allowed_values)
)
);
}
$this->container['input'] = $input;
return $this;
}
|
Sets input
@param string $input Specify the input format.
@return $this
|
entailment
|
public function initialize()
{
parent::initialize();
$this->getEventManager()->on($this, ['priority' => 9]);
$this->ensureConfig();
$this->_setupPaths();
$this->_setupHelpers();
}
|
Initialization hook method.
Properties like $helpers etc. cannot be initialized statically in your custom
view class as they are overwritten by values from controller in constructor.
So this method allows you to manipulate them as required after view instance
is constructed.
@return void
|
entailment
|
protected function _loadAssets()
{
if (Configure::read('CrudView.useAssetCompress')) {
$this->AssetCompress->css('CrudView.crudview', ['block' => true]);
$this->AssetCompress->script('CrudView.crudview_head', ['block' => 'headjs']);
$this->AssetCompress->script('CrudView.crudview', ['block' => true]);
return;
}
$config = Configure::read('CrudView');
if (!$config) {
return;
}
if (!empty($config['css'])) {
$this->Html->css($config['css'], ['block' => true]);
}
if (!empty($config['js'])) {
foreach ($config['js'] as $block => $scripts) {
$this->Html->script($scripts, ['block' => $block]);
}
}
}
|
Read from config which css and js files to load, and add them to the output.
If `AssetCompress` plugin is loaded, use the `asset_compress.ini` configuration
that is part of this plugin.
@return void
|
entailment
|
protected function _setupHelpers()
{
$helpers = [
'Html' => ['className' => 'BootstrapUI.Html'],
'Form' => [
'className' => 'BootstrapUI.Form',
'widgets' => [
'datetime' => ['CrudView\View\Widget\DateTimeWidget', 'select']
],
],
'Flash' => ['className' => 'BootstrapUI.Flash'],
'Paginator' => ['className' => 'BootstrapUI.Paginator'],
'CrudView' => ['className' => 'CrudView.CrudView'],
];
if (class_exists('\Cake\View\Helper\BreadcrumbsHelper')) {
$helpers['Breadcrumbs'] = ['className' => 'BootstrapUI.Breadcrumbs'];
}
if (Configure::read('CrudView.useAssetCompress')) {
$helpers['AssetCompress'] = ['className' => 'AssetCompress.AssetCompress'];
}
$this->helpers = array_merge($helpers, $this->helpers);
}
|
Setup helpers
@return void
|
entailment
|
protected function _setupPaths()
{
$paths = Configure::read('App.paths.templates');
$extraPaths = Configure::read('CrudView.templatePaths');
if (!empty($extraPaths)) {
$paths = array_merge($paths, (array)$extraPaths);
}
$paths[] = Plugin::classPath('CrudView') . 'Template' . DS;
Configure::write('App.paths.templates', $paths);
}
|
Initializes the crud-view template paths
@return void
|
entailment
|
public function fetch($name, $default = '')
{
$viewblock = '';
$viewblocks = $this->get('viewblocks', []);
if (!empty($viewblocks[$name])) {
$viewblock = $this->_createViewblock($viewblocks[$name]);
}
$internal = $this->Blocks->get($name, $default);
return $internal . $viewblock;
}
|
Fetch the content for a block. If a block is
empty or undefined '' will be returned.
@param string $name Name of the block
@param string $default Default text
@return string default The block content or $default if the block does not exist.
@see ViewBlock::get()
|
entailment
|
public function exists($name)
{
$viewblocks = $this->get('viewblocks', []);
return !empty($viewblocks[$name]) || $this->Blocks->exists($name);
}
|
Check if a block exists
@param string $name Name of the block
@return bool
|
entailment
|
protected function _createViewblock($data)
{
$output = '';
foreach ($data as $key => $type) {
if ($type === 'element') {
$output = $this->element($key);
} elseif ($type === 'Html::css') {
$output .= $this->Html->css($key);
} elseif ($type === 'Html::script') {
$output .= $this->Html->script($key);
} else {
$output .= $key;
}
}
return $output;
}
|
Constructs a ViewBlock from an array of configured data
@param array $data ViewBlock data
@return string
|
entailment
|
protected function _getViewFileName($name = null)
{
if ($this->templatePath === 'Error') {
return parent::_getViewFileName($name);
}
try {
return parent::_getViewFileName($name);
} catch (MissingTemplateException $exception) {
$this->subDir = null;
$this->templatePath = 'Scaffold';
}
try {
return parent::_getViewFileName($this->template);
} catch (MissingTemplateException $exception) {
return parent::_getViewFileName($name);
}
}
|
Returns filename of given action's template file (.ctp) as a string.
@param string|null $name Controller action to find template filename for.
@return string Template filename
@throws \Cake\View\Exception\MissingTemplateException When a view file could not be found.
|
entailment
|
public function afterPaginate(Event $event)
{
$event;
if (!$this->_table()->behaviors()->has('Search')) {
return;
}
$enabled = $this->getConfig('enabled') ?: !$this->_request()->is('api');
if (!$enabled) {
return;
}
$fields = $this->fields();
$this->_controller()->set('searchInputs', $fields);
}
|
After paginate event callback.
Only after a crud paginate call does this listener do anything. So listen
for that
@param \Cake\Event\Event $event Event.
@return void
|
entailment
|
protected function _deriveFields()
{
$config = $this->getConfig();
$table = $this->_table();
if (method_exists($table, 'searchConfiguration')) {
$searchManager = $table->searchConfiguration();
} else {
$searchManager = $table->searchManager();
}
$fields = [];
$schema = $table->getSchema();
$request = $this->_request();
foreach ($searchManager->getFilters($config['collection']) as $filter) {
if ($filter->getConfig('form') === false) {
continue;
}
$field = $filter->name();
$input = [
'required' => false,
'type' => 'text'
];
if (substr($field, -3) === '_id' && $field !== '_id') {
$input['type'] = 'select';
}
$filterFormConfig = $filter->getConfig('form');
if (!empty($filterFormConfig)) {
$input = $filterFormConfig + $input;
}
$input['value'] = $request->getQuery($field);
if (empty($input['options']) && $schema->getColumnType($field) === 'boolean') {
$input['options'] = ['No', 'Yes'];
$input['type'] = 'select';
}
if (!empty($input['options'])) {
$input['empty'] = true;
if (empty($input['class']) && !$config['selectize']) {
$input['class'] = 'no-selectize';
}
$fields[$field] = $input;
continue;
}
if (empty($input['class']) && $config['autocomplete']) {
$input['class'] = 'autocomplete';
}
$urlArgs = [];
$fieldKeys = isset($input['fields']) ? $input['fields'] : ['id' => $field, 'value' => $field];
if (is_array($fieldKeys)) {
foreach ($fieldKeys as $key => $val) {
$urlArgs[$key] = $val;
}
}
unset($input['fields']);
$url = array_merge(['action' => 'lookup', '_ext' => 'json'], $urlArgs);
$input['data-url'] = Router::url($url);
$fields[$field] = $input;
}
return $fields;
}
|
Derive field options for search filter inputs based on filter collection.
@return array
|
entailment
|
public function listInvalidProperties()
{
$invalid_properties = [];
if ($this->container['name'] === null) {
$invalid_properties[] = "'name' can't be null";
}
if ($this->container['document_type'] === null) {
$invalid_properties[] = "'document_type' can't be null";
}
$allowed_values = $this->getDocumentTypeAllowableValues();
if (!in_array($this->container['document_type'], $allowed_values)) {
$invalid_properties[] = sprintf(
"invalid value for 'document_type', must be one of '%s'",
implode("', '", $allowed_values)
);
}
if ($this->container['document_content'] === null) {
$invalid_properties[] = "'document_content' can't be null";
}
$allowed_values = $this->getStrictAllowableValues();
if (!in_array($this->container['strict'], $allowed_values)) {
$invalid_properties[] = sprintf(
"invalid value for 'strict', must be one of '%s'",
implode("', '", $allowed_values)
);
}
return $invalid_properties;
}
|
show all the invalid properties with reasons.
@return array invalid properties with reasons
|
entailment
|
public function setDocumentType($document_type)
{
$allowed_values = $this->getDocumentTypeAllowableValues();
if (!in_array($document_type, $allowed_values)) {
throw new \InvalidArgumentException(
sprintf(
"Invalid value for 'document_type', must be one of '%s'",
implode("', '", $allowed_values)
)
);
}
$this->container['document_type'] = $document_type;
return $this;
}
|
Sets document_type
@param string $document_type The type of document being created.
@return $this
|
entailment
|
public function setStrict($strict)
{
$allowed_values = $this->getStrictAllowableValues();
if (!is_null($strict) && !in_array($strict, $allowed_values)) {
throw new \InvalidArgumentException(
sprintf(
"Invalid value for 'strict', must be one of '%s'",
implode("', '", $allowed_values)
)
);
}
$this->container['strict'] = $strict;
return $this;
}
|
Sets strict
@param string $strict Force strict HTML validation.
@return $this
|
entailment
|
public function getColumnChildren($column)
{
$children = $this->get('children');
if (isset($children[$column])) {
return $children[$column];
}
return [];
}
|
Returns the children from a given column
@param int $column a column number
@return array
|
entailment
|
public function addToColumn(Cell $module, $column = 1)
{
$children = $this->get('children');
$children[$column][] = $module;
$this->set('children', $children);
return $this;
}
|
Adds a Cell to a given column
@param Cell $module instance of Cell
@param int $column a column number
@return $this
|
entailment
|
protected function _setColumns($value)
{
$columnMap = [
1 => 12,
2 => 6,
3 => 4,
4 => 3,
6 => 2,
12 => 1,
];
if (!in_array($value, [1, 2, 3, 4, 6, 12])) {
throw new InvalidArgumentException('Valid columns value must be one of [1, 2, 3, 4, 6, 12]');
}
$this->set('columnClass', sprintf('col-md-%d', $columnMap[$value]));
return $value;
}
|
columns property setter
@param int $value A column count
@return int
@throws \InvalidArgumentException the column count is invalid
|
entailment
|
public function toPsrRequest(): RequestInterface {
return new Psr7Request(
$this->method,
$this->getUri(),
$this->Headers->toPsr7Array(),
isset($this->body) ? new Psr7Stream($this->body) : null
);
}
|
Constructs a Psr7 compliant request for use in a Psr7 client.
@return \Psr\Http\Message\RequestInterface
|
entailment
|
protected function _getUtilityNavigation()
{
$action = $this->_action();
$utilityNavigation = $action->getConfig('scaffold.utility_navigation');
if ($utilityNavigation === null) {
$utilityNavigation = [
new MenuItem('Account', ['controller' => 'Users', 'action' => 'account']),
new MenuItem('Log Out', ['controller' => 'Users', 'action' => 'logout']),
];
}
return $utilityNavigation;
}
|
Returns the utility navigation to show on scaffolded view
@return array
|
entailment
|
protected function beforeRenderFormType()
{
$controller = $this->_controller();
$controller->set('formEnableDirtyCheck', $this->_getFormEnableDirtyCheck());
$controller->set('formSubmitButtonText', $this->_getFormSubmitButtonText());
$controller->set('formSubmitExtraButtons', $this->_getFormSubmitExtraButtons());
$controller->set('formSubmitExtraLeftButtons', $this->_getFormSubmitExtraLeftButtons());
$controller->set('formUrl', $this->_getFormUrl());
}
|
beforeRender event
@return void
|
entailment
|
protected function _getFormSubmitExtraButtons()
{
$action = $this->_action();
$buttons = $action->getConfig('scaffold.form_submit_extra_buttons');
if ($buttons === false) {
return [];
}
if ($buttons === null || $buttons === true) {
$buttons = $this->_getDefaultExtraButtons();
}
return $buttons;
}
|
Get extra form submit buttons.
@return bool
|
entailment
|
protected function _getFormSubmitExtraLeftButtons()
{
$action = $this->_action();
$buttons = $action->getConfig('scaffold.form_submit_extra_left_buttons');
if ($buttons === false) {
return [];
}
if ($buttons === null || $buttons === true) {
$buttons = $this->_getDefaultExtraLeftButtons();
}
return $buttons;
}
|
Get extra form submit left buttons.
@return bool
|
entailment
|
protected function _getDefaultExtraLeftButtons()
{
$buttons = [];
$action = $this->_action();
if ($action instanceof EditAction) {
$buttons[] = [
'title' => __d('crud', 'Delete'),
'url' => ['action' => 'delete'],
'options' => [
'block' => 'form.after_end',
'class' => 'btn btn-danger btn-delete',
'confirm' => __d('crud', 'Are you sure you want to delete this record?'),
'name' => '_delete',
'style' => 'margin-left: 0',
],
'type' => 'postLink',
'_label' => 'delete',
];
}
return $buttons;
}
|
Get default extra left buttons
@return array
|
entailment
|
public function ServiceRegister(AgentServiceRegistration $agentServiceRegistration) {
$r = new Request('PUT', 'v1/agent/service/register', $this->config, $agentServiceRegistration);
return $this->requireOK($this->doRequest($r))[2];
}
|
Register a service within Consul
@param \DCarbone\PHPConsulAPI\Agent\AgentServiceRegistration $agentServiceRegistration
@return \DCarbone\PHPConsulAPI\Error|null
|
entailment
|
public function ServiceDeregister(string $serviceID) {
$r = new Request('PUT', sprintf('v1/agent/service/deregister/%s', $serviceID), $this->config);
return $this->requireOK($this->doRequest($r))[2];
}
|
Remove a service from Consul
@param string $serviceID
@return \DCarbone\PHPConsulAPI\Error|null
|
entailment
|
public function beforeRenderSiteTitle()
{
$controller = $this->_controller();
$controller->set('siteTitle', $this->_getSiteTitle());
$controller->set('siteTitleLink', $this->_getSiteTitleLink());
$controller->set('siteTitleImage', $this->_getSiteTitleImage());
}
|
beforeRender event
@return void
|
entailment
|
protected function _getSiteTitle()
{
$action = $this->_action();
$title = $action->getConfig('scaffold.site_title');
if (!empty($title)) {
return $title;
}
return Configure::read('CrudView.siteTitle');
}
|
Get the brand name to use in the default template.
@return string
|
entailment
|
protected function _getSiteTitleLink()
{
$action = $this->_action();
$link = $action->getConfig('scaffold.site_title_link');
if (empty($link)) {
$link = '';
}
return $link;
}
|
Returns the sites title link to show on scaffolded view
@return string
|
entailment
|
protected function _getSiteTitleImage()
{
$action = $this->_action();
$image = $action->getConfig('scaffold.site_title_image');
if (empty($image)) {
$image = '';
}
return $image;
}
|
Returns the sites title image to show on scaffolded view
@return string
|
entailment
|
public function process($field, EntityInterface $data, array $options = [])
{
$this->setContext($data);
$value = $this->fieldValue($data, $field);
$options += ['formatter' => null];
if ($options['formatter'] === 'element') {
$context = $this->getContext();
return $this->_View->element($options['element'], compact('context', 'field', 'value', 'options'));
}
if ($options['formatter'] === 'relation') {
$relation = $this->relation($field);
if ($relation) {
return $relation['output'];
}
}
if (is_callable($options['formatter'])) {
return $options['formatter']($field, $value, $this->getContext(), $options, $this->getView());
}
$value = $this->introspect($field, $value, $options);
return $value;
}
|
Process a single field into an output
@param string $field The field to process.
@param \Cake\Datasource\EntityInterface $data The entity data.
@param array $options Processing options.
@return string|null|array|bool|int
|
entailment
|
public function fieldValue(EntityInterface $data, $field)
{
if (empty($data)) {
$data = $this->getContext();
}
return $data->get($field);
}
|
Get the current field value
@param \Cake\Datasource\EntityInterface $data The entity data.
@param string $field The field to extract, if null, the field from the entity context is used.
@return mixed
|
entailment
|
public function introspect($field, $value, array $options = [])
{
$output = $this->relation($field);
if ($output) {
return $output['output'];
}
$type = $this->columnType($field);
$fieldFormatters = $this->getConfig('fieldFormatters');
if (isset($fieldFormatters[$type])) {
if (is_callable($fieldFormatters[$type])) {
return $fieldFormatters[$type]($field, $value, $this->getContext(), $options, $this->getView());
}
return $this->{$fieldFormatters[$type]}($field, $value, $options);
}
if ($type === 'boolean') {
return $this->formatBoolean($field, $value, $options);
}
if (in_array($type, ['datetime', 'date', 'timestamp'])) {
return $this->formatDate($field, $value, $options);
}
if ($type === 'time') {
return $this->formatTime($field, $value, $options);
}
$value = $this->formatString($field, $value);
if ($field === $this->getViewVar('displayField')) {
return $this->formatDisplayField($value, $options);
}
return $value;
}
|
Returns a formatted output for a given field
@param string $field Name of field.
@param mixed $value The value that the field should have within related data.
@param array $options Options array.
@return array|bool|null|int|string
|
entailment
|
public function formatBoolean($field, $value, $options)
{
return (bool)$value ?
$this->Html->label(__d('crud', 'Yes'), ['type' => empty($options['inverted']) ? 'success' : 'danger']) :
$this->Html->label(__d('crud', 'No'), ['type' => empty($options['inverted']) ? 'danger' : 'success']);
}
|
Format a boolean value for display
@param string $field Name of field.
@param mixed $value Value of field.
@param array $options Options array
@return string
|
entailment
|
public function formatDate($field, $value, array $options)
{
if ($value === null) {
return $this->Html->label(__d('crud', 'N/A'), ['type' => 'info']);
}
if (is_int($value) || is_string($value) || $value instanceof DateTime || $value instanceof DateTimeImmutable) {
return $this->Time->timeAgoInWords($value, $options);
}
return $this->Html->label(__d('crud', 'N/A'), ['type' => 'info']);
}
|
Format a date for display
@param string $field Name of field.
@param mixed $value Value of field.
@param array $options Options array.
@return string
|
entailment
|
public function formatTime($field, $value, array $options)
{
if ($value === null) {
return $this->Html->label(__d('crud', 'N/A'), ['type' => 'info']);
}
$format = isset($options['format']) ? $options['format'] : null;
if (is_int($value) || is_string($value) || $value instanceof DateTime || $value instanceof DateTimeImmutable) {
return $this->Time->nice($value, $format);
}
return $this->Html->label(__d('crud', 'N/A'), ['type' => 'info']);
}
|
Format a time for display
@param string $field Name of field.
@param mixed $value Value of field.
@param array $options Options array.
@return string
|
entailment
|
public function relation($field)
{
$associations = $this->associations();
if (empty($associations['manyToOne'])) {
return false;
}
$data = $this->getContext();
if (empty($data)) {
return false;
}
foreach ($associations['manyToOne'] as $alias => $details) {
if ($field !== $details['foreignKey']) {
continue;
}
$entityName = $details['entity'];
if (empty($data->$entityName)) {
return false;
}
$entity = $data->$entityName;
return [
'alias' => $alias,
'output' => $this->Html->link($entity->{$details['displayField']}, [
'plugin' => $details['plugin'],
'controller' => $details['controller'],
'action' => 'view',
$entity->{$details['primaryKey']}
])
];
}
return false;
}
|
Returns a formatted relation output for a given field
@param string $field Name of field.
@return mixed Array of data to output, false if no match found
|
entailment
|
public function redirectUrl()
{
$redirectUrl = $this->getView()->getRequest()->getQuery('_redirect_url');
$redirectUrlViewVar = $this->getViewVar('_redirect_url');
if (!empty($redirectUrlViewVar)) {
$redirectUrl = $redirectUrlViewVar;
} else {
$context = $this->Form->context();
if ($context->val('_redirect_url')) {
$redirectUrl = $context->val('_redirect_url');
}
}
if (empty($redirectUrl)) {
return null;
}
return $this->Form->hidden('_redirect_url', [
'name' => '_redirect_url',
'value' => $redirectUrl,
'id' => null,
'secure' => FormHelper::SECURE_SKIP
]);
}
|
Returns a hidden input for the redirect_url if it exists
in the request querystring, view variables, form data
@return string|null
|
entailment
|
public function createRelationLink($alias, $relation, $options = [])
{
return $this->Html->link(
__d('crud', 'Add {0}', [Inflector::singularize(Inflector::humanize(Inflector::underscore($alias)))]),
[
'plugin' => $relation['plugin'],
'controller' => $relation['controller'],
'action' => 'add',
'?' => [
$relation['foreignKey'] => $this->getViewVar('primaryKeyValue'),
'_redirect_url' => $this->getView()->getRequest()->getUri()->getPath()
]
],
$options
);
}
|
Create relation link.
@param string $alias Model alias.
@param array $relation Relation information.
@param array $options Options array to be passed to the link function
@return string
|
entailment
|
public function createViewLink($title, $options = [])
{
return $this->Html->link(
$title,
['action' => 'view', $this->getContext()->get($this->getViewVar('primaryKey'))],
$options
);
}
|
Create view link.
@param string $title Link title
@param array $options Options array to be passed to the link function
@return string
|
entailment
|
public function getCssClasses()
{
$action = (string)$this->getView()->getRequest()->getParam('action');
$pluralVar = $this->getViewVar('pluralVar');
$viewClasses = (array)$this->getViewVar('viewClasses');
$args = func_get_args();
return implode(
array_unique(array_merge(
[
'scaffold-action',
sprintf('scaffold-action-%s', $action),
sprintf('scaffold-controller-%s', $pluralVar),
sprintf('scaffold-%s-%s', $pluralVar, $action),
],
$args,
$viewClasses
)),
' '
);
}
|
Get css classes
@return string
|
entailment
|
public function display($tables = null, $blacklist = null)
{
if (empty($tables)) {
$connection = ConnectionManager::get('default');
$schema = $connection->getSchemaCollection();
$tables = $schema->listTables();
ksort($tables);
if (!empty($blacklist)) {
$tables = array_diff($tables, $blacklist);
}
}
$normal = [];
foreach ($tables as $table => $config) {
if (is_string($config)) {
$config = ['table' => $config];
}
if (is_int($table)) {
$table = $config['table'];
}
$config += [
'action' => 'index',
'title' => Inflector::humanize($table),
'controller' => Inflector::camelize($table)
];
$normal[$table] = $config;
}
return $this->set('tables', $normal);
}
|
Default cell method.
@param array $tables Tables list.
@param array $blacklist Blacklisted tables list.
@return array
|
entailment
|
public function beforeFind(Event $event)
{
$related = $this->_getRelatedModels();
if ($related === []) {
$this->associations = [];
} else {
$this->associations = $this->_associations(array_keys($related));
}
if (!$event->getSubject()->query->getContain()) {
$event->getSubject()->query->contain($related);
}
}
|
[beforeFind description]
@param \Cake\Event\Event $event Event.
@return void
|
entailment
|
public function beforeRender(Event $event)
{
if ($this->_controller()->getName() === 'Error') {
return;
}
if (!empty($event->getSubject()->entity)) {
$this->_entity = $event->getSubject()->entity;
}
if ($this->associations === null) {
$this->associations = $this->_associations(array_keys($this->_getRelatedModels()));
}
$this->ensureConfig();
$this->beforeRenderFormType();
$this->beforeRenderIndexType();
$this->beforeRenderSiteTitle();
$this->beforeRenderUtilityNavigation();
$this->beforeRenderSidebarNavigation();
$controller = $this->_controller();
$controller->set('actionConfig', $this->_action()->getConfig());
$controller->set('title', $this->_getPageTitle());
$controller->set('breadcrumbs', $this->_getBreadcrumbs());
$associations = $this->associations;
$controller->set(compact('associations'));
$fields = $this->_scaffoldFields($associations);
$controller->set('fields', $fields);
$controller->set('formTabGroups', $this->_getFormTabGroups($fields));
$controller->set('blacklist', $this->_blacklist());
$controller->set('actions', $this->_getControllerActions());
$controller->set('bulkActions', $this->_getBulkActions());
$controller->set('viewblocks', $this->_getViewBlocks());
$controller->set('actionGroups', $this->_getActionGroups());
$controller->set($this->_getPageVariables());
}
|
beforeRender event
@param \Cake\Event\Event $event Event.
@return void
|
entailment
|
public function setFlash(Event $event)
{
unset($event->getSubject()->params['class']);
$event->getSubject()->element = ltrim($event->getSubject()->type);
}
|
Make sure flash messages are properly handled by BootstrapUI.FlashHelper
@param \Cake\Event\Event $event Event.
@return void
|
entailment
|
protected function _getPageTitle()
{
$action = $this->_action();
$title = $action->getConfig('scaffold.page_title');
if (!empty($title)) {
return $title;
}
$scope = $action->getConfig('scope');
$request = $this->_request();
$actionName = Inflector::humanize(Inflector::underscore($request->getParam('action')));
$controllerName = $this->_controllerName();
if ($scope === 'table') {
if ($actionName === 'Index') {
return $controllerName;
}
return sprintf('%s %s', $controllerName, $actionName);
}
$primaryKeyValue = $this->_primaryKeyValue();
if ($primaryKeyValue === null) {
return sprintf('%s %s', $actionName, $controllerName);
}
$displayFieldValue = $this->_displayFieldValue();
if ($displayFieldValue === null || $this->_table()->getDisplayField() == $this->_table()->getPrimaryKey()) {
return sprintf('%s %s #%s', $actionName, $controllerName, $primaryKeyValue);
}
return sprintf('%s %s #%s: %s', $actionName, $controllerName, $primaryKeyValue, $displayFieldValue);
}
|
Returns the sites title to show on scaffolded view
@return string
|
entailment
|
protected function _getRelatedModels($associationTypes = [])
{
$models = $this->_action()->getConfig('scaffold.relations');
if ($models === false) {
return [];
}
if (empty($models)) {
$associations = [];
if (empty($associationTypes)) {
$associations = $this->_table()->associations();
} else {
foreach ($associationTypes as $assocType) {
$associations = array_merge(
$associations,
$this->_table()->associations()->getByType($assocType)
);
}
}
$models = [];
foreach ($associations as $assoc) {
$models[] = $assoc->getName();
}
}
$models = Hash::normalize($models);
$blacklist = $this->_action()->getConfig('scaffold.relations_blacklist');
if (!empty($blacklist)) {
$blacklist = Hash::normalize($blacklist);
$models = array_diff_key($models, $blacklist);
}
foreach ($models as $key => $value) {
if (!is_array($value)) {
$models[$key] = [];
}
}
return $models;
}
|
Get a list of relevant models to contain using Containable
If the user hasn't configured any relations for an action
we assume all relations will be used.
The user can choose to suppress specific relations using the blacklist
functionality.
@param string[] $associationTypes List of association types.
@return array
|
entailment
|
protected function _getPageVariables()
{
$table = $this->_table();
$controller = $this->_controller();
$scope = $this->_action()->getConfig('scope');
$data = [
'modelClass' => $controller->modelClass,
'singularHumanName' => Inflector::humanize(Inflector::underscore(Inflector::singularize($controller->modelClass))),
'pluralHumanName' => Inflector::humanize(Inflector::underscore($controller->getName())),
'singularVar' => Inflector::singularize($controller->getName()),
'pluralVar' => Inflector::variable($controller->getName()),
];
try {
$data += [
'modelSchema' => $table->getSchema(),
'displayField' => $table->getDisplayField(),
'primaryKey' => $table->getPrimaryKey(),
];
} catch (Exception $e) {
// May be empty if there is no table object for the action
}
if ($scope === 'entity') {
$data += [
'primaryKeyValue' => $this->_primaryKeyValue()
];
}
return $data;
}
|
Publish fairly static variables needed in the view
@return array
|
entailment
|
protected function _scaffoldFields(array $associations = [])
{
$action = $this->_action();
$scaffoldFields = (array)$action->getConfig('scaffold.fields');
if (!empty($scaffoldFields)) {
$scaffoldFields = Hash::normalize($scaffoldFields);
}
if (empty($scaffoldFields) || $action->getConfig('scaffold.autoFields')) {
$cols = $this->_table()->getSchema()->columns();
$cols = Hash::normalize($cols);
$scope = $action->getConfig('scope');
if ($scope === 'entity' && !empty($associations['manyToMany'])) {
foreach ($associations['manyToMany'] as $alias => $options) {
$cols[sprintf('%s._ids', $options['entities'])] = [
'multiple' => true
];
}
}
$scaffoldFields = array_merge($cols, $scaffoldFields);
}
// Check for blacklisted fields
$blacklist = $action->getConfig('scaffold.fields_blacklist');
if (!empty($blacklist)) {
$scaffoldFields = array_diff_key($scaffoldFields, array_combine($blacklist, $blacklist));
}
// Make sure all array values are an array
foreach ($scaffoldFields as $field => $options) {
if (!is_array($options)) {
$scaffoldFields[$field] = (array)$options;
}
$scaffoldFields[$field] += ['formatter' => null];
}
$fieldSettings = $action->getConfig('scaffold.field_settings');
if (empty($fieldSettings)) {
$fieldSettings = [];
}
$fieldSettings = array_intersect_key($fieldSettings, $scaffoldFields);
$scaffoldFields = Hash::merge($scaffoldFields, $fieldSettings);
return $scaffoldFields;
}
|
Returns fields to be displayed on scaffolded template
@param array $associations Associations list.
@return array
|
entailment
|
protected function _controllerName()
{
$inflections = [
'underscore',
'humanize',
];
if ($this->_action()->scope() === 'entity') {
$inflections[] = 'singularize';
}
$baseName = $this->_controller()->getName();
foreach ($inflections as $inflection) {
$baseName = Inflector::$inflection($baseName);
}
return $baseName;
}
|
Get the controller name based on the Crud Action scope
@return string
|
entailment
|
protected function _getControllerActions()
{
$table = $entity = [];
$actions = $this->_getAllowedActions();
foreach ($actions as $actionName => $config) {
list($scope, $actionConfig) = $this->_getControllerActionConfiguration($actionName, $config);
${$scope}[$actionName] = $actionConfig;
}
$actionBlacklist = [];
$groups = $this->_action()->getConfig('scaffold.action_groups') ?: [];
foreach ($groups as $group) {
$group = Hash::normalize($group);
foreach ($group as $actionName => $config) {
if (isset($table[$actionName]) || isset($entity[$actionName])) {
continue;
}
if ($config === null) {
$config = [];
}
list($scope, $actionConfig) = $this->_getControllerActionConfiguration($actionName, $config);
$realAction = Hash::get($actionConfig, 'url.action', $actionName);
if (!isset(${$scope}[$realAction])) {
continue;
}
$actionBlacklist[] = $realAction;
${$scope}[$actionName] = $actionConfig;
}
}
foreach ($actionBlacklist as $actionName) {
unset($table[$actionName]);
unset($entity[$actionName]);
}
return compact('table', 'entity');
}
|
Returns groupings of action types on the scaffolded view
Includes derived actions from scaffold.action_groups
@return array
|
entailment
|
protected function _getControllerActionConfiguration($actionName, $config)
{
$realAction = Hash::get($config, 'url.action', $actionName);
if ($this->_crud()->isActionMapped($realAction)) {
$action = $this->_action($realAction);
$class = get_class($action);
$class = substr($class, strrpos($class, '\\') + 1);
if ($class === 'DeleteAction') {
$config += ['method' => 'DELETE'];
}
if (!isset($config['scope'])) {
$config['scope'] = $class === 'AddAction' ? 'table' : $action->scope();
}
}
// apply defaults if necessary
$scope = isset($config['scope']) ? $config['scope'] : 'entity';
$method = isset($config['method']) ? $config['method'] : 'GET';
$title = !empty($config['link_title']) ? $config['link_title'] : Inflector::humanize(Inflector::underscore($actionName));
$url = ['action' => $realAction];
if (isset($config['url'])) {
$url = $config['url'] + $url;
}
$actionConfig = [
'title' => $title,
'url' => $url,
'method' => $method,
'options' => array_diff_key(
$config,
array_flip(['method', 'scope', 'link_title', 'url', 'scaffold', 'callback'])
)
];
if (!empty($config['callback'])) {
$actionConfig['callback'] = $config['callback'];
}
return [$scope, $actionConfig];
}
|
Returns url action configuration for a given action.
This is used to figure out how a given action should be linked to.
@param string $actionName Action name.
@param array $config Config array.
@return array
|
entailment
|
protected function _getAllowedActions()
{
$actions = $this->_action()->getConfig('scaffold.actions');
if ($actions === null) {
$actions = array_keys($this->_crud()->getConfig('actions'));
}
$extraActions = $this->_action()->getConfig('scaffold.extra_actions') ?: [];
$allActions = array_merge(
$this->_normalizeActions($actions),
$this->_normalizeActions($extraActions)
);
$blacklist = (array)$this->_action()->getConfig('scaffold.actions_blacklist');
$blacklist = array_combine($blacklist, $blacklist);
foreach ($this->_crud()->getConfig('actions') as $action => $config) {
if ($config['className'] === 'Crud.Lookup') {
$blacklist[$action] = $action;
}
}
return array_diff_key($allActions, $blacklist);
}
|
Returns a list of action configs that are allowed to be shown
@return array
|
entailment
|
protected function _normalizeActions($actions)
{
$normalized = [];
foreach ($actions as $key => $config) {
if (is_array($config)) {
$normalized[$key] = $config;
} else {
$normalized[$config] = [];
}
}
return $normalized;
}
|
Convert mixed action configs to unified structure
[
'ACTION_1' => [..config...],
'ACTION_2' => [..config...],
'ACTION_N' => [..config...]
]
@param array $actions Actions
@return array
|
entailment
|
protected function _associations(array $whitelist = [])
{
$table = $this->_table();
$associationConfiguration = [];
$associations = $table->associations();
$keys = $associations->keys();
if (!empty($whitelist)) {
$keys = array_intersect($keys, array_map('strtolower', $whitelist));
}
foreach ($keys as $associationName) {
$association = $associations->get($associationName);
$type = $association->type();
if (!isset($associationConfiguration[$type])) {
$associationConfiguration[$type] = [];
}
$assocKey = $association->getName();
$associationConfiguration[$type][$assocKey]['model'] = $assocKey;
$associationConfiguration[$type][$assocKey]['type'] = $type;
$associationConfiguration[$type][$assocKey]['primaryKey'] = $association->getTarget()->getPrimaryKey();
$associationConfiguration[$type][$assocKey]['displayField'] = $association->getTarget()->getDisplayField();
$associationConfiguration[$type][$assocKey]['foreignKey'] = $association->getForeignKey();
$associationConfiguration[$type][$assocKey]['propertyName'] = $association->getProperty();
$associationConfiguration[$type][$assocKey]['plugin'] = pluginSplit($association->getClassName())[0];
$associationConfiguration[$type][$assocKey]['controller'] = $assocKey;
$associationConfiguration[$type][$assocKey]['entity'] = Inflector::singularize(Inflector::underscore($assocKey));
$associationConfiguration[$type][$assocKey]['entities'] = Inflector::underscore($assocKey);
$associationConfiguration[$type][$assocKey] = array_merge($associationConfiguration[$type][$assocKey], $this->_action()->getConfig('association.' . $assocKey) ?: []);
}
return $associationConfiguration;
}
|
Returns associations for controllers models.
@param array $whitelist Whitelist of associations to return.
@return array Associations for model
|
entailment
|
protected function _primaryKeyValue()
{
$fields = (array)$this->_table()->getPrimaryKey();
$values = [];
foreach ($fields as $field) {
$values[] = $this->_deriveFieldFromContext($field);
}
if (count($values) === 1) {
return $values[0];
}
return $values;
}
|
Derive the Model::primaryKey value from the current context
If no value can be found, NULL is returned
@return array|string
|
entailment
|
protected function _deriveFieldFromContext($field)
{
$controller = $this->_controller();
$entity = $this->_entity();
$request = $this->_request();
$value = $entity->get($field);
if ($value) {
return $value;
}
$path = "{$controller->modelClass}.{$field}";
if (!empty($request->getData())) {
$value = Hash::get((array)$request->getData(), $path);
}
$singularVar = Inflector::variable($controller->modelClass);
if (!empty($controller->viewVars[$singularVar])) {
$value = $entity->get($field);
}
return $value;
}
|
Extract a field value from a either ServerRequest::getData()
or Controller::$viewVars for the current model + the supplied field
@param string $field Name of field.
@return mixed
|
entailment
|
protected function _getActionGroups()
{
$action = $this->_action();
$groups = $action->getConfig('scaffold.action_groups') ?: [];
$groupedActions = [];
foreach ($groups as $group) {
$groupedActions[] = array_keys(Hash::normalize($group));
}
// add "primary" actions (primary should rendered as separate buttons)
$groupedActions = (new Collection($groupedActions))->unfold()->toList();
$groups['primary'] = array_diff(array_keys($this->_getAllowedActions()), $groupedActions);
return $groups;
}
|
Get action groups
@return array
|
entailment
|
protected function _getFormTabGroups(array $fields = [])
{
$action = $this->_action();
$groups = $action->getConfig('scaffold.form_tab_groups');
if (empty($groups)) {
return [];
}
$groupedFields = (new Collection($groups))->unfold()->toList();
$unGroupedFields = array_diff(array_keys($fields), $groupedFields);
if (!empty($unGroupedFields)) {
$primayGroup = $action->getConfig('scaffold.form_primary_tab') ?: __d('crud', 'Primary');
$groups = [$primayGroup => $unGroupedFields] + $groups;
}
return $groups;
}
|
Get field tab groups
@param array $fields Form fields.
@return array
|
entailment
|
public function render(array $data, ContextInterface $context)
{
$id = $data['id'];
$name = $data['name'];
$val = $data['val'];
$type = $data['type'];
$required = $data['required'] ? 'required' : '';
$disabled = isset($data['disabled']) && $data['disabled'] ? 'disabled' : '';
$role = isset($data['role']) ? $data['role'] : 'datetime-picker';
$format = null;
$locale = isset($data['locale']) ? $data['locale'] : I18n::getLocale();
$timezoneAware = Configure::read('CrudView.timezoneAwareDateTimeWidget');
$timestamp = null;
$timezoneOffset = null;
if (isset($data['data-format'])) {
$format = $this->_convertPHPToMomentFormat($data['data-format']);
}
if (!($val instanceof DateTimeInterface) && !empty($val)) {
switch ($type) {
case 'date':
case 'time':
$val = Type::build($type)->marshal($val);
break;
default:
$val = Type::build('datetime')->marshal($val);
}
}
if ($val && !is_string($val)) {
if ($timezoneAware) {
$timestamp = $val->format('U');
$dateTimeZone = new DateTimeZone(date_default_timezone_get());
$timezoneOffset = ($dateTimeZone->getOffset($val) / 60);
}
$val = $val->format($type === 'date' ? 'Y-m-d' : 'Y-m-d H:i:s');
}
if ($format === null) {
if ($type === 'date') {
$format = 'L';
} elseif ($type === 'time') {
$format = 'LT';
} else {
$format = 'L LT';
}
}
$icon = $type === 'time'
? 'time'
: 'calendar';
$widget = <<<html
<div class="input-group $type">
<input
type="text"
class="form-control"
name="$name"
value="$val"
id="$id"
role="$role"
data-locale="$locale"
data-format="$format"
html;
if ($timezoneAware && isset($timestamp, $timezoneOffset)) {
$widget .= <<<html
data-timestamp="$timestamp"
data-timezone-offset="$timezoneOffset"
html;
}
$widget .= <<<html
$required
$disabled
/>
<label for="$id" class="input-group-addon">
<span class="glyphicon glyphicon-$icon"></span>
</label>
</div>
html;
return $widget;
}
|
Renders a date time widget.
@param array $data Data to render with.
@param \Cake\View\Form\ContextInterface $context The current form context.
@return string A generated select box.
@throws \RuntimeException When option data is invalid.
|
entailment
|
public function getImagePath($logicalImageName)
{
$pos = strpos($logicalImageName, ':');
// add support for ::$imagePath syntax as in twig
// @see http://symfony.com/doc/current/book/page_creation.html#optional-step-3-create-the-template
if($pos === false || $pos === 0)
{
return $this->kernel->getRootDir() . '/Resources/public/images/' . ltrim($logicalImageName, ':');
}
$bundleName = substr($logicalImageName, 0, $pos);
$imageName = substr($logicalImageName, $pos + 1);
$bundle = $this->kernel->getBundle($bundleName);
$bundlePath = $bundle->getPath();
return $bundlePath.'/Resources/public/images/'.$imageName;
}
|
Converts image logical name in "BundleName:image-name.extension" format to absolute file path.
@return string file path
@throws /InvalidArgumentException If bundle does not exist.
|
entailment
|
public function usingAutomaticFormatGuessingAction($name)
{
$format = $this->get('request')->get('_format');
return $this->render(sprintf('PsPdfBundle:Example:usingAutomaticFormatGuessing.%s.twig', $format), array(
'name' => $name,
));
}
|
Possible custom headers and external stylesheet file
@Pdf(
headers={"Expires"="Sat, 1 Jan 2000 12:00:00 GMT"},
stylesheet="PsPdfBundle:Example:pdfStylesheet.xml.twig",
enableCache=true
)
|
entailment
|
public function examplesAction()
{
$kernelRootDir = $this->container->getParameter('kernel.root_dir');
$propablyPhpPdfExamplesFilePaths = array($kernelRootDir.'/../vendor/PHPPdf/examples/index.php', $kernelRootDir.'/../vendor/psliwa/php-pdf/examples/index.php');
foreach($propablyPhpPdfExamplesFilePaths as $propablyPhpPdfExamplesFilePath)
{
if(file_exists($propablyPhpPdfExamplesFilePath))
{
require $propablyPhpPdfExamplesFilePath;
exit();
}
}
throw new NotFoundHttpException('File with PHPPdf examples not found.');
}
|
Standard examples of PHPPdf library
|
entailment
|
public function run()
{
$this->echoLoadingTags();
$assets = CoreAsset::register($this->view);
if ($this->theme === true) { // Register the theme
ThemeAsset::register($this->view);
}
if (isset($this->options['language'])) {
$assets->language = $this->options['language'];
}
$assets->googleCalendar = $this->googleCalendar;
$this->clientOptions['header'] = $this->header;
$this->view->registerJs(implode("\n", [
"jQuery('#{$this->options['id']}').fullCalendar({$this->getClientOptions()});",
]), \yii\web\View::POS_READY);
}
|
Load the options and start the widget
|
entailment
|
private function echoLoadingTags()
{
echo \yii\helpers\Html::beginTag('div', $this->options) . "\n";
echo \yii\helpers\Html::beginTag('div', ['class' => 'fc-loading', 'style' => 'display:none;']);
echo \yii\helpers\Html::encode($this->loading);
echo \yii\helpers\Html::endTag('div') . "\n";
echo \yii\helpers\Html::endTag('div') . "\n";
}
|
Echo the tags to show the loading state for the calendar
|
entailment
|
public function dump($array, $indent = false, $wordwrap = false)
{
// Dumps to some very clean YAML. We'll have to add some more features
// and options soon. And better support for folding.
// New features and options.
if ($indent === false or !is_numeric($indent)) {
$this->dumpIndent = 2;
} else {
$this->dumpIndent = $indent;
}
if ($wordwrap === false or !is_numeric($wordwrap)) {
$this->dumpWordWrap = 40;
} else {
$this->dumpWordWrap = $wordwrap;
}
// New YAML document
$string = "---\n";
// Start at the base of the array and move through it.
if ($array) {
$array = (array)$array;
$previous_key = -1;
foreach ($array as $key => $value) {
if (!isset($first_key)) {
$first_key = $key;
}
$string .= $this->yamlize($key,$value,0,$previous_key, $first_key, $array);
$previous_key = $key;
}
}
return $string;
}
|
Dump PHP array to YAML
The dump method, when supplied with an array, will do its best
to convert the array into friendly YAML. Pretty simple. Feel free to
save the returned string as tasteful.yaml and pass it around.
Oh, and you can decide how big the indent is and what the wordwrap
for folding is. Pretty cool -- just pass in 'false' for either if
you want to use the default.
Indent's default is 2 spaces, wordwrap's default is 40 characters. And
you can turn off wordwrap by passing in 0.
@access public
@return string
@param array $array PHP array
@param int $indent Pass in false to use the default, which is 2
@param int $wordwrap Pass in 0 for no wordwrap, false for default (40)
|
entailment
|
private function yamlize($key, $value, $indent, $previous_key = -1, $first_key = 0, $source_array = null)
{
if (is_array($value)) {
if (empty ($value)) {
return $this->dumpNode($key, array(), $indent, $previous_key, $first_key, $source_array);
}
// It has children. What to do?
// Make it the right kind of item
$string = $this->dumpNode($key, self::REMPTY, $indent, $previous_key, $first_key, $source_array);
// Add the indent
$indent += $this->dumpIndent;
// Yamlize the array
$string .= $this->yamlizeArray($value,$indent);
} elseif (!is_array($value)) {
// It doesn't have children. Yip.
$string = $this->dumpNode($key, $value, $indent, $previous_key, $first_key, $source_array);
}
return $string;
}
|
Attempts to convert a key / value array item to YAML
@access private
@return string
@param $key The name of the key
@param $value The value of the item
@param $indent The indent of the current node
|
entailment
|
private function yamlizeArray($array, $indent)
{
if (is_array($array)) {
$string = '';
$previous_key = -1;
foreach ($array as $key => $value) {
if (!isset($first_key)) {
$first_key = $key;
}
$string .= $this->yamlize($key, $value, $indent, $previous_key, $first_key, $array);
$previous_key = $key;
}
return $string;
} else {
return false;
}
}
|
Attempts to convert an array to YAML
@access private
@return string
@param $array The array you want to convert
@param $indent The indent of the current level
|
entailment
|
private function dumpNode($key, $value, $indent, $previous_key = -1, $first_key = 0, $source_array = null)
{
// do some folding here, for blocks
if (is_string ($value) && ((strpos($value,"\n") !== false || strpos($value,": ") !== false ||
strpos($value,"- ") !== false || strpos($value,"*") !== false || strpos($value,"#") !== false ||
strpos($value,"<") !== false || strpos($value,">") !== false || strpos ($value, ' ') !== false ||
strpos($value,"[") !== false || strpos($value,"]") !== false || strpos($value,"{") !== false ||
strpos($value,"}") !== false) || strpos($value,"&") !== false || strpos($value, "'") !== false ||
strpos($value, "!") === 0 || substr ($value, -1, 1) == ':')
) {
$value = $this->doLiteralBlock($value,$indent);
} else {
$value = $this->doFolding($value,$indent);
}
if ($value === array()) {
$value = '[ ]';
}
if (in_array ($value, array ('true', 'TRUE', 'false', 'FALSE', 'y', 'Y', 'n', 'N', 'null', 'NULL'), true)) {
$value = $this->doLiteralBlock($value,$indent);
}
if (trim ($value) != $value) {
$value = $this->doLiteralBlock($value,$indent);
}
if (is_bool($value)) {
$value = ($value) ? "true" : "false";
}
if ($value === null) {
$value = 'null';
}
if ($value === "'" . self::REMPTY . "'") {
$value = null;
}
$spaces = str_repeat(' ',$indent);
//if (is_int($key) && $key - 1 == $previous_key && $first_key===0) {
if (is_array($source_array) && array_keys($source_array) === range(0, count($source_array) - 1)) {
// It's a sequence
$string = $spaces.'- '.$value."\n";
} else {
//if ($first_key===0) {
// throw new Exception('Keys are all screwy. The first one was zero, now it\'s "'. $key .'"');
//}
// It's mapped
if (strpos($key, ":") !== false || strpos($key, "#") !== false) {
$key = '"' . $key . '"';
}
$string = rtrim ($spaces.$key.': '.$value)."\n";
}
return $string;
}
|
Returns YAML from a key and a value
@access private
@return string
@param $key The name of the key
@param $value The value of the item
@param $indent The indent of the current node
|
entailment
|
private function doLiteralBlock($value, $indent)
{
if ($value === "\n") {
return '\n';
}
if (strpos($value, "\n") === false && strpos($value, "'") === false) {
return sprintf ("'%s'", $value);
}
if (strpos($value, "\n") === false && strpos($value, '"') === false) {
return sprintf ('"%s"', $value);
}
$exploded = explode("\n",$value);
$newValue = '|';
$indent += $this->dumpIndent;
$spaces = str_repeat(' ',$indent);
foreach ($exploded as $line) {
$newValue .= "\n" . $spaces . $line;
}
return $newValue;
}
|
Creates a literal block for dumping
@access private
@return string
@param $value
@param $indent int The value of the indent
|
entailment
|
private function doFolding($value, $indent)
{
// Don't do anything if wordwrap is set to 0
if ($this->dumpWordWrap !== 0 && is_string ($value) && strlen($value) > $this->dumpWordWrap) {
$indent += $this->dumpIndent;
$indent = str_repeat(' ',$indent);
$wrapped = wordwrap($value,$this->dumpWordWrap,"\n$indent");
$value = ">\n".$indent.$wrapped;
} else {
if ($this->settingDumpForceQuotes && is_string ($value) && $value !== self::REMPTY) {
$value = '"' . $value . '"';
}
}
return $value;
}
|
Folds a string of text, if necessary
@access private
@return string
@param $value The string you wish to fold
|
entailment
|
private function loadWithSource($Source)
{
if (empty ($Source)) {
return array();
}
if ($this->settingUseSyckIsPossible && function_exists ('syck_load')) {
$array = syck_load (implode ('', $Source));
return is_array($array) ? $array : array();
}
$this->path = array();
$this->result = array();
$cnt = count($Source);
for ($i = 0; $i < $cnt; $i++) {
$line = $Source[$i];
$this->indent = strlen($line) - strlen(ltrim($line));
$tempPath = $this->getParentPathByIndent($this->indent);
$line = self::stripIndent($line, $this->indent);
if (self::isComment($line)) {
continue;
}
if (self::isEmpty($line)) {
continue;
}
$this->path = $tempPath;
$literalBlockStyle = self::startsLiteralBlock($line);
if ($literalBlockStyle) {
$line = rtrim ($line, $literalBlockStyle . " \n");
$literalBlock = '';
$line .= $this->LiteralPlaceHolder;
$literal_block_indent = strlen($Source[$i+1]) - strlen(ltrim($Source[$i+1]));
while (++$i < $cnt && $this->literalBlockContinues($Source[$i], $this->indent)) {
$literalBlock = $this->addLiteralLine(
$literalBlock, $Source[$i], $literalBlockStyle, $literal_block_indent
);
}
$i--;
}
while (++$i < $cnt && self::greedilyNeedNextLine($line)) {
$line = rtrim($line, " \n\t\r") . ' ' . ltrim($Source[$i], " \t");
}
$i--;
if (strpos($line, '#')) {
if (strpos($line, '"') === false && strpos($line, "'") === false) {
$line = preg_replace('/\s+#(.+)$/','',$line);
}
}
$lineArray = $this->parseLine($line);
if ($literalBlockStyle) {
$lineArray = $this->revertLiteralPlaceHolder ($lineArray, $literalBlock);
}
$this->addArray($lineArray, $this->indent);
foreach ($this->delayedPath as $indent => $delayedPath) {
$this->path[$indent] = $delayedPath;
}
$this->delayedPath = array();
}
return $this->result;
}
|
LOADING FUNCTIONS
|
entailment
|
private function parseLine($line)
{
if (!$line) {
return array();
}
$line = trim($line);
if (!$line) {
return array();
}
$array = array();
$group = $this->nodeContainsGroup($line);
if ($group) {
$this->addGroup($line, $group);
$line = $this->stripGroup ($line, $group);
}
if ($this->startsMappedSequence($line)) {
return $this->returnMappedSequence($line);
}
if ($this->startsMappedValue($line)) {
return $this->returnMappedValue($line);
}
if ($this->isArrayElement($line)) {
return $this->returnArrayElement($line);
}
if ($this->isPlainArray($line)) {
return $this->returnPlainArray($line);
}
return $this->returnKeyValuePair($line);
}
|
Parses YAML code and returns an array for a node
@access private
@return array
@param string $line A line from the YAML file
|
entailment
|
public static function fromDict($rsp, $txnType, $returnType = 'HpsCheckResponse')
{
$response = $rsp->Transaction->$txnType;
$sale = parent::fromDict($rsp, $txnType, $returnType);
$sale->responseCode = (isset($response->RspCode) ? (string)$response->RspCode : null);
$sale->responseText = (isset($response->RspMessage) ? (string)$response->RspMessage : null);
$sale->authorizationCode = (isset($response->AuthCode) ? (string)$response->AuthCode : null);
if ($response->CheckRspInfo) {
$sale->details = array();
$checkInfo = $response->CheckRspInfo;
if (count($checkInfo) > 1) {
foreach ($checkInfo as $details) {
$sale->details[] = self::_hydrateRspDetails($details);
}
} else {
$sale->details = self::_hydrateRspDetails($checkInfo);
}
}
return $sale;
}
|
@param $rsp
@param $txnType
@param string $returnType
@return mixed
|
entailment
|
private static function _hydrateRspDetails($checkInfo)
{
$details = new HpsCheckResponseDetails();
$details->messageType = (isset($checkInfo->Type) ? (string)$checkInfo->Type : null);
$details->code = (isset($checkInfo->Code) ? (string)$checkInfo->Code : null);
$details->message = (isset($checkInfo->Message) ? (string)$checkInfo->Message : null);
$details->fieldNumber = (isset($checkInfo->FieldNumber) ? (string)$checkInfo->FieldNumber : null);
$details->fieldName = (isset($checkInfo->FieldName) ? (string)$checkInfo->FieldName : null);
return $details;
}
|
@param $checkInfo
@return \HpsCheckResponseDetails
|
entailment
|
protected function addValidation($callback, $exceptionType, $exceptionMessage = '')
{
$this->validations[] = array(
'callback' => $callback,
'exceptionType' => $exceptionType,
'exceptionMessage' => $exceptionMessage,
);
return $this;
}
|
@param callable $callback
@param string $exceptionType
@param string $exceptionMessage
@return HpsBuilderAbstract
|
entailment
|
private function setPropertyIfExists($property, $value)
{
if (property_exists($this, $property)) {
if ($value == null) {
return $this;
}
$action = new HpsBuilderAction($property, array($this, 'setProperty'));
$action->arguments = array($property, $value);
$this->addAction($action);
} else {
throw new HpsUnknownPropertyException($this, $property);
}
return $this;
}
|
Sets a property if it exists on the current object.
@param string $property
@param mixed $value
@throws HpsUnknownPropertyException
@return null
|
entailment
|
public static function fromDict($rsp, $txnType, $returnType = 'HpsAltPaymentAuth')
{
$authorize = $rsp->Transaction->$txnType;
$auth = parent::fromDict($rsp, $txnType, $returnType);
$auth->status = isset($authorize->Status) ? (string)$authorize->Status : null;
$auth->statusMessage = isset($authorize->StatusMessage) ? (string)$authorize->StatusMessage : null;
return $auth;
}
|
@param $rsp
@param $txnType
@param string $returnType
@return mixed
|
entailment
|
public static function fromDict($rsp, $txnType, $returnType = 'HpsReportTransactionDetails')
{
$reportResponse = $rsp->Transaction->$txnType;
$details = parent::fromDict($rsp, $txnType, $returnType);
$details->originalTransactionId = (isset($reportResponse->OriginalGatewayTxnId) ? (string)$reportResponse->OriginalGatewayTxnId : null);
$details->authorizedAmount = (isset($reportResponse->Data->AuthAmt) ? (string)$reportResponse->Data->AuthAmt : null);
$details->maskedCardNumber = (isset($reportResponse->Data->MaskedCardNbr) ? (string)$reportResponse->Data->MaskedCardNbr : null);
$details->authorizationCode = (isset($reportResponse->Data->AuthCode) ? (string)$reportResponse->Data->AuthCode : null);
$details->avsResultCode = (isset($reportResponse->Data->AVSRsltCode) ? (string)$reportResponse->Data->AVSRsltCode : null);
$details->avsResultText = (isset($reportResponse->Data->AVSRsltText) ? (string)$reportResponse->Data->AVSRsltText : null);
$details->cardType = (isset($reportResponse->Data->CardType) ? (string)$reportResponse->Data->CardType : null);
$details->descriptor = (isset($reportResponse->Data->TxnDescriptor) ? (string)$reportResponse->Data->TxnDescriptor : null);
$details->transactionType = (isset($reportResponse->ServiceName) ? HpsTransaction::serviceNameToTransactionType((string)$reportResponse->ServiceName) : null);
$details->transactionUTCDate = (isset($reportResponse->RspUtcDT) ? (string)$reportResponse->RspUtcDT : null);
$details->cpcIndicator = (isset($reportResponse->Data->CPCInd) ? (string)$reportResponse->Data->CPCInd : null);
$details->cvvResultCode = (isset($reportResponse->Data->CVVRsltCode) ? (string)$reportResponse->Data->CVVRsltCode : null);
$details->cvvResultText = (isset($reportResponse->Data->CVVRsltText) ? (string)$reportResponse->Data->CVVRsltText : null);
$details->referenceNumber = (isset($reportResponse->Data->RefNbr) ? (string)$reportResponse->Data->RefNbr : null);
$details->responseCode = (isset($reportResponse->Data->RspCode) ? (string)$reportResponse->Data->RspCode : null);
$details->responseText = (isset($reportResponse->Data->RspText) ? (string)$reportResponse->Data->RspText : null);
$details->transactionStatus = (isset($reportResponse->Data->TxnStatus) ? (string)$reportResponse->Data->TxnStatus : null);
$details->gratuityAmount = (isset($reportResponse->Data->GratuityAmtInfo) ? (string)$reportResponse->Data->GratuityAmtInfo : null);
$details->settlementAmount = (isset($reportResponse->Data->SettlementAmt) ? (string)$reportResponse->Data->SettlementAmt : null);
$details->convenienceAmount = (isset($reportResponse->Data->ConvenienceAmtInfo) ? (string)$reportResponse->Data->ConvenienceAmtInfo : null);
$details->shippingAmount = (isset($reportResponse->Data->ShippingAmtInfo) ? (string)$reportResponse->Data->ShippingAmtInfo : null);
if (isset($reportResponse->Data->TokenizationMsg)) {
$details->tokenData = new HpsTokenData();
$details->tokenData->responseMessage = (string)$reportResponse->Data->TokenizationMsg;
}
if (isset($reportResponse->Data->AdditionalTxnFields)) {
$additionalTxnFields = $reportResponse->Data->AdditionalTxnFields;
$details->memo = (isset($additionalTxnFields->Description) ? (string)$additionalTxnFields->Description : null);
$details->invoiceNumber = (isset($additionalTxnFields->InvoiceNbr) ? (string)$additionalTxnFields->InvoiceNbr : null);
$details->customerId = (isset($additionalTxnFields->CustomerID) ? (string)$additionalTxnFields->CustomerID : null);
}
if ((string)$reportResponse->GatewayRspCode != '0' && (string)$reportResponse->Data->RspCode != '00') {
if ($details->exceptions == null) {
$details->exceptions = new HpsChargeExceptions();
}
$details->exceptions->issuerException = HpsIssuerResponseValidation::getException(
(string)$rsp->Header->GatewayTxnId,
(string)$reportResponse->Data->RspCode,
(string)$reportResponse->Data->RspText,
'credit'
);
}
return $details;
}
|
@param $rsp
@param $txnType
@param string $returnType
@return mixed
|
entailment
|
public static function fromDict($rsp, $txnType, $returnType = 'HpsTransaction')
{
$transaction = new $returnType();
// Hydrate the header
$transaction->_header = new HpsTransactionHeader();
$transaction->_header->gatewayResponseCode = (string)$rsp->Header->GatewayRspCode;
$transaction->_header->gatewayResponseMessage = (string)$rsp->Header->GatewayRspMsg;
$transaction->_header->responseDt = (string)$rsp->Header->RspDT;
$transaction->_header->clientTxnId = (isset($rsp->Header->ClientTxnId) ? (string)$rsp->Header->ClientTxnId : null);
$transaction->transactionId = (string)$rsp->Header->GatewayTxnId;
if (isset($rsp->Header->ClientTxnId)) {
$transaction->clientTransactionId = (string)$rsp->Header->ClientTxnId;
}
// Hydrate the body
if (!isset($rsp->Transaction) || !isset($rsp->Transaction->{$txnType})) {
return $transaction;
}
// Hydrate the body
$item = $rsp->Transaction->{$txnType};
if ($item != null) {
$transaction->responseCode = (isset($item->RspCode) ? (string)$item->RspCode : null);
$transaction->responseText = (isset($item->RspText) ? (string)$item->RspText : null);
$transaction->referenceNumber = (isset($item->RefNbr) ? (string)$item->RefNbr : null);
}
return $transaction;
}
|
@param $rsp
@param $txnType
@param string $returnType
@return mixed
|
entailment
|
public static function transactionTypeToServiceName($transactionType)
{
switch ($transactionType) {
case HpsTransactionType::AUTHORIZE:
return HpsItemChoiceTypePosResponseVer10Transaction::CREDIT_AUTH;
break;
case HpsTransactionType::CAPTURE:
return HpsItemChoiceTypePosResponseVer10Transaction::CREDIT_ADD_TO_BATCH;
break;
case HpsTransactionType::CHARGE:
return HpsItemChoiceTypePosResponseVer10Transaction::CREDIT_SALE;
break;
case HpsTransactionType::REFUND:
return HpsItemChoiceTypePosResponseVer10Transaction::CREDIT_RETURN;
break;
case HpsTransactionType::REVERSE:
return HpsItemChoiceTypePosResponseVer10Transaction::CREDIT_REVERSAL;
break;
case HpsTransactionType::VERIFY:
return HpsItemChoiceTypePosResponseVer10Transaction::CREDIT_ACCOUNT_VERIFY;
break;
case HpsTransactionType::LIST_TRANSACTION:
return HpsItemChoiceTypePosResponseVer10Transaction::REPORT_ACTIVITY;
break;
case HpsTransactionType::GET:
return HpsItemChoiceTypePosResponseVer10Transaction::REPORT_TXN_DETAIL;
break;
case HpsTransactionType::VOID:
return HpsItemChoiceTypePosResponseVer10Transaction::CREDIT_VOID;
break;
case HpsTransactionType::BATCH_CLOSE:
return HpsItemChoiceTypePosResponseVer10Transaction::BATCH_CLOSE;
break;
case HpsTransactionType::SECURITY_ERROR:
return "SecurityError";
break;
default:
return "";
}
}
|
@param $transactionType
@return string
|
entailment
|
public static function serviceNameToTransactionType($serviceName)
{
switch ($serviceName) {
case HpsItemChoiceTypePosResponseVer10Transaction::CREDIT_AUTH:
return HpsTransactionType::AUTHORIZE;
break;
case HpsItemChoiceTypePosResponseVer10Transaction::CREDIT_ADD_TO_BATCH:
return HpsTransactionType::CAPTURE;
break;
case HpsItemChoiceTypePosResponseVer10Transaction::CREDIT_SALE:
return HpsTransactionType::CHARGE;
break;
case HpsItemChoiceTypePosResponseVer10Transaction::CREDIT_RETURN:
return HpsTransactionType::REFUND;
break;
case HpsItemChoiceTypePosResponseVer10Transaction::CREDIT_REVERSAL:
return HpsTransactionType::REVERSE;
break;
case HpsItemChoiceTypePosResponseVer10Transaction::CREDIT_ACCOUNT_VERIFY:
return HpsTransactionType::VERIFY;
break;
case HpsItemChoiceTypePosResponseVer10Transaction::REPORT_ACTIVITY:
return HpsTransactionType::LIST_TRANSACTION;
break;
case HpsItemChoiceTypePosResponseVer10Transaction::REPORT_TXN_DETAIL:
return HpsTransactionType::GET;
break;
case HpsItemChoiceTypePosResponseVer10Transaction::CREDIT_VOID:
return HpsTransactionType::VOID;
break;
case HpsItemChoiceTypePosResponseVer10Transaction::BATCH_CLOSE:
return HpsTransactionType::BATCH_CLOSE;
break;
default:
return null;
}
}
|
@param $serviceName
@return int|null
|
entailment
|
public function execute()
{
parent::execute();
$returnSvc = new HpsDebitService($this->service->servicesConfig());
return $returnSvc->returnDebit(
$this->transactionId,
$this->amount,
$this->trackData,
$this->pinBlock,
$this->allowDuplicates,
$this->cardHolder,
$this->encryptionData,
$this->details,
$this->clientTransactionId
);
}
|
Creates a return transaction through the HpsDebitService
|
entailment
|
public static function checkResponse($transactionId, $responseCode, $responseText, $type = 'credit')
{
$e = HpsIssuerResponseValidation::getException(
(string)$transactionId,
(string)$responseCode,
(string)$responseText,
$type
);
if ($e != null) {
throw $e;
}
}
|
@param $transactionId
@param $responseCode
@param $responseText
@param string $type
@throws \HpsCreditException
@throws null
|
entailment
|
public static function getException($transactionId, $responseCode, $responseText, $type)
{
$acceptedCodes = array('00', '0');
$map = array();
switch ($type) {
case 'credit':
$acceptedCodes = array_merge($acceptedCodes, array('85', '10'));
$map = self::$_issuerCodeToCreditExceptionCode;
break;
case 'gift':
$acceptedCodes = array_merge($acceptedCodes, array('13'));
$map = self::$_issuerCodeToGiftExceptionCode;
break;
}
if (in_array($responseCode, $acceptedCodes)) {
return null;
}
$code = null;
if (array_key_exists($responseCode, $map)) {
$code = $map[$responseCode];
}
if ($code == null) {
return new HpsCreditException(
$transactionId,
HpsExceptionCodes::UNKNOWN_CREDIT_ERROR,
self::$_creditExceptionCodeToMessage[HpsExceptionCodes::UNKNOWN_CREDIT_ERROR],
$responseCode,
$responseText
);
}
$message = null;
if (array_key_exists($code, self::$_creditExceptionCodeToMessage)) {
$message = self::$_creditExceptionCodeToMessage[$code];
} else {
$message = 'Unknown issuer error';
}
return new HpsCreditException($transactionId, $code, $message, $responseCode, $responseText);
}
|
@param $transactionId
@param $responseCode
@param $responseText
@param $type
@return \HpsCreditException|null
|
entailment
|
public function authorize($amount, $currency, $cardOrToken, $cardHolder = null, $requestMultiUseToken = false, $details = null, $txnDescriptor = null, $allowPartialAuth = false, $cpcReq = false, $convenienceAmtInfo = null, $shippingAmtInfo = null)
{
HpsInputValidation::checkCurrency($currency);
$this->_currency = $currency;
$this->_amount = HpsInputValidation::checkAmount($amount);
$xml = new DOMDocument();
$hpsTransaction = $xml->createElement('hps:Transaction');
$hpsCreditAuth = $xml->createElement('hps:CreditAuth');
$hpsBlock1 = $xml->createElement('hps:Block1');
$hpsBlock1->appendChild($xml->createElement('hps:AllowDup', 'Y'));
$hpsBlock1->appendChild($xml->createElement('hps:AllowPartialAuth', ($allowPartialAuth ? 'Y' : 'N')));
$hpsBlock1->appendChild($xml->createElement('hps:Amt', $amount));
//update convenienceAmtInfo if passed
if ($convenienceAmtInfo != null && $convenienceAmtInfo != '') {
$hpsBlock1->appendChild($xml->createElement('hps:ConvenienceAmtInfo', $convenienceAmtInfo));
}
//update shippingAmtInfo if passed
if ($shippingAmtInfo != null && $shippingAmtInfo != '') {
$hpsBlock1->appendChild($xml->createElement('hps:ShippingAmtInfo', $shippingAmtInfo));
}
if ($cardHolder != null) {
$hpsBlock1->appendChild($this->_hydrateCardHolderData($cardHolder, $xml));
}
if ($details != null) {
$hpsBlock1->appendChild($this->_hydrateAdditionalTxnFields($details, $xml));
}
if ($txnDescriptor != null && $txnDescriptor != '') {
$hpsBlock1->appendChild($xml->createElement('hps:TxnDescriptor', $txnDescriptor));
}
$cardData = $xml->createElement('hps:CardData');
if ($cardOrToken instanceof HpsCreditCard) {
$cardData->appendChild($this->_hydrateManualEntry($cardOrToken, $xml));
} else {
$cardData->appendChild($this->_hydrateTokenData($cardOrToken, $xml));
}
$cardData->appendChild($xml->createElement('hps:TokenRequest', ($requestMultiUseToken) ? 'Y' : 'N'));
if ($cpcReq) {
$hpsBlock1->appendChild($xml->createElement('hps:CPCReq', 'Y'));
}
$hpsBlock1->appendChild($cardData);
$hpsCreditAuth->appendChild($hpsBlock1);
$hpsTransaction->appendChild($hpsCreditAuth);
return $this->_submitTransaction($hpsTransaction, 'CreditAuth', (isset($details->clientTransactionId) ? $details->clientTransactionId : null), $cardOrToken);
}
|
@param $amount
@param $currency
@param $cardOrToken
@param null $cardHolder
@param bool $requestMultiUseToken
@param null $details
@param null $txnDescriptor
@param bool $allowPartialAuth
@param bool $cpcReq
@param null $convenienceAmtInfo
@param null $shippingAmtInfo
@return array|null
@throws \HpsException
@throws \HpsGatewayException
@throws \HpsInvalidRequestException
|
entailment
|
public function capture($transactionId, $amount = null, $gratuity = null, $clientTransactionId = null, $directMarketData = null)
{
$xml = new DOMDocument();
$hpsTransaction = $xml->createElement('hps:Transaction');
$hpsCreditAddToBatch = $xml->createElement('hps:CreditAddToBatch');
$hpsCreditAddToBatch->appendChild($xml->createElement('hps:GatewayTxnId', $transactionId));
if ($amount != null) {
$amount = sprintf("%0.2f", round($amount, 3));
$hpsCreditAddToBatch->appendChild($xml->createElement('hps:Amt', $amount));
}
if ($gratuity != null) {
$hpsCreditAddToBatch->appendChild($xml->createElement('hps:GratuityAmtInfo', $gratuity));
}
if ($directMarketData != null && $directMarketData->invoiceNumber != null) {
$hpsCreditAddToBatch->appendChild($this->_hydrateDirectMarketData($directMarketData, $xml));
}
$hpsTransaction->appendChild($hpsCreditAddToBatch);
$options = array();
if ($clientTransactionId != null) {
$options['clientTransactionId'] = $clientTransactionId;
}
$response = $this->doRequest($hpsTransaction, $options);
$this->_processChargeGatewayResponse($response, 'CreditAddToBatch');
return $this->get($transactionId);
}
|
@param $transactionId
@param null $amount
@param null $gratuity
@param null $clientTransactionId
@param null $directMarketData
@return array|null
@throws \HpsArgumentException
@throws \HpsGatewayException
|
entailment
|
public function recurring($schedule, $amount, $cardOrTokenOrPMKey, $cardHolder = null, $oneTime = false, $details = null)
{
$this->_amount = HpsInputValidation::checkAmount($amount);
$xml = new DOMDocument();
$hpsTransaction = $xml->createElement('hps:Transaction');
$hpsRecurringBilling = $xml->createElement('hps:RecurringBilling');
$hpsBlock1 = $xml->createElement('hps:Block1');
$hpsBlock1->appendChild($xml->createElement('hps:AllowDup', 'Y'));
$hpsBlock1->appendChild($xml->createElement('hps:Amt', $amount));
if ($cardHolder != null) {
$hpsBlock1->appendChild($this->_hydrateCardHolderData($cardHolder, $xml));
}
if ($details != null) {
$hpsBlock1->appendChild($this->_hydrateAdditionalTxnFields($details, $xml));
}
if ($cardOrTokenOrPMKey instanceof HpsCreditCard) {
$cardData = $xml->createElement('hps:CardData');
$cardData->appendChild($this->_hydrateManualEntry($cardOrTokenOrPMKey, $xml));
$hpsBlock1->appendChild($cardData);
} else if ($cardOrTokenOrPMKey instanceof HpsTokenData) {
$cardData = $xml->createElement('hps:CardData');
$cardData->appendChild($this->_hydrateTokenData($cardOrTokenOrPMKey, $xml));
$hpsBlock1->appendChild($cardData);
} else {
$hpsBlock1->appendChild($xml->createElement('hps:PaymentMethodKey', $cardOrTokenOrPMKey));
}
$id = $schedule;
if ($schedule instanceof HpsPayPlanSchedule) {
$id = $schedule->scheduleIdentifier;
}
$recurringData = $xml->createElement('hps:RecurringData');
$recurringData->appendChild($xml->createElement('hps:ScheduleID', $id));
$recurringData->appendChild($xml->createElement('hps:OneTime', ($oneTime ? 'Y' : 'N')));
$hpsBlock1->appendChild($recurringData);
$hpsRecurringBilling->appendChild($hpsBlock1);
$hpsTransaction->appendChild($hpsRecurringBilling);
return $this->_submitTransaction($hpsTransaction, 'RecurringBilling', (isset($details->clientTransactionId) ? $details->clientTransactionId : null), $cardOrTokenOrPMKey);
}
|
@param $schedule
@param $amount
@param $cardOrTokenOrPMKey
@param null $cardHolder
@param bool $oneTime
@param null $details
@return array|null
@throws \HpsException
@throws \HpsGatewayException
@throws \HpsInvalidRequestException
|
entailment
|
public function cpcEdit($transactionId, $cpcData)
{
$xml = new DOMDocument();
$hpsTransaction = $xml->createElement('hps:Transaction');
$hpsPosCreditCPCEdit = $xml->createElement('hps:CreditCPCEdit');
$hpsPosCreditCPCEdit->appendChild($xml->createElement('hps:GatewayTxnId', $transactionId));
$hpsPosCreditCPCEdit->appendChild($this->_hydrateCPCData($cpcData, $xml));
$hpsTransaction->appendChild($hpsPosCreditCPCEdit);
return $this->_submitTransaction($hpsTransaction, 'CreditCPCEdit');
}
|
@param $transactionId
@param $cpcData
@return array|null
@throws \HpsException
@throws \HpsGatewayException
|
entailment
|
public function edit($transactionId, $amount = null, $gratuity = null, $clientTransactionId = null)
{
$xml = new DOMDocument();
$hpsTransaction = $xml->createElement('hps:Transaction');
$hpsCreditTxnEdit = $xml->createElement('hps:CreditTxnEdit');
$hpsCreditTxnEdit->appendChild($xml->createElement('hps:GatewayTxnId', $transactionId));
if ($amount != null) {
$amount = sprintf('%0.2f', round($amount, 3));
$hpsCreditTxnEdit->appendChild($xml->createElement('hps:Amt', $amount));
}
if ($gratuity != null) {
$hpsCreditTxnEdit->appendChild($xml->createElement('hps:GratuityAmtInfo', $gratuity));
}
$hpsTransaction->appendChild($hpsCreditTxnEdit);
$trans = $this->_submitTransaction($hpsTransaction, 'CreditTxnEdit', $clientTransactionId);
$trans->responseCode = '00';
$trans->responseText = '';
return $trans;
}
|
@param $transactionId
@param null $amount
@param null $gratuity
@param null $clientTransactionId
@return array|null
@throws \HpsException
@throws \HpsGatewayException
|
entailment
|
public function updateTokenExpiration($tokenValue, $expMonth, $expYear) {
// new DOM
$xml = new DOMDocument();
$hpsTransaction = $xml->createElement('hps:Transaction');
$hpsManageTokens = $xml->createElement('hps:ManageTokens');
$hpsManageTokens->appendChild($xml->createElement('hps:TokenValue', trim((string)$tokenValue)));
$hpsTokenActions = $xml->createElement('hps:TokenActions');
$hpsSet = $xml->createElement('hps:Set');
$hpsAttribute = $xml->createElement('hps:Attribute');
$hpsAttribute->appendChild($xml->createElement('hps:Name', 'ExpMonth'));
$hpsAttribute->appendChild($xml->createElement('hps:Value', (string)sprintf("%'.02d", (int)$expMonth)));
$hpsSet->appendChild($hpsAttribute);
$hpsAttribute = $xml->createElement('hps:Attribute');
$hpsAttribute->appendChild($xml->createElement('hps:Name', 'ExpYear'));
$hpsAttribute->appendChild($xml->createElement('hps:Value', (string)$expYear));
$hpsSet->appendChild($hpsAttribute);
$hpsTokenActions->appendChild($hpsSet);
$hpsManageTokens->appendChild($hpsTokenActions);
$hpsTransaction->appendChild($hpsManageTokens);
return $this->_submitTransaction($hpsTransaction, 'ManageTokens');
}
|
builds soap transaction for Portico so that expiration dates can be updated for expired cards with a new current issuance
@param string $tokenValue
@param int $expMonth 1-12 padding will be handled automatically
@param int $expYear must be 4 digits.
@return \HpsManageTokensResponse
@throws \HpsException
@throws \HpsGatewayException
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.