repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
QoboLtd/cakephp-csv-migrations
src/Utility/Validate/Check/AbstractCheck.php
AbstractCheck.addFieldsToSchema
protected function addFieldsToSchema(array $schema, string $module): array { if (isset($schema['definitions']['fieldName'])) { $fields = Utility::getRealModuleFields($module, false); if (!empty($fields)) { $schema['definitions']['fieldName']['enum'] = $fields; } } return $schema; }
php
protected function addFieldsToSchema(array $schema, string $module): array { if (isset($schema['definitions']['fieldName'])) { $fields = Utility::getRealModuleFields($module, false); if (!empty($fields)) { $schema['definitions']['fieldName']['enum'] = $fields; } } return $schema; }
[ "protected", "function", "addFieldsToSchema", "(", "array", "$", "schema", ",", "string", "$", "module", ")", ":", "array", "{", "if", "(", "isset", "(", "$", "schema", "[", "'definitions'", "]", "[", "'fieldName'", "]", ")", ")", "{", "$", "fields", "=", "Utility", "::", "getRealModuleFields", "(", "$", "module", ",", "false", ")", ";", "if", "(", "!", "empty", "(", "$", "fields", ")", ")", "{", "$", "schema", "[", "'definitions'", "]", "[", "'fieldName'", "]", "[", "'enum'", "]", "=", "$", "fields", ";", "}", "}", "return", "$", "schema", ";", "}" ]
Add fields from migration config to schema. @param mixed[] $schema Schema. @param string $module Module name @return string[] Schema.
[ "Add", "fields", "from", "migration", "config", "to", "schema", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Validate/Check/AbstractCheck.php#L28-L38
train
QoboLtd/cakephp-csv-migrations
src/Utility/Validate/Check/AbstractCheck.php
AbstractCheck.addVirtualFieldsToSchema
protected function addVirtualFieldsToSchema(array $schema, string $module): array { if (isset($schema['definitions']['virtualFieldName'])) { $virtualFields = Utility::getVirtualModuleFields($module, false); if (!empty($virtualFields)) { $schema['definitions']['virtualFieldName']['enum'] = array_keys($virtualFields); } } return $schema; }
php
protected function addVirtualFieldsToSchema(array $schema, string $module): array { if (isset($schema['definitions']['virtualFieldName'])) { $virtualFields = Utility::getVirtualModuleFields($module, false); if (!empty($virtualFields)) { $schema['definitions']['virtualFieldName']['enum'] = array_keys($virtualFields); } } return $schema; }
[ "protected", "function", "addVirtualFieldsToSchema", "(", "array", "$", "schema", ",", "string", "$", "module", ")", ":", "array", "{", "if", "(", "isset", "(", "$", "schema", "[", "'definitions'", "]", "[", "'virtualFieldName'", "]", ")", ")", "{", "$", "virtualFields", "=", "Utility", "::", "getVirtualModuleFields", "(", "$", "module", ",", "false", ")", ";", "if", "(", "!", "empty", "(", "$", "virtualFields", ")", ")", "{", "$", "schema", "[", "'definitions'", "]", "[", "'virtualFieldName'", "]", "[", "'enum'", "]", "=", "array_keys", "(", "$", "virtualFields", ")", ";", "}", "}", "return", "$", "schema", ";", "}" ]
Add virtual fields from migration config to schema. @param mixed[] $schema Schema. @param string $module Module name @return string[] Schema.
[ "Add", "virtual", "fields", "from", "migration", "config", "to", "schema", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Validate/Check/AbstractCheck.php#L47-L57
train
QoboLtd/cakephp-csv-migrations
src/Utility/Validate/Check/AbstractCheck.php
AbstractCheck.addModulesToSchema
protected function addModulesToSchema(array $schema, string $module): array { if (isset($schema['definitions']['moduleName'])) { $modules = Utility::getModules(); if (!empty($modules)) { $schema['definitions']['moduleName']['enum'] = array_values($modules); } } return $schema; }
php
protected function addModulesToSchema(array $schema, string $module): array { if (isset($schema['definitions']['moduleName'])) { $modules = Utility::getModules(); if (!empty($modules)) { $schema['definitions']['moduleName']['enum'] = array_values($modules); } } return $schema; }
[ "protected", "function", "addModulesToSchema", "(", "array", "$", "schema", ",", "string", "$", "module", ")", ":", "array", "{", "if", "(", "isset", "(", "$", "schema", "[", "'definitions'", "]", "[", "'moduleName'", "]", ")", ")", "{", "$", "modules", "=", "Utility", "::", "getModules", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "modules", ")", ")", "{", "$", "schema", "[", "'definitions'", "]", "[", "'moduleName'", "]", "[", "'enum'", "]", "=", "array_values", "(", "$", "modules", ")", ";", "}", "}", "return", "$", "schema", ";", "}" ]
Add available modules to schema. @param mixed[] $schema Schema. @param string $module Module name @return string[] Schema.
[ "Add", "available", "modules", "to", "schema", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Validate/Check/AbstractCheck.php#L66-L76
train
QoboLtd/cakephp-csv-migrations
src/Utility/Validate/Check/AbstractCheck.php
AbstractCheck.addRelationToSchema
protected function addRelationToSchema(array $schema, string $module): array { if (isset($schema['definitions']['relation'])) { $relations = Utility::getRealRelationFields($module); if (!empty($relations)) { $schema['definitions']['relation']['enum'] = $relations; } } return $schema; }
php
protected function addRelationToSchema(array $schema, string $module): array { if (isset($schema['definitions']['relation'])) { $relations = Utility::getRealRelationFields($module); if (!empty($relations)) { $schema['definitions']['relation']['enum'] = $relations; } } return $schema; }
[ "protected", "function", "addRelationToSchema", "(", "array", "$", "schema", ",", "string", "$", "module", ")", ":", "array", "{", "if", "(", "isset", "(", "$", "schema", "[", "'definitions'", "]", "[", "'relation'", "]", ")", ")", "{", "$", "relations", "=", "Utility", "::", "getRealRelationFields", "(", "$", "module", ")", ";", "if", "(", "!", "empty", "(", "$", "relations", ")", ")", "{", "$", "schema", "[", "'definitions'", "]", "[", "'relation'", "]", "[", "'enum'", "]", "=", "$", "relations", ";", "}", "}", "return", "$", "schema", ";", "}" ]
Add relation fields @param mixed[] $schema Schema. @param string $module Module name @return string[] Schema.
[ "Add", "relation", "fields" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Validate/Check/AbstractCheck.php#L85-L95
train
QoboLtd/cakephp-csv-migrations
src/Utility/FileUpload.php
FileUpload.getFiles
public function getFiles(string $field, string $id) : ResultSetInterface { $query = $this->storageTable->find('all') ->where([self::FILE_STORAGE_FOREIGN_KEY => $id, 'model' => $this->table->getTable(), 'model_field' => $field]) ->order($this->getOrderClause($field)); $result = $query->all(); foreach ($result as $entity) { $entity = $this->attachThumbnails($entity); } return $result; }
php
public function getFiles(string $field, string $id) : ResultSetInterface { $query = $this->storageTable->find('all') ->where([self::FILE_STORAGE_FOREIGN_KEY => $id, 'model' => $this->table->getTable(), 'model_field' => $field]) ->order($this->getOrderClause($field)); $result = $query->all(); foreach ($result as $entity) { $entity = $this->attachThumbnails($entity); } return $result; }
[ "public", "function", "getFiles", "(", "string", "$", "field", ",", "string", "$", "id", ")", ":", "ResultSetInterface", "{", "$", "query", "=", "$", "this", "->", "storageTable", "->", "find", "(", "'all'", ")", "->", "where", "(", "[", "self", "::", "FILE_STORAGE_FOREIGN_KEY", "=>", "$", "id", ",", "'model'", "=>", "$", "this", "->", "table", "->", "getTable", "(", ")", ",", "'model_field'", "=>", "$", "field", "]", ")", "->", "order", "(", "$", "this", "->", "getOrderClause", "(", "$", "field", ")", ")", ";", "$", "result", "=", "$", "query", "->", "all", "(", ")", ";", "foreach", "(", "$", "result", "as", "$", "entity", ")", "{", "$", "entity", "=", "$", "this", "->", "attachThumbnails", "(", "$", "entity", ")", ";", "}", "return", "$", "result", ";", "}" ]
Get files by foreign key record. @param string $field Field name @param string $id Foreign key value (UUID) @return \Cake\Datasource\ResultSetInterface
[ "Get", "files", "by", "foreign", "key", "record", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/FileUpload.php#L105-L117
train
QoboLtd/cakephp-csv-migrations
src/Utility/FileUpload.php
FileUpload.getOrderClause
private function getOrderClause(string $field) : array { $className = App::shortName(get_class($this->table), 'Model/Table', 'Table'); $config = (new ModuleConfig(ConfigType::FIELDS(), $className))->parse(); if (! property_exists($config, $field)) { return []; } if (! property_exists($config->{$field}, 'orderBy')) { return []; } if (! property_exists($config->{$field}, 'orderDir')) { return []; } return [$config->{$field}->orderBy => $config->{$field}->orderDir]; }
php
private function getOrderClause(string $field) : array { $className = App::shortName(get_class($this->table), 'Model/Table', 'Table'); $config = (new ModuleConfig(ConfigType::FIELDS(), $className))->parse(); if (! property_exists($config, $field)) { return []; } if (! property_exists($config->{$field}, 'orderBy')) { return []; } if (! property_exists($config->{$field}, 'orderDir')) { return []; } return [$config->{$field}->orderBy => $config->{$field}->orderDir]; }
[ "private", "function", "getOrderClause", "(", "string", "$", "field", ")", ":", "array", "{", "$", "className", "=", "App", "::", "shortName", "(", "get_class", "(", "$", "this", "->", "table", ")", ",", "'Model/Table'", ",", "'Table'", ")", ";", "$", "config", "=", "(", "new", "ModuleConfig", "(", "ConfigType", "::", "FIELDS", "(", ")", ",", "$", "className", ")", ")", "->", "parse", "(", ")", ";", "if", "(", "!", "property_exists", "(", "$", "config", ",", "$", "field", ")", ")", "{", "return", "[", "]", ";", "}", "if", "(", "!", "property_exists", "(", "$", "config", "->", "{", "$", "field", "}", ",", "'orderBy'", ")", ")", "{", "return", "[", "]", ";", "}", "if", "(", "!", "property_exists", "(", "$", "config", "->", "{", "$", "field", "}", ",", "'orderDir'", ")", ")", "{", "return", "[", "]", ";", "}", "return", "[", "$", "config", "->", "{", "$", "field", "}", "->", "orderBy", "=>", "$", "config", "->", "{", "$", "field", "}", "->", "orderDir", "]", ";", "}" ]
Adds order clause to the provided Query based on specified field configuration. @see https://github.com/QoboLtd/cakephp-utils/blob/v9.2.0/src/ModuleConfig/Parser/Schema/fields.json#L30-L40 @param string $field Field name @return mixed[]
[ "Adds", "order", "clause", "to", "the", "provided", "Query", "based", "on", "specified", "field", "configuration", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/FileUpload.php#L126-L144
train
QoboLtd/cakephp-csv-migrations
src/Utility/FileUpload.php
FileUpload.attachThumbnails
private function attachThumbnails(FileStorage $entity) : FileStorage { $entity->set('thumbnails', $this->getThumbnails($entity)); return $entity; }
php
private function attachThumbnails(FileStorage $entity) : FileStorage { $entity->set('thumbnails', $this->getThumbnails($entity)); return $entity; }
[ "private", "function", "attachThumbnails", "(", "FileStorage", "$", "entity", ")", ":", "FileStorage", "{", "$", "entity", "->", "set", "(", "'thumbnails'", ",", "$", "this", "->", "getThumbnails", "(", "$", "entity", ")", ")", ";", "return", "$", "entity", ";", "}" ]
Attaches thumbnails field to FileStorage entity. @param \Burzum\FileStorage\Model\Entity\FileStorage $entity FileStorage entity @return \Burzum\FileStorage\Model\Entity\FileStorage
[ "Attaches", "thumbnails", "field", "to", "FileStorage", "entity", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/FileUpload.php#L152-L157
train
QoboLtd/cakephp-csv-migrations
src/Utility/FileUpload.php
FileUpload.getThumbnails
public function getThumbnails(FileStorage $entity) : array { $versions = (array)Configure::read('FileStorage.imageHashes.file_storage'); if (empty($versions)) { return []; } $result = []; foreach (array_keys($versions) as $version) { $result[$version] = $this->getThumbnail($entity, (string)$version); } return $result; }
php
public function getThumbnails(FileStorage $entity) : array { $versions = (array)Configure::read('FileStorage.imageHashes.file_storage'); if (empty($versions)) { return []; } $result = []; foreach (array_keys($versions) as $version) { $result[$version] = $this->getThumbnail($entity, (string)$version); } return $result; }
[ "public", "function", "getThumbnails", "(", "FileStorage", "$", "entity", ")", ":", "array", "{", "$", "versions", "=", "(", "array", ")", "Configure", "::", "read", "(", "'FileStorage.imageHashes.file_storage'", ")", ";", "if", "(", "empty", "(", "$", "versions", ")", ")", "{", "return", "[", "]", ";", "}", "$", "result", "=", "[", "]", ";", "foreach", "(", "array_keys", "(", "$", "versions", ")", "as", "$", "version", ")", "{", "$", "result", "[", "$", "version", "]", "=", "$", "this", "->", "getThumbnail", "(", "$", "entity", ",", "(", "string", ")", "$", "version", ")", ";", "}", "return", "$", "result", ";", "}" ]
File storage entity thumbnails getter. @param \Burzum\FileStorage\Model\Entity\FileStorage $entity File storage entity @return string[]
[ "File", "storage", "entity", "thumbnails", "getter", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/FileUpload.php#L165-L178
train
QoboLtd/cakephp-csv-migrations
src/Utility/FileUpload.php
FileUpload.getThumbnail
public function getThumbnail(FileStorage $entity, string $version) : string { $versions = (array)Configure::read('FileStorage.imageHashes.file_storage'); if (empty($versions)) { return str_replace(DS, '/', $entity->get('path')); } if (! array_key_exists($version, $versions)) { return str_replace(DS, '/', $entity->get('path')); } $path = in_array(strtolower($entity->get('extension')), self::IMAGE_EXTENSIONS) ? $this->getImagePath($entity, $version) : $this->getIconPath($entity, $version); return str_replace(DS, '/', $path); }
php
public function getThumbnail(FileStorage $entity, string $version) : string { $versions = (array)Configure::read('FileStorage.imageHashes.file_storage'); if (empty($versions)) { return str_replace(DS, '/', $entity->get('path')); } if (! array_key_exists($version, $versions)) { return str_replace(DS, '/', $entity->get('path')); } $path = in_array(strtolower($entity->get('extension')), self::IMAGE_EXTENSIONS) ? $this->getImagePath($entity, $version) : $this->getIconPath($entity, $version); return str_replace(DS, '/', $path); }
[ "public", "function", "getThumbnail", "(", "FileStorage", "$", "entity", ",", "string", "$", "version", ")", ":", "string", "{", "$", "versions", "=", "(", "array", ")", "Configure", "::", "read", "(", "'FileStorage.imageHashes.file_storage'", ")", ";", "if", "(", "empty", "(", "$", "versions", ")", ")", "{", "return", "str_replace", "(", "DS", ",", "'/'", ",", "$", "entity", "->", "get", "(", "'path'", ")", ")", ";", "}", "if", "(", "!", "array_key_exists", "(", "$", "version", ",", "$", "versions", ")", ")", "{", "return", "str_replace", "(", "DS", ",", "'/'", ",", "$", "entity", "->", "get", "(", "'path'", ")", ")", ";", "}", "$", "path", "=", "in_array", "(", "strtolower", "(", "$", "entity", "->", "get", "(", "'extension'", ")", ")", ",", "self", "::", "IMAGE_EXTENSIONS", ")", "?", "$", "this", "->", "getImagePath", "(", "$", "entity", ",", "$", "version", ")", ":", "$", "this", "->", "getIconPath", "(", "$", "entity", ",", "$", "version", ")", ";", "return", "str_replace", "(", "DS", ",", "'/'", ",", "$", "path", ")", ";", "}" ]
File storage entity thumbnail url getter by version. @param \Burzum\FileStorage\Model\Entity\FileStorage $entity FileStorage entity @param string $version Version name @return string
[ "File", "storage", "entity", "thumbnail", "url", "getter", "by", "version", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/FileUpload.php#L187-L203
train
QoboLtd/cakephp-csv-migrations
src/Utility/FileUpload.php
FileUpload.getThumbnailSizeList
public function getThumbnailSizeList(): array { $thumbnails = []; $versions = Configure::read('ThumbnailVersions', []); foreach ($versions as $version => $definition) { $thumbnails[$version] = sprintf( '%s (%d x %d)', ucfirst($version), $definition['thumbnail']['width'], $definition['thumbnail']['height'] ); } return $thumbnails; }
php
public function getThumbnailSizeList(): array { $thumbnails = []; $versions = Configure::read('ThumbnailVersions', []); foreach ($versions as $version => $definition) { $thumbnails[$version] = sprintf( '%s (%d x %d)', ucfirst($version), $definition['thumbnail']['width'], $definition['thumbnail']['height'] ); } return $thumbnails; }
[ "public", "function", "getThumbnailSizeList", "(", ")", ":", "array", "{", "$", "thumbnails", "=", "[", "]", ";", "$", "versions", "=", "Configure", "::", "read", "(", "'ThumbnailVersions'", ",", "[", "]", ")", ";", "foreach", "(", "$", "versions", "as", "$", "version", "=>", "$", "definition", ")", "{", "$", "thumbnails", "[", "$", "version", "]", "=", "sprintf", "(", "'%s (%d x %d)'", ",", "ucfirst", "(", "$", "version", ")", ",", "$", "definition", "[", "'thumbnail'", "]", "[", "'width'", "]", ",", "$", "definition", "[", "'thumbnail'", "]", "[", "'height'", "]", ")", ";", "}", "return", "$", "thumbnails", ";", "}" ]
Return all the available sizes for thumbnails @return mixed[]
[ "Return", "all", "the", "available", "sizes", "for", "thumbnails" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/FileUpload.php#L233-L247
train
QoboLtd/cakephp-csv-migrations
src/Utility/FileUpload.php
FileUpload.getImagePath
private function getImagePath(FileStorage $entity, string $version) : string { $hash = (string)Configure::read(sprintf('FileStorage.imageHashes.file_storage.%s', $version)); if (empty($hash)) { return $entity->get('path'); } $event = new Event('ImageVersion.getVersions', $this, [ 'hash' => $hash, 'image' => $entity, 'version' => $version, 'options' => [], 'pathType' => 'fullPath' ]); EventManager::instance()->dispatch($event); if (! $event->getResult()) { return $entity->get('path'); } return file_exists(WWW_ROOT . trim($event->getResult(), DS)) ? $event->getResult() : $entity->get('path'); }
php
private function getImagePath(FileStorage $entity, string $version) : string { $hash = (string)Configure::read(sprintf('FileStorage.imageHashes.file_storage.%s', $version)); if (empty($hash)) { return $entity->get('path'); } $event = new Event('ImageVersion.getVersions', $this, [ 'hash' => $hash, 'image' => $entity, 'version' => $version, 'options' => [], 'pathType' => 'fullPath' ]); EventManager::instance()->dispatch($event); if (! $event->getResult()) { return $entity->get('path'); } return file_exists(WWW_ROOT . trim($event->getResult(), DS)) ? $event->getResult() : $entity->get('path'); }
[ "private", "function", "getImagePath", "(", "FileStorage", "$", "entity", ",", "string", "$", "version", ")", ":", "string", "{", "$", "hash", "=", "(", "string", ")", "Configure", "::", "read", "(", "sprintf", "(", "'FileStorage.imageHashes.file_storage.%s'", ",", "$", "version", ")", ")", ";", "if", "(", "empty", "(", "$", "hash", ")", ")", "{", "return", "$", "entity", "->", "get", "(", "'path'", ")", ";", "}", "$", "event", "=", "new", "Event", "(", "'ImageVersion.getVersions'", ",", "$", "this", ",", "[", "'hash'", "=>", "$", "hash", ",", "'image'", "=>", "$", "entity", ",", "'version'", "=>", "$", "version", ",", "'options'", "=>", "[", "]", ",", "'pathType'", "=>", "'fullPath'", "]", ")", ";", "EventManager", "::", "instance", "(", ")", "->", "dispatch", "(", "$", "event", ")", ";", "if", "(", "!", "$", "event", "->", "getResult", "(", ")", ")", "{", "return", "$", "entity", "->", "get", "(", "'path'", ")", ";", "}", "return", "file_exists", "(", "WWW_ROOT", ".", "trim", "(", "$", "event", "->", "getResult", "(", ")", ",", "DS", ")", ")", "?", "$", "event", "->", "getResult", "(", ")", ":", "$", "entity", "->", "get", "(", "'path'", ")", ";", "}" ]
Image path getter. @param \Burzum\FileStorage\Model\Entity\FileStorage $entity FileStorage entity @param string $version Version name @return string
[ "Image", "path", "getter", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/FileUpload.php#L256-L280
train
QoboLtd/cakephp-csv-migrations
src/Utility/FileUpload.php
FileUpload.getIconPath
private function getIconPath(FileStorage $entity, string $version) : string { $imgSizes = (array)Configure::read(sprintf('FileStorage.imageSizes.%s', $entity->get('model'))); // no image sizes, return default if (empty($imgSizes)) { return Utility::getFileTypeIcon($entity->get('extension')); } // sort by size, biggest first and get current version position in the array $position = array_search($version, array_keys(Hash::sort($imgSizes, 'width')), true); // no position, return default if (false === $position) { return Utility::getFileTypeIcon($entity->get('extension')); } $iconSizes = [512, 48, 32, 16]; // traversing recursively through the icon sizes until it finds the closest one by key position $funcGetIconSize = function (int $pos) use ($iconSizes, &$funcGetIconSize) { if (! array_key_exists($pos, $iconSizes)) { return $funcGetIconSize($pos - 1); } return $iconSizes[$pos]; }; $result = Utility::getFileTypeIcon($entity->get('extension'), sprintf('%dpx', $funcGetIconSize($position))); $result = $this->getUrlHelper()->image($result); return $result; }
php
private function getIconPath(FileStorage $entity, string $version) : string { $imgSizes = (array)Configure::read(sprintf('FileStorage.imageSizes.%s', $entity->get('model'))); // no image sizes, return default if (empty($imgSizes)) { return Utility::getFileTypeIcon($entity->get('extension')); } // sort by size, biggest first and get current version position in the array $position = array_search($version, array_keys(Hash::sort($imgSizes, 'width')), true); // no position, return default if (false === $position) { return Utility::getFileTypeIcon($entity->get('extension')); } $iconSizes = [512, 48, 32, 16]; // traversing recursively through the icon sizes until it finds the closest one by key position $funcGetIconSize = function (int $pos) use ($iconSizes, &$funcGetIconSize) { if (! array_key_exists($pos, $iconSizes)) { return $funcGetIconSize($pos - 1); } return $iconSizes[$pos]; }; $result = Utility::getFileTypeIcon($entity->get('extension'), sprintf('%dpx', $funcGetIconSize($position))); $result = $this->getUrlHelper()->image($result); return $result; }
[ "private", "function", "getIconPath", "(", "FileStorage", "$", "entity", ",", "string", "$", "version", ")", ":", "string", "{", "$", "imgSizes", "=", "(", "array", ")", "Configure", "::", "read", "(", "sprintf", "(", "'FileStorage.imageSizes.%s'", ",", "$", "entity", "->", "get", "(", "'model'", ")", ")", ")", ";", "// no image sizes, return default", "if", "(", "empty", "(", "$", "imgSizes", ")", ")", "{", "return", "Utility", "::", "getFileTypeIcon", "(", "$", "entity", "->", "get", "(", "'extension'", ")", ")", ";", "}", "// sort by size, biggest first and get current version position in the array", "$", "position", "=", "array_search", "(", "$", "version", ",", "array_keys", "(", "Hash", "::", "sort", "(", "$", "imgSizes", ",", "'width'", ")", ")", ",", "true", ")", ";", "// no position, return default", "if", "(", "false", "===", "$", "position", ")", "{", "return", "Utility", "::", "getFileTypeIcon", "(", "$", "entity", "->", "get", "(", "'extension'", ")", ")", ";", "}", "$", "iconSizes", "=", "[", "512", ",", "48", ",", "32", ",", "16", "]", ";", "// traversing recursively through the icon sizes until it finds the closest one by key position", "$", "funcGetIconSize", "=", "function", "(", "int", "$", "pos", ")", "use", "(", "$", "iconSizes", ",", "&", "$", "funcGetIconSize", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "pos", ",", "$", "iconSizes", ")", ")", "{", "return", "$", "funcGetIconSize", "(", "$", "pos", "-", "1", ")", ";", "}", "return", "$", "iconSizes", "[", "$", "pos", "]", ";", "}", ";", "$", "result", "=", "Utility", "::", "getFileTypeIcon", "(", "$", "entity", "->", "get", "(", "'extension'", ")", ",", "sprintf", "(", "'%dpx'", ",", "$", "funcGetIconSize", "(", "$", "position", ")", ")", ")", ";", "$", "result", "=", "$", "this", "->", "getUrlHelper", "(", ")", "->", "image", "(", "$", "result", ")", ";", "return", "$", "result", ";", "}" ]
Icon path getter. @param \Burzum\FileStorage\Model\Entity\FileStorage $entity FileStorage entity @param string $version Version name @return string
[ "Icon", "path", "getter", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/FileUpload.php#L289-L321
train
QoboLtd/cakephp-csv-migrations
src/Utility/FileUpload.php
FileUpload.getUrlHelper
private function getUrlHelper() : UrlHelper { if (null === $this->urlHelper) { $this->urlHelper = new UrlHelper(new View()); } return $this->urlHelper; }
php
private function getUrlHelper() : UrlHelper { if (null === $this->urlHelper) { $this->urlHelper = new UrlHelper(new View()); } return $this->urlHelper; }
[ "private", "function", "getUrlHelper", "(", ")", ":", "UrlHelper", "{", "if", "(", "null", "===", "$", "this", "->", "urlHelper", ")", "{", "$", "this", "->", "urlHelper", "=", "new", "UrlHelper", "(", "new", "View", "(", ")", ")", ";", "}", "return", "$", "this", "->", "urlHelper", ";", "}" ]
UrlHelper getter method. @return \Cake\View\Helper\UrlHelper
[ "UrlHelper", "getter", "method", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/FileUpload.php#L328-L335
train
QoboLtd/cakephp-csv-migrations
src/Utility/FileUpload.php
FileUpload.getFileFields
private function getFileFields() : array { $config = new ModuleConfig(ConfigType::MIGRATION(), $this->table->getAlias()); $config = json_encode($config->parse()); if (false === $config) { return []; } $fields = json_decode($config, true); if (empty($fields)) { return []; } $fields = array_filter($fields, function ($params) { return in_array($params['type'], self::FIELD_TYPES); }); return array_keys($fields); }
php
private function getFileFields() : array { $config = new ModuleConfig(ConfigType::MIGRATION(), $this->table->getAlias()); $config = json_encode($config->parse()); if (false === $config) { return []; } $fields = json_decode($config, true); if (empty($fields)) { return []; } $fields = array_filter($fields, function ($params) { return in_array($params['type'], self::FIELD_TYPES); }); return array_keys($fields); }
[ "private", "function", "getFileFields", "(", ")", ":", "array", "{", "$", "config", "=", "new", "ModuleConfig", "(", "ConfigType", "::", "MIGRATION", "(", ")", ",", "$", "this", "->", "table", "->", "getAlias", "(", ")", ")", ";", "$", "config", "=", "json_encode", "(", "$", "config", "->", "parse", "(", ")", ")", ";", "if", "(", "false", "===", "$", "config", ")", "{", "return", "[", "]", ";", "}", "$", "fields", "=", "json_decode", "(", "$", "config", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "fields", ")", ")", "{", "return", "[", "]", ";", "}", "$", "fields", "=", "array_filter", "(", "$", "fields", ",", "function", "(", "$", "params", ")", "{", "return", "in_array", "(", "$", "params", "[", "'type'", "]", ",", "self", "::", "FIELD_TYPES", ")", ";", "}", ")", ";", "return", "array_keys", "(", "$", "fields", ")", ";", "}" ]
File-type fields getter. @return mixed[]
[ "File", "-", "type", "fields", "getter", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/FileUpload.php#L456-L475
train
QoboLtd/cakephp-csv-migrations
src/Utility/FileUpload.php
FileUpload.delete
public function delete(string $id) : bool { $query = $this->storageTable->find('all', [ 'conditions' => [self::FILE_STORAGE_FOREIGN_KEY => $id] ]); $entity = $query->first(); if (is_null($entity)) { return false; } if ($this->storageTable->delete($entity)) { $this->removeThumbnails($entity); return true; } return false; }
php
public function delete(string $id) : bool { $query = $this->storageTable->find('all', [ 'conditions' => [self::FILE_STORAGE_FOREIGN_KEY => $id] ]); $entity = $query->first(); if (is_null($entity)) { return false; } if ($this->storageTable->delete($entity)) { $this->removeThumbnails($entity); return true; } return false; }
[ "public", "function", "delete", "(", "string", "$", "id", ")", ":", "bool", "{", "$", "query", "=", "$", "this", "->", "storageTable", "->", "find", "(", "'all'", ",", "[", "'conditions'", "=>", "[", "self", "::", "FILE_STORAGE_FOREIGN_KEY", "=>", "$", "id", "]", "]", ")", ";", "$", "entity", "=", "$", "query", "->", "first", "(", ")", ";", "if", "(", "is_null", "(", "$", "entity", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "this", "->", "storageTable", "->", "delete", "(", "$", "entity", ")", ")", "{", "$", "this", "->", "removeThumbnails", "(", "$", "entity", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
File delete method. @param string $id Associated Entity id @return bool @todo seems like this code is no longer in use, even though it should, as it handles thumbnails removal.
[ "File", "delete", "method", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/FileUpload.php#L503-L521
train
QoboLtd/cakephp-csv-migrations
src/Utility/FileUpload.php
FileUpload.handleThumbnails
private function handleThumbnails(FileStorage $entity, string $eventName) : bool { if (! in_array(strtolower($entity->get('extension')), self::IMAGE_EXTENSIONS)) { return false; } $imgSizes = (array)Configure::read(sprintf('FileStorage.imageSizes.%s', $entity->get('model'))); if (empty($imgSizes)) { $this->log( sprintf('Failed to %s: no image sizes defined for model "%s"', $eventName, $entity->get('model')), 'warning' ); return false; } $event = new Event($eventName, $this, [ 'entity' => $entity, 'versions' => array_keys($imgSizes), ]); EventManager::instance()->dispatch($event); $eventResult = $event->getResult(); if (empty($eventResult)) { $this->log(sprintf('Failed to %s: event result is empty', $eventName), 'error'); return false; } $result = true; foreach (array_keys($imgSizes) as $version) { if (! array_key_exists($version, $eventResult)) { $result = false; $this->log(sprintf('Failed to %s for version "%s"', $eventName, $version), 'error'); } if ('error' === $eventResult[$version]['status']) { $result = false; $this->log(sprintf('Failed to handle thumbnail: %s', $eventResult[$version]['error']), 'error'); } } return $result; }
php
private function handleThumbnails(FileStorage $entity, string $eventName) : bool { if (! in_array(strtolower($entity->get('extension')), self::IMAGE_EXTENSIONS)) { return false; } $imgSizes = (array)Configure::read(sprintf('FileStorage.imageSizes.%s', $entity->get('model'))); if (empty($imgSizes)) { $this->log( sprintf('Failed to %s: no image sizes defined for model "%s"', $eventName, $entity->get('model')), 'warning' ); return false; } $event = new Event($eventName, $this, [ 'entity' => $entity, 'versions' => array_keys($imgSizes), ]); EventManager::instance()->dispatch($event); $eventResult = $event->getResult(); if (empty($eventResult)) { $this->log(sprintf('Failed to %s: event result is empty', $eventName), 'error'); return false; } $result = true; foreach (array_keys($imgSizes) as $version) { if (! array_key_exists($version, $eventResult)) { $result = false; $this->log(sprintf('Failed to %s for version "%s"', $eventName, $version), 'error'); } if ('error' === $eventResult[$version]['status']) { $result = false; $this->log(sprintf('Failed to handle thumbnail: %s', $eventResult[$version]['error']), 'error'); } } return $result; }
[ "private", "function", "handleThumbnails", "(", "FileStorage", "$", "entity", ",", "string", "$", "eventName", ")", ":", "bool", "{", "if", "(", "!", "in_array", "(", "strtolower", "(", "$", "entity", "->", "get", "(", "'extension'", ")", ")", ",", "self", "::", "IMAGE_EXTENSIONS", ")", ")", "{", "return", "false", ";", "}", "$", "imgSizes", "=", "(", "array", ")", "Configure", "::", "read", "(", "sprintf", "(", "'FileStorage.imageSizes.%s'", ",", "$", "entity", "->", "get", "(", "'model'", ")", ")", ")", ";", "if", "(", "empty", "(", "$", "imgSizes", ")", ")", "{", "$", "this", "->", "log", "(", "sprintf", "(", "'Failed to %s: no image sizes defined for model \"%s\"'", ",", "$", "eventName", ",", "$", "entity", "->", "get", "(", "'model'", ")", ")", ",", "'warning'", ")", ";", "return", "false", ";", "}", "$", "event", "=", "new", "Event", "(", "$", "eventName", ",", "$", "this", ",", "[", "'entity'", "=>", "$", "entity", ",", "'versions'", "=>", "array_keys", "(", "$", "imgSizes", ")", ",", "]", ")", ";", "EventManager", "::", "instance", "(", ")", "->", "dispatch", "(", "$", "event", ")", ";", "$", "eventResult", "=", "$", "event", "->", "getResult", "(", ")", ";", "if", "(", "empty", "(", "$", "eventResult", ")", ")", "{", "$", "this", "->", "log", "(", "sprintf", "(", "'Failed to %s: event result is empty'", ",", "$", "eventName", ")", ",", "'error'", ")", ";", "return", "false", ";", "}", "$", "result", "=", "true", ";", "foreach", "(", "array_keys", "(", "$", "imgSizes", ")", "as", "$", "version", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "version", ",", "$", "eventResult", ")", ")", "{", "$", "result", "=", "false", ";", "$", "this", "->", "log", "(", "sprintf", "(", "'Failed to %s for version \"%s\"'", ",", "$", "eventName", ",", "$", "version", ")", ",", "'error'", ")", ";", "}", "if", "(", "'error'", "===", "$", "eventResult", "[", "$", "version", "]", "[", "'status'", "]", ")", "{", "$", "result", "=", "false", ";", "$", "this", "->", "log", "(", "sprintf", "(", "'Failed to handle thumbnail: %s'", ",", "$", "eventResult", "[", "$", "version", "]", "[", "'error'", "]", ")", ",", "'error'", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Method used for handling image file thumbnails creation and removal. Note that the code on this method was borrowed fromBurzum/FileStorage plugin, ImageVersionShell Class _loop method. @param \Burzum\FileStorage\Model\Entity\FileStorage $entity FileStorage entity @param string $eventName Event name @return bool
[ "Method", "used", "for", "handling", "image", "file", "thumbnails", "creation", "and", "removal", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/FileUpload.php#L555-L599
train
QoboLtd/cakephp-csv-migrations
src/Table.php
Table.validationDefault
public function validationDefault(Validator $validator) : Validator { // configurable in config/csv_migrations.php if (! Configure::read('CsvMigrations.tableValidation')) { return $validator; } return $this->validationEnabled($validator); }
php
public function validationDefault(Validator $validator) : Validator { // configurable in config/csv_migrations.php if (! Configure::read('CsvMigrations.tableValidation')) { return $validator; } return $this->validationEnabled($validator); }
[ "public", "function", "validationDefault", "(", "Validator", "$", "validator", ")", ":", "Validator", "{", "// configurable in config/csv_migrations.php", "if", "(", "!", "Configure", "::", "read", "(", "'CsvMigrations.tableValidation'", ")", ")", "{", "return", "$", "validator", ";", "}", "return", "$", "this", "->", "validationEnabled", "(", "$", "validator", ")", ";", "}" ]
Set Table validation rules if the validation is globally enabled. @param \Cake\Validation\Validator $validator Validator instance @return \Cake\Validation\Validator
[ "Set", "Table", "validation", "rules", "if", "the", "validation", "is", "globally", "enabled", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Table.php#L83-L91
train
QoboLtd/cakephp-csv-migrations
src/Table.php
Table.validationEnabled
public function validationEnabled(Validator $validator) : Validator { $className = App::shortName(get_class($this), 'Model/Table', 'Table'); $config = (new ModuleConfig(ConfigType::MIGRATION(), $className))->parse(); $config = json_encode($config); if (false === $config) { return $validator; } $config = json_decode($config, true); $factory = new FieldHandlerFactory(); foreach ($config as $column) { $validator = $factory->setValidationRules($this, $column['name'], $validator); } return $validator; }
php
public function validationEnabled(Validator $validator) : Validator { $className = App::shortName(get_class($this), 'Model/Table', 'Table'); $config = (new ModuleConfig(ConfigType::MIGRATION(), $className))->parse(); $config = json_encode($config); if (false === $config) { return $validator; } $config = json_decode($config, true); $factory = new FieldHandlerFactory(); foreach ($config as $column) { $validator = $factory->setValidationRules($this, $column['name'], $validator); } return $validator; }
[ "public", "function", "validationEnabled", "(", "Validator", "$", "validator", ")", ":", "Validator", "{", "$", "className", "=", "App", "::", "shortName", "(", "get_class", "(", "$", "this", ")", ",", "'Model/Table'", ",", "'Table'", ")", ";", "$", "config", "=", "(", "new", "ModuleConfig", "(", "ConfigType", "::", "MIGRATION", "(", ")", ",", "$", "className", ")", ")", "->", "parse", "(", ")", ";", "$", "config", "=", "json_encode", "(", "$", "config", ")", ";", "if", "(", "false", "===", "$", "config", ")", "{", "return", "$", "validator", ";", "}", "$", "config", "=", "json_decode", "(", "$", "config", ",", "true", ")", ";", "$", "factory", "=", "new", "FieldHandlerFactory", "(", ")", ";", "foreach", "(", "$", "config", "as", "$", "column", ")", "{", "$", "validator", "=", "$", "factory", "->", "setValidationRules", "(", "$", "this", ",", "$", "column", "[", "'name'", "]", ",", "$", "validator", ")", ";", "}", "return", "$", "validator", ";", "}" ]
Set Table validation rules. @param \Cake\Validation\Validator $validator Validator instance @return \Cake\Validation\Validator
[ "Set", "Table", "validation", "rules", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Table.php#L99-L115
train
QoboLtd/cakephp-csv-migrations
src/Table.php
Table.getFieldsDefinitions
public function getFieldsDefinitions(array $stubFields = []) : array { $result = []; // Get cached definitions if (! empty($this->_fieldDefinitions)) { $result = $this->_fieldDefinitions; } // Fetch definitions from CSV if cache is empty if (empty($result)) { $moduleName = App::shortName(get_class($this), 'Model/Table', 'Table'); list(, $moduleName) = pluginSplit($moduleName); $mc = new ModuleConfig(ConfigType::MIGRATION(), $moduleName); $config = json_encode($mc->parse()); $result = false === $config ? [] : json_decode($config, true); if (! empty($result)) { $this->_fieldDefinitions = $result; } } if (empty($stubFields)) { return $result; } // Merge $result with $stubFields foreach ($stubFields as $field => $definition) { if (!array_key_exists($field, $result)) { $result[$field] = $definition; } } return $result; }
php
public function getFieldsDefinitions(array $stubFields = []) : array { $result = []; // Get cached definitions if (! empty($this->_fieldDefinitions)) { $result = $this->_fieldDefinitions; } // Fetch definitions from CSV if cache is empty if (empty($result)) { $moduleName = App::shortName(get_class($this), 'Model/Table', 'Table'); list(, $moduleName) = pluginSplit($moduleName); $mc = new ModuleConfig(ConfigType::MIGRATION(), $moduleName); $config = json_encode($mc->parse()); $result = false === $config ? [] : json_decode($config, true); if (! empty($result)) { $this->_fieldDefinitions = $result; } } if (empty($stubFields)) { return $result; } // Merge $result with $stubFields foreach ($stubFields as $field => $definition) { if (!array_key_exists($field, $result)) { $result[$field] = $definition; } } return $result; }
[ "public", "function", "getFieldsDefinitions", "(", "array", "$", "stubFields", "=", "[", "]", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "// Get cached definitions", "if", "(", "!", "empty", "(", "$", "this", "->", "_fieldDefinitions", ")", ")", "{", "$", "result", "=", "$", "this", "->", "_fieldDefinitions", ";", "}", "// Fetch definitions from CSV if cache is empty", "if", "(", "empty", "(", "$", "result", ")", ")", "{", "$", "moduleName", "=", "App", "::", "shortName", "(", "get_class", "(", "$", "this", ")", ",", "'Model/Table'", ",", "'Table'", ")", ";", "list", "(", ",", "$", "moduleName", ")", "=", "pluginSplit", "(", "$", "moduleName", ")", ";", "$", "mc", "=", "new", "ModuleConfig", "(", "ConfigType", "::", "MIGRATION", "(", ")", ",", "$", "moduleName", ")", ";", "$", "config", "=", "json_encode", "(", "$", "mc", "->", "parse", "(", ")", ")", ";", "$", "result", "=", "false", "===", "$", "config", "?", "[", "]", ":", "json_decode", "(", "$", "config", ",", "true", ")", ";", "if", "(", "!", "empty", "(", "$", "result", ")", ")", "{", "$", "this", "->", "_fieldDefinitions", "=", "$", "result", ";", "}", "}", "if", "(", "empty", "(", "$", "stubFields", ")", ")", "{", "return", "$", "result", ";", "}", "// Merge $result with $stubFields", "foreach", "(", "$", "stubFields", "as", "$", "field", "=>", "$", "definition", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "field", ",", "$", "result", ")", ")", "{", "$", "result", "[", "$", "field", "]", "=", "$", "definition", ";", "}", "}", "return", "$", "result", ";", "}" ]
Get fields from CSV file This method gets all fields defined in the CSV and returns them as an associative array. Additionally, an associative array of stub fields can be passed, which will be included in the returned definitions. This is useful when working with fields which are NOT part of the migration.csv definitions, such as combined fields and virtual fields. If the field exists in the CSV configuration and is passed as a stub field, then the CSV definition will be preferred. Note that this method is called very frequently during the rendering of the views, so performance is important. For this reason, parsed definitions are stored in the property to avoid unnecessary processing of files and conversion of data. Stub fields, however, won't be cached as they are not real definitions and might vary from call to call. There are cases, when no field definitions are available at all. For example, external, non-CSV modules. For those cases, all exceptions and errors are silenced and an empty array of field definitions is returned. Unless, of course, there are stub fields provided. @param mixed[] $stubFields Stub fields @return mixed[] Associative array of fields and their definitions
[ "Get", "fields", "from", "CSV", "file" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Table.php#L165-L199
train
QoboLtd/cakephp-csv-migrations
src/Aggregator/Configuration.php
Configuration.setJoinData
public function setJoinData(Table $table, EntityInterface $entity) : self { $entityClass = $table->getEntityClass(); if (! $entity instanceof $entityClass) { throw new InvalidArgumentException(sprintf( 'Entity must be an instance of "%s". Instead, instance of "%s" was provided.', $table->getEntityClass(), get_class($entity) )); } $this->joinTable = $table; $this->entity = $entity; return $this; }
php
public function setJoinData(Table $table, EntityInterface $entity) : self { $entityClass = $table->getEntityClass(); if (! $entity instanceof $entityClass) { throw new InvalidArgumentException(sprintf( 'Entity must be an instance of "%s". Instead, instance of "%s" was provided.', $table->getEntityClass(), get_class($entity) )); } $this->joinTable = $table; $this->entity = $entity; return $this; }
[ "public", "function", "setJoinData", "(", "Table", "$", "table", ",", "EntityInterface", "$", "entity", ")", ":", "self", "{", "$", "entityClass", "=", "$", "table", "->", "getEntityClass", "(", ")", ";", "if", "(", "!", "$", "entity", "instanceof", "$", "entityClass", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Entity must be an instance of \"%s\". Instead, instance of \"%s\" was provided.'", ",", "$", "table", "->", "getEntityClass", "(", ")", ",", "get_class", "(", "$", "entity", ")", ")", ")", ";", "}", "$", "this", "->", "joinTable", "=", "$", "table", ";", "$", "this", "->", "entity", "=", "$", "entity", ";", "return", "$", "this", ";", "}" ]
Join data setter. @param \Cake\ORM\Table $table Join table intsance @param \Cake\Datasource\EntityInterface $entity Entity instance from join table @return self
[ "Join", "data", "setter", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Aggregator/Configuration.php#L155-L170
train
QoboLtd/cakephp-csv-migrations
src/FieldHandlers/Provider/FieldValue/MixedFieldValue.php
MixedFieldValue.provideFromRequest
protected function provideFromRequest(RequestInterface $request, string $field) : string { Assert::isInstanceOf($request, ServerRequest::class); $data = $request->getData(); $result = is_array($data) && array_key_exists($field, $data) ? (string)$data[$field] : ''; return $result; }
php
protected function provideFromRequest(RequestInterface $request, string $field) : string { Assert::isInstanceOf($request, ServerRequest::class); $data = $request->getData(); $result = is_array($data) && array_key_exists($field, $data) ? (string)$data[$field] : ''; return $result; }
[ "protected", "function", "provideFromRequest", "(", "RequestInterface", "$", "request", ",", "string", "$", "field", ")", ":", "string", "{", "Assert", "::", "isInstanceOf", "(", "$", "request", ",", "ServerRequest", "::", "class", ")", ";", "$", "data", "=", "$", "request", "->", "getData", "(", ")", ";", "$", "result", "=", "is_array", "(", "$", "data", ")", "&&", "array_key_exists", "(", "$", "field", ",", "$", "data", ")", "?", "(", "string", ")", "$", "data", "[", "$", "field", "]", ":", "''", ";", "return", "$", "result", ";", "}" ]
Get field value from Request Use $request->data[$field] if available. @param \Psr\Http\Message\RequestInterface $request Request to look for field value in @param string $field Field name @return string Field value
[ "Get", "field", "value", "from", "Request" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/FieldHandlers/Provider/FieldValue/MixedFieldValue.php#L76-L85
train
QoboLtd/cakephp-csv-migrations
src/FieldHandlers/Provider/RenderName/DefaultRenderer.php
DefaultRenderer.provide
public function provide($data = null, array $options = []) { $result = ''; // Return as is, if not empty if (!empty($data)) { return $data; } // Fallback on the field name $result = $this->config->getField(); $result = $this->cleanName($result); return $result; }
php
public function provide($data = null, array $options = []) { $result = ''; // Return as is, if not empty if (!empty($data)) { return $data; } // Fallback on the field name $result = $this->config->getField(); $result = $this->cleanName($result); return $result; }
[ "public", "function", "provide", "(", "$", "data", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "result", "=", "''", ";", "// Return as is, if not empty", "if", "(", "!", "empty", "(", "$", "data", ")", ")", "{", "return", "$", "data", ";", "}", "// Fallback on the field name", "$", "result", "=", "$", "this", "->", "config", "->", "getField", "(", ")", ";", "$", "result", "=", "$", "this", "->", "cleanName", "(", "$", "result", ")", ";", "return", "$", "result", ";", "}" ]
Provide rendered name @param mixed $data Data to use for provision @param array $options Options to use for provision @return mixed
[ "Provide", "rendered", "name" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/FieldHandlers/Provider/RenderName/DefaultRenderer.php#L32-L47
train
QoboLtd/cakephp-csv-migrations
src/View/Cell/DblistCell.php
DblistCell.renderValue
public function renderValue(string $value, string $list) : void { /** * @var \CsvMigrations\Model\Table\DblistsTable */ $table = $this->loadModel('CsvMigrations.Dblists'); $this->_createList($list); $query = $table->find() ->enableHydration(true) ->where([$table->aliasField('name') => $list]) ->matching('DblistItems', function ($q) use ($value) { return $q->where(['DblistItems.value' => $value]); }); try { $entity = $query->firstOrFail(); } catch (RecordNotFoundException $e) { $this->set('data', '' !== trim($value) ? sprintf(ListRenderer::VALUE_NOT_FOUND_HTML, $value) : ''); return; } Assert::isInstanceOf($entity, EntityInterface::class); $this->set('data', $entity->get('_matchingData')['DblistItems']->get('name')); }
php
public function renderValue(string $value, string $list) : void { /** * @var \CsvMigrations\Model\Table\DblistsTable */ $table = $this->loadModel('CsvMigrations.Dblists'); $this->_createList($list); $query = $table->find() ->enableHydration(true) ->where([$table->aliasField('name') => $list]) ->matching('DblistItems', function ($q) use ($value) { return $q->where(['DblistItems.value' => $value]); }); try { $entity = $query->firstOrFail(); } catch (RecordNotFoundException $e) { $this->set('data', '' !== trim($value) ? sprintf(ListRenderer::VALUE_NOT_FOUND_HTML, $value) : ''); return; } Assert::isInstanceOf($entity, EntityInterface::class); $this->set('data', $entity->get('_matchingData')['DblistItems']->get('name')); }
[ "public", "function", "renderValue", "(", "string", "$", "value", ",", "string", "$", "list", ")", ":", "void", "{", "/**\n * @var \\CsvMigrations\\Model\\Table\\DblistsTable\n */", "$", "table", "=", "$", "this", "->", "loadModel", "(", "'CsvMigrations.Dblists'", ")", ";", "$", "this", "->", "_createList", "(", "$", "list", ")", ";", "$", "query", "=", "$", "table", "->", "find", "(", ")", "->", "enableHydration", "(", "true", ")", "->", "where", "(", "[", "$", "table", "->", "aliasField", "(", "'name'", ")", "=>", "$", "list", "]", ")", "->", "matching", "(", "'DblistItems'", ",", "function", "(", "$", "q", ")", "use", "(", "$", "value", ")", "{", "return", "$", "q", "->", "where", "(", "[", "'DblistItems.value'", "=>", "$", "value", "]", ")", ";", "}", ")", ";", "try", "{", "$", "entity", "=", "$", "query", "->", "firstOrFail", "(", ")", ";", "}", "catch", "(", "RecordNotFoundException", "$", "e", ")", "{", "$", "this", "->", "set", "(", "'data'", ",", "''", "!==", "trim", "(", "$", "value", ")", "?", "sprintf", "(", "ListRenderer", "::", "VALUE_NOT_FOUND_HTML", ",", "$", "value", ")", ":", "''", ")", ";", "return", ";", "}", "Assert", "::", "isInstanceOf", "(", "$", "entity", ",", "EntityInterface", "::", "class", ")", ";", "$", "this", "->", "set", "(", "'data'", ",", "$", "entity", "->", "get", "(", "'_matchingData'", ")", "[", "'DblistItems'", "]", "->", "get", "(", "'name'", ")", ")", ";", "}" ]
Match and render the sucessfull value. Checks the given list if it has the given value in its list items. @param string $value List item value @param string $list Name of the list @return void
[ "Match", "and", "render", "the", "sucessfull", "value", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/View/Cell/DblistCell.php#L43-L68
train
QoboLtd/cakephp-csv-migrations
src/View/Cell/DblistCell.php
DblistCell._createList
protected function _createList(string $name) : bool { /** * @var \CsvMigrations\Model\Table\DblistsTable */ $table = $this->loadModel('CsvMigrations.Dblists'); if ($table->exists(['name' => $name])) { return false; } $entity = $table->newEntity(['name' => $name]); return (bool)$table->save($entity); }
php
protected function _createList(string $name) : bool { /** * @var \CsvMigrations\Model\Table\DblistsTable */ $table = $this->loadModel('CsvMigrations.Dblists'); if ($table->exists(['name' => $name])) { return false; } $entity = $table->newEntity(['name' => $name]); return (bool)$table->save($entity); }
[ "protected", "function", "_createList", "(", "string", "$", "name", ")", ":", "bool", "{", "/**\n * @var \\CsvMigrations\\Model\\Table\\DblistsTable\n */", "$", "table", "=", "$", "this", "->", "loadModel", "(", "'CsvMigrations.Dblists'", ")", ";", "if", "(", "$", "table", "->", "exists", "(", "[", "'name'", "=>", "$", "name", "]", ")", ")", "{", "return", "false", ";", "}", "$", "entity", "=", "$", "table", "->", "newEntity", "(", "[", "'name'", "=>", "$", "name", "]", ")", ";", "return", "(", "bool", ")", "$", "table", "->", "save", "(", "$", "entity", ")", ";", "}" ]
Create new list. It will fail to create a new list if the given name already exists. @param string $name List name @return bool
[ "Create", "new", "list", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/View/Cell/DblistCell.php#L78-L92
train
QoboLtd/cakephp-csv-migrations
src/Utility/Import.php
Import.getProcessedFile
public static function getProcessedFile(ImportEntity $import, bool $fullBase = true) : string { $pathInfo = pathinfo($import->get('filename')); $extension = $pathInfo['extension'] ?? ''; if (!empty($extension)) { $extension = '.' . $extension; } $result = $pathInfo['filename'] . static::PROCESSED_FILE_SUFFIX . $extension; if (!$fullBase) { return $result; } $result = $pathInfo['dirname'] . DS . $result; return $result; }
php
public static function getProcessedFile(ImportEntity $import, bool $fullBase = true) : string { $pathInfo = pathinfo($import->get('filename')); $extension = $pathInfo['extension'] ?? ''; if (!empty($extension)) { $extension = '.' . $extension; } $result = $pathInfo['filename'] . static::PROCESSED_FILE_SUFFIX . $extension; if (!$fullBase) { return $result; } $result = $pathInfo['dirname'] . DS . $result; return $result; }
[ "public", "static", "function", "getProcessedFile", "(", "ImportEntity", "$", "import", ",", "bool", "$", "fullBase", "=", "true", ")", ":", "string", "{", "$", "pathInfo", "=", "pathinfo", "(", "$", "import", "->", "get", "(", "'filename'", ")", ")", ";", "$", "extension", "=", "$", "pathInfo", "[", "'extension'", "]", "??", "''", ";", "if", "(", "!", "empty", "(", "$", "extension", ")", ")", "{", "$", "extension", "=", "'.'", ".", "$", "extension", ";", "}", "$", "result", "=", "$", "pathInfo", "[", "'filename'", "]", ".", "static", "::", "PROCESSED_FILE_SUFFIX", ".", "$", "extension", ";", "if", "(", "!", "$", "fullBase", ")", "{", "return", "$", "result", ";", "}", "$", "result", "=", "$", "pathInfo", "[", "'dirname'", "]", ".", "DS", ".", "$", "result", ";", "return", "$", "result", ";", "}" ]
Processed filename getter. @param \CsvMigrations\Model\Entity\Import $import Import entity @param bool $fullBase Full base flag @return string
[ "Processed", "filename", "getter", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Import.php#L90-L106
train
QoboLtd/cakephp-csv-migrations
src/Utility/Import.php
Import.upload
public function upload() : string { if (!$this->_validateUpload()) { return ''; } $result = $this->_uploadFile(); if ('' === $result) { $this->flash->error('Unable to upload file to the specified directory.'); } return $result; }
php
public function upload() : string { if (!$this->_validateUpload()) { return ''; } $result = $this->_uploadFile(); if ('' === $result) { $this->flash->error('Unable to upload file to the specified directory.'); } return $result; }
[ "public", "function", "upload", "(", ")", ":", "string", "{", "if", "(", "!", "$", "this", "->", "_validateUpload", "(", ")", ")", "{", "return", "''", ";", "}", "$", "result", "=", "$", "this", "->", "_uploadFile", "(", ")", ";", "if", "(", "''", "===", "$", "result", ")", "{", "$", "this", "->", "flash", "->", "error", "(", "'Unable to upload file to the specified directory.'", ")", ";", "}", "return", "$", "result", ";", "}" ]
Import file upload logic. @return string
[ "Import", "file", "upload", "logic", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Import.php#L113-L126
train
QoboLtd/cakephp-csv-migrations
src/Utility/Import.php
Import.create
public function create(ImportsTable $table, ImportEntity $entity, string $filename) : bool { $modelName = $this->request->getParam('controller'); if ($this->request->getParam('plugin')) { $modelName = $this->request->getParam('plugin') . '.' . $modelName; } $data = [ 'filename' => $filename, 'status' => $table::STATUS_PENDING, 'model_name' => $modelName, 'attempts' => 0 ]; $entity = $table->patchEntity($entity, $data); return (bool)$table->save($entity); }
php
public function create(ImportsTable $table, ImportEntity $entity, string $filename) : bool { $modelName = $this->request->getParam('controller'); if ($this->request->getParam('plugin')) { $modelName = $this->request->getParam('plugin') . '.' . $modelName; } $data = [ 'filename' => $filename, 'status' => $table::STATUS_PENDING, 'model_name' => $modelName, 'attempts' => 0 ]; $entity = $table->patchEntity($entity, $data); return (bool)$table->save($entity); }
[ "public", "function", "create", "(", "ImportsTable", "$", "table", ",", "ImportEntity", "$", "entity", ",", "string", "$", "filename", ")", ":", "bool", "{", "$", "modelName", "=", "$", "this", "->", "request", "->", "getParam", "(", "'controller'", ")", ";", "if", "(", "$", "this", "->", "request", "->", "getParam", "(", "'plugin'", ")", ")", "{", "$", "modelName", "=", "$", "this", "->", "request", "->", "getParam", "(", "'plugin'", ")", ".", "'.'", ".", "$", "modelName", ";", "}", "$", "data", "=", "[", "'filename'", "=>", "$", "filename", ",", "'status'", "=>", "$", "table", "::", "STATUS_PENDING", ",", "'model_name'", "=>", "$", "modelName", ",", "'attempts'", "=>", "0", "]", ";", "$", "entity", "=", "$", "table", "->", "patchEntity", "(", "$", "entity", ",", "$", "data", ")", ";", "return", "(", "bool", ")", "$", "table", "->", "save", "(", "$", "entity", ")", ";", "}" ]
Create import record. @param \CsvMigrations\Model\Table\ImportsTable $table Table instance @param \CsvMigrations\Model\Entity\Import $entity Import entity @param string $filename Uploaded file name @return bool
[ "Create", "import", "record", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Import.php#L136-L153
train
QoboLtd/cakephp-csv-migrations
src/Utility/Import.php
Import.getImportResults
public function getImportResults(ImportEntity $entity, array $columns) : QueryInterface { $sortCol = Hash::get($this->request->getQueryParams(), 'order.0.column', 0); $sortCol = array_key_exists($sortCol, $columns) ? $columns[$sortCol] : current($columns); $sortDir = Hash::get($this->request->getQueryParams(), 'order.0.dir', 'asc'); if (!in_array($sortDir, ['asc', 'desc'])) { $sortDir = 'asc'; } $table = TableRegistry::get('CsvMigrations.ImportResults'); $query = $table->find('all') ->where([$table->aliasField('import_id') => $entity->id]) ->order([$table->aliasField($sortCol) => $sortDir]); return $query; }
php
public function getImportResults(ImportEntity $entity, array $columns) : QueryInterface { $sortCol = Hash::get($this->request->getQueryParams(), 'order.0.column', 0); $sortCol = array_key_exists($sortCol, $columns) ? $columns[$sortCol] : current($columns); $sortDir = Hash::get($this->request->getQueryParams(), 'order.0.dir', 'asc'); if (!in_array($sortDir, ['asc', 'desc'])) { $sortDir = 'asc'; } $table = TableRegistry::get('CsvMigrations.ImportResults'); $query = $table->find('all') ->where([$table->aliasField('import_id') => $entity->id]) ->order([$table->aliasField($sortCol) => $sortDir]); return $query; }
[ "public", "function", "getImportResults", "(", "ImportEntity", "$", "entity", ",", "array", "$", "columns", ")", ":", "QueryInterface", "{", "$", "sortCol", "=", "Hash", "::", "get", "(", "$", "this", "->", "request", "->", "getQueryParams", "(", ")", ",", "'order.0.column'", ",", "0", ")", ";", "$", "sortCol", "=", "array_key_exists", "(", "$", "sortCol", ",", "$", "columns", ")", "?", "$", "columns", "[", "$", "sortCol", "]", ":", "current", "(", "$", "columns", ")", ";", "$", "sortDir", "=", "Hash", "::", "get", "(", "$", "this", "->", "request", "->", "getQueryParams", "(", ")", ",", "'order.0.dir'", ",", "'asc'", ")", ";", "if", "(", "!", "in_array", "(", "$", "sortDir", ",", "[", "'asc'", ",", "'desc'", "]", ")", ")", "{", "$", "sortDir", "=", "'asc'", ";", "}", "$", "table", "=", "TableRegistry", "::", "get", "(", "'CsvMigrations.ImportResults'", ")", ";", "$", "query", "=", "$", "table", "->", "find", "(", "'all'", ")", "->", "where", "(", "[", "$", "table", "->", "aliasField", "(", "'import_id'", ")", "=>", "$", "entity", "->", "id", "]", ")", "->", "order", "(", "[", "$", "table", "->", "aliasField", "(", "$", "sortCol", ")", "=>", "$", "sortDir", "]", ")", ";", "return", "$", "query", ";", "}" ]
Import results getter. @param \CsvMigrations\Model\Entity\Import $entity Import entity @param string[] $columns Display columns @return \Cake\Datasource\QueryInterface
[ "Import", "results", "getter", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Import.php#L162-L179
train
QoboLtd/cakephp-csv-migrations
src/Utility/Import.php
Import.prepareOptions
public static function prepareOptions(array $options) : array { if (empty($options['fields'])) { return []; } $result = []; foreach ($options['fields'] as $field => $params) { if (empty($params['column']) && empty($params['default'])) { continue; } $result['fields'][$field] = $params; } return $result; }
php
public static function prepareOptions(array $options) : array { if (empty($options['fields'])) { return []; } $result = []; foreach ($options['fields'] as $field => $params) { if (empty($params['column']) && empty($params['default'])) { continue; } $result['fields'][$field] = $params; } return $result; }
[ "public", "static", "function", "prepareOptions", "(", "array", "$", "options", ")", ":", "array", "{", "if", "(", "empty", "(", "$", "options", "[", "'fields'", "]", ")", ")", "{", "return", "[", "]", ";", "}", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "options", "[", "'fields'", "]", "as", "$", "field", "=>", "$", "params", ")", "{", "if", "(", "empty", "(", "$", "params", "[", "'column'", "]", ")", "&&", "empty", "(", "$", "params", "[", "'default'", "]", ")", ")", "{", "continue", ";", "}", "$", "result", "[", "'fields'", "]", "[", "$", "field", "]", "=", "$", "params", ";", "}", "return", "$", "result", ";", "}" ]
Prepare import options by removing fields with empty mapping parameters. @param mixed[] $options Import options @return mixed[]
[ "Prepare", "import", "options", "by", "removing", "fields", "with", "empty", "mapping", "parameters", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Import.php#L187-L203
train
QoboLtd/cakephp-csv-migrations
src/Utility/Import.php
Import.getRowsCount
public static function getRowsCount(string $path, bool $withHeader = false) : int { $result = trim(exec("/usr/bin/env wc -l '" . $path . "'", $output, $return)); if (0 === $return) { list($result, ) = explode(' ', $result); $result = (int)$result; if (0 < $result) { $result -= 1; } return $result; } $reader = Reader::createFromPath($path, 'r'); $result = $reader->each(function ($row) { return true; }); if (! $withHeader) { $result = $result - 1; } return $result; }
php
public static function getRowsCount(string $path, bool $withHeader = false) : int { $result = trim(exec("/usr/bin/env wc -l '" . $path . "'", $output, $return)); if (0 === $return) { list($result, ) = explode(' ', $result); $result = (int)$result; if (0 < $result) { $result -= 1; } return $result; } $reader = Reader::createFromPath($path, 'r'); $result = $reader->each(function ($row) { return true; }); if (! $withHeader) { $result = $result - 1; } return $result; }
[ "public", "static", "function", "getRowsCount", "(", "string", "$", "path", ",", "bool", "$", "withHeader", "=", "false", ")", ":", "int", "{", "$", "result", "=", "trim", "(", "exec", "(", "\"/usr/bin/env wc -l '\"", ".", "$", "path", ".", "\"'\"", ",", "$", "output", ",", "$", "return", ")", ")", ";", "if", "(", "0", "===", "$", "return", ")", "{", "list", "(", "$", "result", ",", ")", "=", "explode", "(", "' '", ",", "$", "result", ")", ";", "$", "result", "=", "(", "int", ")", "$", "result", ";", "if", "(", "0", "<", "$", "result", ")", "{", "$", "result", "-=", "1", ";", "}", "return", "$", "result", ";", "}", "$", "reader", "=", "Reader", "::", "createFromPath", "(", "$", "path", ",", "'r'", ")", ";", "$", "result", "=", "$", "reader", "->", "each", "(", "function", "(", "$", "row", ")", "{", "return", "true", ";", "}", ")", ";", "if", "(", "!", "$", "withHeader", ")", "{", "$", "result", "=", "$", "result", "-", "1", ";", "}", "return", "$", "result", ";", "}" ]
Get CSV file rows count. @param string $path File path @param bool $withHeader Include header row into the count @return int
[ "Get", "CSV", "file", "rows", "count", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Import.php#L212-L236
train
QoboLtd/cakephp-csv-migrations
src/Utility/Import.php
Import.getTableColumns
public function getTableColumns() : array { $schema = $this->table->getSchema(); $result = []; foreach ($schema->columns() as $column) { if (in_array($column, CsvMigration::getRequiredFields())) { continue; } $result[] = $column; } return $result; }
php
public function getTableColumns() : array { $schema = $this->table->getSchema(); $result = []; foreach ($schema->columns() as $column) { if (in_array($column, CsvMigration::getRequiredFields())) { continue; } $result[] = $column; } return $result; }
[ "public", "function", "getTableColumns", "(", ")", ":", "array", "{", "$", "schema", "=", "$", "this", "->", "table", "->", "getSchema", "(", ")", ";", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "schema", "->", "columns", "(", ")", "as", "$", "column", ")", "{", "if", "(", "in_array", "(", "$", "column", ",", "CsvMigration", "::", "getRequiredFields", "(", ")", ")", ")", "{", "continue", ";", "}", "$", "result", "[", "]", "=", "$", "column", ";", "}", "return", "$", "result", ";", "}" ]
Get target module fields. @return string[]
[ "Get", "target", "module", "fields", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Import.php#L256-L270
train
QoboLtd/cakephp-csv-migrations
src/Utility/Import.php
Import.actionButtons
public static function actionButtons(ResultSetInterface $resultSet, Table $table, array $data) : array { $view = new View(); list($plugin, $controller) = pluginSplit($table->getRegistryAlias()); foreach ($resultSet as $key => $entity) { if (!$entity->get('model_id')) { $data[$key][] = ''; continue; } $url = [ 'prefix' => false, 'plugin' => $plugin, 'controller' => $controller, 'action' => 'view', $entity->get('model_id') ]; $link = $view->Html->link('<i class="fa fa-eye"></i>', $url, [ 'title' => __('View'), 'class' => 'btn btn-default', 'escape' => false ]); $html = '<div class="btn-group btn-group-xs" role="group">' . $link . '</div>'; $data[$key][] = $html; } return $data; }
php
public static function actionButtons(ResultSetInterface $resultSet, Table $table, array $data) : array { $view = new View(); list($plugin, $controller) = pluginSplit($table->getRegistryAlias()); foreach ($resultSet as $key => $entity) { if (!$entity->get('model_id')) { $data[$key][] = ''; continue; } $url = [ 'prefix' => false, 'plugin' => $plugin, 'controller' => $controller, 'action' => 'view', $entity->get('model_id') ]; $link = $view->Html->link('<i class="fa fa-eye"></i>', $url, [ 'title' => __('View'), 'class' => 'btn btn-default', 'escape' => false ]); $html = '<div class="btn-group btn-group-xs" role="group">' . $link . '</div>'; $data[$key][] = $html; } return $data; }
[ "public", "static", "function", "actionButtons", "(", "ResultSetInterface", "$", "resultSet", ",", "Table", "$", "table", ",", "array", "$", "data", ")", ":", "array", "{", "$", "view", "=", "new", "View", "(", ")", ";", "list", "(", "$", "plugin", ",", "$", "controller", ")", "=", "pluginSplit", "(", "$", "table", "->", "getRegistryAlias", "(", ")", ")", ";", "foreach", "(", "$", "resultSet", "as", "$", "key", "=>", "$", "entity", ")", "{", "if", "(", "!", "$", "entity", "->", "get", "(", "'model_id'", ")", ")", "{", "$", "data", "[", "$", "key", "]", "[", "]", "=", "''", ";", "continue", ";", "}", "$", "url", "=", "[", "'prefix'", "=>", "false", ",", "'plugin'", "=>", "$", "plugin", ",", "'controller'", "=>", "$", "controller", ",", "'action'", "=>", "'view'", ",", "$", "entity", "->", "get", "(", "'model_id'", ")", "]", ";", "$", "link", "=", "$", "view", "->", "Html", "->", "link", "(", "'<i class=\"fa fa-eye\"></i>'", ",", "$", "url", ",", "[", "'title'", "=>", "__", "(", "'View'", ")", ",", "'class'", "=>", "'btn btn-default'", ",", "'escape'", "=>", "false", "]", ")", ";", "$", "html", "=", "'<div class=\"btn-group btn-group-xs\" role=\"group\">'", ".", "$", "link", ".", "'</div>'", ";", "$", "data", "[", "$", "key", "]", "[", "]", "=", "$", "html", ";", "}", "return", "$", "data", ";", "}" ]
Add action buttons to response data. @param \Cake\Datasource\ResultSetInterface $resultSet ResultSet @param \Cake\ORM\Table $table Table instance @param mixed[] $data Response data @return mixed[]
[ "Add", "action", "buttons", "to", "response", "data", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Import.php#L304-L334
train
QoboLtd/cakephp-csv-migrations
src/Utility/Import.php
Import.setStatusLabels
public static function setStatusLabels(array $data, int $index) : array { $view = new View(); $statusLabels = [ ImportResultsTable::STATUS_SUCCESS => 'success', ImportResultsTable::STATUS_PENDING => 'warning', ImportResultsTable::STATUS_FAIL => 'danger' ]; foreach ($data as $key => $value) { $data[$key][$index] = $view->Html->tag('span', $value[$index], [ 'class' => 'label label-' . $statusLabels[$value[$index]] ]); } return $data; }
php
public static function setStatusLabels(array $data, int $index) : array { $view = new View(); $statusLabels = [ ImportResultsTable::STATUS_SUCCESS => 'success', ImportResultsTable::STATUS_PENDING => 'warning', ImportResultsTable::STATUS_FAIL => 'danger' ]; foreach ($data as $key => $value) { $data[$key][$index] = $view->Html->tag('span', $value[$index], [ 'class' => 'label label-' . $statusLabels[$value[$index]] ]); } return $data; }
[ "public", "static", "function", "setStatusLabels", "(", "array", "$", "data", ",", "int", "$", "index", ")", ":", "array", "{", "$", "view", "=", "new", "View", "(", ")", ";", "$", "statusLabels", "=", "[", "ImportResultsTable", "::", "STATUS_SUCCESS", "=>", "'success'", ",", "ImportResultsTable", "::", "STATUS_PENDING", "=>", "'warning'", ",", "ImportResultsTable", "::", "STATUS_FAIL", "=>", "'danger'", "]", ";", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "data", "[", "$", "key", "]", "[", "$", "index", "]", "=", "$", "view", "->", "Html", "->", "tag", "(", "'span'", ",", "$", "value", "[", "$", "index", "]", ",", "[", "'class'", "=>", "'label label-'", ".", "$", "statusLabels", "[", "$", "value", "[", "$", "index", "]", "]", "]", ")", ";", "}", "return", "$", "data", ";", "}" ]
Response data status labels setter. @param mixed[] $data Response data @param int $index Status column index @return mixed[]
[ "Response", "data", "status", "labels", "setter", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Import.php#L343-L358
train
QoboLtd/cakephp-csv-migrations
src/Utility/Import.php
Import._validateUpload
protected function _validateUpload() : bool { if (! $this->request->getData('file')) { $this->flash->error('Please choose a file to upload.'); return false; } if (! in_array($this->request->getData('file.type'), $this->__supportedMimeTypes)) { $this->flash->error('Unable to upload file, unsupported file provided.'); return false; } return true; }
php
protected function _validateUpload() : bool { if (! $this->request->getData('file')) { $this->flash->error('Please choose a file to upload.'); return false; } if (! in_array($this->request->getData('file.type'), $this->__supportedMimeTypes)) { $this->flash->error('Unable to upload file, unsupported file provided.'); return false; } return true; }
[ "protected", "function", "_validateUpload", "(", ")", ":", "bool", "{", "if", "(", "!", "$", "this", "->", "request", "->", "getData", "(", "'file'", ")", ")", "{", "$", "this", "->", "flash", "->", "error", "(", "'Please choose a file to upload.'", ")", ";", "return", "false", ";", "}", "if", "(", "!", "in_array", "(", "$", "this", "->", "request", "->", "getData", "(", "'file.type'", ")", ",", "$", "this", "->", "__supportedMimeTypes", ")", ")", "{", "$", "this", "->", "flash", "->", "error", "(", "'Unable to upload file, unsupported file provided.'", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Upload file validation. @return bool
[ "Upload", "file", "validation", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Import.php#L365-L380
train
QoboLtd/cakephp-csv-migrations
src/Utility/Import.php
Import._uploadFile
protected function _uploadFile() : string { if (! is_string($this->request->getData('file.name'))) { return ''; } if (! is_string($this->request->getData('file.tmp_name'))) { return ''; } $uploadPath = $this->_getUploadPath(); if ('' === $uploadPath) { return ''; } $pathInfo = pathinfo($this->request->getData('file.name')); $filename = (string)preg_replace('/\W/', '_', $pathInfo['filename']); $filename = (string)preg_replace('/_+/', '_', $filename); $filename = trim($filename, '_'); $extension = $pathInfo['extension'] ?? ''; if (!empty($extension)) { $extension = '.' . $extension; } $path = sprintf( '%s%s_%s%s', $uploadPath, (new Time())->i18nFormat('yyyyMMddHHmmss'), $filename, $extension ); if (! move_uploaded_file($this->request->getData('file.tmp_name'), $path)) { return ''; } return $path; }
php
protected function _uploadFile() : string { if (! is_string($this->request->getData('file.name'))) { return ''; } if (! is_string($this->request->getData('file.tmp_name'))) { return ''; } $uploadPath = $this->_getUploadPath(); if ('' === $uploadPath) { return ''; } $pathInfo = pathinfo($this->request->getData('file.name')); $filename = (string)preg_replace('/\W/', '_', $pathInfo['filename']); $filename = (string)preg_replace('/_+/', '_', $filename); $filename = trim($filename, '_'); $extension = $pathInfo['extension'] ?? ''; if (!empty($extension)) { $extension = '.' . $extension; } $path = sprintf( '%s%s_%s%s', $uploadPath, (new Time())->i18nFormat('yyyyMMddHHmmss'), $filename, $extension ); if (! move_uploaded_file($this->request->getData('file.tmp_name'), $path)) { return ''; } return $path; }
[ "protected", "function", "_uploadFile", "(", ")", ":", "string", "{", "if", "(", "!", "is_string", "(", "$", "this", "->", "request", "->", "getData", "(", "'file.name'", ")", ")", ")", "{", "return", "''", ";", "}", "if", "(", "!", "is_string", "(", "$", "this", "->", "request", "->", "getData", "(", "'file.tmp_name'", ")", ")", ")", "{", "return", "''", ";", "}", "$", "uploadPath", "=", "$", "this", "->", "_getUploadPath", "(", ")", ";", "if", "(", "''", "===", "$", "uploadPath", ")", "{", "return", "''", ";", "}", "$", "pathInfo", "=", "pathinfo", "(", "$", "this", "->", "request", "->", "getData", "(", "'file.name'", ")", ")", ";", "$", "filename", "=", "(", "string", ")", "preg_replace", "(", "'/\\W/'", ",", "'_'", ",", "$", "pathInfo", "[", "'filename'", "]", ")", ";", "$", "filename", "=", "(", "string", ")", "preg_replace", "(", "'/_+/'", ",", "'_'", ",", "$", "filename", ")", ";", "$", "filename", "=", "trim", "(", "$", "filename", ",", "'_'", ")", ";", "$", "extension", "=", "$", "pathInfo", "[", "'extension'", "]", "??", "''", ";", "if", "(", "!", "empty", "(", "$", "extension", ")", ")", "{", "$", "extension", "=", "'.'", ".", "$", "extension", ";", "}", "$", "path", "=", "sprintf", "(", "'%s%s_%s%s'", ",", "$", "uploadPath", ",", "(", "new", "Time", "(", ")", ")", "->", "i18nFormat", "(", "'yyyyMMddHHmmss'", ")", ",", "$", "filename", ",", "$", "extension", ")", ";", "if", "(", "!", "move_uploaded_file", "(", "$", "this", "->", "request", "->", "getData", "(", "'file.tmp_name'", ")", ",", "$", "path", ")", ")", "{", "return", "''", ";", "}", "return", "$", "path", ";", "}" ]
Upload data file. @return string
[ "Upload", "data", "file", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Import.php#L387-L425
train
QoboLtd/cakephp-csv-migrations
src/Utility/Import.php
Import._getUploadPath
protected function _getUploadPath() : string { $result = Configure::read('Importer.path'); // if no path specified, fallback to the default. if (!$result) { $result = WWW_ROOT . 'uploads' . DS; } // include trailing directory separator. $result = rtrim($result, DS); $result .= DS; if (file_exists($result)) { return $result; } // create upload path, recursively. if (!mkdir($result, 0777, true)) { $this->flash->error('Failed to create upload directory.'); return ''; } return $result; }
php
protected function _getUploadPath() : string { $result = Configure::read('Importer.path'); // if no path specified, fallback to the default. if (!$result) { $result = WWW_ROOT . 'uploads' . DS; } // include trailing directory separator. $result = rtrim($result, DS); $result .= DS; if (file_exists($result)) { return $result; } // create upload path, recursively. if (!mkdir($result, 0777, true)) { $this->flash->error('Failed to create upload directory.'); return ''; } return $result; }
[ "protected", "function", "_getUploadPath", "(", ")", ":", "string", "{", "$", "result", "=", "Configure", "::", "read", "(", "'Importer.path'", ")", ";", "// if no path specified, fallback to the default.", "if", "(", "!", "$", "result", ")", "{", "$", "result", "=", "WWW_ROOT", ".", "'uploads'", ".", "DS", ";", "}", "// include trailing directory separator.", "$", "result", "=", "rtrim", "(", "$", "result", ",", "DS", ")", ";", "$", "result", ".=", "DS", ";", "if", "(", "file_exists", "(", "$", "result", ")", ")", "{", "return", "$", "result", ";", "}", "// create upload path, recursively.", "if", "(", "!", "mkdir", "(", "$", "result", ",", "0777", ",", "true", ")", ")", "{", "$", "this", "->", "flash", "->", "error", "(", "'Failed to create upload directory.'", ")", ";", "return", "''", ";", "}", "return", "$", "result", ";", "}" ]
Upload path getter. @return string
[ "Upload", "path", "getter", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Import.php#L432-L457
train
QoboLtd/cakephp-csv-migrations
src/Utility/ICal/IcEvent.php
IcEvent.configureEvent
public function configureEvent(array $params = []) : void { $params = array_merge($this->defaultParams, $params); foreach ($params as $name => $value) { $method = 'set' . ucfirst((string)$name); if (method_exists($this, $method) && is_callable([$this, $method])) { $this->$method($value); } } }
php
public function configureEvent(array $params = []) : void { $params = array_merge($this->defaultParams, $params); foreach ($params as $name => $value) { $method = 'set' . ucfirst((string)$name); if (method_exists($this, $method) && is_callable([$this, $method])) { $this->$method($value); } } }
[ "public", "function", "configureEvent", "(", "array", "$", "params", "=", "[", "]", ")", ":", "void", "{", "$", "params", "=", "array_merge", "(", "$", "this", "->", "defaultParams", ",", "$", "params", ")", ";", "foreach", "(", "$", "params", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "method", "=", "'set'", ".", "ucfirst", "(", "(", "string", ")", "$", "name", ")", ";", "if", "(", "method_exists", "(", "$", "this", ",", "$", "method", ")", "&&", "is_callable", "(", "[", "$", "this", ",", "$", "method", "]", ")", ")", "{", "$", "this", "->", "$", "method", "(", "$", "value", ")", ";", "}", "}", "}" ]
Configure Event parameters @param mixed[] $params Event parameters @return void
[ "Configure", "Event", "parameters" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/ICal/IcEvent.php#L70-L79
train
QoboLtd/cakephp-csv-migrations
src/Utility/ICal/IcEvent.php
IcEvent.setOrganizer
public function setOrganizer(string $email) : void { if ('' !== $email) { $this->event->setOrganizer( new Organizer($email, ['MAILTO' => $email]) ); } }
php
public function setOrganizer(string $email) : void { if ('' !== $email) { $this->event->setOrganizer( new Organizer($email, ['MAILTO' => $email]) ); } }
[ "public", "function", "setOrganizer", "(", "string", "$", "email", ")", ":", "void", "{", "if", "(", "''", "!==", "$", "email", ")", "{", "$", "this", "->", "event", "->", "setOrganizer", "(", "new", "Organizer", "(", "$", "email", ",", "[", "'MAILTO'", "=>", "$", "email", "]", ")", ")", ";", "}", "}" ]
Set Event organizer @param string $email Organizer email @return void
[ "Set", "Event", "organizer" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/ICal/IcEvent.php#L138-L145
train
QoboLtd/cakephp-csv-migrations
src/Utility/ICal/IcEvent.php
IcEvent.setAttendees
public function setAttendees(array $attendees = []) : void { $iCalAttendees = new Attendees(); foreach ($attendees as $email) { $iCalAttendees->add("MAILTO:$email", [ 'ROLE' => 'REQ-PARTICIPANT', 'PARTSTAT' => 'NEEDS-ACTION', 'RSVP' => 'TRUE', ]); } $this->event->setAttendees($iCalAttendees); }
php
public function setAttendees(array $attendees = []) : void { $iCalAttendees = new Attendees(); foreach ($attendees as $email) { $iCalAttendees->add("MAILTO:$email", [ 'ROLE' => 'REQ-PARTICIPANT', 'PARTSTAT' => 'NEEDS-ACTION', 'RSVP' => 'TRUE', ]); } $this->event->setAttendees($iCalAttendees); }
[ "public", "function", "setAttendees", "(", "array", "$", "attendees", "=", "[", "]", ")", ":", "void", "{", "$", "iCalAttendees", "=", "new", "Attendees", "(", ")", ";", "foreach", "(", "$", "attendees", "as", "$", "email", ")", "{", "$", "iCalAttendees", "->", "add", "(", "\"MAILTO:$email\"", ",", "[", "'ROLE'", "=>", "'REQ-PARTICIPANT'", ",", "'PARTSTAT'", "=>", "'NEEDS-ACTION'", ",", "'RSVP'", "=>", "'TRUE'", ",", "]", ")", ";", "}", "$", "this", "->", "event", "->", "setAttendees", "(", "$", "iCalAttendees", ")", ";", "}" ]
Set Event attendees @param string[] $attendees A list of attendees' emails @return void
[ "Set", "Event", "attendees" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/ICal/IcEvent.php#L210-L221
train
QoboLtd/cakephp-csv-migrations
src/Controller/AppController.php
AppController.fetchEntity
protected function fetchEntity(string $id) : EntityInterface { $table = $this->loadModel(); Assert::isInstanceOf($table, Table::class); $primaryKey = $table->getPrimaryKey(); if (! is_string($primaryKey)) { throw new UnsupportedPrimaryKeyException(); } try { $entity = $table->find() ->where([$table->aliasField($primaryKey) => $id]) ->enableHydration(true) ->firstOrFail(); Assert::isInstanceOf($entity, EntityInterface::class); return $entity; } catch (Exception $e) { // $id is a UUID, re-throwing the exception as we cannot fetch the record by lookup field(s) if (Validation::uuid($id)) { throw $e; } } /** * Try to fetch record by lookup field(s) * * @var \Cake\Datasource\EntityInterface */ $entity = $table->find() ->applyOptions(['lookup' => true, 'value' => $id]) ->enableHydration(true) ->firstOrFail(); return $entity; }
php
protected function fetchEntity(string $id) : EntityInterface { $table = $this->loadModel(); Assert::isInstanceOf($table, Table::class); $primaryKey = $table->getPrimaryKey(); if (! is_string($primaryKey)) { throw new UnsupportedPrimaryKeyException(); } try { $entity = $table->find() ->where([$table->aliasField($primaryKey) => $id]) ->enableHydration(true) ->firstOrFail(); Assert::isInstanceOf($entity, EntityInterface::class); return $entity; } catch (Exception $e) { // $id is a UUID, re-throwing the exception as we cannot fetch the record by lookup field(s) if (Validation::uuid($id)) { throw $e; } } /** * Try to fetch record by lookup field(s) * * @var \Cake\Datasource\EntityInterface */ $entity = $table->find() ->applyOptions(['lookup' => true, 'value' => $id]) ->enableHydration(true) ->firstOrFail(); return $entity; }
[ "protected", "function", "fetchEntity", "(", "string", "$", "id", ")", ":", "EntityInterface", "{", "$", "table", "=", "$", "this", "->", "loadModel", "(", ")", ";", "Assert", "::", "isInstanceOf", "(", "$", "table", ",", "Table", "::", "class", ")", ";", "$", "primaryKey", "=", "$", "table", "->", "getPrimaryKey", "(", ")", ";", "if", "(", "!", "is_string", "(", "$", "primaryKey", ")", ")", "{", "throw", "new", "UnsupportedPrimaryKeyException", "(", ")", ";", "}", "try", "{", "$", "entity", "=", "$", "table", "->", "find", "(", ")", "->", "where", "(", "[", "$", "table", "->", "aliasField", "(", "$", "primaryKey", ")", "=>", "$", "id", "]", ")", "->", "enableHydration", "(", "true", ")", "->", "firstOrFail", "(", ")", ";", "Assert", "::", "isInstanceOf", "(", "$", "entity", ",", "EntityInterface", "::", "class", ")", ";", "return", "$", "entity", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "// $id is a UUID, re-throwing the exception as we cannot fetch the record by lookup field(s)", "if", "(", "Validation", "::", "uuid", "(", "$", "id", ")", ")", "{", "throw", "$", "e", ";", "}", "}", "/**\n * Try to fetch record by lookup field(s)\n *\n * @var \\Cake\\Datasource\\EntityInterface\n */", "$", "entity", "=", "$", "table", "->", "find", "(", ")", "->", "applyOptions", "(", "[", "'lookup'", "=>", "true", ",", "'value'", "=>", "$", "id", "]", ")", "->", "enableHydration", "(", "true", ")", "->", "firstOrFail", "(", ")", ";", "return", "$", "entity", ";", "}" ]
Fetches entity from database. Tries to fetch the record using the primary key, if no record found and the ID value is not a UUID it will try to fetch the record using the lookup fields. If that fails as well then a record not found exception will be thrown. @param string $id Entity id @return \Cake\Datasource\EntityInterface @throws \Cake\Datasource\Exception\RecordNotFoundException When the record is not found
[ "Fetches", "entity", "from", "database", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Controller/AppController.php#L197-L233
train
QoboLtd/cakephp-csv-migrations
src/Controller/AppController.php
AppController.getBatchRedirectUrl
protected function getBatchRedirectUrl() : string { // default url $result = ['plugin' => $this->plugin, 'controller' => $this->name, 'action' => 'index']; $currentUrl = $this->request->getEnv('HTTP_ORIGIN') . $this->request->getRequestTarget(); // if referer does not match current url, redirect to referer (delete action) if (false === strpos($this->referer(), $currentUrl)) { $result = $this->referer(); } // use batch redirect url if provided (edit action) if ($this->request->getData('batch.redirect_url')) { $result = $this->request->getData('batch.redirect_url'); } return Router::url($result); }
php
protected function getBatchRedirectUrl() : string { // default url $result = ['plugin' => $this->plugin, 'controller' => $this->name, 'action' => 'index']; $currentUrl = $this->request->getEnv('HTTP_ORIGIN') . $this->request->getRequestTarget(); // if referer does not match current url, redirect to referer (delete action) if (false === strpos($this->referer(), $currentUrl)) { $result = $this->referer(); } // use batch redirect url if provided (edit action) if ($this->request->getData('batch.redirect_url')) { $result = $this->request->getData('batch.redirect_url'); } return Router::url($result); }
[ "protected", "function", "getBatchRedirectUrl", "(", ")", ":", "string", "{", "// default url", "$", "result", "=", "[", "'plugin'", "=>", "$", "this", "->", "plugin", ",", "'controller'", "=>", "$", "this", "->", "name", ",", "'action'", "=>", "'index'", "]", ";", "$", "currentUrl", "=", "$", "this", "->", "request", "->", "getEnv", "(", "'HTTP_ORIGIN'", ")", ".", "$", "this", "->", "request", "->", "getRequestTarget", "(", ")", ";", "// if referer does not match current url, redirect to referer (delete action)", "if", "(", "false", "===", "strpos", "(", "$", "this", "->", "referer", "(", ")", ",", "$", "currentUrl", ")", ")", "{", "$", "result", "=", "$", "this", "->", "referer", "(", ")", ";", "}", "// use batch redirect url if provided (edit action)", "if", "(", "$", "this", "->", "request", "->", "getData", "(", "'batch.redirect_url'", ")", ")", "{", "$", "result", "=", "$", "this", "->", "request", "->", "getData", "(", "'batch.redirect_url'", ")", ";", "}", "return", "Router", "::", "url", "(", "$", "result", ")", ";", "}" ]
Fetch batch redirect url. @return string
[ "Fetch", "batch", "redirect", "url", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Controller/AppController.php#L497-L514
train
QoboLtd/cakephp-csv-migrations
src/Validation/Validator.php
Validator.inModuleList
public function inModuleList(string $item, string $moduleName, string $listName) { try { $items = (new ModuleConfig(ConfigType::LISTS(), $moduleName, $listName))->parseToArray(); } catch (InvalidArgumentException $e) { return $e->getMessage(); } /** @var mixed[]|null $config */ $inactive = $items['items'][$item]['inactive'] ?? null; if ($inactive === null || $inactive === true) { return (string)__('Invalid list item: `{0}`', $item); } return true; }
php
public function inModuleList(string $item, string $moduleName, string $listName) { try { $items = (new ModuleConfig(ConfigType::LISTS(), $moduleName, $listName))->parseToArray(); } catch (InvalidArgumentException $e) { return $e->getMessage(); } /** @var mixed[]|null $config */ $inactive = $items['items'][$item]['inactive'] ?? null; if ($inactive === null || $inactive === true) { return (string)__('Invalid list item: `{0}`', $item); } return true; }
[ "public", "function", "inModuleList", "(", "string", "$", "item", ",", "string", "$", "moduleName", ",", "string", "$", "listName", ")", "{", "try", "{", "$", "items", "=", "(", "new", "ModuleConfig", "(", "ConfigType", "::", "LISTS", "(", ")", ",", "$", "moduleName", ",", "$", "listName", ")", ")", "->", "parseToArray", "(", ")", ";", "}", "catch", "(", "InvalidArgumentException", "$", "e", ")", "{", "return", "$", "e", "->", "getMessage", "(", ")", ";", "}", "/** @var mixed[]|null $config */", "$", "inactive", "=", "$", "items", "[", "'items'", "]", "[", "$", "item", "]", "[", "'inactive'", "]", "??", "null", ";", "if", "(", "$", "inactive", "===", "null", "||", "$", "inactive", "===", "true", ")", "{", "return", "(", "string", ")", "__", "(", "'Invalid list item: `{0}`'", ",", "$", "item", ")", ";", "}", "return", "true", ";", "}" ]
Returns true if the passed list item is valid and enabled. @param string $item List item. @param string $moduleName Module name. @param string $listName List name. @return string|true True if list item is enabled, error string otherwise.
[ "Returns", "true", "if", "the", "passed", "list", "item", "is", "valid", "and", "enabled", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Validation/Validator.php#L32-L47
train
QoboLtd/cakephp-csv-migrations
src/FieldHandlers/Config/ConfigFactory.php
ConfigFactory.getByType
public static function getByType(string $type, string $field, $table = '', array $options = []) : ConfigInterface { $configClass = __NAMESPACE__ . '\\' . ucfirst($type) . 'Config'; if (!class_exists($configClass)) { throw new InvalidArgumentException("Configuration type [$type] is not supported"); } $result = new $configClass($field, $table, $options); return $result; }
php
public static function getByType(string $type, string $field, $table = '', array $options = []) : ConfigInterface { $configClass = __NAMESPACE__ . '\\' . ucfirst($type) . 'Config'; if (!class_exists($configClass)) { throw new InvalidArgumentException("Configuration type [$type] is not supported"); } $result = new $configClass($field, $table, $options); return $result; }
[ "public", "static", "function", "getByType", "(", "string", "$", "type", ",", "string", "$", "field", ",", "$", "table", "=", "''", ",", "array", "$", "options", "=", "[", "]", ")", ":", "ConfigInterface", "{", "$", "configClass", "=", "__NAMESPACE__", ".", "'\\\\'", ".", "ucfirst", "(", "$", "type", ")", ".", "'Config'", ";", "if", "(", "!", "class_exists", "(", "$", "configClass", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Configuration type [$type] is not supported\"", ")", ";", "}", "$", "result", "=", "new", "$", "configClass", "(", "$", "field", ",", "$", "table", ",", "$", "options", ")", ";", "return", "$", "result", ";", "}" ]
Get configuration instance by type @throws \InvalidArgumentException for unsupported configuration types @param string $type Configuration type (e.g.: string, email, uuid) @param string $field Field name @param \Cake\Datasource\RepositoryInterface|string $table Table name or instance @param mixed[] $options Configuration options @return \CsvMigrations\FieldHandlers\Config\ConfigInterface
[ "Get", "configuration", "instance", "by", "type" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/FieldHandlers/Config/ConfigFactory.php#L34-L44
train
QoboLtd/cakephp-csv-migrations
src/FieldHandlers/Provider/SelectOptions/ListSelectOptions.php
ListSelectOptions.provide
public function provide($data = null, array $options = []) : array { $spacer = isset($options['spacer']) ? (string)$options['spacer'] : ' - '; $flatten = isset($options['flatten']) ? (bool)$options['flatten'] : true; list($module, $list) = false !== strpos($data, '.') ? explode('.', $data, 2) : [App::shortName(get_class($this->config->getTable()), 'Model/Table', 'Table'), $data]; $result = []; try { $config = new ModuleConfig(ConfigType::LISTS(), $module, $list, ['flatten' => $flatten, 'filter' => true]); $config = $config->parse(); if (! property_exists($config, 'items')) { return []; } $config = json_encode($config->items); if (false === $config) { return []; } $result = json_decode($config, true); } catch (InvalidArgumentException $e) { /* Do nothing. * * ModuleConfig checks for the file to exist and to be readable and so on, but here we do load lists * recursively (for sub-lists, etc), which might result in files not always being there. * * In this particular case, it's not the end of the world. */ return []; } if (empty($result)) { return []; } if (! $flatten) { return $result; } foreach ($result as $key => $value) { $result[$key] = str_repeat($spacer, substr_count($key, '.')) . $value['label']; } return $result; }
php
public function provide($data = null, array $options = []) : array { $spacer = isset($options['spacer']) ? (string)$options['spacer'] : ' - '; $flatten = isset($options['flatten']) ? (bool)$options['flatten'] : true; list($module, $list) = false !== strpos($data, '.') ? explode('.', $data, 2) : [App::shortName(get_class($this->config->getTable()), 'Model/Table', 'Table'), $data]; $result = []; try { $config = new ModuleConfig(ConfigType::LISTS(), $module, $list, ['flatten' => $flatten, 'filter' => true]); $config = $config->parse(); if (! property_exists($config, 'items')) { return []; } $config = json_encode($config->items); if (false === $config) { return []; } $result = json_decode($config, true); } catch (InvalidArgumentException $e) { /* Do nothing. * * ModuleConfig checks for the file to exist and to be readable and so on, but here we do load lists * recursively (for sub-lists, etc), which might result in files not always being there. * * In this particular case, it's not the end of the world. */ return []; } if (empty($result)) { return []; } if (! $flatten) { return $result; } foreach ($result as $key => $value) { $result[$key] = str_repeat($spacer, substr_count($key, '.')) . $value['label']; } return $result; }
[ "public", "function", "provide", "(", "$", "data", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", ":", "array", "{", "$", "spacer", "=", "isset", "(", "$", "options", "[", "'spacer'", "]", ")", "?", "(", "string", ")", "$", "options", "[", "'spacer'", "]", ":", "' - '", ";", "$", "flatten", "=", "isset", "(", "$", "options", "[", "'flatten'", "]", ")", "?", "(", "bool", ")", "$", "options", "[", "'flatten'", "]", ":", "true", ";", "list", "(", "$", "module", ",", "$", "list", ")", "=", "false", "!==", "strpos", "(", "$", "data", ",", "'.'", ")", "?", "explode", "(", "'.'", ",", "$", "data", ",", "2", ")", ":", "[", "App", "::", "shortName", "(", "get_class", "(", "$", "this", "->", "config", "->", "getTable", "(", ")", ")", ",", "'Model/Table'", ",", "'Table'", ")", ",", "$", "data", "]", ";", "$", "result", "=", "[", "]", ";", "try", "{", "$", "config", "=", "new", "ModuleConfig", "(", "ConfigType", "::", "LISTS", "(", ")", ",", "$", "module", ",", "$", "list", ",", "[", "'flatten'", "=>", "$", "flatten", ",", "'filter'", "=>", "true", "]", ")", ";", "$", "config", "=", "$", "config", "->", "parse", "(", ")", ";", "if", "(", "!", "property_exists", "(", "$", "config", ",", "'items'", ")", ")", "{", "return", "[", "]", ";", "}", "$", "config", "=", "json_encode", "(", "$", "config", "->", "items", ")", ";", "if", "(", "false", "===", "$", "config", ")", "{", "return", "[", "]", ";", "}", "$", "result", "=", "json_decode", "(", "$", "config", ",", "true", ")", ";", "}", "catch", "(", "InvalidArgumentException", "$", "e", ")", "{", "/* Do nothing.\n *\n * ModuleConfig checks for the file to exist and to be readable and so on, but here we do load lists\n * recursively (for sub-lists, etc), which might result in files not always being there.\n *\n * In this particular case, it's not the end of the world.\n */", "return", "[", "]", ";", "}", "if", "(", "empty", "(", "$", "result", ")", ")", "{", "return", "[", "]", ";", "}", "if", "(", "!", "$", "flatten", ")", "{", "return", "$", "result", ";", "}", "foreach", "(", "$", "result", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "result", "[", "$", "key", "]", "=", "str_repeat", "(", "$", "spacer", ",", "substr_count", "(", "$", "key", ",", "'.'", ")", ")", ".", "$", "value", "[", "'label'", "]", ";", "}", "return", "$", "result", ";", "}" ]
Provide select options @param mixed $data Data to use for provision @param array $options Options to use for provision @return array
[ "Provide", "select", "options" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/FieldHandlers/Provider/SelectOptions/ListSelectOptions.php#L33-L80
train
QoboLtd/cakephp-csv-migrations
src/FieldHandlers/FieldHandler.php
FieldHandler.setDefaultFieldOptions
protected function setDefaultFieldOptions() : void { $table = $this->config->getTable(); $field = $this->config->getField(); $mc = new ModuleConfig(ConfigType::FIELDS(), Inflector::camelize($table->getTable())); $config = $mc->parseToArray(); if (! empty($config[$field])) { $this->defaultOptions = array_replace_recursive($this->defaultOptions, $config[$field]); } }
php
protected function setDefaultFieldOptions() : void { $table = $this->config->getTable(); $field = $this->config->getField(); $mc = new ModuleConfig(ConfigType::FIELDS(), Inflector::camelize($table->getTable())); $config = $mc->parseToArray(); if (! empty($config[$field])) { $this->defaultOptions = array_replace_recursive($this->defaultOptions, $config[$field]); } }
[ "protected", "function", "setDefaultFieldOptions", "(", ")", ":", "void", "{", "$", "table", "=", "$", "this", "->", "config", "->", "getTable", "(", ")", ";", "$", "field", "=", "$", "this", "->", "config", "->", "getField", "(", ")", ";", "$", "mc", "=", "new", "ModuleConfig", "(", "ConfigType", "::", "FIELDS", "(", ")", ",", "Inflector", "::", "camelize", "(", "$", "table", "->", "getTable", "(", ")", ")", ")", ";", "$", "config", "=", "$", "mc", "->", "parseToArray", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "config", "[", "$", "field", "]", ")", ")", "{", "$", "this", "->", "defaultOptions", "=", "array_replace_recursive", "(", "$", "this", "->", "defaultOptions", ",", "$", "config", "[", "$", "field", "]", ")", ";", "}", "}" ]
Set default field options from config Read fields.ini configuration file and if there are any options defined for the current field, use them as defaults. @return void
[ "Set", "default", "field", "options", "from", "config" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/FieldHandlers/FieldHandler.php#L101-L111
train
QoboLtd/cakephp-csv-migrations
src/FieldHandlers/FieldHandler.php
FieldHandler.setDefaultFieldDefinitions
protected function setDefaultFieldDefinitions() : void { $table = $this->config->getTable(); $field = $this->config->getField(); $dbFieldType = $this->getDbFieldType(); // set $options['fieldDefinitions'] $stubFields = [ $field => [ 'name' => $field, 'type' => $dbFieldType, ], ]; if ($table instanceof HasFieldsInterface) { $fieldDefinitions = $table->getFieldsDefinitions($stubFields); $this->defaultOptions['fieldDefinitions'] = new CsvField($fieldDefinitions[$field]); } // This should never be the case, except, maybe // for some unit test runs or custom non-CSV // modules. if (empty($this->defaultOptions['fieldDefinitions'])) { $this->defaultOptions['fieldDefinitions'] = new CsvField($stubFields[$field]); } }
php
protected function setDefaultFieldDefinitions() : void { $table = $this->config->getTable(); $field = $this->config->getField(); $dbFieldType = $this->getDbFieldType(); // set $options['fieldDefinitions'] $stubFields = [ $field => [ 'name' => $field, 'type' => $dbFieldType, ], ]; if ($table instanceof HasFieldsInterface) { $fieldDefinitions = $table->getFieldsDefinitions($stubFields); $this->defaultOptions['fieldDefinitions'] = new CsvField($fieldDefinitions[$field]); } // This should never be the case, except, maybe // for some unit test runs or custom non-CSV // modules. if (empty($this->defaultOptions['fieldDefinitions'])) { $this->defaultOptions['fieldDefinitions'] = new CsvField($stubFields[$field]); } }
[ "protected", "function", "setDefaultFieldDefinitions", "(", ")", ":", "void", "{", "$", "table", "=", "$", "this", "->", "config", "->", "getTable", "(", ")", ";", "$", "field", "=", "$", "this", "->", "config", "->", "getField", "(", ")", ";", "$", "dbFieldType", "=", "$", "this", "->", "getDbFieldType", "(", ")", ";", "// set $options['fieldDefinitions']", "$", "stubFields", "=", "[", "$", "field", "=>", "[", "'name'", "=>", "$", "field", ",", "'type'", "=>", "$", "dbFieldType", ",", "]", ",", "]", ";", "if", "(", "$", "table", "instanceof", "HasFieldsInterface", ")", "{", "$", "fieldDefinitions", "=", "$", "table", "->", "getFieldsDefinitions", "(", "$", "stubFields", ")", ";", "$", "this", "->", "defaultOptions", "[", "'fieldDefinitions'", "]", "=", "new", "CsvField", "(", "$", "fieldDefinitions", "[", "$", "field", "]", ")", ";", "}", "// This should never be the case, except, maybe", "// for some unit test runs or custom non-CSV", "// modules.", "if", "(", "empty", "(", "$", "this", "->", "defaultOptions", "[", "'fieldDefinitions'", "]", ")", ")", "{", "$", "this", "->", "defaultOptions", "[", "'fieldDefinitions'", "]", "=", "new", "CsvField", "(", "$", "stubFields", "[", "$", "field", "]", ")", ";", "}", "}" ]
Set default field definitions @return void
[ "Set", "default", "field", "definitions" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/FieldHandlers/FieldHandler.php#L132-L156
train
QoboLtd/cakephp-csv-migrations
src/FieldHandlers/FieldHandler.php
FieldHandler.setDefaultValue
protected function setDefaultValue() : void { if (empty($this->defaultOptions['default'])) { return; } // If we have a default value from configuration, pass it through // processing for magic/dynamic values like dates and usernames. $eventName = (string)EventName::FIELD_HANDLER_DEFAULT_VALUE(); $event = new Event($eventName, $this, [ 'default' => $this->defaultOptions['default'] ]); $view = $this->config->getView(); $view->getEventManager()->dispatch($event); // Only overwrite the default if any events were triggered $listeners = $view->getEventManager()->listeners($eventName); if (empty($listeners)) { return; } $this->defaultOptions['default'] = $event->result; }
php
protected function setDefaultValue() : void { if (empty($this->defaultOptions['default'])) { return; } // If we have a default value from configuration, pass it through // processing for magic/dynamic values like dates and usernames. $eventName = (string)EventName::FIELD_HANDLER_DEFAULT_VALUE(); $event = new Event($eventName, $this, [ 'default' => $this->defaultOptions['default'] ]); $view = $this->config->getView(); $view->getEventManager()->dispatch($event); // Only overwrite the default if any events were triggered $listeners = $view->getEventManager()->listeners($eventName); if (empty($listeners)) { return; } $this->defaultOptions['default'] = $event->result; }
[ "protected", "function", "setDefaultValue", "(", ")", ":", "void", "{", "if", "(", "empty", "(", "$", "this", "->", "defaultOptions", "[", "'default'", "]", ")", ")", "{", "return", ";", "}", "// If we have a default value from configuration, pass it through", "// processing for magic/dynamic values like dates and usernames.", "$", "eventName", "=", "(", "string", ")", "EventName", "::", "FIELD_HANDLER_DEFAULT_VALUE", "(", ")", ";", "$", "event", "=", "new", "Event", "(", "$", "eventName", ",", "$", "this", ",", "[", "'default'", "=>", "$", "this", "->", "defaultOptions", "[", "'default'", "]", "]", ")", ";", "$", "view", "=", "$", "this", "->", "config", "->", "getView", "(", ")", ";", "$", "view", "->", "getEventManager", "(", ")", "->", "dispatch", "(", "$", "event", ")", ";", "// Only overwrite the default if any events were triggered", "$", "listeners", "=", "$", "view", "->", "getEventManager", "(", ")", "->", "listeners", "(", "$", "eventName", ")", ";", "if", "(", "empty", "(", "$", "listeners", ")", ")", "{", "return", ";", "}", "$", "this", "->", "defaultOptions", "[", "'default'", "]", "=", "$", "event", "->", "result", ";", "}" ]
Set default field value @return void
[ "Set", "default", "field", "value" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/FieldHandlers/FieldHandler.php#L163-L185
train
QoboLtd/cakephp-csv-migrations
src/FieldHandlers/FieldHandler.php
FieldHandler.fixOptions
protected function fixOptions(array $options = []) : array { $result = $options; if (empty($result)) { return $result; } if (empty($result['fieldDefinitions'])) { return $result; } if (!is_array($result['fieldDefinitions'])) { return $result; } // Sometimes, when setting fieldDefinitions manually to render a particular // type, the name is omitted. This works for an array, but doesn't work for // the CsvField instance, as the name is required. Gladly, we know the name // and can fix it easily. if (empty($result['fieldDefinitions']['name'])) { $result['fieldDefinitions']['name'] = $this->config->getField(); } // Previously, fieldDefinitions could be either an array or a CsvField instance. // Now we expect it to always be a CsvField instance. So, if we have a non-empty // array, then instantiate CsvField with the values from it. $result['fieldDefinitions'] = new CsvField($result['fieldDefinitions']); return $result; }
php
protected function fixOptions(array $options = []) : array { $result = $options; if (empty($result)) { return $result; } if (empty($result['fieldDefinitions'])) { return $result; } if (!is_array($result['fieldDefinitions'])) { return $result; } // Sometimes, when setting fieldDefinitions manually to render a particular // type, the name is omitted. This works for an array, but doesn't work for // the CsvField instance, as the name is required. Gladly, we know the name // and can fix it easily. if (empty($result['fieldDefinitions']['name'])) { $result['fieldDefinitions']['name'] = $this->config->getField(); } // Previously, fieldDefinitions could be either an array or a CsvField instance. // Now we expect it to always be a CsvField instance. So, if we have a non-empty // array, then instantiate CsvField with the values from it. $result['fieldDefinitions'] = new CsvField($result['fieldDefinitions']); return $result; }
[ "protected", "function", "fixOptions", "(", "array", "$", "options", "=", "[", "]", ")", ":", "array", "{", "$", "result", "=", "$", "options", ";", "if", "(", "empty", "(", "$", "result", ")", ")", "{", "return", "$", "result", ";", "}", "if", "(", "empty", "(", "$", "result", "[", "'fieldDefinitions'", "]", ")", ")", "{", "return", "$", "result", ";", "}", "if", "(", "!", "is_array", "(", "$", "result", "[", "'fieldDefinitions'", "]", ")", ")", "{", "return", "$", "result", ";", "}", "// Sometimes, when setting fieldDefinitions manually to render a particular", "// type, the name is omitted. This works for an array, but doesn't work for", "// the CsvField instance, as the name is required. Gladly, we know the name", "// and can fix it easily.", "if", "(", "empty", "(", "$", "result", "[", "'fieldDefinitions'", "]", "[", "'name'", "]", ")", ")", "{", "$", "result", "[", "'fieldDefinitions'", "]", "[", "'name'", "]", "=", "$", "this", "->", "config", "->", "getField", "(", ")", ";", "}", "// Previously, fieldDefinitions could be either an array or a CsvField instance.", "// Now we expect it to always be a CsvField instance. So, if we have a non-empty", "// array, then instantiate CsvField with the values from it.", "$", "result", "[", "'fieldDefinitions'", "]", "=", "new", "CsvField", "(", "$", "result", "[", "'fieldDefinitions'", "]", ")", ";", "return", "$", "result", ";", "}" ]
Fix provided options This method is here to fix some issues with backward compatibility and make sure that $options parameters are consistent throughout. @param mixed[] $options Options to fix @return mixed[] Fixed options
[ "Fix", "provided", "options" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/FieldHandlers/FieldHandler.php#L197-L226
train
QoboLtd/cakephp-csv-migrations
src/FieldHandlers/FieldHandler.php
FieldHandler.renderInput
public function renderInput($data = '', array $options = []) : string { $options = array_merge($this->defaultOptions, $this->fixOptions($options)); $data = $this->getFieldValueFromData($data, $options); // Workaround for BLOBs if (is_resource($data)) { $data = stream_get_contents($data); } if (empty($data) && !empty($options['default'])) { $data = $options['default']; } $options['label'] = !isset($options['label']) ? $this->renderName() : $options['label']; $searchOptions = $this->config->getProvider('renderInput'); $searchOptions = new $searchOptions($this->config); $result = $searchOptions->provide($data, $options); return $result; }
php
public function renderInput($data = '', array $options = []) : string { $options = array_merge($this->defaultOptions, $this->fixOptions($options)); $data = $this->getFieldValueFromData($data, $options); // Workaround for BLOBs if (is_resource($data)) { $data = stream_get_contents($data); } if (empty($data) && !empty($options['default'])) { $data = $options['default']; } $options['label'] = !isset($options['label']) ? $this->renderName() : $options['label']; $searchOptions = $this->config->getProvider('renderInput'); $searchOptions = new $searchOptions($this->config); $result = $searchOptions->provide($data, $options); return $result; }
[ "public", "function", "renderInput", "(", "$", "data", "=", "''", ",", "array", "$", "options", "=", "[", "]", ")", ":", "string", "{", "$", "options", "=", "array_merge", "(", "$", "this", "->", "defaultOptions", ",", "$", "this", "->", "fixOptions", "(", "$", "options", ")", ")", ";", "$", "data", "=", "$", "this", "->", "getFieldValueFromData", "(", "$", "data", ",", "$", "options", ")", ";", "// Workaround for BLOBs", "if", "(", "is_resource", "(", "$", "data", ")", ")", "{", "$", "data", "=", "stream_get_contents", "(", "$", "data", ")", ";", "}", "if", "(", "empty", "(", "$", "data", ")", "&&", "!", "empty", "(", "$", "options", "[", "'default'", "]", ")", ")", "{", "$", "data", "=", "$", "options", "[", "'default'", "]", ";", "}", "$", "options", "[", "'label'", "]", "=", "!", "isset", "(", "$", "options", "[", "'label'", "]", ")", "?", "$", "this", "->", "renderName", "(", ")", ":", "$", "options", "[", "'label'", "]", ";", "$", "searchOptions", "=", "$", "this", "->", "config", "->", "getProvider", "(", "'renderInput'", ")", ";", "$", "searchOptions", "=", "new", "$", "searchOptions", "(", "$", "this", "->", "config", ")", ";", "$", "result", "=", "$", "searchOptions", "->", "provide", "(", "$", "data", ",", "$", "options", ")", ";", "return", "$", "result", ";", "}" ]
Render field input This method prepares the form input for the given field, including the input itself, label, pre-populated value, and so on. The result can be controlled via the variety of options. @param mixed $data Field data @param array $options Field options @return string Field input HTML
[ "Render", "field", "input" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/FieldHandlers/FieldHandler.php#L240-L261
train
QoboLtd/cakephp-csv-migrations
src/FieldHandlers/FieldHandler.php
FieldHandler.getSearchOptions
public function getSearchOptions(array $options = []) : array { $result = []; $options = array_merge($this->defaultOptions, $this->fixOptions($options)); if ($options['fieldDefinitions']->getNonSearchable()) { return $result; } $options['label'] = empty($options['label']) ? $this->renderName() : $options['label']; $searchOptions = $this->config->getProvider('searchOptions'); $searchOptions = new $searchOptions($this->config); $result = $searchOptions->provide(null, $options); return $result; }
php
public function getSearchOptions(array $options = []) : array { $result = []; $options = array_merge($this->defaultOptions, $this->fixOptions($options)); if ($options['fieldDefinitions']->getNonSearchable()) { return $result; } $options['label'] = empty($options['label']) ? $this->renderName() : $options['label']; $searchOptions = $this->config->getProvider('searchOptions'); $searchOptions = new $searchOptions($this->config); $result = $searchOptions->provide(null, $options); return $result; }
[ "public", "function", "getSearchOptions", "(", "array", "$", "options", "=", "[", "]", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "$", "options", "=", "array_merge", "(", "$", "this", "->", "defaultOptions", ",", "$", "this", "->", "fixOptions", "(", "$", "options", ")", ")", ";", "if", "(", "$", "options", "[", "'fieldDefinitions'", "]", "->", "getNonSearchable", "(", ")", ")", "{", "return", "$", "result", ";", "}", "$", "options", "[", "'label'", "]", "=", "empty", "(", "$", "options", "[", "'label'", "]", ")", "?", "$", "this", "->", "renderName", "(", ")", ":", "$", "options", "[", "'label'", "]", ";", "$", "searchOptions", "=", "$", "this", "->", "config", "->", "getProvider", "(", "'searchOptions'", ")", ";", "$", "searchOptions", "=", "new", "$", "searchOptions", "(", "$", "this", "->", "config", ")", ";", "$", "result", "=", "$", "searchOptions", "->", "provide", "(", "null", ",", "$", "options", ")", ";", "return", "$", "result", ";", "}" ]
Get options for field search This method prepares an array of search options, which includes label, form input, supported search operators, etc. The result can be controlled with a variety of options. @param array $options Field options @return array Array of field input HTML, pre and post CSS, JS, etc
[ "Get", "options", "for", "field", "search" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/FieldHandlers/FieldHandler.php#L273-L290
train
QoboLtd/cakephp-csv-migrations
src/FieldHandlers/FieldHandler.php
FieldHandler.renderName
public function renderName() : string { $label = !empty($this->defaultOptions['label']) ? $this->defaultOptions['label'] : ''; $renderer = $this->config->getProvider('renderName'); $renderer = new $renderer($this->config); $result = $renderer->provide($label); return $result; }
php
public function renderName() : string { $label = !empty($this->defaultOptions['label']) ? $this->defaultOptions['label'] : ''; $renderer = $this->config->getProvider('renderName'); $renderer = new $renderer($this->config); $result = $renderer->provide($label); return $result; }
[ "public", "function", "renderName", "(", ")", ":", "string", "{", "$", "label", "=", "!", "empty", "(", "$", "this", "->", "defaultOptions", "[", "'label'", "]", ")", "?", "$", "this", "->", "defaultOptions", "[", "'label'", "]", ":", "''", ";", "$", "renderer", "=", "$", "this", "->", "config", "->", "getProvider", "(", "'renderName'", ")", ";", "$", "renderer", "=", "new", "$", "renderer", "(", "$", "this", "->", "config", ")", ";", "$", "result", "=", "$", "renderer", "->", "provide", "(", "$", "label", ")", ";", "return", "$", "result", ";", "}" ]
Render field name @return string
[ "Render", "field", "name" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/FieldHandlers/FieldHandler.php#L297-L306
train
QoboLtd/cakephp-csv-migrations
src/FieldHandlers/FieldHandler.php
FieldHandler.fieldToDb
public static function fieldToDb(CsvField $csvField) : array { $config = ConfigFactory::getByType($csvField->getType(), $csvField->getName()); $fieldToDb = $config->getProvider('fieldToDb'); $fieldToDb = new $fieldToDb($config); $result = $fieldToDb->provide($csvField); return $result; }
php
public static function fieldToDb(CsvField $csvField) : array { $config = ConfigFactory::getByType($csvField->getType(), $csvField->getName()); $fieldToDb = $config->getProvider('fieldToDb'); $fieldToDb = new $fieldToDb($config); $result = $fieldToDb->provide($csvField); return $result; }
[ "public", "static", "function", "fieldToDb", "(", "CsvField", "$", "csvField", ")", ":", "array", "{", "$", "config", "=", "ConfigFactory", "::", "getByType", "(", "$", "csvField", "->", "getType", "(", ")", ",", "$", "csvField", "->", "getName", "(", ")", ")", ";", "$", "fieldToDb", "=", "$", "config", "->", "getProvider", "(", "'fieldToDb'", ")", ";", "$", "fieldToDb", "=", "new", "$", "fieldToDb", "(", "$", "config", ")", ";", "$", "result", "=", "$", "fieldToDb", "->", "provide", "(", "$", "csvField", ")", ";", "return", "$", "result", ";", "}" ]
Convert CsvField to one or more DbField instances Simple fields from migrations CSV map one-to-one to the database fields. More complex fields can combine multiple database fields for a single CSV entry. @param \CsvMigrations\FieldHandlers\CsvField $csvField CsvField instance @return array DbField instances
[ "Convert", "CsvField", "to", "one", "or", "more", "DbField", "instances" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/FieldHandlers/FieldHandler.php#L378-L386
train
QoboLtd/cakephp-csv-migrations
src/FieldHandlers/FieldHandler.php
FieldHandler.getDbFieldType
public function getDbFieldType() : string { $dbFieldType = $this->config->getProvider('dbFieldType'); $dbFieldType = new $dbFieldType($this->config); $dbFieldType = $dbFieldType->provide(); return $dbFieldType; }
php
public function getDbFieldType() : string { $dbFieldType = $this->config->getProvider('dbFieldType'); $dbFieldType = new $dbFieldType($this->config); $dbFieldType = $dbFieldType->provide(); return $dbFieldType; }
[ "public", "function", "getDbFieldType", "(", ")", ":", "string", "{", "$", "dbFieldType", "=", "$", "this", "->", "config", "->", "getProvider", "(", "'dbFieldType'", ")", ";", "$", "dbFieldType", "=", "new", "$", "dbFieldType", "(", "$", "this", "->", "config", ")", ";", "$", "dbFieldType", "=", "$", "dbFieldType", "->", "provide", "(", ")", ";", "return", "$", "dbFieldType", ";", "}" ]
Get database field type @return string
[ "Get", "database", "field", "type" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/FieldHandlers/FieldHandler.php#L393-L400
train
QoboLtd/cakephp-csv-migrations
src/FieldHandlers/FieldHandler.php
FieldHandler.getFieldValueFromData
protected function getFieldValueFromData($data, array $options) { $fieldValue = $this->config->getProvider('fieldValue'); $fieldValue = new $fieldValue($this->config); $result = $fieldValue->provide($data, $options); return $result; }
php
protected function getFieldValueFromData($data, array $options) { $fieldValue = $this->config->getProvider('fieldValue'); $fieldValue = new $fieldValue($this->config); $result = $fieldValue->provide($data, $options); return $result; }
[ "protected", "function", "getFieldValueFromData", "(", "$", "data", ",", "array", "$", "options", ")", "{", "$", "fieldValue", "=", "$", "this", "->", "config", "->", "getProvider", "(", "'fieldValue'", ")", ";", "$", "fieldValue", "=", "new", "$", "fieldValue", "(", "$", "this", "->", "config", ")", ";", "$", "result", "=", "$", "fieldValue", "->", "provide", "(", "$", "data", ",", "$", "options", ")", ";", "return", "$", "result", ";", "}" ]
Get field value from given data @param mixed $data Variable to extract value from @param mixed[] $options Field options @return mixed
[ "Get", "field", "value", "from", "given", "data" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/FieldHandlers/FieldHandler.php#L409-L416
train
QoboLtd/cakephp-csv-migrations
src/Event/Model/AutoIncrementEventListener.php
AutoIncrementEventListener.autoIncrementFieldValue
public function autoIncrementFieldValue(Event $event, EntityInterface $entity, ArrayObject $options) : void { $table = $event->getSubject(); if (!$table instanceof Table) { return; } $fields = $this->getAutoIncrementFields($table); // skip if no auto-increment fields are defined if (empty($fields)) { return; } // skip modifying auto-increment field(s) on existing records. if (! $entity->isNew()) { foreach (array_keys($fields) as $field) { $entity->unsetProperty((string)$field); } return; } foreach ($fields as $field => $options) { // get max value $query = $table->find('withTrashed'); try { $max = $query->select([$field => $query->func()->max($field)]) ->enableHydration(true) ->firstOrFail(); Assert::isInstanceOf($max, EntityInterface::class); $max = (float)$max->get((string)$field); } catch (RecordNotFoundException $e) { $max = 0; } if (empty($options['min'])) { $entity->set((string)$field, $max + 1); continue; } // if value is less than the allowed minimum, then set it to the minimum. $max = $max < $options['min'] ? $options['min'] : $max + 1; $entity->set((string)$field, $max); } }
php
public function autoIncrementFieldValue(Event $event, EntityInterface $entity, ArrayObject $options) : void { $table = $event->getSubject(); if (!$table instanceof Table) { return; } $fields = $this->getAutoIncrementFields($table); // skip if no auto-increment fields are defined if (empty($fields)) { return; } // skip modifying auto-increment field(s) on existing records. if (! $entity->isNew()) { foreach (array_keys($fields) as $field) { $entity->unsetProperty((string)$field); } return; } foreach ($fields as $field => $options) { // get max value $query = $table->find('withTrashed'); try { $max = $query->select([$field => $query->func()->max($field)]) ->enableHydration(true) ->firstOrFail(); Assert::isInstanceOf($max, EntityInterface::class); $max = (float)$max->get((string)$field); } catch (RecordNotFoundException $e) { $max = 0; } if (empty($options['min'])) { $entity->set((string)$field, $max + 1); continue; } // if value is less than the allowed minimum, then set it to the minimum. $max = $max < $options['min'] ? $options['min'] : $max + 1; $entity->set((string)$field, $max); } }
[ "public", "function", "autoIncrementFieldValue", "(", "Event", "$", "event", ",", "EntityInterface", "$", "entity", ",", "ArrayObject", "$", "options", ")", ":", "void", "{", "$", "table", "=", "$", "event", "->", "getSubject", "(", ")", ";", "if", "(", "!", "$", "table", "instanceof", "Table", ")", "{", "return", ";", "}", "$", "fields", "=", "$", "this", "->", "getAutoIncrementFields", "(", "$", "table", ")", ";", "// skip if no auto-increment fields are defined", "if", "(", "empty", "(", "$", "fields", ")", ")", "{", "return", ";", "}", "// skip modifying auto-increment field(s) on existing records.", "if", "(", "!", "$", "entity", "->", "isNew", "(", ")", ")", "{", "foreach", "(", "array_keys", "(", "$", "fields", ")", "as", "$", "field", ")", "{", "$", "entity", "->", "unsetProperty", "(", "(", "string", ")", "$", "field", ")", ";", "}", "return", ";", "}", "foreach", "(", "$", "fields", "as", "$", "field", "=>", "$", "options", ")", "{", "// get max value", "$", "query", "=", "$", "table", "->", "find", "(", "'withTrashed'", ")", ";", "try", "{", "$", "max", "=", "$", "query", "->", "select", "(", "[", "$", "field", "=>", "$", "query", "->", "func", "(", ")", "->", "max", "(", "$", "field", ")", "]", ")", "->", "enableHydration", "(", "true", ")", "->", "firstOrFail", "(", ")", ";", "Assert", "::", "isInstanceOf", "(", "$", "max", ",", "EntityInterface", "::", "class", ")", ";", "$", "max", "=", "(", "float", ")", "$", "max", "->", "get", "(", "(", "string", ")", "$", "field", ")", ";", "}", "catch", "(", "RecordNotFoundException", "$", "e", ")", "{", "$", "max", "=", "0", ";", "}", "if", "(", "empty", "(", "$", "options", "[", "'min'", "]", ")", ")", "{", "$", "entity", "->", "set", "(", "(", "string", ")", "$", "field", ",", "$", "max", "+", "1", ")", ";", "continue", ";", "}", "// if value is less than the allowed minimum, then set it to the minimum.", "$", "max", "=", "$", "max", "<", "$", "options", "[", "'min'", "]", "?", "$", "options", "[", "'min'", "]", ":", "$", "max", "+", "1", ";", "$", "entity", "->", "set", "(", "(", "string", ")", "$", "field", ",", "$", "max", ")", ";", "}", "}" ]
Auto-increment reference number. @param \Cake\Event\Event $event Event object @param \Cake\Datasource\EntityInterface $entity Translation entity @param \ArrayObject $options entity options @return void
[ "Auto", "-", "increment", "reference", "number", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Event/Model/AutoIncrementEventListener.php#L47-L96
train
QoboLtd/cakephp-csv-migrations
src/Event/Model/AutoIncrementEventListener.php
AutoIncrementEventListener.getAutoIncrementFields
private function getAutoIncrementFields(Table $table) : array { $moduleName = Inflector::camelize($table->getTable()); $mc = new ModuleConfig(ConfigType::FIELDS(), $moduleName); $config = json_encode($mc->parse()); $config = false === $config ? [] : json_decode($config, true); if (empty($config)) { return []; } $result = []; foreach (array_keys($table->getFieldsDefinitions()) as $field) { $autoIncrement = empty($config[$field]['auto-increment']) ? false : (bool)$config[$field]['auto-increment']; if (!$autoIncrement) { continue; } $result[$field] = []; $min = empty($config[$field]['min']) ? null : $config[$field]['min']; if (!is_int($min) && !is_float($min)) { continue; } $result[$field] = [ 'min' => $min ]; } return $result; }
php
private function getAutoIncrementFields(Table $table) : array { $moduleName = Inflector::camelize($table->getTable()); $mc = new ModuleConfig(ConfigType::FIELDS(), $moduleName); $config = json_encode($mc->parse()); $config = false === $config ? [] : json_decode($config, true); if (empty($config)) { return []; } $result = []; foreach (array_keys($table->getFieldsDefinitions()) as $field) { $autoIncrement = empty($config[$field]['auto-increment']) ? false : (bool)$config[$field]['auto-increment']; if (!$autoIncrement) { continue; } $result[$field] = []; $min = empty($config[$field]['min']) ? null : $config[$field]['min']; if (!is_int($min) && !is_float($min)) { continue; } $result[$field] = [ 'min' => $min ]; } return $result; }
[ "private", "function", "getAutoIncrementFields", "(", "Table", "$", "table", ")", ":", "array", "{", "$", "moduleName", "=", "Inflector", "::", "camelize", "(", "$", "table", "->", "getTable", "(", ")", ")", ";", "$", "mc", "=", "new", "ModuleConfig", "(", "ConfigType", "::", "FIELDS", "(", ")", ",", "$", "moduleName", ")", ";", "$", "config", "=", "json_encode", "(", "$", "mc", "->", "parse", "(", ")", ")", ";", "$", "config", "=", "false", "===", "$", "config", "?", "[", "]", ":", "json_decode", "(", "$", "config", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "config", ")", ")", "{", "return", "[", "]", ";", "}", "$", "result", "=", "[", "]", ";", "foreach", "(", "array_keys", "(", "$", "table", "->", "getFieldsDefinitions", "(", ")", ")", "as", "$", "field", ")", "{", "$", "autoIncrement", "=", "empty", "(", "$", "config", "[", "$", "field", "]", "[", "'auto-increment'", "]", ")", "?", "false", ":", "(", "bool", ")", "$", "config", "[", "$", "field", "]", "[", "'auto-increment'", "]", ";", "if", "(", "!", "$", "autoIncrement", ")", "{", "continue", ";", "}", "$", "result", "[", "$", "field", "]", "=", "[", "]", ";", "$", "min", "=", "empty", "(", "$", "config", "[", "$", "field", "]", "[", "'min'", "]", ")", "?", "null", ":", "$", "config", "[", "$", "field", "]", "[", "'min'", "]", ";", "if", "(", "!", "is_int", "(", "$", "min", ")", "&&", "!", "is_float", "(", "$", "min", ")", ")", "{", "continue", ";", "}", "$", "result", "[", "$", "field", "]", "=", "[", "'min'", "=>", "$", "min", "]", ";", "}", "return", "$", "result", ";", "}" ]
Retrieves auto-increment fields for specified Module. Retrieves and returns auto-increment fields along with their related properties (such as 'min' value). @param \CsvMigrations\Table $table Table instance @return mixed[]
[ "Retrieves", "auto", "-", "increment", "fields", "for", "specified", "Module", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Event/Model/AutoIncrementEventListener.php#L107-L137
train
QoboLtd/cakephp-csv-migrations
src/FieldHandlers/Provider/RenderInput/AggregatedRenderer.php
AggregatedRenderer.getAggregatedValue
private function getAggregatedValue(array $options) { // for cases where the entity does not exist yet if (! $options['entity'] instanceof EntityInterface) { return ''; } $config = explode(',', $options['fieldDefinitions']->getLimit(), 4); $configuration = new Configuration(TableRegistry::get($config[1]), $config[2]); $configuration->setJoinData($this->config->getTable(), $options['entity']) ->setDisplayField(isset($config[3]) ? $config[3] : ''); $aggregator = new $config[0]($configuration); $factory = new FieldHandlerFactory($this->config->getView()); return $factory->renderValue( $aggregator->getConfig()->getTable(), $aggregator->getConfig()->getDisplayField(), AggregateResult::get($aggregator), ['entity' => $options['entity']] ); }
php
private function getAggregatedValue(array $options) { // for cases where the entity does not exist yet if (! $options['entity'] instanceof EntityInterface) { return ''; } $config = explode(',', $options['fieldDefinitions']->getLimit(), 4); $configuration = new Configuration(TableRegistry::get($config[1]), $config[2]); $configuration->setJoinData($this->config->getTable(), $options['entity']) ->setDisplayField(isset($config[3]) ? $config[3] : ''); $aggregator = new $config[0]($configuration); $factory = new FieldHandlerFactory($this->config->getView()); return $factory->renderValue( $aggregator->getConfig()->getTable(), $aggregator->getConfig()->getDisplayField(), AggregateResult::get($aggregator), ['entity' => $options['entity']] ); }
[ "private", "function", "getAggregatedValue", "(", "array", "$", "options", ")", "{", "// for cases where the entity does not exist yet", "if", "(", "!", "$", "options", "[", "'entity'", "]", "instanceof", "EntityInterface", ")", "{", "return", "''", ";", "}", "$", "config", "=", "explode", "(", "','", ",", "$", "options", "[", "'fieldDefinitions'", "]", "->", "getLimit", "(", ")", ",", "4", ")", ";", "$", "configuration", "=", "new", "Configuration", "(", "TableRegistry", "::", "get", "(", "$", "config", "[", "1", "]", ")", ",", "$", "config", "[", "2", "]", ")", ";", "$", "configuration", "->", "setJoinData", "(", "$", "this", "->", "config", "->", "getTable", "(", ")", ",", "$", "options", "[", "'entity'", "]", ")", "->", "setDisplayField", "(", "isset", "(", "$", "config", "[", "3", "]", ")", "?", "$", "config", "[", "3", "]", ":", "''", ")", ";", "$", "aggregator", "=", "new", "$", "config", "[", "0", "]", "(", "$", "configuration", ")", ";", "$", "factory", "=", "new", "FieldHandlerFactory", "(", "$", "this", "->", "config", "->", "getView", "(", ")", ")", ";", "return", "$", "factory", "->", "renderValue", "(", "$", "aggregator", "->", "getConfig", "(", ")", "->", "getTable", "(", ")", ",", "$", "aggregator", "->", "getConfig", "(", ")", "->", "getDisplayField", "(", ")", ",", "AggregateResult", "::", "get", "(", "$", "aggregator", ")", ",", "[", "'entity'", "=>", "$", "options", "[", "'entity'", "]", "]", ")", ";", "}" ]
Aggregated value getter. @param mixed[] $options Options to use for provision @return mixed
[ "Aggregated", "value", "getter", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/FieldHandlers/Provider/RenderInput/AggregatedRenderer.php#L56-L79
train
QoboLtd/cakephp-csv-migrations
src/Controller/Component/CsvViewComponent.php
CsvViewComponent.filterFields
protected function filterFields(Event $event) : void { $panelActions = (array)Configure::read('CsvMigrations.panels.actions'); $dynamicPanelActions = (array)Configure::read('CsvMigrations.panels.dynamic_actions'); if (!in_array($this->request->getParam('action'), array_diff($panelActions, $dynamicPanelActions))) { return; } $controller = $event->getSubject(); Assert::isInstanceOf($controller, Controller::class); $config = new ModuleConfig(ConfigType::MODULE(), $controller->getName()); $config = json_encode($config->parse()); $config = false === $config ? [] : json_decode($config, true); $panels = $this->getPanels($config, $controller->viewVars['entity']->toArray()); if (! empty($panels['fail'])) { // filter out fields of hidden panels $controller->viewVars['fields'] = array_diff_key( $controller->viewVars['fields'], array_flip($panels['fail']) ); } if ((string)Configure::read('CsvMigrations.batch.action') === $this->request->getParam('action')) { $this->filterBatchFields($event); } }
php
protected function filterFields(Event $event) : void { $panelActions = (array)Configure::read('CsvMigrations.panels.actions'); $dynamicPanelActions = (array)Configure::read('CsvMigrations.panels.dynamic_actions'); if (!in_array($this->request->getParam('action'), array_diff($panelActions, $dynamicPanelActions))) { return; } $controller = $event->getSubject(); Assert::isInstanceOf($controller, Controller::class); $config = new ModuleConfig(ConfigType::MODULE(), $controller->getName()); $config = json_encode($config->parse()); $config = false === $config ? [] : json_decode($config, true); $panels = $this->getPanels($config, $controller->viewVars['entity']->toArray()); if (! empty($panels['fail'])) { // filter out fields of hidden panels $controller->viewVars['fields'] = array_diff_key( $controller->viewVars['fields'], array_flip($panels['fail']) ); } if ((string)Configure::read('CsvMigrations.batch.action') === $this->request->getParam('action')) { $this->filterBatchFields($event); } }
[ "protected", "function", "filterFields", "(", "Event", "$", "event", ")", ":", "void", "{", "$", "panelActions", "=", "(", "array", ")", "Configure", "::", "read", "(", "'CsvMigrations.panels.actions'", ")", ";", "$", "dynamicPanelActions", "=", "(", "array", ")", "Configure", "::", "read", "(", "'CsvMigrations.panels.dynamic_actions'", ")", ";", "if", "(", "!", "in_array", "(", "$", "this", "->", "request", "->", "getParam", "(", "'action'", ")", ",", "array_diff", "(", "$", "panelActions", ",", "$", "dynamicPanelActions", ")", ")", ")", "{", "return", ";", "}", "$", "controller", "=", "$", "event", "->", "getSubject", "(", ")", ";", "Assert", "::", "isInstanceOf", "(", "$", "controller", ",", "Controller", "::", "class", ")", ";", "$", "config", "=", "new", "ModuleConfig", "(", "ConfigType", "::", "MODULE", "(", ")", ",", "$", "controller", "->", "getName", "(", ")", ")", ";", "$", "config", "=", "json_encode", "(", "$", "config", "->", "parse", "(", ")", ")", ";", "$", "config", "=", "false", "===", "$", "config", "?", "[", "]", ":", "json_decode", "(", "$", "config", ",", "true", ")", ";", "$", "panels", "=", "$", "this", "->", "getPanels", "(", "$", "config", ",", "$", "controller", "->", "viewVars", "[", "'entity'", "]", "->", "toArray", "(", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "panels", "[", "'fail'", "]", ")", ")", "{", "// filter out fields of hidden panels", "$", "controller", "->", "viewVars", "[", "'fields'", "]", "=", "array_diff_key", "(", "$", "controller", "->", "viewVars", "[", "'fields'", "]", ",", "array_flip", "(", "$", "panels", "[", "'fail'", "]", ")", ")", ";", "}", "if", "(", "(", "string", ")", "Configure", "::", "read", "(", "'CsvMigrations.batch.action'", ")", "===", "$", "this", "->", "request", "->", "getParam", "(", "'action'", ")", ")", "{", "$", "this", "->", "filterBatchFields", "(", "$", "event", ")", ";", "}", "}" ]
Filter csv fields. @param \Cake\Event\Event $event Event instance @return void
[ "Filter", "csv", "fields", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Controller/Component/CsvViewComponent.php#L75-L102
train
QoboLtd/cakephp-csv-migrations
src/Controller/Component/CsvViewComponent.php
CsvViewComponent.filterBatchFields
protected function filterBatchFields(Event $event) : void { $config = new ModuleConfig(ConfigType::MIGRATION(), $this->request->getParam('controller')); $config = json_encode($config->parse()); $fields = false === $config ? [] : json_decode($config, true); $batchFields = (array)Configure::read('CsvMigrations.batch.types'); $nonBatchFields = []; foreach ($fields as $field) { $csvField = new CsvField($field); if (in_array($csvField->getType(), $batchFields)) { continue; } $nonBatchFields[] = $csvField->getName(); } if (empty($nonBatchFields)) { return; } $controller = $event->getSubject(); Assert::isInstanceOf($controller, Controller::class); $fields = $controller->viewVars['fields']; foreach ($fields as $panel => $panelFields) { foreach ($panelFields as $section => $sectionFields) { foreach ($sectionFields as $key => $field) { if (!in_array($field['name'], $nonBatchFields)) { continue; } $fields[$panel][$section][$key]['name'] = ''; } } } $controller->viewVars['fields'] = $fields; }
php
protected function filterBatchFields(Event $event) : void { $config = new ModuleConfig(ConfigType::MIGRATION(), $this->request->getParam('controller')); $config = json_encode($config->parse()); $fields = false === $config ? [] : json_decode($config, true); $batchFields = (array)Configure::read('CsvMigrations.batch.types'); $nonBatchFields = []; foreach ($fields as $field) { $csvField = new CsvField($field); if (in_array($csvField->getType(), $batchFields)) { continue; } $nonBatchFields[] = $csvField->getName(); } if (empty($nonBatchFields)) { return; } $controller = $event->getSubject(); Assert::isInstanceOf($controller, Controller::class); $fields = $controller->viewVars['fields']; foreach ($fields as $panel => $panelFields) { foreach ($panelFields as $section => $sectionFields) { foreach ($sectionFields as $key => $field) { if (!in_array($field['name'], $nonBatchFields)) { continue; } $fields[$panel][$section][$key]['name'] = ''; } } } $controller->viewVars['fields'] = $fields; }
[ "protected", "function", "filterBatchFields", "(", "Event", "$", "event", ")", ":", "void", "{", "$", "config", "=", "new", "ModuleConfig", "(", "ConfigType", "::", "MIGRATION", "(", ")", ",", "$", "this", "->", "request", "->", "getParam", "(", "'controller'", ")", ")", ";", "$", "config", "=", "json_encode", "(", "$", "config", "->", "parse", "(", ")", ")", ";", "$", "fields", "=", "false", "===", "$", "config", "?", "[", "]", ":", "json_decode", "(", "$", "config", ",", "true", ")", ";", "$", "batchFields", "=", "(", "array", ")", "Configure", "::", "read", "(", "'CsvMigrations.batch.types'", ")", ";", "$", "nonBatchFields", "=", "[", "]", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "$", "csvField", "=", "new", "CsvField", "(", "$", "field", ")", ";", "if", "(", "in_array", "(", "$", "csvField", "->", "getType", "(", ")", ",", "$", "batchFields", ")", ")", "{", "continue", ";", "}", "$", "nonBatchFields", "[", "]", "=", "$", "csvField", "->", "getName", "(", ")", ";", "}", "if", "(", "empty", "(", "$", "nonBatchFields", ")", ")", "{", "return", ";", "}", "$", "controller", "=", "$", "event", "->", "getSubject", "(", ")", ";", "Assert", "::", "isInstanceOf", "(", "$", "controller", ",", "Controller", "::", "class", ")", ";", "$", "fields", "=", "$", "controller", "->", "viewVars", "[", "'fields'", "]", ";", "foreach", "(", "$", "fields", "as", "$", "panel", "=>", "$", "panelFields", ")", "{", "foreach", "(", "$", "panelFields", "as", "$", "section", "=>", "$", "sectionFields", ")", "{", "foreach", "(", "$", "sectionFields", "as", "$", "key", "=>", "$", "field", ")", "{", "if", "(", "!", "in_array", "(", "$", "field", "[", "'name'", "]", ",", "$", "nonBatchFields", ")", ")", "{", "continue", ";", "}", "$", "fields", "[", "$", "panel", "]", "[", "$", "section", "]", "[", "$", "key", "]", "[", "'name'", "]", "=", "''", ";", "}", "}", "}", "$", "controller", "->", "viewVars", "[", "'fields'", "]", "=", "$", "fields", ";", "}" ]
Filter batch fields. @param \Cake\Event\Event $event Event instance @return void
[ "Filter", "batch", "fields", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Controller/Component/CsvViewComponent.php#L110-L149
train
QoboLtd/cakephp-csv-migrations
src/CsvMigration.php
CsvMigration.csv
public function csv(Table $table, string $path = '') : Table { $this->factory = new FieldHandlerFactory(); $this->table = $table; $this->handleCsv(); return $this->table; }
php
public function csv(Table $table, string $path = '') : Table { $this->factory = new FieldHandlerFactory(); $this->table = $table; $this->handleCsv(); return $this->table; }
[ "public", "function", "csv", "(", "Table", "$", "table", ",", "string", "$", "path", "=", "''", ")", ":", "Table", "{", "$", "this", "->", "factory", "=", "new", "FieldHandlerFactory", "(", ")", ";", "$", "this", "->", "table", "=", "$", "table", ";", "$", "this", "->", "handleCsv", "(", ")", ";", "return", "$", "this", "->", "table", ";", "}" ]
Method that handles migrations using JSON file. @param \Migrations\Table $table Migrations table object @param string $path JSON File path @return \Migrations\Table
[ "Method", "that", "handles", "migrations", "using", "JSON", "file", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/CsvMigration.php#L106-L113
train
QoboLtd/cakephp-csv-migrations
src/CsvMigration.php
CsvMigration.handleCsv
private function handleCsv() : void { $tableName = Inflector::pluralize(Inflector::classify($this->table->getName())); $mc = new ModuleConfig(ConfigType::MIGRATION(), $tableName); $data = json_encode($mc->parse()); if (false === $data) { $this->log(sprintf('No data found for %s module', $tableName), LogLevel::ERROR); return; } $data = json_decode($data, true); $data = array_merge($data, self::$_requiredFields); try { $tableFields = $this->table->getColumns(); } catch (PDOException $e) { $tableFields = []; } empty($tableFields) ? $this->createFromCsv($data, $tableName) : $this->updateFromCsv($data, $tableName, $tableFields); }
php
private function handleCsv() : void { $tableName = Inflector::pluralize(Inflector::classify($this->table->getName())); $mc = new ModuleConfig(ConfigType::MIGRATION(), $tableName); $data = json_encode($mc->parse()); if (false === $data) { $this->log(sprintf('No data found for %s module', $tableName), LogLevel::ERROR); return; } $data = json_decode($data, true); $data = array_merge($data, self::$_requiredFields); try { $tableFields = $this->table->getColumns(); } catch (PDOException $e) { $tableFields = []; } empty($tableFields) ? $this->createFromCsv($data, $tableName) : $this->updateFromCsv($data, $tableName, $tableFields); }
[ "private", "function", "handleCsv", "(", ")", ":", "void", "{", "$", "tableName", "=", "Inflector", "::", "pluralize", "(", "Inflector", "::", "classify", "(", "$", "this", "->", "table", "->", "getName", "(", ")", ")", ")", ";", "$", "mc", "=", "new", "ModuleConfig", "(", "ConfigType", "::", "MIGRATION", "(", ")", ",", "$", "tableName", ")", ";", "$", "data", "=", "json_encode", "(", "$", "mc", "->", "parse", "(", ")", ")", ";", "if", "(", "false", "===", "$", "data", ")", "{", "$", "this", "->", "log", "(", "sprintf", "(", "'No data found for %s module'", ",", "$", "tableName", ")", ",", "LogLevel", "::", "ERROR", ")", ";", "return", ";", "}", "$", "data", "=", "json_decode", "(", "$", "data", ",", "true", ")", ";", "$", "data", "=", "array_merge", "(", "$", "data", ",", "self", "::", "$", "_requiredFields", ")", ";", "try", "{", "$", "tableFields", "=", "$", "this", "->", "table", "->", "getColumns", "(", ")", ";", "}", "catch", "(", "PDOException", "$", "e", ")", "{", "$", "tableFields", "=", "[", "]", ";", "}", "empty", "(", "$", "tableFields", ")", "?", "$", "this", "->", "createFromCsv", "(", "$", "data", ",", "$", "tableName", ")", ":", "$", "this", "->", "updateFromCsv", "(", "$", "data", ",", "$", "tableName", ",", "$", "tableFields", ")", ";", "}" ]
Apply changes from the JSON file @return void
[ "Apply", "changes", "from", "the", "JSON", "file" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/CsvMigration.php#L120-L142
train
QoboLtd/cakephp-csv-migrations
src/CsvMigration.php
CsvMigration.getRequiredFields
public static function getRequiredFields(bool $withSchema = false) : array { return $withSchema ? self::$_requiredFields : array_keys(self::$_requiredFields); }
php
public static function getRequiredFields(bool $withSchema = false) : array { return $withSchema ? self::$_requiredFields : array_keys(self::$_requiredFields); }
[ "public", "static", "function", "getRequiredFields", "(", "bool", "$", "withSchema", "=", "false", ")", ":", "array", "{", "return", "$", "withSchema", "?", "self", "::", "$", "_requiredFields", ":", "array_keys", "(", "self", "::", "$", "_requiredFields", ")", ";", "}" ]
Required fields getter method. Returns either just the field names or with their schema definition. @param bool $withSchema Schema inclusion flag @return mixed[]|string[]
[ "Required", "fields", "getter", "method", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/CsvMigration.php#L169-L172
train
QoboLtd/cakephp-csv-migrations
src/CsvMigration.php
CsvMigration.createFromCsv
private function createFromCsv(array $data, string $table) : void { foreach ($data as $col) { $csvField = new CsvField($col); $dbFields = $this->factory->fieldToDb($csvField, $table); if (empty($dbFields)) { continue; } foreach ($dbFields as $dbField) { $this->createColumn($dbField); } } }
php
private function createFromCsv(array $data, string $table) : void { foreach ($data as $col) { $csvField = new CsvField($col); $dbFields = $this->factory->fieldToDb($csvField, $table); if (empty($dbFields)) { continue; } foreach ($dbFields as $dbField) { $this->createColumn($dbField); } } }
[ "private", "function", "createFromCsv", "(", "array", "$", "data", ",", "string", "$", "table", ")", ":", "void", "{", "foreach", "(", "$", "data", "as", "$", "col", ")", "{", "$", "csvField", "=", "new", "CsvField", "(", "$", "col", ")", ";", "$", "dbFields", "=", "$", "this", "->", "factory", "->", "fieldToDb", "(", "$", "csvField", ",", "$", "table", ")", ";", "if", "(", "empty", "(", "$", "dbFields", ")", ")", "{", "continue", ";", "}", "foreach", "(", "$", "dbFields", "as", "$", "dbField", ")", "{", "$", "this", "->", "createColumn", "(", "$", "dbField", ")", ";", "}", "}", "}" ]
Create new fields from JSON data. @param mixed[] $data JSON data @param string $table Table name @return void
[ "Create", "new", "fields", "from", "JSON", "data", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/CsvMigration.php#L181-L195
train
QoboLtd/cakephp-csv-migrations
src/CsvMigration.php
CsvMigration.createColumn
private function createColumn(DbField $dbField) : void { $this->table->addColumn($dbField->getName(), $dbField->getType(), $dbField->getOptions()); // set id as primary key if ('id' === $dbField->getName()) { $this->table->addPrimaryKey([ $dbField->getName(), ]); } $this->addIndexes($dbField, false); }
php
private function createColumn(DbField $dbField) : void { $this->table->addColumn($dbField->getName(), $dbField->getType(), $dbField->getOptions()); // set id as primary key if ('id' === $dbField->getName()) { $this->table->addPrimaryKey([ $dbField->getName(), ]); } $this->addIndexes($dbField, false); }
[ "private", "function", "createColumn", "(", "DbField", "$", "dbField", ")", ":", "void", "{", "$", "this", "->", "table", "->", "addColumn", "(", "$", "dbField", "->", "getName", "(", ")", ",", "$", "dbField", "->", "getType", "(", ")", ",", "$", "dbField", "->", "getOptions", "(", ")", ")", ";", "// set id as primary key", "if", "(", "'id'", "===", "$", "dbField", "->", "getName", "(", ")", ")", "{", "$", "this", "->", "table", "->", "addPrimaryKey", "(", "[", "$", "dbField", "->", "getName", "(", ")", ",", "]", ")", ";", "}", "$", "this", "->", "addIndexes", "(", "$", "dbField", ",", "false", ")", ";", "}" ]
Method used for creating new DB table column. @param \CsvMigrations\FieldHandlers\DbField $dbField DbField object @return void
[ "Method", "used", "for", "creating", "new", "DB", "table", "column", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/CsvMigration.php#L246-L258
train
QoboLtd/cakephp-csv-migrations
src/CsvMigration.php
CsvMigration.updateColumn
private function updateColumn(DbField $dbField) : void { $this->table->changeColumn($dbField->getName(), $dbField->getType(), $dbField->getOptions()); // set field as unique if ($dbField->getUnique()) { // avoid creation of duplicate indexes if (!$this->table->hasIndex($dbField->getName())) { $this->table->addIndex([$dbField->getName()], ['unique' => true]); } } else { if ($this->table->hasIndex($dbField->getName())) { $this->table->removeIndexByName($dbField->getName()); } } $this->addIndexes($dbField); }
php
private function updateColumn(DbField $dbField) : void { $this->table->changeColumn($dbField->getName(), $dbField->getType(), $dbField->getOptions()); // set field as unique if ($dbField->getUnique()) { // avoid creation of duplicate indexes if (!$this->table->hasIndex($dbField->getName())) { $this->table->addIndex([$dbField->getName()], ['unique' => true]); } } else { if ($this->table->hasIndex($dbField->getName())) { $this->table->removeIndexByName($dbField->getName()); } } $this->addIndexes($dbField); }
[ "private", "function", "updateColumn", "(", "DbField", "$", "dbField", ")", ":", "void", "{", "$", "this", "->", "table", "->", "changeColumn", "(", "$", "dbField", "->", "getName", "(", ")", ",", "$", "dbField", "->", "getType", "(", ")", ",", "$", "dbField", "->", "getOptions", "(", ")", ")", ";", "// set field as unique", "if", "(", "$", "dbField", "->", "getUnique", "(", ")", ")", "{", "// avoid creation of duplicate indexes", "if", "(", "!", "$", "this", "->", "table", "->", "hasIndex", "(", "$", "dbField", "->", "getName", "(", ")", ")", ")", "{", "$", "this", "->", "table", "->", "addIndex", "(", "[", "$", "dbField", "->", "getName", "(", ")", "]", ",", "[", "'unique'", "=>", "true", "]", ")", ";", "}", "}", "else", "{", "if", "(", "$", "this", "->", "table", "->", "hasIndex", "(", "$", "dbField", "->", "getName", "(", ")", ")", ")", "{", "$", "this", "->", "table", "->", "removeIndexByName", "(", "$", "dbField", "->", "getName", "(", ")", ")", ";", "}", "}", "$", "this", "->", "addIndexes", "(", "$", "dbField", ")", ";", "}" ]
Method used for updating an existing DB table column. @param \CsvMigrations\FieldHandlers\DbField $dbField DbField object @return void
[ "Method", "used", "for", "updating", "an", "existing", "DB", "table", "column", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/CsvMigration.php#L266-L282
train
QoboLtd/cakephp-csv-migrations
src/CsvMigration.php
CsvMigration.addIndexes
private function addIndexes(DbField $dbField, bool $exists = true) : void { if ('id' === $dbField->getName()) { return; } $this->removeIndexes($dbField, $exists); $added = false; if ($dbField->getUnique()) { $added = $this->addIndex($dbField, 'unique', $exists); } if (!$added && 'uuid' === $dbField->getType()) { $this->addIndex($dbField, 'lookup', $exists); } }
php
private function addIndexes(DbField $dbField, bool $exists = true) : void { if ('id' === $dbField->getName()) { return; } $this->removeIndexes($dbField, $exists); $added = false; if ($dbField->getUnique()) { $added = $this->addIndex($dbField, 'unique', $exists); } if (!$added && 'uuid' === $dbField->getType()) { $this->addIndex($dbField, 'lookup', $exists); } }
[ "private", "function", "addIndexes", "(", "DbField", "$", "dbField", ",", "bool", "$", "exists", "=", "true", ")", ":", "void", "{", "if", "(", "'id'", "===", "$", "dbField", "->", "getName", "(", ")", ")", "{", "return", ";", "}", "$", "this", "->", "removeIndexes", "(", "$", "dbField", ",", "$", "exists", ")", ";", "$", "added", "=", "false", ";", "if", "(", "$", "dbField", "->", "getUnique", "(", ")", ")", "{", "$", "added", "=", "$", "this", "->", "addIndex", "(", "$", "dbField", ",", "'unique'", ",", "$", "exists", ")", ";", "}", "if", "(", "!", "$", "added", "&&", "'uuid'", "===", "$", "dbField", "->", "getType", "(", ")", ")", "{", "$", "this", "->", "addIndex", "(", "$", "dbField", ",", "'lookup'", ",", "$", "exists", ")", ";", "}", "}" ]
Adds indexes to specified dbField. @param \CsvMigrations\FieldHandlers\DbField $dbField DbField object @param bool $exists Table exists flag @return void
[ "Adds", "indexes", "to", "specified", "dbField", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/CsvMigration.php#L291-L307
train
QoboLtd/cakephp-csv-migrations
src/CsvMigration.php
CsvMigration.removeIndexes
private function removeIndexes(DbField $dbField, bool $exists = true) : void { if (! $exists) { return; } // remove legacy index $this->table->removeIndexByName($dbField->getName()); // remove unique index if (!$dbField->getUnique() && $this->table->hasIndex($dbField->getName())) { $indexName = 'unique_' . $dbField->getName(); $this->table->removeIndexByName($indexName); } // remove lookup index if ('uuid' !== $dbField->getType() && $this->table->hasIndex($dbField->getName())) { $indexName = 'lookup_' . $dbField->getName(); $this->table->removeIndexByName($indexName); } }
php
private function removeIndexes(DbField $dbField, bool $exists = true) : void { if (! $exists) { return; } // remove legacy index $this->table->removeIndexByName($dbField->getName()); // remove unique index if (!$dbField->getUnique() && $this->table->hasIndex($dbField->getName())) { $indexName = 'unique_' . $dbField->getName(); $this->table->removeIndexByName($indexName); } // remove lookup index if ('uuid' !== $dbField->getType() && $this->table->hasIndex($dbField->getName())) { $indexName = 'lookup_' . $dbField->getName(); $this->table->removeIndexByName($indexName); } }
[ "private", "function", "removeIndexes", "(", "DbField", "$", "dbField", ",", "bool", "$", "exists", "=", "true", ")", ":", "void", "{", "if", "(", "!", "$", "exists", ")", "{", "return", ";", "}", "// remove legacy index", "$", "this", "->", "table", "->", "removeIndexByName", "(", "$", "dbField", "->", "getName", "(", ")", ")", ";", "// remove unique index", "if", "(", "!", "$", "dbField", "->", "getUnique", "(", ")", "&&", "$", "this", "->", "table", "->", "hasIndex", "(", "$", "dbField", "->", "getName", "(", ")", ")", ")", "{", "$", "indexName", "=", "'unique_'", ".", "$", "dbField", "->", "getName", "(", ")", ";", "$", "this", "->", "table", "->", "removeIndexByName", "(", "$", "indexName", ")", ";", "}", "// remove lookup index", "if", "(", "'uuid'", "!==", "$", "dbField", "->", "getType", "(", ")", "&&", "$", "this", "->", "table", "->", "hasIndex", "(", "$", "dbField", "->", "getName", "(", ")", ")", ")", "{", "$", "indexName", "=", "'lookup_'", ".", "$", "dbField", "->", "getName", "(", ")", ";", "$", "this", "->", "table", "->", "removeIndexByName", "(", "$", "indexName", ")", ";", "}", "}" ]
Remove column indexes. @param \CsvMigrations\FieldHandlers\DbField $dbField DbField object @param bool $exists Table exists flag @return void
[ "Remove", "column", "indexes", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/CsvMigration.php#L316-L336
train
QoboLtd/cakephp-csv-migrations
src/CsvMigration.php
CsvMigration.addIndex
private function addIndex(DbField $dbField, string $type, bool $exists = true) : bool { if (empty($type)) { return false; } // skip if table exists and has specified index if ($exists && $this->table->hasIndex($dbField->getName())) { return false; } $options = []; $options['name'] = $type . '_' . $dbField->getName(); if ('unique' === $type) { $options['unique'] = true; } $this->table->addIndex($dbField->getName(), $options); return true; }
php
private function addIndex(DbField $dbField, string $type, bool $exists = true) : bool { if (empty($type)) { return false; } // skip if table exists and has specified index if ($exists && $this->table->hasIndex($dbField->getName())) { return false; } $options = []; $options['name'] = $type . '_' . $dbField->getName(); if ('unique' === $type) { $options['unique'] = true; } $this->table->addIndex($dbField->getName(), $options); return true; }
[ "private", "function", "addIndex", "(", "DbField", "$", "dbField", ",", "string", "$", "type", ",", "bool", "$", "exists", "=", "true", ")", ":", "bool", "{", "if", "(", "empty", "(", "$", "type", ")", ")", "{", "return", "false", ";", "}", "// skip if table exists and has specified index", "if", "(", "$", "exists", "&&", "$", "this", "->", "table", "->", "hasIndex", "(", "$", "dbField", "->", "getName", "(", ")", ")", ")", "{", "return", "false", ";", "}", "$", "options", "=", "[", "]", ";", "$", "options", "[", "'name'", "]", "=", "$", "type", ".", "'_'", ".", "$", "dbField", "->", "getName", "(", ")", ";", "if", "(", "'unique'", "===", "$", "type", ")", "{", "$", "options", "[", "'unique'", "]", "=", "true", ";", "}", "$", "this", "->", "table", "->", "addIndex", "(", "$", "dbField", "->", "getName", "(", ")", ",", "$", "options", ")", ";", "return", "true", ";", "}" ]
Add column index by type. @param \CsvMigrations\FieldHandlers\DbField $dbField DbField object @param string $type Index type @param bool $exists Table exists flag @return bool
[ "Add", "column", "index", "by", "type", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/CsvMigration.php#L346-L366
train
QoboLtd/cakephp-csv-migrations
src/Shell/Task/CsvMigrationTask.php
CsvMigrationTask._getCsvModules
protected function _getCsvModules() : array { $dir = new Folder(Configure::read('CsvMigrations.modules.path')); $folders = $dir->read(true)[0]; return (array)$folders; }
php
protected function _getCsvModules() : array { $dir = new Folder(Configure::read('CsvMigrations.modules.path')); $folders = $dir->read(true)[0]; return (array)$folders; }
[ "protected", "function", "_getCsvModules", "(", ")", ":", "array", "{", "$", "dir", "=", "new", "Folder", "(", "Configure", "::", "read", "(", "'CsvMigrations.modules.path'", ")", ")", ";", "$", "folders", "=", "$", "dir", "->", "read", "(", "true", ")", "[", "0", "]", ";", "return", "(", "array", ")", "$", "folders", ";", "}" ]
Get CSV module names from defined modules directory. @return mixed[]
[ "Get", "CSV", "module", "names", "from", "defined", "modules", "directory", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Shell/Task/CsvMigrationTask.php#L110-L116
train
QoboLtd/cakephp-csv-migrations
src/Shell/Task/CsvMigrationTask.php
CsvMigrationTask._getVars
protected function _getVars(string $tableName) : array { $table = Inflector::tableize($tableName); $name = Inflector::camelize($tableName) . $this->_getLastModifiedTime($table); return [$table, $name]; }
php
protected function _getVars(string $tableName) : array { $table = Inflector::tableize($tableName); $name = Inflector::camelize($tableName) . $this->_getLastModifiedTime($table); return [$table, $name]; }
[ "protected", "function", "_getVars", "(", "string", "$", "tableName", ")", ":", "array", "{", "$", "table", "=", "Inflector", "::", "tableize", "(", "$", "tableName", ")", ";", "$", "name", "=", "Inflector", "::", "camelize", "(", "$", "tableName", ")", ".", "$", "this", "->", "_getLastModifiedTime", "(", "$", "table", ")", ";", "return", "[", "$", "table", ",", "$", "name", "]", ";", "}" ]
Returns variables for bake template. @param string $tableName Table name @return string[]
[ "Returns", "variables", "for", "bake", "template", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Shell/Task/CsvMigrationTask.php#L124-L131
train
QoboLtd/cakephp-csv-migrations
src/Shell/Task/CsvMigrationTask.php
CsvMigrationTask._getLastModifiedTime
protected function _getLastModifiedTime(string $tableName) : string { $tableName = Inflector::camelize($tableName); $mc = new ModuleConfig(ConfigType::MIGRATION(), $tableName); $path = $mc->find(); $mtime = filemtime($path); if (false === $mtime) { $this->abort('Failed to get file\'s last modified time'); } // Unit time stamp to YYYYMMDDhhmmss return date('YmdHis', $mtime); }
php
protected function _getLastModifiedTime(string $tableName) : string { $tableName = Inflector::camelize($tableName); $mc = new ModuleConfig(ConfigType::MIGRATION(), $tableName); $path = $mc->find(); $mtime = filemtime($path); if (false === $mtime) { $this->abort('Failed to get file\'s last modified time'); } // Unit time stamp to YYYYMMDDhhmmss return date('YmdHis', $mtime); }
[ "protected", "function", "_getLastModifiedTime", "(", "string", "$", "tableName", ")", ":", "string", "{", "$", "tableName", "=", "Inflector", "::", "camelize", "(", "$", "tableName", ")", ";", "$", "mc", "=", "new", "ModuleConfig", "(", "ConfigType", "::", "MIGRATION", "(", ")", ",", "$", "tableName", ")", ";", "$", "path", "=", "$", "mc", "->", "find", "(", ")", ";", "$", "mtime", "=", "filemtime", "(", "$", "path", ")", ";", "if", "(", "false", "===", "$", "mtime", ")", "{", "$", "this", "->", "abort", "(", "'Failed to get file\\'s last modified time'", ")", ";", "}", "// Unit time stamp to YYYYMMDDhhmmss", "return", "date", "(", "'YmdHis'", ",", "$", "mtime", ")", ";", "}" ]
Get csv file's last modified time. @param string $tableName target table name @return string
[ "Get", "csv", "file", "s", "last", "modified", "time", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Shell/Task/CsvMigrationTask.php#L139-L153
train
QoboLtd/cakephp-csv-migrations
src/Model/AssociationsAwareTrait.php
AssociationsAwareTrait.setAssociation
protected function setAssociation(string $type, string $alias, array $options) : void { $this->{$type}($alias, $options); }
php
protected function setAssociation(string $type, string $alias, array $options) : void { $this->{$type}($alias, $options); }
[ "protected", "function", "setAssociation", "(", "string", "$", "type", ",", "string", "$", "alias", ",", "array", "$", "options", ")", ":", "void", "{", "$", "this", "->", "{", "$", "type", "}", "(", "$", "alias", ",", "$", "options", ")", ";", "}" ]
Association setter method. @see \Cake\ORM\Table::belongsTo() @see \Cake\ORM\Table::belongsToMany() @see \Cake\ORM\Table::hasMany() @see \Cake\ORM\Table::hasOne() @param string $type Association type @param string $alias Association alias @param mixed[] $options Association options @return void
[ "Association", "setter", "method", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Model/AssociationsAwareTrait.php#L58-L61
train
QoboLtd/cakephp-csv-migrations
src/Model/AssociationsAwareTrait.php
AssociationsAwareTrait.setByTypeRelation
private function setByTypeRelation(string $module, array $fields) : void { $moduleField = $this->getModuleRelatedField($fields); if (is_null($moduleField)) { return; } $selfrelated = $this->getSelfRelated($fields); if (!empty($selfrelated)) { $this->setByTypeSelfRelationField($module, $selfrelated); return; } foreach ($fields as $field) { $this->setByTypeRelationField($module, $field, $moduleField); } }
php
private function setByTypeRelation(string $module, array $fields) : void { $moduleField = $this->getModuleRelatedField($fields); if (is_null($moduleField)) { return; } $selfrelated = $this->getSelfRelated($fields); if (!empty($selfrelated)) { $this->setByTypeSelfRelationField($module, $selfrelated); return; } foreach ($fields as $field) { $this->setByTypeRelationField($module, $field, $moduleField); } }
[ "private", "function", "setByTypeRelation", "(", "string", "$", "module", ",", "array", "$", "fields", ")", ":", "void", "{", "$", "moduleField", "=", "$", "this", "->", "getModuleRelatedField", "(", "$", "fields", ")", ";", "if", "(", "is_null", "(", "$", "moduleField", ")", ")", "{", "return", ";", "}", "$", "selfrelated", "=", "$", "this", "->", "getSelfRelated", "(", "$", "fields", ")", ";", "if", "(", "!", "empty", "(", "$", "selfrelated", ")", ")", "{", "$", "this", "->", "setByTypeSelfRelationField", "(", "$", "module", ",", "$", "selfrelated", ")", ";", "return", ";", "}", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "$", "this", "->", "setByTypeRelationField", "(", "$", "module", ",", "$", "field", ",", "$", "moduleField", ")", ";", "}", "}" ]
Set associations from "relation" type Modules. @param string $module Module name @param mixed[] $fields Module fields @return void
[ "Set", "associations", "from", "relation", "type", "Modules", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Model/AssociationsAwareTrait.php#L116-L134
train
QoboLtd/cakephp-csv-migrations
src/Model/AssociationsAwareTrait.php
AssociationsAwareTrait.setByTypeModuleField
private function setByTypeModuleField(string $module, CsvField $field) : void { // skip non related type if (! $this->isRelatedType($field)) { return; } // skip associations between other modules if (! in_array($this->getTableName(), [$module, $field->getAssocCsvModule()])) { return; } $className = ''; $associationType = ''; /** * for current table instance "Articles", assuming that the provide $module is "Articles" and * a field "author_id" of type "related(Authors)" is found in its migration.json config, * then we set the association as follows: * * $articlesTable->belongTo('AuthorIdAuthors', ['className' => 'Authors', 'foreignKey' => 'author_id']); */ if ($this->getTableName() === $module) { $className = $field->getAssocCsvModule(); $associationType = 'belongsTo'; } /** * for current table instance "Authors", assuming that the provide $module is "Articles" and * a field "related_author" of type "related(Authors)" is found in its migration.json config, * then we set the association as follows: * * $authorsTable->hasMany('RelatedAuthorArticles', ['className' => 'Articles', 'foreignKey' => 'related_author']); */ if ($this->getTableName() === $field->getAssocCsvModule()) { $className = $module; $associationType = 'hasMany'; } /** * for current table instance "Articles", assuming that the provide $module is "Articles" and * a field "main_article" of type "related(Articles)" is found in its migration.json config, * then we set the association as follows: * * $articlesTable->belongTo('MainArticleArticles', ['className' => 'Articles', 'foreignKey' => 'main_article']); */ if ($field->getAssocCsvModule() === $module) { $className = $module; $associationType = 'belongsTo'; } $this->setAssociation( $associationType, static::generateAssociationName($className, $field->getName()), ['className' => $className, 'foreignKey' => $field->getName()] ); }
php
private function setByTypeModuleField(string $module, CsvField $field) : void { // skip non related type if (! $this->isRelatedType($field)) { return; } // skip associations between other modules if (! in_array($this->getTableName(), [$module, $field->getAssocCsvModule()])) { return; } $className = ''; $associationType = ''; /** * for current table instance "Articles", assuming that the provide $module is "Articles" and * a field "author_id" of type "related(Authors)" is found in its migration.json config, * then we set the association as follows: * * $articlesTable->belongTo('AuthorIdAuthors', ['className' => 'Authors', 'foreignKey' => 'author_id']); */ if ($this->getTableName() === $module) { $className = $field->getAssocCsvModule(); $associationType = 'belongsTo'; } /** * for current table instance "Authors", assuming that the provide $module is "Articles" and * a field "related_author" of type "related(Authors)" is found in its migration.json config, * then we set the association as follows: * * $authorsTable->hasMany('RelatedAuthorArticles', ['className' => 'Articles', 'foreignKey' => 'related_author']); */ if ($this->getTableName() === $field->getAssocCsvModule()) { $className = $module; $associationType = 'hasMany'; } /** * for current table instance "Articles", assuming that the provide $module is "Articles" and * a field "main_article" of type "related(Articles)" is found in its migration.json config, * then we set the association as follows: * * $articlesTable->belongTo('MainArticleArticles', ['className' => 'Articles', 'foreignKey' => 'main_article']); */ if ($field->getAssocCsvModule() === $module) { $className = $module; $associationType = 'belongsTo'; } $this->setAssociation( $associationType, static::generateAssociationName($className, $field->getName()), ['className' => $className, 'foreignKey' => $field->getName()] ); }
[ "private", "function", "setByTypeModuleField", "(", "string", "$", "module", ",", "CsvField", "$", "field", ")", ":", "void", "{", "// skip non related type", "if", "(", "!", "$", "this", "->", "isRelatedType", "(", "$", "field", ")", ")", "{", "return", ";", "}", "// skip associations between other modules", "if", "(", "!", "in_array", "(", "$", "this", "->", "getTableName", "(", ")", ",", "[", "$", "module", ",", "$", "field", "->", "getAssocCsvModule", "(", ")", "]", ")", ")", "{", "return", ";", "}", "$", "className", "=", "''", ";", "$", "associationType", "=", "''", ";", "/**\n * for current table instance \"Articles\", assuming that the provide $module is \"Articles\" and\n * a field \"author_id\" of type \"related(Authors)\" is found in its migration.json config,\n * then we set the association as follows:\n *\n * $articlesTable->belongTo('AuthorIdAuthors', ['className' => 'Authors', 'foreignKey' => 'author_id']);\n */", "if", "(", "$", "this", "->", "getTableName", "(", ")", "===", "$", "module", ")", "{", "$", "className", "=", "$", "field", "->", "getAssocCsvModule", "(", ")", ";", "$", "associationType", "=", "'belongsTo'", ";", "}", "/**\n * for current table instance \"Authors\", assuming that the provide $module is \"Articles\" and\n * a field \"related_author\" of type \"related(Authors)\" is found in its migration.json config,\n * then we set the association as follows:\n *\n * $authorsTable->hasMany('RelatedAuthorArticles', ['className' => 'Articles', 'foreignKey' => 'related_author']);\n */", "if", "(", "$", "this", "->", "getTableName", "(", ")", "===", "$", "field", "->", "getAssocCsvModule", "(", ")", ")", "{", "$", "className", "=", "$", "module", ";", "$", "associationType", "=", "'hasMany'", ";", "}", "/**\n * for current table instance \"Articles\", assuming that the provide $module is \"Articles\" and\n * a field \"main_article\" of type \"related(Articles)\" is found in its migration.json config,\n * then we set the association as follows:\n *\n * $articlesTable->belongTo('MainArticleArticles', ['className' => 'Articles', 'foreignKey' => 'main_article']);\n */", "if", "(", "$", "field", "->", "getAssocCsvModule", "(", ")", "===", "$", "module", ")", "{", "$", "className", "=", "$", "module", ";", "$", "associationType", "=", "'belongsTo'", ";", "}", "$", "this", "->", "setAssociation", "(", "$", "associationType", ",", "static", "::", "generateAssociationName", "(", "$", "className", ",", "$", "field", "->", "getName", "(", ")", ")", ",", "[", "'className'", "=>", "$", "className", ",", "'foreignKey'", "=>", "$", "field", "->", "getName", "(", ")", "]", ")", ";", "}" ]
Set associations by field, for "module" type Modules. @param string $module Module name @param \CsvMigrations\FieldHandlers\CsvField $field CSV Field instance @return void
[ "Set", "associations", "by", "field", "for", "module", "type", "Modules", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Model/AssociationsAwareTrait.php#L199-L255
train
QoboLtd/cakephp-csv-migrations
src/Model/AssociationsAwareTrait.php
AssociationsAwareTrait.setByTypeSelfRelationField
private function setByTypeSelfRelationField(string $module, array $fields) : void { $first = $fields[0]; $second = $fields[1]; $this->setAssociation( 'belongsToMany', static::generateAssociationName($module, $first->getName()), [ 'joinTable' => Inflector::tableize($module), 'className' => $first->getAssocCsvModule(), 'foreignKey' => $second->getName(), 'targetForeignKey' => $first->getName() ] ); $this->setAssociation( 'belongsToMany', static::generateAssociationName($module, $second->getName()), [ 'joinTable' => Inflector::tableize($module), 'className' => $second->getAssocCsvModule(), 'foreignKey' => $first->getName(), 'targetForeignKey' => $second->getName() ] ); }
php
private function setByTypeSelfRelationField(string $module, array $fields) : void { $first = $fields[0]; $second = $fields[1]; $this->setAssociation( 'belongsToMany', static::generateAssociationName($module, $first->getName()), [ 'joinTable' => Inflector::tableize($module), 'className' => $first->getAssocCsvModule(), 'foreignKey' => $second->getName(), 'targetForeignKey' => $first->getName() ] ); $this->setAssociation( 'belongsToMany', static::generateAssociationName($module, $second->getName()), [ 'joinTable' => Inflector::tableize($module), 'className' => $second->getAssocCsvModule(), 'foreignKey' => $first->getName(), 'targetForeignKey' => $second->getName() ] ); }
[ "private", "function", "setByTypeSelfRelationField", "(", "string", "$", "module", ",", "array", "$", "fields", ")", ":", "void", "{", "$", "first", "=", "$", "fields", "[", "0", "]", ";", "$", "second", "=", "$", "fields", "[", "1", "]", ";", "$", "this", "->", "setAssociation", "(", "'belongsToMany'", ",", "static", "::", "generateAssociationName", "(", "$", "module", ",", "$", "first", "->", "getName", "(", ")", ")", ",", "[", "'joinTable'", "=>", "Inflector", "::", "tableize", "(", "$", "module", ")", ",", "'className'", "=>", "$", "first", "->", "getAssocCsvModule", "(", ")", ",", "'foreignKey'", "=>", "$", "second", "->", "getName", "(", ")", ",", "'targetForeignKey'", "=>", "$", "first", "->", "getName", "(", ")", "]", ")", ";", "$", "this", "->", "setAssociation", "(", "'belongsToMany'", ",", "static", "::", "generateAssociationName", "(", "$", "module", ",", "$", "second", "->", "getName", "(", ")", ")", ",", "[", "'joinTable'", "=>", "Inflector", "::", "tableize", "(", "$", "module", ")", ",", "'className'", "=>", "$", "second", "->", "getAssocCsvModule", "(", ")", ",", "'foreignKey'", "=>", "$", "first", "->", "getName", "(", ")", ",", "'targetForeignKey'", "=>", "$", "second", "->", "getName", "(", ")", "]", ")", ";", "}" ]
Set associations for "self relation" type Modules. @param string $module Module name @param mixed[] $fields CSV Fields @return void
[ "Set", "associations", "for", "self", "relation", "type", "Modules", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Model/AssociationsAwareTrait.php#L264-L290
train
QoboLtd/cakephp-csv-migrations
src/Model/AssociationsAwareTrait.php
AssociationsAwareTrait.setByTypeRelationField
private function setByTypeRelationField(string $module, CsvField $field, CsvField $moduleField) : void { if (! $this->isRelatedType($field)) { return; } // skip for field with type "related(Articles)" when current module is "Articles" if ($this->getTableName() === $field->getAssocCsvModule()) { return; } // skip for fields associated with Footprint behavior ('related' type fields associated with Users table) if ($this->isFootprintField($field) || $this->isFootprintField($moduleField)) { return; } $this->setAssociation( 'belongsToMany', static::generateAssociationName($module, $field->getName()), [ 'joinTable' => Inflector::tableize($module), 'className' => $field->getAssocCsvModule(), 'foreignKey' => $moduleField->getName(), 'targetForeignKey' => $field->getName() ] ); }
php
private function setByTypeRelationField(string $module, CsvField $field, CsvField $moduleField) : void { if (! $this->isRelatedType($field)) { return; } // skip for field with type "related(Articles)" when current module is "Articles" if ($this->getTableName() === $field->getAssocCsvModule()) { return; } // skip for fields associated with Footprint behavior ('related' type fields associated with Users table) if ($this->isFootprintField($field) || $this->isFootprintField($moduleField)) { return; } $this->setAssociation( 'belongsToMany', static::generateAssociationName($module, $field->getName()), [ 'joinTable' => Inflector::tableize($module), 'className' => $field->getAssocCsvModule(), 'foreignKey' => $moduleField->getName(), 'targetForeignKey' => $field->getName() ] ); }
[ "private", "function", "setByTypeRelationField", "(", "string", "$", "module", ",", "CsvField", "$", "field", ",", "CsvField", "$", "moduleField", ")", ":", "void", "{", "if", "(", "!", "$", "this", "->", "isRelatedType", "(", "$", "field", ")", ")", "{", "return", ";", "}", "// skip for field with type \"related(Articles)\" when current module is \"Articles\"", "if", "(", "$", "this", "->", "getTableName", "(", ")", "===", "$", "field", "->", "getAssocCsvModule", "(", ")", ")", "{", "return", ";", "}", "// skip for fields associated with Footprint behavior ('related' type fields associated with Users table)", "if", "(", "$", "this", "->", "isFootprintField", "(", "$", "field", ")", "||", "$", "this", "->", "isFootprintField", "(", "$", "moduleField", ")", ")", "{", "return", ";", "}", "$", "this", "->", "setAssociation", "(", "'belongsToMany'", ",", "static", "::", "generateAssociationName", "(", "$", "module", ",", "$", "field", "->", "getName", "(", ")", ")", ",", "[", "'joinTable'", "=>", "Inflector", "::", "tableize", "(", "$", "module", ")", ",", "'className'", "=>", "$", "field", "->", "getAssocCsvModule", "(", ")", ",", "'foreignKey'", "=>", "$", "moduleField", "->", "getName", "(", ")", ",", "'targetForeignKey'", "=>", "$", "field", "->", "getName", "(", ")", "]", ")", ";", "}" ]
Set associations by field, for "relation" type Modules. @param string $module Module name @param \CsvMigrations\FieldHandlers\CsvField $field CSV Field instance @param \CsvMigrations\FieldHandlers\CsvField $moduleField Module related CSV Field instance @return void
[ "Set", "associations", "by", "field", "for", "relation", "type", "Modules", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Model/AssociationsAwareTrait.php#L300-L326
train
QoboLtd/cakephp-csv-migrations
src/Model/AssociationsAwareTrait.php
AssociationsAwareTrait.isFootprintField
private function isFootprintField(CsvField $field) : bool { if (! $this->hasBehavior('Footprint')) { return false; } $behavior = $this->behaviors()->get('Footprint'); Assert::isInstanceOf($behavior, Behavior::class); return in_array($field->getName(), $behavior->getConfig()); }
php
private function isFootprintField(CsvField $field) : bool { if (! $this->hasBehavior('Footprint')) { return false; } $behavior = $this->behaviors()->get('Footprint'); Assert::isInstanceOf($behavior, Behavior::class); return in_array($field->getName(), $behavior->getConfig()); }
[ "private", "function", "isFootprintField", "(", "CsvField", "$", "field", ")", ":", "bool", "{", "if", "(", "!", "$", "this", "->", "hasBehavior", "(", "'Footprint'", ")", ")", "{", "return", "false", ";", "}", "$", "behavior", "=", "$", "this", "->", "behaviors", "(", ")", "->", "get", "(", "'Footprint'", ")", ";", "Assert", "::", "isInstanceOf", "(", "$", "behavior", ",", "Behavior", "::", "class", ")", ";", "return", "in_array", "(", "$", "field", "->", "getName", "(", ")", ",", "$", "behavior", "->", "getConfig", "(", ")", ")", ";", "}" ]
Validates whether the provided field is used in Footprint behavior. @param \CsvMigrations\FieldHandlers\CsvField $field CSV Field instance @return bool
[ "Validates", "whether", "the", "provided", "field", "is", "used", "in", "Footprint", "behavior", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Model/AssociationsAwareTrait.php#L334-L344
train
QoboLtd/cakephp-csv-migrations
src/Model/AssociationsAwareTrait.php
AssociationsAwareTrait.setByTypeFileField
private function setByTypeFileField(CsvField $field) : void { if (! in_array($field->getType(), ['files', 'images'])) { return; } $this->setAssociation( 'hasMany', static::generateAssociationName(FileUpload::FILE_STORAGE_TABLE_NAME, $field->getName()), [ 'className' => FileUpload::FILE_STORAGE_TABLE_NAME, 'foreignKey' => 'foreign_key', 'conditions' => ['model' => $this->getTable(), 'model_field' => $field->getName()] ] ); }
php
private function setByTypeFileField(CsvField $field) : void { if (! in_array($field->getType(), ['files', 'images'])) { return; } $this->setAssociation( 'hasMany', static::generateAssociationName(FileUpload::FILE_STORAGE_TABLE_NAME, $field->getName()), [ 'className' => FileUpload::FILE_STORAGE_TABLE_NAME, 'foreignKey' => 'foreign_key', 'conditions' => ['model' => $this->getTable(), 'model_field' => $field->getName()] ] ); }
[ "private", "function", "setByTypeFileField", "(", "CsvField", "$", "field", ")", ":", "void", "{", "if", "(", "!", "in_array", "(", "$", "field", "->", "getType", "(", ")", ",", "[", "'files'", ",", "'images'", "]", ")", ")", "{", "return", ";", "}", "$", "this", "->", "setAssociation", "(", "'hasMany'", ",", "static", "::", "generateAssociationName", "(", "FileUpload", "::", "FILE_STORAGE_TABLE_NAME", ",", "$", "field", "->", "getName", "(", ")", ")", ",", "[", "'className'", "=>", "FileUpload", "::", "FILE_STORAGE_TABLE_NAME", ",", "'foreignKey'", "=>", "'foreign_key'", ",", "'conditions'", "=>", "[", "'model'", "=>", "$", "this", "->", "getTable", "(", ")", ",", "'model_field'", "=>", "$", "field", "->", "getName", "(", ")", "]", "]", ")", ";", "}" ]
Set associations by file type field, for "module" type Modules. @param \CsvMigrations\FieldHandlers\CsvField $field CSV Field instance @return void
[ "Set", "associations", "by", "file", "type", "field", "for", "module", "type", "Modules", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Model/AssociationsAwareTrait.php#L352-L367
train
QoboLtd/cakephp-csv-migrations
src/Model/AssociationsAwareTrait.php
AssociationsAwareTrait.getModuleRelatedField
private function getModuleRelatedField(array $fields) : ?CsvField { foreach ($fields as $field) { if ($this->getTableName() === $field->getAssocCsvModule()) { return $field; } } return null; }
php
private function getModuleRelatedField(array $fields) : ?CsvField { foreach ($fields as $field) { if ($this->getTableName() === $field->getAssocCsvModule()) { return $field; } } return null; }
[ "private", "function", "getModuleRelatedField", "(", "array", "$", "fields", ")", ":", "?", "CsvField", "{", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "if", "(", "$", "this", "->", "getTableName", "(", ")", "===", "$", "field", "->", "getAssocCsvModule", "(", ")", ")", "{", "return", "$", "field", ";", "}", "}", "return", "null", ";", "}" ]
Retrieves current module related field, from "relation" type Modules. @param mixed[] $fields Module fields @return \CsvMigrations\FieldHandlers\CsvField|null
[ "Retrieves", "current", "module", "related", "field", "from", "relation", "type", "Modules", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Model/AssociationsAwareTrait.php#L385-L394
train
QoboLtd/cakephp-csv-migrations
src/Model/AssociationsAwareTrait.php
AssociationsAwareTrait.getModuleFields
private function getModuleFields(string $module) : array { $config = (new ModuleConfig(ConfigType::MIGRATION(), $module))->parse(); $config = json_encode($config); if (false === $config) { return []; } $fields = json_decode($config, true); foreach ($fields as $k => $v) { $fields[$k] = new CsvField($v); } return $fields; }
php
private function getModuleFields(string $module) : array { $config = (new ModuleConfig(ConfigType::MIGRATION(), $module))->parse(); $config = json_encode($config); if (false === $config) { return []; } $fields = json_decode($config, true); foreach ($fields as $k => $v) { $fields[$k] = new CsvField($v); } return $fields; }
[ "private", "function", "getModuleFields", "(", "string", "$", "module", ")", ":", "array", "{", "$", "config", "=", "(", "new", "ModuleConfig", "(", "ConfigType", "::", "MIGRATION", "(", ")", ",", "$", "module", ")", ")", "->", "parse", "(", ")", ";", "$", "config", "=", "json_encode", "(", "$", "config", ")", ";", "if", "(", "false", "===", "$", "config", ")", "{", "return", "[", "]", ";", "}", "$", "fields", "=", "json_decode", "(", "$", "config", ",", "true", ")", ";", "foreach", "(", "$", "fields", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "fields", "[", "$", "k", "]", "=", "new", "CsvField", "(", "$", "v", ")", ";", "}", "return", "$", "fields", ";", "}" ]
Retrieves specified Module fields. @param string $module Module name @return mixed[]
[ "Retrieves", "specified", "Module", "fields", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Model/AssociationsAwareTrait.php#L413-L428
train
QoboLtd/cakephp-csv-migrations
src/Model/AssociationsAwareTrait.php
AssociationsAwareTrait.generateAssociationName
public static function generateAssociationName(string $tableName, string $foreignKey) : string { list($plugin, $tableName) = pluginSplit($tableName); $plugin = false !== strpos($plugin, '/') ? substr($plugin, strpos($plugin, '/') + 1) : $plugin; return Inflector::camelize($foreignKey) . $plugin . $tableName; }
php
public static function generateAssociationName(string $tableName, string $foreignKey) : string { list($plugin, $tableName) = pluginSplit($tableName); $plugin = false !== strpos($plugin, '/') ? substr($plugin, strpos($plugin, '/') + 1) : $plugin; return Inflector::camelize($foreignKey) . $plugin . $tableName; }
[ "public", "static", "function", "generateAssociationName", "(", "string", "$", "tableName", ",", "string", "$", "foreignKey", ")", ":", "string", "{", "list", "(", "$", "plugin", ",", "$", "tableName", ")", "=", "pluginSplit", "(", "$", "tableName", ")", ";", "$", "plugin", "=", "false", "!==", "strpos", "(", "$", "plugin", ",", "'/'", ")", "?", "substr", "(", "$", "plugin", ",", "strpos", "(", "$", "plugin", ",", "'/'", ")", "+", "1", ")", ":", "$", "plugin", ";", "return", "Inflector", "::", "camelize", "(", "$", "foreignKey", ")", ".", "$", "plugin", ".", "$", "tableName", ";", "}" ]
Generates unique association name based on Table name and foreign key. For example, "Articles" migration.json includes a field "author_id,related(Authors)": AuthorIdArticles @param string $tableName Table name @param string $foreignKey Foreign key @return string
[ "Generates", "unique", "association", "name", "based", "on", "Table", "name", "and", "foreign", "key", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Model/AssociationsAwareTrait.php#L441-L447
train
QoboLtd/cakephp-csv-migrations
src/Utility/Validate/Check/MigrationCheck.php
MigrationCheck.checkFields
public function checkFields(string $module, array $fields = []): void { $seenFields = []; // Check each field one by one foreach ($fields as $field) { // Check for field duplicates if (in_array($field['name'], $seenFields)) { $this->errors[] = $module . " migration specifies field '" . $field['name'] . "' more than once"; continue; } $seenFields[] = $field['name']; $type = $field['type']; $limit = null; // Matches: // * date, time, string, and other simple types // * list(something), related(Others) and other simple limits // * related(Vendor/Plugin.Model) and other complex limits // * aggregated(CsvMigrations\\Aggregator\\MaxAggregator,TableName,field_name) aggregated configuration if (preg_match('/^(\w+?)\(([\w\/\.\,\\\]+?)\)$/', $field['type'], $matches)) { $type = $matches[1]; $limit = $matches[2]; } // Field type must be valid if (!Utility::isValidFieldType($type)) { $this->errors[] = $module . " migration specifies invalid type '" . $type . "' for field '" . $field['name'] . "'"; continue; } switch ($type) { case 'related': // Only check for simple modules, not the vendor/plugin ones if (preg_match('/^\w+$/', $limit) && !Utility::isValidModule($limit)) { $errors[] = $module . " migration relates to unknown module '$limit' in '" . $field['name'] . "' field"; } // Documents module can be used as `files(Documents)` for a container of the uploaded files, // or as `related(Documents)` as a regular module relationship. It's often easy to overlook // which one was desired. Failing on either one is incorrect, as both are valid. A // warning is needed instead for the `related(Documents)` case instead. // The only known legitimate case is in the Files, which is join table between Documents and FileStorage. if (('Documents' == $limit) && ('Files' != $module)) { $this->warnings[] = $module . " migration uses 'related' type for 'Documents' in '" . $field['name'] . "'. Maybe wanted 'files(Documents)'?"; } break; case 'list': case 'money': case 'metric': if (!Utility::isValidList($limit, $module)) { $this->errors[] = $module . " migration uses unknown or empty list '$limit' in '" . $field['name'] . "' field"; } break; } } }
php
public function checkFields(string $module, array $fields = []): void { $seenFields = []; // Check each field one by one foreach ($fields as $field) { // Check for field duplicates if (in_array($field['name'], $seenFields)) { $this->errors[] = $module . " migration specifies field '" . $field['name'] . "' more than once"; continue; } $seenFields[] = $field['name']; $type = $field['type']; $limit = null; // Matches: // * date, time, string, and other simple types // * list(something), related(Others) and other simple limits // * related(Vendor/Plugin.Model) and other complex limits // * aggregated(CsvMigrations\\Aggregator\\MaxAggregator,TableName,field_name) aggregated configuration if (preg_match('/^(\w+?)\(([\w\/\.\,\\\]+?)\)$/', $field['type'], $matches)) { $type = $matches[1]; $limit = $matches[2]; } // Field type must be valid if (!Utility::isValidFieldType($type)) { $this->errors[] = $module . " migration specifies invalid type '" . $type . "' for field '" . $field['name'] . "'"; continue; } switch ($type) { case 'related': // Only check for simple modules, not the vendor/plugin ones if (preg_match('/^\w+$/', $limit) && !Utility::isValidModule($limit)) { $errors[] = $module . " migration relates to unknown module '$limit' in '" . $field['name'] . "' field"; } // Documents module can be used as `files(Documents)` for a container of the uploaded files, // or as `related(Documents)` as a regular module relationship. It's often easy to overlook // which one was desired. Failing on either one is incorrect, as both are valid. A // warning is needed instead for the `related(Documents)` case instead. // The only known legitimate case is in the Files, which is join table between Documents and FileStorage. if (('Documents' == $limit) && ('Files' != $module)) { $this->warnings[] = $module . " migration uses 'related' type for 'Documents' in '" . $field['name'] . "'. Maybe wanted 'files(Documents)'?"; } break; case 'list': case 'money': case 'metric': if (!Utility::isValidList($limit, $module)) { $this->errors[] = $module . " migration uses unknown or empty list '$limit' in '" . $field['name'] . "' field"; } break; } } }
[ "public", "function", "checkFields", "(", "string", "$", "module", ",", "array", "$", "fields", "=", "[", "]", ")", ":", "void", "{", "$", "seenFields", "=", "[", "]", ";", "// Check each field one by one", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "// Check for field duplicates", "if", "(", "in_array", "(", "$", "field", "[", "'name'", "]", ",", "$", "seenFields", ")", ")", "{", "$", "this", "->", "errors", "[", "]", "=", "$", "module", ".", "\" migration specifies field '\"", ".", "$", "field", "[", "'name'", "]", ".", "\"' more than once\"", ";", "continue", ";", "}", "$", "seenFields", "[", "]", "=", "$", "field", "[", "'name'", "]", ";", "$", "type", "=", "$", "field", "[", "'type'", "]", ";", "$", "limit", "=", "null", ";", "// Matches:", "// * date, time, string, and other simple types", "// * list(something), related(Others) and other simple limits", "// * related(Vendor/Plugin.Model) and other complex limits", "// * aggregated(CsvMigrations\\\\Aggregator\\\\MaxAggregator,TableName,field_name) aggregated configuration", "if", "(", "preg_match", "(", "'/^(\\w+?)\\(([\\w\\/\\.\\,\\\\\\]+?)\\)$/'", ",", "$", "field", "[", "'type'", "]", ",", "$", "matches", ")", ")", "{", "$", "type", "=", "$", "matches", "[", "1", "]", ";", "$", "limit", "=", "$", "matches", "[", "2", "]", ";", "}", "// Field type must be valid", "if", "(", "!", "Utility", "::", "isValidFieldType", "(", "$", "type", ")", ")", "{", "$", "this", "->", "errors", "[", "]", "=", "$", "module", ".", "\" migration specifies invalid type '\"", ".", "$", "type", ".", "\"' for field '\"", ".", "$", "field", "[", "'name'", "]", ".", "\"'\"", ";", "continue", ";", "}", "switch", "(", "$", "type", ")", "{", "case", "'related'", ":", "// Only check for simple modules, not the vendor/plugin ones", "if", "(", "preg_match", "(", "'/^\\w+$/'", ",", "$", "limit", ")", "&&", "!", "Utility", "::", "isValidModule", "(", "$", "limit", ")", ")", "{", "$", "errors", "[", "]", "=", "$", "module", ".", "\" migration relates to unknown module '$limit' in '\"", ".", "$", "field", "[", "'name'", "]", ".", "\"' field\"", ";", "}", "// Documents module can be used as `files(Documents)` for a container of the uploaded files,", "// or as `related(Documents)` as a regular module relationship. It's often easy to overlook", "// which one was desired. Failing on either one is incorrect, as both are valid. A", "// warning is needed instead for the `related(Documents)` case instead.", "// The only known legitimate case is in the Files, which is join table between Documents and FileStorage.", "if", "(", "(", "'Documents'", "==", "$", "limit", ")", "&&", "(", "'Files'", "!=", "$", "module", ")", ")", "{", "$", "this", "->", "warnings", "[", "]", "=", "$", "module", ".", "\" migration uses 'related' type for 'Documents' in '\"", ".", "$", "field", "[", "'name'", "]", ".", "\"'. Maybe wanted 'files(Documents)'?\"", ";", "}", "break", ";", "case", "'list'", ":", "case", "'money'", ":", "case", "'metric'", ":", "if", "(", "!", "Utility", "::", "isValidList", "(", "$", "limit", ",", "$", "module", ")", ")", "{", "$", "this", "->", "errors", "[", "]", "=", "$", "module", ".", "\" migration uses unknown or empty list '$limit' in '\"", ".", "$", "field", "[", "'name'", "]", ".", "\"' field\"", ";", "}", "break", ";", "}", "}", "}" ]
Check fields and their types. @param string $module Module name. @param mixed[] $fields List of field definitions. @return void
[ "Check", "fields", "and", "their", "types", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/Validate/Check/MigrationCheck.php#L63-L119
train
QoboLtd/cakephp-csv-migrations
src/Aggregator/FirstAggregator.php
FirstAggregator.applyConditionsWithOrder
private function applyConditionsWithOrder(QueryInterface $query) : QueryInterface { $table = $this->getConfig()->getTable(); $aggregateField = $table->aliasField($this->getConfig()->getField()); $query->select($this->getConfig()->getDisplayField()) ->order([$aggregateField => 'ASC']); return $query; }
php
private function applyConditionsWithOrder(QueryInterface $query) : QueryInterface { $table = $this->getConfig()->getTable(); $aggregateField = $table->aliasField($this->getConfig()->getField()); $query->select($this->getConfig()->getDisplayField()) ->order([$aggregateField => 'ASC']); return $query; }
[ "private", "function", "applyConditionsWithOrder", "(", "QueryInterface", "$", "query", ")", ":", "QueryInterface", "{", "$", "table", "=", "$", "this", "->", "getConfig", "(", ")", "->", "getTable", "(", ")", ";", "$", "aggregateField", "=", "$", "table", "->", "aliasField", "(", "$", "this", "->", "getConfig", "(", ")", "->", "getField", "(", ")", ")", ";", "$", "query", "->", "select", "(", "$", "this", "->", "getConfig", "(", ")", "->", "getDisplayField", "(", ")", ")", "->", "order", "(", "[", "$", "aggregateField", "=>", "'ASC'", "]", ")", ";", "return", "$", "query", ";", "}" ]
If the aggregated field and display field are NOT the same we are using ordering on the aggregated field to retrieve the latest record. @param \Cake\Datasource\QueryInterface $query Query instance @return \Cake\Datasource\QueryInterface @link https://stackoverflow.com/a/19411219/2562232
[ "If", "the", "aggregated", "field", "and", "display", "field", "are", "NOT", "the", "same", "we", "are", "using", "ordering", "on", "the", "aggregated", "field", "to", "retrieve", "the", "latest", "record", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Aggregator/FirstAggregator.php#L36-L46
train
QoboLtd/cakephp-csv-migrations
src/Utility/ICal/IcEmail.php
IcEmail.sendCalendarEmail
public function sendCalendarEmail(string $to, string $subject, string $content, array $eventOptions, string $config = 'default') : array { // Get iCal calendar $calendar = $this->getEventCalendar($eventOptions); // FIXME: WTF happened to new lines??? $headers = "Content-Type: text/calendar; charset=utf-8"; $headers .= 'Content-Disposition: attachment; filename="event.ics"'; $emailer = new Email($config); $emailer->setTo($to) ->setHeaders([$headers]) ->setSubject($subject) ->addAttachments(['event.ics' => [ 'contentDisposition' => true, 'mimetype' => 'text/calendar', 'data' => $calendar->render() ]]); return $emailer->send($content); }
php
public function sendCalendarEmail(string $to, string $subject, string $content, array $eventOptions, string $config = 'default') : array { // Get iCal calendar $calendar = $this->getEventCalendar($eventOptions); // FIXME: WTF happened to new lines??? $headers = "Content-Type: text/calendar; charset=utf-8"; $headers .= 'Content-Disposition: attachment; filename="event.ics"'; $emailer = new Email($config); $emailer->setTo($to) ->setHeaders([$headers]) ->setSubject($subject) ->addAttachments(['event.ics' => [ 'contentDisposition' => true, 'mimetype' => 'text/calendar', 'data' => $calendar->render() ]]); return $emailer->send($content); }
[ "public", "function", "sendCalendarEmail", "(", "string", "$", "to", ",", "string", "$", "subject", ",", "string", "$", "content", ",", "array", "$", "eventOptions", ",", "string", "$", "config", "=", "'default'", ")", ":", "array", "{", "// Get iCal calendar", "$", "calendar", "=", "$", "this", "->", "getEventCalendar", "(", "$", "eventOptions", ")", ";", "// FIXME: WTF happened to new lines???", "$", "headers", "=", "\"Content-Type: text/calendar; charset=utf-8\"", ";", "$", "headers", ".=", "'Content-Disposition: attachment; filename=\"event.ics\"'", ";", "$", "emailer", "=", "new", "Email", "(", "$", "config", ")", ";", "$", "emailer", "->", "setTo", "(", "$", "to", ")", "->", "setHeaders", "(", "[", "$", "headers", "]", ")", "->", "setSubject", "(", "$", "subject", ")", "->", "addAttachments", "(", "[", "'event.ics'", "=>", "[", "'contentDisposition'", "=>", "true", ",", "'mimetype'", "=>", "'text/calendar'", ",", "'data'", "=>", "$", "calendar", "->", "render", "(", ")", "]", "]", ")", ";", "return", "$", "emailer", "->", "send", "(", "$", "content", ")", ";", "}" ]
Send email with calendar attachment @param string $to Destination email address @param string $subject Email subject @param string $content Email message content @param mixed[] $eventOptions Event options for calendar attachment @param string $config Email config to use ('default' if omitted) @return mixed[] Result of \Cake\Mailer\Email::send()
[ "Send", "email", "with", "calendar", "attachment" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/ICal/IcEmail.php#L70-L90
train
QoboLtd/cakephp-csv-migrations
src/Utility/ICal/IcEmail.php
IcEmail.getEventCalendar
protected function getEventCalendar(array $eventOptions) : Calendar { // New iCal event $event = (new IcEvent($eventOptions))->getEvent(); // New iCal calendar $calendar = new IcCalendar(); $calendar->addEvent($event); return $calendar->getCalendar(); }
php
protected function getEventCalendar(array $eventOptions) : Calendar { // New iCal event $event = (new IcEvent($eventOptions))->getEvent(); // New iCal calendar $calendar = new IcCalendar(); $calendar->addEvent($event); return $calendar->getCalendar(); }
[ "protected", "function", "getEventCalendar", "(", "array", "$", "eventOptions", ")", ":", "Calendar", "{", "// New iCal event", "$", "event", "=", "(", "new", "IcEvent", "(", "$", "eventOptions", ")", ")", "->", "getEvent", "(", ")", ";", "// New iCal calendar", "$", "calendar", "=", "new", "IcCalendar", "(", ")", ";", "$", "calendar", "->", "addEvent", "(", "$", "event", ")", ";", "return", "$", "calendar", "->", "getCalendar", "(", ")", ";", "}" ]
Get iCal calendar with given event @param mixed[] $eventOptions Options for event creation @return \Eluceo\iCal\Component\Calendar Whatever IcCalendar::getCalendar() returns
[ "Get", "iCal", "calendar", "with", "given", "event" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/ICal/IcEmail.php#L98-L108
train
QoboLtd/cakephp-csv-migrations
src/Utility/ICal/IcEmail.php
IcEmail.getDisplayValue
protected function getDisplayValue() : string { try { $displayField = $this->table->getDisplayField(); $displayValue = $this->entity->get($displayField); $factory = new FieldHandlerFactory(); $result = $factory->renderValue($this->table, $displayField, $displayValue, [ 'renderAs' => 'plain']); } catch (InvalidArgumentException $e) { $result = 'reminder'; } return $result; }
php
protected function getDisplayValue() : string { try { $displayField = $this->table->getDisplayField(); $displayValue = $this->entity->get($displayField); $factory = new FieldHandlerFactory(); $result = $factory->renderValue($this->table, $displayField, $displayValue, [ 'renderAs' => 'plain']); } catch (InvalidArgumentException $e) { $result = 'reminder'; } return $result; }
[ "protected", "function", "getDisplayValue", "(", ")", ":", "string", "{", "try", "{", "$", "displayField", "=", "$", "this", "->", "table", "->", "getDisplayField", "(", ")", ";", "$", "displayValue", "=", "$", "this", "->", "entity", "->", "get", "(", "$", "displayField", ")", ";", "$", "factory", "=", "new", "FieldHandlerFactory", "(", ")", ";", "$", "result", "=", "$", "factory", "->", "renderValue", "(", "$", "this", "->", "table", ",", "$", "displayField", ",", "$", "displayValue", ",", "[", "'renderAs'", "=>", "'plain'", "]", ")", ";", "}", "catch", "(", "InvalidArgumentException", "$", "e", ")", "{", "$", "result", "=", "'reminder'", ";", "}", "return", "$", "result", ";", "}" ]
Get plain value of the entity display field @return string
[ "Get", "plain", "value", "of", "the", "entity", "display", "field" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/ICal/IcEmail.php#L115-L128
train
QoboLtd/cakephp-csv-migrations
src/Utility/ICal/IcEmail.php
IcEmail.getEmailSubject
public function getEmailSubject() : string { $result = sprintf( '%s: %s', Inflector::singularize($this->table->getAlias()), $this->getDisplayValue() ); if (! $this->entity->isNew()) { $result = sprintf('(Updated) %s', $result); } return $result; }
php
public function getEmailSubject() : string { $result = sprintf( '%s: %s', Inflector::singularize($this->table->getAlias()), $this->getDisplayValue() ); if (! $this->entity->isNew()) { $result = sprintf('(Updated) %s', $result); } return $result; }
[ "public", "function", "getEmailSubject", "(", ")", ":", "string", "{", "$", "result", "=", "sprintf", "(", "'%s: %s'", ",", "Inflector", "::", "singularize", "(", "$", "this", "->", "table", "->", "getAlias", "(", ")", ")", ",", "$", "this", "->", "getDisplayValue", "(", ")", ")", ";", "if", "(", "!", "$", "this", "->", "entity", "->", "isNew", "(", ")", ")", "{", "$", "result", "=", "sprintf", "(", "'(Updated) %s'", ",", "$", "result", ")", ";", "}", "return", "$", "result", ";", "}" ]
Get email subject @return string
[ "Get", "email", "subject" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/ICal/IcEmail.php#L135-L148
train
QoboLtd/cakephp-csv-migrations
src/Utility/ICal/IcEmail.php
IcEmail.getEmailContent
public function getEmailContent() : string { $result = ''; $module = Inflector::singularize($this->table->getAlias()); $displayValue = $this->getDisplayValue(); $user = $this->getUserString(); $action = $this->entity->isNew() ? 'created' : 'updated'; // Example: Lead Foobar created by System $result = sprintf("%s %s %s by %s", $module, $displayValue, $action, $user); $changeLog = $this->getChangelog(); if (!empty($changeLog)) { $result .= "\n\n"; $result .= $changeLog; $result .= "\n"; } $result .= "\n\n"; $result .= "See more: "; $result .= $this->getEntityUrl(); return $result; }
php
public function getEmailContent() : string { $result = ''; $module = Inflector::singularize($this->table->getAlias()); $displayValue = $this->getDisplayValue(); $user = $this->getUserString(); $action = $this->entity->isNew() ? 'created' : 'updated'; // Example: Lead Foobar created by System $result = sprintf("%s %s %s by %s", $module, $displayValue, $action, $user); $changeLog = $this->getChangelog(); if (!empty($changeLog)) { $result .= "\n\n"; $result .= $changeLog; $result .= "\n"; } $result .= "\n\n"; $result .= "See more: "; $result .= $this->getEntityUrl(); return $result; }
[ "public", "function", "getEmailContent", "(", ")", ":", "string", "{", "$", "result", "=", "''", ";", "$", "module", "=", "Inflector", "::", "singularize", "(", "$", "this", "->", "table", "->", "getAlias", "(", ")", ")", ";", "$", "displayValue", "=", "$", "this", "->", "getDisplayValue", "(", ")", ";", "$", "user", "=", "$", "this", "->", "getUserString", "(", ")", ";", "$", "action", "=", "$", "this", "->", "entity", "->", "isNew", "(", ")", "?", "'created'", ":", "'updated'", ";", "// Example: Lead Foobar created by System", "$", "result", "=", "sprintf", "(", "\"%s %s %s by %s\"", ",", "$", "module", ",", "$", "displayValue", ",", "$", "action", ",", "$", "user", ")", ";", "$", "changeLog", "=", "$", "this", "->", "getChangelog", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "changeLog", ")", ")", "{", "$", "result", ".=", "\"\\n\\n\"", ";", "$", "result", ".=", "$", "changeLog", ";", "$", "result", ".=", "\"\\n\"", ";", "}", "$", "result", ".=", "\"\\n\\n\"", ";", "$", "result", ".=", "\"See more: \"", ";", "$", "result", ".=", "$", "this", "->", "getEntityUrl", "(", ")", ";", "return", "$", "result", ";", "}" ]
Get email content @return string
[ "Get", "email", "content" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/ICal/IcEmail.php#L155-L179
train
QoboLtd/cakephp-csv-migrations
src/Utility/ICal/IcEmail.php
IcEmail.getEntityUrl
public function getEntityUrl() : string { $result = Router::url( [ 'prefix' => false, 'controller' => $this->table->getTable(), 'action' => 'view', $this->entity->id ], true ); return $result; }
php
public function getEntityUrl() : string { $result = Router::url( [ 'prefix' => false, 'controller' => $this->table->getTable(), 'action' => 'view', $this->entity->id ], true ); return $result; }
[ "public", "function", "getEntityUrl", "(", ")", ":", "string", "{", "$", "result", "=", "Router", "::", "url", "(", "[", "'prefix'", "=>", "false", ",", "'controller'", "=>", "$", "this", "->", "table", "->", "getTable", "(", ")", ",", "'action'", "=>", "'view'", ",", "$", "this", "->", "entity", "->", "id", "]", ",", "true", ")", ";", "return", "$", "result", ";", "}" ]
Get full URL to the entity view @return string
[ "Get", "full", "URL", "to", "the", "entity", "view" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/ICal/IcEmail.php#L229-L242
train
QoboLtd/cakephp-csv-migrations
src/Utility/ICal/IcEmail.php
IcEmail.getUserString
protected function getUserString() : string { $result = 'System'; $userFields = [ 'name', 'username', 'email', ]; $currentUser = User::getCurrentUser(); if (empty($currentUser) || !is_array($currentUser)) { return $result; } foreach ($userFields as $field) { if (!empty($currentUser[$field])) { return $currentUser[$field]; } } return $result; }
php
protected function getUserString() : string { $result = 'System'; $userFields = [ 'name', 'username', 'email', ]; $currentUser = User::getCurrentUser(); if (empty($currentUser) || !is_array($currentUser)) { return $result; } foreach ($userFields as $field) { if (!empty($currentUser[$field])) { return $currentUser[$field]; } } return $result; }
[ "protected", "function", "getUserString", "(", ")", ":", "string", "{", "$", "result", "=", "'System'", ";", "$", "userFields", "=", "[", "'name'", ",", "'username'", ",", "'email'", ",", "]", ";", "$", "currentUser", "=", "User", "::", "getCurrentUser", "(", ")", ";", "if", "(", "empty", "(", "$", "currentUser", ")", "||", "!", "is_array", "(", "$", "currentUser", ")", ")", "{", "return", "$", "result", ";", "}", "foreach", "(", "$", "userFields", "as", "$", "field", ")", "{", "if", "(", "!", "empty", "(", "$", "currentUser", "[", "$", "field", "]", ")", ")", "{", "return", "$", "currentUser", "[", "$", "field", "]", ";", "}", "}", "return", "$", "result", ";", "}" ]
Get plain value of the current user @return string
[ "Get", "plain", "value", "of", "the", "current", "user" ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/ICal/IcEmail.php#L249-L271
train
QoboLtd/cakephp-csv-migrations
src/Utility/ICal/IcEmail.php
IcEmail.getChangelog
protected function getChangelog() : string { $result = ''; // plain changelog if entity is new if ($this->entity->isNew()) { return $result; } // get entity's modified fields $fields = $this->entity->extractOriginalChanged($this->entity->visibleProperties()); if (empty($fields)) { return $result; } // remove ignored fields foreach ($this->ignoredFields as $field) { if (array_key_exists($field, $fields)) { unset($fields[$field]); } } if (empty($fields)) { return $result; } foreach ($fields as $k => $v) { $result .= sprintf(static::CHANGELOG, Inflector::humanize($k), $v, $this->entity->{$k}); } return $result; }
php
protected function getChangelog() : string { $result = ''; // plain changelog if entity is new if ($this->entity->isNew()) { return $result; } // get entity's modified fields $fields = $this->entity->extractOriginalChanged($this->entity->visibleProperties()); if (empty($fields)) { return $result; } // remove ignored fields foreach ($this->ignoredFields as $field) { if (array_key_exists($field, $fields)) { unset($fields[$field]); } } if (empty($fields)) { return $result; } foreach ($fields as $k => $v) { $result .= sprintf(static::CHANGELOG, Inflector::humanize($k), $v, $this->entity->{$k}); } return $result; }
[ "protected", "function", "getChangelog", "(", ")", ":", "string", "{", "$", "result", "=", "''", ";", "// plain changelog if entity is new", "if", "(", "$", "this", "->", "entity", "->", "isNew", "(", ")", ")", "{", "return", "$", "result", ";", "}", "// get entity's modified fields", "$", "fields", "=", "$", "this", "->", "entity", "->", "extractOriginalChanged", "(", "$", "this", "->", "entity", "->", "visibleProperties", "(", ")", ")", ";", "if", "(", "empty", "(", "$", "fields", ")", ")", "{", "return", "$", "result", ";", "}", "// remove ignored fields", "foreach", "(", "$", "this", "->", "ignoredFields", "as", "$", "field", ")", "{", "if", "(", "array_key_exists", "(", "$", "field", ",", "$", "fields", ")", ")", "{", "unset", "(", "$", "fields", "[", "$", "field", "]", ")", ";", "}", "}", "if", "(", "empty", "(", "$", "fields", ")", ")", "{", "return", "$", "result", ";", "}", "foreach", "(", "$", "fields", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "result", ".=", "sprintf", "(", "static", "::", "CHANGELOG", ",", "Inflector", "::", "humanize", "(", "$", "k", ")", ",", "$", "v", ",", "$", "this", "->", "entity", "->", "{", "$", "k", "}", ")", ";", "}", "return", "$", "result", ";", "}" ]
Creates changelog report in string format. Example: Subject: changed from 'Foo' to 'Bar'. Content: changed from 'Hello world' to 'Hi there'. @return string
[ "Creates", "changelog", "report", "in", "string", "format", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Utility/ICal/IcEmail.php#L283-L315
train
QoboLtd/cakephp-csv-migrations
src/Model/Table/DblistItemsTable.php
DblistItemsTable.findTreeEntities
public function findTreeEntities(QueryInterface $query, array $options) : QueryInterface { $query = $query->where(['dblist_id' => $options['listId']]) ->order(['lft' => 'asc']); // workaround for getting spacer. $tree = $this->find('treeList', ['spacer' => '&nbsp;&nbsp;&nbsp;&nbsp;']) ->toArray(); foreach ($query->all() as $item) { $id = $item->get('id'); if (in_array($id, array_keys($tree))) { $item->set('spacer', $tree[$id]); } } return $query; }
php
public function findTreeEntities(QueryInterface $query, array $options) : QueryInterface { $query = $query->where(['dblist_id' => $options['listId']]) ->order(['lft' => 'asc']); // workaround for getting spacer. $tree = $this->find('treeList', ['spacer' => '&nbsp;&nbsp;&nbsp;&nbsp;']) ->toArray(); foreach ($query->all() as $item) { $id = $item->get('id'); if (in_array($id, array_keys($tree))) { $item->set('spacer', $tree[$id]); } } return $query; }
[ "public", "function", "findTreeEntities", "(", "QueryInterface", "$", "query", ",", "array", "$", "options", ")", ":", "QueryInterface", "{", "$", "query", "=", "$", "query", "->", "where", "(", "[", "'dblist_id'", "=>", "$", "options", "[", "'listId'", "]", "]", ")", "->", "order", "(", "[", "'lft'", "=>", "'asc'", "]", ")", ";", "// workaround for getting spacer.", "$", "tree", "=", "$", "this", "->", "find", "(", "'treeList'", ",", "[", "'spacer'", "=>", "'&nbsp;&nbsp;&nbsp;&nbsp;'", "]", ")", "->", "toArray", "(", ")", ";", "foreach", "(", "$", "query", "->", "all", "(", ")", "as", "$", "item", ")", "{", "$", "id", "=", "$", "item", "->", "get", "(", "'id'", ")", ";", "if", "(", "in_array", "(", "$", "id", ",", "array_keys", "(", "$", "tree", ")", ")", ")", "{", "$", "item", "->", "set", "(", "'spacer'", ",", "$", "tree", "[", "$", "id", "]", ")", ";", "}", "}", "return", "$", "query", ";", "}" ]
Return all the entities along with the spacer from the treeList. Options should be - listId: List Id to fetch its items. @see \Cake\ORM\Behavior\TreeBehavior::findTreeList @param \Cake\Datasource\QueryInterface $query The query @param mixed[] $options Query options @return \Cake\Datasource\QueryInterface
[ "Return", "all", "the", "entities", "along", "with", "the", "spacer", "from", "the", "treeList", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Model/Table/DblistItemsTable.php#L119-L136
train
QoboLtd/cakephp-csv-migrations
src/Shell/ImportShell.php
ImportShell.processImportFile
protected function processImportFile(Import $import) : void { $this->out('Processing import file ..'); $path = ImportUtility::getProcessedFile($import); if (file_exists($path)) { return; } // create processed file $writer = Writer::createFromPath($path, 'w+'); $reader = Reader::createFromPath($import->get('filename'), 'r'); $results = $reader->fetch(); foreach ($results as $row) { if (empty(array_filter($row))) { continue; } $writer->insertOne($row); } }
php
protected function processImportFile(Import $import) : void { $this->out('Processing import file ..'); $path = ImportUtility::getProcessedFile($import); if (file_exists($path)) { return; } // create processed file $writer = Writer::createFromPath($path, 'w+'); $reader = Reader::createFromPath($import->get('filename'), 'r'); $results = $reader->fetch(); foreach ($results as $row) { if (empty(array_filter($row))) { continue; } $writer->insertOne($row); } }
[ "protected", "function", "processImportFile", "(", "Import", "$", "import", ")", ":", "void", "{", "$", "this", "->", "out", "(", "'Processing import file ..'", ")", ";", "$", "path", "=", "ImportUtility", "::", "getProcessedFile", "(", "$", "import", ")", ";", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "return", ";", "}", "// create processed file", "$", "writer", "=", "Writer", "::", "createFromPath", "(", "$", "path", ",", "'w+'", ")", ";", "$", "reader", "=", "Reader", "::", "createFromPath", "(", "$", "import", "->", "get", "(", "'filename'", ")", ",", "'r'", ")", ";", "$", "results", "=", "$", "reader", "->", "fetch", "(", ")", ";", "foreach", "(", "$", "results", "as", "$", "row", ")", "{", "if", "(", "empty", "(", "array_filter", "(", "$", "row", ")", ")", ")", "{", "continue", ";", "}", "$", "writer", "->", "insertOne", "(", "$", "row", ")", ";", "}", "}" ]
Process import file. @param \CsvMigrations\Model\Entity\Import $import Import entity @return void
[ "Process", "import", "file", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Shell/ImportShell.php#L152-L174
train
QoboLtd/cakephp-csv-migrations
src/Shell/ImportShell.php
ImportShell._newImport
protected function _newImport(ImportsTable $table, Import $import, int $count) : bool { $data = [ 'status' => $table::STATUS_IN_PROGRESS, 'attempts' => 1, 'attempted_date' => Time::now() ]; $import = $table->patchEntity($import, $data); $table->save($import); $this->_run($import, $count); // mark import as completed $data = [ 'status' => $table::STATUS_COMPLETED ]; $import = $table->patchEntity($import, $data); return (bool)$table->save($import); }
php
protected function _newImport(ImportsTable $table, Import $import, int $count) : bool { $data = [ 'status' => $table::STATUS_IN_PROGRESS, 'attempts' => 1, 'attempted_date' => Time::now() ]; $import = $table->patchEntity($import, $data); $table->save($import); $this->_run($import, $count); // mark import as completed $data = [ 'status' => $table::STATUS_COMPLETED ]; $import = $table->patchEntity($import, $data); return (bool)$table->save($import); }
[ "protected", "function", "_newImport", "(", "ImportsTable", "$", "table", ",", "Import", "$", "import", ",", "int", "$", "count", ")", ":", "bool", "{", "$", "data", "=", "[", "'status'", "=>", "$", "table", "::", "STATUS_IN_PROGRESS", ",", "'attempts'", "=>", "1", ",", "'attempted_date'", "=>", "Time", "::", "now", "(", ")", "]", ";", "$", "import", "=", "$", "table", "->", "patchEntity", "(", "$", "import", ",", "$", "data", ")", ";", "$", "table", "->", "save", "(", "$", "import", ")", ";", "$", "this", "->", "_run", "(", "$", "import", ",", "$", "count", ")", ";", "// mark import as completed", "$", "data", "=", "[", "'status'", "=>", "$", "table", "::", "STATUS_COMPLETED", "]", ";", "$", "import", "=", "$", "table", "->", "patchEntity", "(", "$", "import", ",", "$", "data", ")", ";", "return", "(", "bool", ")", "$", "table", "->", "save", "(", "$", "import", ")", ";", "}" ]
New import. @param \CsvMigrations\Model\Table\ImportsTable $table Import table instance @param \CsvMigrations\Model\Entity\Import $import Import entity @param int $count Progress count @return bool
[ "New", "import", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Shell/ImportShell.php#L184-L205
train
QoboLtd/cakephp-csv-migrations
src/Shell/ImportShell.php
ImportShell._existingImport
protected function _existingImport(ImportsTable $table, Import $import, int $count) : bool { $result = false; $data = ['attempted_date' => Time::now()]; // max attempts rearched if ($import->get('attempts') >= (int)Configure::read('Importer.max_attempts')) { // set import as failed $data['status'] = $table::STATUS_FAIL; $import = $table->patchEntity($import, $data); return (bool)$table->save($import); } // increase attempts count $data['attempts'] = $import->get('attempts') + 1; $import = $table->patchEntity($import, $data); $table->save($import); $this->_run($import, $count); // mark import as completed $data['status'] = $table::STATUS_COMPLETED; $import = $table->patchEntity($import, $data); return (bool)$table->save($import); }
php
protected function _existingImport(ImportsTable $table, Import $import, int $count) : bool { $result = false; $data = ['attempted_date' => Time::now()]; // max attempts rearched if ($import->get('attempts') >= (int)Configure::read('Importer.max_attempts')) { // set import as failed $data['status'] = $table::STATUS_FAIL; $import = $table->patchEntity($import, $data); return (bool)$table->save($import); } // increase attempts count $data['attempts'] = $import->get('attempts') + 1; $import = $table->patchEntity($import, $data); $table->save($import); $this->_run($import, $count); // mark import as completed $data['status'] = $table::STATUS_COMPLETED; $import = $table->patchEntity($import, $data); return (bool)$table->save($import); }
[ "protected", "function", "_existingImport", "(", "ImportsTable", "$", "table", ",", "Import", "$", "import", ",", "int", "$", "count", ")", ":", "bool", "{", "$", "result", "=", "false", ";", "$", "data", "=", "[", "'attempted_date'", "=>", "Time", "::", "now", "(", ")", "]", ";", "// max attempts rearched", "if", "(", "$", "import", "->", "get", "(", "'attempts'", ")", ">=", "(", "int", ")", "Configure", "::", "read", "(", "'Importer.max_attempts'", ")", ")", "{", "// set import as failed", "$", "data", "[", "'status'", "]", "=", "$", "table", "::", "STATUS_FAIL", ";", "$", "import", "=", "$", "table", "->", "patchEntity", "(", "$", "import", ",", "$", "data", ")", ";", "return", "(", "bool", ")", "$", "table", "->", "save", "(", "$", "import", ")", ";", "}", "// increase attempts count", "$", "data", "[", "'attempts'", "]", "=", "$", "import", "->", "get", "(", "'attempts'", ")", "+", "1", ";", "$", "import", "=", "$", "table", "->", "patchEntity", "(", "$", "import", ",", "$", "data", ")", ";", "$", "table", "->", "save", "(", "$", "import", ")", ";", "$", "this", "->", "_run", "(", "$", "import", ",", "$", "count", ")", ";", "// mark import as completed", "$", "data", "[", "'status'", "]", "=", "$", "table", "::", "STATUS_COMPLETED", ";", "$", "import", "=", "$", "table", "->", "patchEntity", "(", "$", "import", ",", "$", "data", ")", ";", "return", "(", "bool", ")", "$", "table", "->", "save", "(", "$", "import", ")", ";", "}" ]
Existing import. @param \CsvMigrations\Model\Table\ImportsTable $table Import table instance @param \CsvMigrations\Model\Entity\Import $import Import entity @param int $count Progress count @return bool
[ "Existing", "import", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Shell/ImportShell.php#L215-L242
train
QoboLtd/cakephp-csv-migrations
src/Shell/ImportShell.php
ImportShell._run
protected function _run(Import $import, int $count) : void { // generate import results records $this->createImportResults($import, $count); $this->out('Importing records ..'); $progress = $this->helper('Progress'); Assert::isInstanceOf($progress, ProgressHelper::class); $progress->init(); $headers = ImportUtility::getUploadHeaders($import); $filename = ImportUtility::getProcessedFile($import); $reader = Reader::createFromPath($filename, 'r'); foreach ($reader as $index => $row) { // skip first csv row if (0 === $index) { continue; } // skip empty row if (empty($row)) { continue; } $this->_importResult($import, $headers, $index, $row); $progress->increment(100 / $count); $progress->draw(); } $this->out(null); }
php
protected function _run(Import $import, int $count) : void { // generate import results records $this->createImportResults($import, $count); $this->out('Importing records ..'); $progress = $this->helper('Progress'); Assert::isInstanceOf($progress, ProgressHelper::class); $progress->init(); $headers = ImportUtility::getUploadHeaders($import); $filename = ImportUtility::getProcessedFile($import); $reader = Reader::createFromPath($filename, 'r'); foreach ($reader as $index => $row) { // skip first csv row if (0 === $index) { continue; } // skip empty row if (empty($row)) { continue; } $this->_importResult($import, $headers, $index, $row); $progress->increment(100 / $count); $progress->draw(); } $this->out(null); }
[ "protected", "function", "_run", "(", "Import", "$", "import", ",", "int", "$", "count", ")", ":", "void", "{", "// generate import results records", "$", "this", "->", "createImportResults", "(", "$", "import", ",", "$", "count", ")", ";", "$", "this", "->", "out", "(", "'Importing records ..'", ")", ";", "$", "progress", "=", "$", "this", "->", "helper", "(", "'Progress'", ")", ";", "Assert", "::", "isInstanceOf", "(", "$", "progress", ",", "ProgressHelper", "::", "class", ")", ";", "$", "progress", "->", "init", "(", ")", ";", "$", "headers", "=", "ImportUtility", "::", "getUploadHeaders", "(", "$", "import", ")", ";", "$", "filename", "=", "ImportUtility", "::", "getProcessedFile", "(", "$", "import", ")", ";", "$", "reader", "=", "Reader", "::", "createFromPath", "(", "$", "filename", ",", "'r'", ")", ";", "foreach", "(", "$", "reader", "as", "$", "index", "=>", "$", "row", ")", "{", "// skip first csv row", "if", "(", "0", "===", "$", "index", ")", "{", "continue", ";", "}", "// skip empty row", "if", "(", "empty", "(", "$", "row", ")", ")", "{", "continue", ";", "}", "$", "this", "->", "_importResult", "(", "$", "import", ",", "$", "headers", ",", "$", "index", ",", "$", "row", ")", ";", "$", "progress", "->", "increment", "(", "100", "/", "$", "count", ")", ";", "$", "progress", "->", "draw", "(", ")", ";", "}", "$", "this", "->", "out", "(", "null", ")", ";", "}" ]
Run data import. @param \CsvMigrations\Model\Entity\Import $import Import entity @param int $count Progress count @return void
[ "Run", "data", "import", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Shell/ImportShell.php#L251-L282
train
QoboLtd/cakephp-csv-migrations
src/Shell/ImportShell.php
ImportShell.createImportResults
protected function createImportResults(Import $import, int $count) : void { $this->out('Preparing records ..'); $progress = $this->helper('Progress'); Assert::isInstanceOf($progress, ProgressHelper::class); $progress->init(); $table = TableRegistry::get('CsvMigrations.ImportResults'); Assert::isInstanceOf($table, ImportResultsTable::class); $query = $table->find('all')->where(['import_id' => $import->get('id')]); $queryCount = $query->count(); if ($queryCount >= $count) { return; } $data = [ 'import_id' => $import->get('id'), 'status' => $table::STATUS_PENDING, 'status_message' => $table::STATUS_PENDING_MESSAGE, 'model_name' => $import->get('model_name') ]; $i = $queryCount + 1; $progressCount = $count - $queryCount; // set $i = 1 to skip header row for ($i; $i <= $count; $i++) { $data['row_number'] = $i; $entity = $table->newEntity(); $entity = $table->patchEntity($entity, $data); $table->save($entity); $progress->increment(100 / $progressCount); $progress->draw(); } $this->out(null); }
php
protected function createImportResults(Import $import, int $count) : void { $this->out('Preparing records ..'); $progress = $this->helper('Progress'); Assert::isInstanceOf($progress, ProgressHelper::class); $progress->init(); $table = TableRegistry::get('CsvMigrations.ImportResults'); Assert::isInstanceOf($table, ImportResultsTable::class); $query = $table->find('all')->where(['import_id' => $import->get('id')]); $queryCount = $query->count(); if ($queryCount >= $count) { return; } $data = [ 'import_id' => $import->get('id'), 'status' => $table::STATUS_PENDING, 'status_message' => $table::STATUS_PENDING_MESSAGE, 'model_name' => $import->get('model_name') ]; $i = $queryCount + 1; $progressCount = $count - $queryCount; // set $i = 1 to skip header row for ($i; $i <= $count; $i++) { $data['row_number'] = $i; $entity = $table->newEntity(); $entity = $table->patchEntity($entity, $data); $table->save($entity); $progress->increment(100 / $progressCount); $progress->draw(); } $this->out(null); }
[ "protected", "function", "createImportResults", "(", "Import", "$", "import", ",", "int", "$", "count", ")", ":", "void", "{", "$", "this", "->", "out", "(", "'Preparing records ..'", ")", ";", "$", "progress", "=", "$", "this", "->", "helper", "(", "'Progress'", ")", ";", "Assert", "::", "isInstanceOf", "(", "$", "progress", ",", "ProgressHelper", "::", "class", ")", ";", "$", "progress", "->", "init", "(", ")", ";", "$", "table", "=", "TableRegistry", "::", "get", "(", "'CsvMigrations.ImportResults'", ")", ";", "Assert", "::", "isInstanceOf", "(", "$", "table", ",", "ImportResultsTable", "::", "class", ")", ";", "$", "query", "=", "$", "table", "->", "find", "(", "'all'", ")", "->", "where", "(", "[", "'import_id'", "=>", "$", "import", "->", "get", "(", "'id'", ")", "]", ")", ";", "$", "queryCount", "=", "$", "query", "->", "count", "(", ")", ";", "if", "(", "$", "queryCount", ">=", "$", "count", ")", "{", "return", ";", "}", "$", "data", "=", "[", "'import_id'", "=>", "$", "import", "->", "get", "(", "'id'", ")", ",", "'status'", "=>", "$", "table", "::", "STATUS_PENDING", ",", "'status_message'", "=>", "$", "table", "::", "STATUS_PENDING_MESSAGE", ",", "'model_name'", "=>", "$", "import", "->", "get", "(", "'model_name'", ")", "]", ";", "$", "i", "=", "$", "queryCount", "+", "1", ";", "$", "progressCount", "=", "$", "count", "-", "$", "queryCount", ";", "// set $i = 1 to skip header row", "for", "(", "$", "i", ";", "$", "i", "<=", "$", "count", ";", "$", "i", "++", ")", "{", "$", "data", "[", "'row_number'", "]", "=", "$", "i", ";", "$", "entity", "=", "$", "table", "->", "newEntity", "(", ")", ";", "$", "entity", "=", "$", "table", "->", "patchEntity", "(", "$", "entity", ",", "$", "data", ")", ";", "$", "table", "->", "save", "(", "$", "entity", ")", ";", "$", "progress", "->", "increment", "(", "100", "/", "$", "progressCount", ")", ";", "$", "progress", "->", "draw", "(", ")", ";", "}", "$", "this", "->", "out", "(", "null", ")", ";", "}" ]
Import results generator. @param \CsvMigrations\Model\Entity\Import $import Import entity @param int $count Progress count @return void
[ "Import", "results", "generator", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Shell/ImportShell.php#L291-L332
train
QoboLtd/cakephp-csv-migrations
src/Shell/ImportShell.php
ImportShell._importResult
protected function _importResult(Import $import, array $headers, int $rowNumber, array $data) : void { $importTable = TableRegistry::get('CsvMigrations.ImportResults'); Assert::isInstanceOf($importTable, ImportResultsTable::class); $query = $importTable->find('all') ->enableHydration(true) ->where(['import_id' => $import->get('id'), 'row_number' => $rowNumber]); try { $importResult = $query->firstOrFail(); } catch (RecordNotFoundException $e) { return; } Assert::isInstanceOf($importResult, ImportResult::class); // skip successful imports if ($importTable::STATUS_SUCCESS === $importResult->get('status')) { return; } $table = TableRegistry::get($importResult->get('model_name')); $data = $this->_prepareData($import, $headers, $data); $csvFields = FieldUtility::getCsv($table); $data = $this->_processData($table, $csvFields, $data); // skip empty processed data if (empty($data)) { $this->_importFail($importResult, ['Row has no data']); return; } try { $entity = $table->newEntity(); $entity = $table->patchEntity($entity, $data); $table->save($entity) ? $this->_importSuccess($importResult, $entity) : $this->_importFail($importResult, $entity->getErrors()); } catch (CakeException $e) { $this->_importFail($importResult, [$e->getMessage()]); } catch (PDOException $e) { $this->_importFail($importResult, [$e->getMessage()]); } }
php
protected function _importResult(Import $import, array $headers, int $rowNumber, array $data) : void { $importTable = TableRegistry::get('CsvMigrations.ImportResults'); Assert::isInstanceOf($importTable, ImportResultsTable::class); $query = $importTable->find('all') ->enableHydration(true) ->where(['import_id' => $import->get('id'), 'row_number' => $rowNumber]); try { $importResult = $query->firstOrFail(); } catch (RecordNotFoundException $e) { return; } Assert::isInstanceOf($importResult, ImportResult::class); // skip successful imports if ($importTable::STATUS_SUCCESS === $importResult->get('status')) { return; } $table = TableRegistry::get($importResult->get('model_name')); $data = $this->_prepareData($import, $headers, $data); $csvFields = FieldUtility::getCsv($table); $data = $this->_processData($table, $csvFields, $data); // skip empty processed data if (empty($data)) { $this->_importFail($importResult, ['Row has no data']); return; } try { $entity = $table->newEntity(); $entity = $table->patchEntity($entity, $data); $table->save($entity) ? $this->_importSuccess($importResult, $entity) : $this->_importFail($importResult, $entity->getErrors()); } catch (CakeException $e) { $this->_importFail($importResult, [$e->getMessage()]); } catch (PDOException $e) { $this->_importFail($importResult, [$e->getMessage()]); } }
[ "protected", "function", "_importResult", "(", "Import", "$", "import", ",", "array", "$", "headers", ",", "int", "$", "rowNumber", ",", "array", "$", "data", ")", ":", "void", "{", "$", "importTable", "=", "TableRegistry", "::", "get", "(", "'CsvMigrations.ImportResults'", ")", ";", "Assert", "::", "isInstanceOf", "(", "$", "importTable", ",", "ImportResultsTable", "::", "class", ")", ";", "$", "query", "=", "$", "importTable", "->", "find", "(", "'all'", ")", "->", "enableHydration", "(", "true", ")", "->", "where", "(", "[", "'import_id'", "=>", "$", "import", "->", "get", "(", "'id'", ")", ",", "'row_number'", "=>", "$", "rowNumber", "]", ")", ";", "try", "{", "$", "importResult", "=", "$", "query", "->", "firstOrFail", "(", ")", ";", "}", "catch", "(", "RecordNotFoundException", "$", "e", ")", "{", "return", ";", "}", "Assert", "::", "isInstanceOf", "(", "$", "importResult", ",", "ImportResult", "::", "class", ")", ";", "// skip successful imports", "if", "(", "$", "importTable", "::", "STATUS_SUCCESS", "===", "$", "importResult", "->", "get", "(", "'status'", ")", ")", "{", "return", ";", "}", "$", "table", "=", "TableRegistry", "::", "get", "(", "$", "importResult", "->", "get", "(", "'model_name'", ")", ")", ";", "$", "data", "=", "$", "this", "->", "_prepareData", "(", "$", "import", ",", "$", "headers", ",", "$", "data", ")", ";", "$", "csvFields", "=", "FieldUtility", "::", "getCsv", "(", "$", "table", ")", ";", "$", "data", "=", "$", "this", "->", "_processData", "(", "$", "table", ",", "$", "csvFields", ",", "$", "data", ")", ";", "// skip empty processed data", "if", "(", "empty", "(", "$", "data", ")", ")", "{", "$", "this", "->", "_importFail", "(", "$", "importResult", ",", "[", "'Row has no data'", "]", ")", ";", "return", ";", "}", "try", "{", "$", "entity", "=", "$", "table", "->", "newEntity", "(", ")", ";", "$", "entity", "=", "$", "table", "->", "patchEntity", "(", "$", "entity", ",", "$", "data", ")", ";", "$", "table", "->", "save", "(", "$", "entity", ")", "?", "$", "this", "->", "_importSuccess", "(", "$", "importResult", ",", "$", "entity", ")", ":", "$", "this", "->", "_importFail", "(", "$", "importResult", ",", "$", "entity", "->", "getErrors", "(", ")", ")", ";", "}", "catch", "(", "CakeException", "$", "e", ")", "{", "$", "this", "->", "_importFail", "(", "$", "importResult", ",", "[", "$", "e", "->", "getMessage", "(", ")", "]", ")", ";", "}", "catch", "(", "PDOException", "$", "e", ")", "{", "$", "this", "->", "_importFail", "(", "$", "importResult", ",", "[", "$", "e", "->", "getMessage", "(", ")", "]", ")", ";", "}", "}" ]
Import row. @param \CsvMigrations\Model\Entity\Import $import Import entity @param string[] $headers Upload file headers @param int $rowNumber Current row number @param mixed[] $data Row data @return void
[ "Import", "row", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Shell/ImportShell.php#L343-L390
train
QoboLtd/cakephp-csv-migrations
src/Shell/ImportShell.php
ImportShell._prepareData
protected function _prepareData(Import $import, array $headers, array $data) : array { $result = []; $options = $import->get('options'); $flipped = array_flip($headers); foreach ($options['fields'] as $field => $params) { if (empty($params['column']) && empty($params['default'])) { continue; } if (array_key_exists($params['column'], $flipped)) { $value = $data[$flipped[$params['column']]]; if (!empty($value)) { $result[$field] = $value; continue; } } if (!empty($params['default'])) { $result[$field] = $params['default']; } } return $result; }
php
protected function _prepareData(Import $import, array $headers, array $data) : array { $result = []; $options = $import->get('options'); $flipped = array_flip($headers); foreach ($options['fields'] as $field => $params) { if (empty($params['column']) && empty($params['default'])) { continue; } if (array_key_exists($params['column'], $flipped)) { $value = $data[$flipped[$params['column']]]; if (!empty($value)) { $result[$field] = $value; continue; } } if (!empty($params['default'])) { $result[$field] = $params['default']; } } return $result; }
[ "protected", "function", "_prepareData", "(", "Import", "$", "import", ",", "array", "$", "headers", ",", "array", "$", "data", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "$", "options", "=", "$", "import", "->", "get", "(", "'options'", ")", ";", "$", "flipped", "=", "array_flip", "(", "$", "headers", ")", ";", "foreach", "(", "$", "options", "[", "'fields'", "]", "as", "$", "field", "=>", "$", "params", ")", "{", "if", "(", "empty", "(", "$", "params", "[", "'column'", "]", ")", "&&", "empty", "(", "$", "params", "[", "'default'", "]", ")", ")", "{", "continue", ";", "}", "if", "(", "array_key_exists", "(", "$", "params", "[", "'column'", "]", ",", "$", "flipped", ")", ")", "{", "$", "value", "=", "$", "data", "[", "$", "flipped", "[", "$", "params", "[", "'column'", "]", "]", "]", ";", "if", "(", "!", "empty", "(", "$", "value", ")", ")", "{", "$", "result", "[", "$", "field", "]", "=", "$", "value", ";", "continue", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "params", "[", "'default'", "]", ")", ")", "{", "$", "result", "[", "$", "field", "]", "=", "$", "params", "[", "'default'", "]", ";", "}", "}", "return", "$", "result", ";", "}" ]
Prepare row data. @param \CsvMigrations\Model\Entity\Import $import Import entity @param string[] $headers Upload file headers @param mixed[] $data Row data @return mixed[]
[ "Prepare", "row", "data", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Shell/ImportShell.php#L400-L427
train
QoboLtd/cakephp-csv-migrations
src/Shell/ImportShell.php
ImportShell._processData
protected function _processData(Table $table, array $csvFields, array $data) : array { $schema = $table->getSchema(); foreach ($data as $field => $value) { if (!empty($csvFields) && in_array($field, array_keys($csvFields))) { switch ($csvFields[$field]->getType()) { case 'related': $data[$field] = $this->_findRelatedRecord($table, $field, $value); break; case 'list': $data[$field] = $this->_findListValue($table, $csvFields[$field]->getLimit(), $value); break; case 'country': $data[$field] = $this->_findListValue($table, 'countries', $value); break; } } else { if ('uuid' === $schema->columnType($field)) { $data[$field] = $this->_findRelatedRecord($table, $field, $value); } else { $data[$field] = $value; } } } return $data; }
php
protected function _processData(Table $table, array $csvFields, array $data) : array { $schema = $table->getSchema(); foreach ($data as $field => $value) { if (!empty($csvFields) && in_array($field, array_keys($csvFields))) { switch ($csvFields[$field]->getType()) { case 'related': $data[$field] = $this->_findRelatedRecord($table, $field, $value); break; case 'list': $data[$field] = $this->_findListValue($table, $csvFields[$field]->getLimit(), $value); break; case 'country': $data[$field] = $this->_findListValue($table, 'countries', $value); break; } } else { if ('uuid' === $schema->columnType($field)) { $data[$field] = $this->_findRelatedRecord($table, $field, $value); } else { $data[$field] = $value; } } } return $data; }
[ "protected", "function", "_processData", "(", "Table", "$", "table", ",", "array", "$", "csvFields", ",", "array", "$", "data", ")", ":", "array", "{", "$", "schema", "=", "$", "table", "->", "getSchema", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "field", "=>", "$", "value", ")", "{", "if", "(", "!", "empty", "(", "$", "csvFields", ")", "&&", "in_array", "(", "$", "field", ",", "array_keys", "(", "$", "csvFields", ")", ")", ")", "{", "switch", "(", "$", "csvFields", "[", "$", "field", "]", "->", "getType", "(", ")", ")", "{", "case", "'related'", ":", "$", "data", "[", "$", "field", "]", "=", "$", "this", "->", "_findRelatedRecord", "(", "$", "table", ",", "$", "field", ",", "$", "value", ")", ";", "break", ";", "case", "'list'", ":", "$", "data", "[", "$", "field", "]", "=", "$", "this", "->", "_findListValue", "(", "$", "table", ",", "$", "csvFields", "[", "$", "field", "]", "->", "getLimit", "(", ")", ",", "$", "value", ")", ";", "break", ";", "case", "'country'", ":", "$", "data", "[", "$", "field", "]", "=", "$", "this", "->", "_findListValue", "(", "$", "table", ",", "'countries'", ",", "$", "value", ")", ";", "break", ";", "}", "}", "else", "{", "if", "(", "'uuid'", "===", "$", "schema", "->", "columnType", "(", "$", "field", ")", ")", "{", "$", "data", "[", "$", "field", "]", "=", "$", "this", "->", "_findRelatedRecord", "(", "$", "table", ",", "$", "field", ",", "$", "value", ")", ";", "}", "else", "{", "$", "data", "[", "$", "field", "]", "=", "$", "value", ";", "}", "}", "}", "return", "$", "data", ";", "}" ]
Process row data. @param \Cake\ORM\Table $table Table instance @param mixed[] $csvFields Table csv fields @param mixed[] $data Entity data @return mixed[]
[ "Process", "row", "data", "." ]
49300070cdd9b829670a3c40f747c535c8e539b3
https://github.com/QoboLtd/cakephp-csv-migrations/blob/49300070cdd9b829670a3c40f747c535c8e539b3/src/Shell/ImportShell.php#L437-L463
train