repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
nyeholt/silverstripe-external-content
code/transform/QueuedExternalContentImporter.php
QueuedExternalContentImporter.process
public function process() { $remainingChildren = $this->remainingChildren; if (!count($remainingChildren)) { $this->isComplete = true; return; } $this->currentStep++; // lets process our first item $pair = array_shift($remainingChildren); $sourceObject = ExternalContent::getDataObjectFor($pair->sourceID); if (!$sourceObject) { $this->addMessage("Missing source object for " . $pair->sourceID, 'WARNING'); $this->remainingChildren = $remainingChildren; return; } $targetObject = DataObject::get_by_id($pair->targetType, $pair->targetID); if (!$targetObject) { $this->addMessage("Missing target object for $pair->targetType $pair->sourceID", 'WARNING'); $this->remainingChildren = $remainingChildren; return; } // lets do a single import first, then check the children and append them $pageType = $this->getExternalType($sourceObject); if (isset($this->contentTransforms[$pageType])) { $transformer = $this->contentTransforms[$pageType]; $result = $transformer->transform($sourceObject, $targetObject, $this->duplicateStrategy); // if there's more, then transform them if ($this->includeChildren && $result && $result->children && count($result->children)) { foreach ($result->children as $child) { $remainingChildren[] = new EC_SourceTarget($child->ID, $result->page->ID, $result->page->ClassName); $this->totalSteps++; } } } $this->remainingChildren = $remainingChildren; if (!count($remainingChildren)) { $this->isComplete = true; return; } }
php
public function process() { $remainingChildren = $this->remainingChildren; if (!count($remainingChildren)) { $this->isComplete = true; return; } $this->currentStep++; // lets process our first item $pair = array_shift($remainingChildren); $sourceObject = ExternalContent::getDataObjectFor($pair->sourceID); if (!$sourceObject) { $this->addMessage("Missing source object for " . $pair->sourceID, 'WARNING'); $this->remainingChildren = $remainingChildren; return; } $targetObject = DataObject::get_by_id($pair->targetType, $pair->targetID); if (!$targetObject) { $this->addMessage("Missing target object for $pair->targetType $pair->sourceID", 'WARNING'); $this->remainingChildren = $remainingChildren; return; } // lets do a single import first, then check the children and append them $pageType = $this->getExternalType($sourceObject); if (isset($this->contentTransforms[$pageType])) { $transformer = $this->contentTransforms[$pageType]; $result = $transformer->transform($sourceObject, $targetObject, $this->duplicateStrategy); // if there's more, then transform them if ($this->includeChildren && $result && $result->children && count($result->children)) { foreach ($result->children as $child) { $remainingChildren[] = new EC_SourceTarget($child->ID, $result->page->ID, $result->page->ClassName); $this->totalSteps++; } } } $this->remainingChildren = $remainingChildren; if (!count($remainingChildren)) { $this->isComplete = true; return; } }
[ "public", "function", "process", "(", ")", "{", "$", "remainingChildren", "=", "$", "this", "->", "remainingChildren", ";", "if", "(", "!", "count", "(", "$", "remainingChildren", ")", ")", "{", "$", "this", "->", "isComplete", "=", "true", ";", "return", ";", "}", "$", "this", "->", "currentStep", "++", ";", "// lets process our first item", "$", "pair", "=", "array_shift", "(", "$", "remainingChildren", ")", ";", "$", "sourceObject", "=", "ExternalContent", "::", "getDataObjectFor", "(", "$", "pair", "->", "sourceID", ")", ";", "if", "(", "!", "$", "sourceObject", ")", "{", "$", "this", "->", "addMessage", "(", "\"Missing source object for \"", ".", "$", "pair", "->", "sourceID", ",", "'WARNING'", ")", ";", "$", "this", "->", "remainingChildren", "=", "$", "remainingChildren", ";", "return", ";", "}", "$", "targetObject", "=", "DataObject", "::", "get_by_id", "(", "$", "pair", "->", "targetType", ",", "$", "pair", "->", "targetID", ")", ";", "if", "(", "!", "$", "targetObject", ")", "{", "$", "this", "->", "addMessage", "(", "\"Missing target object for $pair->targetType $pair->sourceID\"", ",", "'WARNING'", ")", ";", "$", "this", "->", "remainingChildren", "=", "$", "remainingChildren", ";", "return", ";", "}", "// lets do a single import first, then check the children and append them", "$", "pageType", "=", "$", "this", "->", "getExternalType", "(", "$", "sourceObject", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "contentTransforms", "[", "$", "pageType", "]", ")", ")", "{", "$", "transformer", "=", "$", "this", "->", "contentTransforms", "[", "$", "pageType", "]", ";", "$", "result", "=", "$", "transformer", "->", "transform", "(", "$", "sourceObject", ",", "$", "targetObject", ",", "$", "this", "->", "duplicateStrategy", ")", ";", "// if there's more, then transform them", "if", "(", "$", "this", "->", "includeChildren", "&&", "$", "result", "&&", "$", "result", "->", "children", "&&", "count", "(", "$", "result", "->", "children", ")", ")", "{", "foreach", "(", "$", "result", "->", "children", "as", "$", "child", ")", "{", "$", "remainingChildren", "[", "]", "=", "new", "EC_SourceTarget", "(", "$", "child", "->", "ID", ",", "$", "result", "->", "page", "->", "ID", ",", "$", "result", "->", "page", "->", "ClassName", ")", ";", "$", "this", "->", "totalSteps", "++", ";", "}", "}", "}", "$", "this", "->", "remainingChildren", "=", "$", "remainingChildren", ";", "if", "(", "!", "count", "(", "$", "remainingChildren", ")", ")", "{", "$", "this", "->", "isComplete", "=", "true", ";", "return", ";", "}", "}" ]
Lets process a single node, and collect its children
[ "Lets", "process", "a", "single", "node", "and", "collect", "its", "children" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/code/transform/QueuedExternalContentImporter.php#L115-L163
SachaMorard/phalcon-console-migration
Library/Phalcon/Migrations.php
Migrations.run
public function run($version) { $versions = array(); $iterator = new \DirectoryIterator($this->migrationsDir); foreach ($iterator as $fileinfo) { if (!$fileinfo->isDir()) { $versions[] = str_replace('.php', '', $fileinfo->getFilename()); } } /** @var Mysql $connection */ $connection = $this->getDI()->get($this->migrationAdapter); try { $lastMig = $connection->fetchOne('SELECT * FROM migration ORDER BY id DESC', \PDO::FETCH_ASSOC); } catch (\PDOException $ex) { if ($this->migrationAdapter === 'dbMysql') { $connection->query('CREATE TABLE migration (`id` INT NOT NULL AUTO_INCREMENT,`version` VARCHAR(45) NOT NULL,`run_at` DATETIME NOT NULL, PRIMARY KEY (`id`))'); } else { $connection->query('CREATE TABLE "public"."migration" ("id" SERIAL NOT NULL,"version" CHARACTER VARYING(45),"run_at" TIMESTAMP,PRIMARY KEY ("id"));'); } } if (isset($lastMig)) { $fromVersion = $lastMig['version']; } else { $fromVersion = '0'; } $toZero = false; if (count($versions) == 0) { throw new CommandsException('Migrations were not found at ' . $this->migrationsDir); } else { if ($version === null) { $version = Version::maximum($versions); } else { if ($version == '0') { $toZero = true; $versionsSorted = Version::sortAsc($versions); $version = $versionsSorted[0]; } elseif ($version === 'up') { $versionsSorted = Version::sortAsc($versions); foreach ($versionsSorted as $k => $v) { if ($v === $fromVersion) { $currentK = $k; } } $version = isset($versionsSorted[$currentK + 1]) ? $versionsSorted[$currentK + 1] : Version::maximum($versions); } elseif ($version === 'down') { $versionsSorted = Version::sortAsc($versions); foreach ($versionsSorted as $k => $v) { if ($v === $fromVersion) { $currentK = $k; } } $version = isset($versionsSorted[$currentK - 1]) ? $versionsSorted[$currentK - 1] : $versionsSorted[0]; } $migrationPath = $this->migrationsDir . '/' . $version . '.php'; if (!file_exists($migrationPath)) { throw new CommandsException('Migration class was not found ' . $migrationPath); } } } $versionsBetween = Version::between($fromVersion, $version, $versions); if ($toZero === true) { $theTwoFirstMigrations = []; $theTwoFirstMigrations[] = $versionsBetween[count($versionsBetween) - 1]; $versionsBetween = $theTwoFirstMigrations; } try { $direction = 'up'; foreach ($versionsBetween as $k => $v) { $migrationPath = $this->migrationsDir . '/' . $v['version'] . '.php'; $this->_migrateFile((string)$v['version'], $migrationPath, $v['direction']); if ($v['direction'] === 'down' && $k === 0) { $direction = $v['direction']; continue; } else { $connection->insert("migration", array((string)$v['version'], date('Y-m-d H:i:s')), array("version", "run_at")); } $direction = $v['direction']; } if (count($versionsBetween) > 0 && $direction === 'down') { $connection->insert("migration", array((string)$version, date('Y-m-d H:i:s')), array("version", "run_at")); } elseif (count($versionsBetween) === 0) { print Color::colorize('No migration to run' . PHP_EOL . PHP_EOL, Color::FG_GREEN); } exit(0); } catch (\Throwable $e){ print PHP_EOL . Color::error($e->getMessage()) . PHP_EOL; exit(1); } }
php
public function run($version) { $versions = array(); $iterator = new \DirectoryIterator($this->migrationsDir); foreach ($iterator as $fileinfo) { if (!$fileinfo->isDir()) { $versions[] = str_replace('.php', '', $fileinfo->getFilename()); } } /** @var Mysql $connection */ $connection = $this->getDI()->get($this->migrationAdapter); try { $lastMig = $connection->fetchOne('SELECT * FROM migration ORDER BY id DESC', \PDO::FETCH_ASSOC); } catch (\PDOException $ex) { if ($this->migrationAdapter === 'dbMysql') { $connection->query('CREATE TABLE migration (`id` INT NOT NULL AUTO_INCREMENT,`version` VARCHAR(45) NOT NULL,`run_at` DATETIME NOT NULL, PRIMARY KEY (`id`))'); } else { $connection->query('CREATE TABLE "public"."migration" ("id" SERIAL NOT NULL,"version" CHARACTER VARYING(45),"run_at" TIMESTAMP,PRIMARY KEY ("id"));'); } } if (isset($lastMig)) { $fromVersion = $lastMig['version']; } else { $fromVersion = '0'; } $toZero = false; if (count($versions) == 0) { throw new CommandsException('Migrations were not found at ' . $this->migrationsDir); } else { if ($version === null) { $version = Version::maximum($versions); } else { if ($version == '0') { $toZero = true; $versionsSorted = Version::sortAsc($versions); $version = $versionsSorted[0]; } elseif ($version === 'up') { $versionsSorted = Version::sortAsc($versions); foreach ($versionsSorted as $k => $v) { if ($v === $fromVersion) { $currentK = $k; } } $version = isset($versionsSorted[$currentK + 1]) ? $versionsSorted[$currentK + 1] : Version::maximum($versions); } elseif ($version === 'down') { $versionsSorted = Version::sortAsc($versions); foreach ($versionsSorted as $k => $v) { if ($v === $fromVersion) { $currentK = $k; } } $version = isset($versionsSorted[$currentK - 1]) ? $versionsSorted[$currentK - 1] : $versionsSorted[0]; } $migrationPath = $this->migrationsDir . '/' . $version . '.php'; if (!file_exists($migrationPath)) { throw new CommandsException('Migration class was not found ' . $migrationPath); } } } $versionsBetween = Version::between($fromVersion, $version, $versions); if ($toZero === true) { $theTwoFirstMigrations = []; $theTwoFirstMigrations[] = $versionsBetween[count($versionsBetween) - 1]; $versionsBetween = $theTwoFirstMigrations; } try { $direction = 'up'; foreach ($versionsBetween as $k => $v) { $migrationPath = $this->migrationsDir . '/' . $v['version'] . '.php'; $this->_migrateFile((string)$v['version'], $migrationPath, $v['direction']); if ($v['direction'] === 'down' && $k === 0) { $direction = $v['direction']; continue; } else { $connection->insert("migration", array((string)$v['version'], date('Y-m-d H:i:s')), array("version", "run_at")); } $direction = $v['direction']; } if (count($versionsBetween) > 0 && $direction === 'down') { $connection->insert("migration", array((string)$version, date('Y-m-d H:i:s')), array("version", "run_at")); } elseif (count($versionsBetween) === 0) { print Color::colorize('No migration to run' . PHP_EOL . PHP_EOL, Color::FG_GREEN); } exit(0); } catch (\Throwable $e){ print PHP_EOL . Color::error($e->getMessage()) . PHP_EOL; exit(1); } }
[ "public", "function", "run", "(", "$", "version", ")", "{", "$", "versions", "=", "array", "(", ")", ";", "$", "iterator", "=", "new", "\\", "DirectoryIterator", "(", "$", "this", "->", "migrationsDir", ")", ";", "foreach", "(", "$", "iterator", "as", "$", "fileinfo", ")", "{", "if", "(", "!", "$", "fileinfo", "->", "isDir", "(", ")", ")", "{", "$", "versions", "[", "]", "=", "str_replace", "(", "'.php'", ",", "''", ",", "$", "fileinfo", "->", "getFilename", "(", ")", ")", ";", "}", "}", "/** @var Mysql $connection */", "$", "connection", "=", "$", "this", "->", "getDI", "(", ")", "->", "get", "(", "$", "this", "->", "migrationAdapter", ")", ";", "try", "{", "$", "lastMig", "=", "$", "connection", "->", "fetchOne", "(", "'SELECT * FROM migration ORDER BY id DESC'", ",", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "}", "catch", "(", "\\", "PDOException", "$", "ex", ")", "{", "if", "(", "$", "this", "->", "migrationAdapter", "===", "'dbMysql'", ")", "{", "$", "connection", "->", "query", "(", "'CREATE TABLE migration (`id` INT NOT NULL AUTO_INCREMENT,`version` VARCHAR(45) NOT NULL,`run_at` DATETIME NOT NULL, PRIMARY KEY (`id`))'", ")", ";", "}", "else", "{", "$", "connection", "->", "query", "(", "'CREATE TABLE \"public\".\"migration\" (\"id\" SERIAL NOT NULL,\"version\" CHARACTER VARYING(45),\"run_at\" TIMESTAMP,PRIMARY KEY (\"id\"));'", ")", ";", "}", "}", "if", "(", "isset", "(", "$", "lastMig", ")", ")", "{", "$", "fromVersion", "=", "$", "lastMig", "[", "'version'", "]", ";", "}", "else", "{", "$", "fromVersion", "=", "'0'", ";", "}", "$", "toZero", "=", "false", ";", "if", "(", "count", "(", "$", "versions", ")", "==", "0", ")", "{", "throw", "new", "CommandsException", "(", "'Migrations were not found at '", ".", "$", "this", "->", "migrationsDir", ")", ";", "}", "else", "{", "if", "(", "$", "version", "===", "null", ")", "{", "$", "version", "=", "Version", "::", "maximum", "(", "$", "versions", ")", ";", "}", "else", "{", "if", "(", "$", "version", "==", "'0'", ")", "{", "$", "toZero", "=", "true", ";", "$", "versionsSorted", "=", "Version", "::", "sortAsc", "(", "$", "versions", ")", ";", "$", "version", "=", "$", "versionsSorted", "[", "0", "]", ";", "}", "elseif", "(", "$", "version", "===", "'up'", ")", "{", "$", "versionsSorted", "=", "Version", "::", "sortAsc", "(", "$", "versions", ")", ";", "foreach", "(", "$", "versionsSorted", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "$", "v", "===", "$", "fromVersion", ")", "{", "$", "currentK", "=", "$", "k", ";", "}", "}", "$", "version", "=", "isset", "(", "$", "versionsSorted", "[", "$", "currentK", "+", "1", "]", ")", "?", "$", "versionsSorted", "[", "$", "currentK", "+", "1", "]", ":", "Version", "::", "maximum", "(", "$", "versions", ")", ";", "}", "elseif", "(", "$", "version", "===", "'down'", ")", "{", "$", "versionsSorted", "=", "Version", "::", "sortAsc", "(", "$", "versions", ")", ";", "foreach", "(", "$", "versionsSorted", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "$", "v", "===", "$", "fromVersion", ")", "{", "$", "currentK", "=", "$", "k", ";", "}", "}", "$", "version", "=", "isset", "(", "$", "versionsSorted", "[", "$", "currentK", "-", "1", "]", ")", "?", "$", "versionsSorted", "[", "$", "currentK", "-", "1", "]", ":", "$", "versionsSorted", "[", "0", "]", ";", "}", "$", "migrationPath", "=", "$", "this", "->", "migrationsDir", ".", "'/'", ".", "$", "version", ".", "'.php'", ";", "if", "(", "!", "file_exists", "(", "$", "migrationPath", ")", ")", "{", "throw", "new", "CommandsException", "(", "'Migration class was not found '", ".", "$", "migrationPath", ")", ";", "}", "}", "}", "$", "versionsBetween", "=", "Version", "::", "between", "(", "$", "fromVersion", ",", "$", "version", ",", "$", "versions", ")", ";", "if", "(", "$", "toZero", "===", "true", ")", "{", "$", "theTwoFirstMigrations", "=", "[", "]", ";", "$", "theTwoFirstMigrations", "[", "]", "=", "$", "versionsBetween", "[", "count", "(", "$", "versionsBetween", ")", "-", "1", "]", ";", "$", "versionsBetween", "=", "$", "theTwoFirstMigrations", ";", "}", "try", "{", "$", "direction", "=", "'up'", ";", "foreach", "(", "$", "versionsBetween", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "migrationPath", "=", "$", "this", "->", "migrationsDir", ".", "'/'", ".", "$", "v", "[", "'version'", "]", ".", "'.php'", ";", "$", "this", "->", "_migrateFile", "(", "(", "string", ")", "$", "v", "[", "'version'", "]", ",", "$", "migrationPath", ",", "$", "v", "[", "'direction'", "]", ")", ";", "if", "(", "$", "v", "[", "'direction'", "]", "===", "'down'", "&&", "$", "k", "===", "0", ")", "{", "$", "direction", "=", "$", "v", "[", "'direction'", "]", ";", "continue", ";", "}", "else", "{", "$", "connection", "->", "insert", "(", "\"migration\"", ",", "array", "(", "(", "string", ")", "$", "v", "[", "'version'", "]", ",", "date", "(", "'Y-m-d H:i:s'", ")", ")", ",", "array", "(", "\"version\"", ",", "\"run_at\"", ")", ")", ";", "}", "$", "direction", "=", "$", "v", "[", "'direction'", "]", ";", "}", "if", "(", "count", "(", "$", "versionsBetween", ")", ">", "0", "&&", "$", "direction", "===", "'down'", ")", "{", "$", "connection", "->", "insert", "(", "\"migration\"", ",", "array", "(", "(", "string", ")", "$", "version", ",", "date", "(", "'Y-m-d H:i:s'", ")", ")", ",", "array", "(", "\"version\"", ",", "\"run_at\"", ")", ")", ";", "}", "elseif", "(", "count", "(", "$", "versionsBetween", ")", "===", "0", ")", "{", "print", "Color", "::", "colorize", "(", "'No migration to run'", ".", "PHP_EOL", ".", "PHP_EOL", ",", "Color", "::", "FG_GREEN", ")", ";", "}", "exit", "(", "0", ")", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "print", "PHP_EOL", ".", "Color", "::", "error", "(", "$", "e", "->", "getMessage", "(", ")", ")", ".", "PHP_EOL", ";", "exit", "(", "1", ")", ";", "}", "}" ]
Run Migrations @param $version @throws CommandsException
[ "Run", "Migrations" ]
train
https://github.com/SachaMorard/phalcon-console-migration/blob/6b79ecb04f3790844eae04d33e3489a98f4f1214/Library/Phalcon/Migrations.php#L101-L199
SachaMorard/phalcon-console-migration
Library/Phalcon/Migrations.php
Migrations._migrateFile
protected function _migrateFile($version, $filePath, $direction = 'up') { $classVersion = preg_replace('/[^0-9A-Za-z]/', '', $version); $className = 'Migration_' . $classVersion; if (file_exists($filePath)) { require_once $filePath; if (class_exists($className)) { $migration = new $className($this->config, $version); if ($direction === 'up') { $migration->up(); if (method_exists($migration, 'afterUp')) { $migration->afterUp(); } print PHP_EOL . Color::success('Upgrade Version ' . $version . ' was successfully migrated') . PHP_EOL; } elseif ($direction === 'down') { $migration->down(); if (method_exists($migration, 'afterDown')) { $migration->afterDown(); } print PHP_EOL . Color::info('Downgrade Version ' . $version . ' was successfully migrated') . PHP_EOL; } } } else { throw new CommandsException('Migration class cannot be found ' . $className . ' at ' . $filePath); } }
php
protected function _migrateFile($version, $filePath, $direction = 'up') { $classVersion = preg_replace('/[^0-9A-Za-z]/', '', $version); $className = 'Migration_' . $classVersion; if (file_exists($filePath)) { require_once $filePath; if (class_exists($className)) { $migration = new $className($this->config, $version); if ($direction === 'up') { $migration->up(); if (method_exists($migration, 'afterUp')) { $migration->afterUp(); } print PHP_EOL . Color::success('Upgrade Version ' . $version . ' was successfully migrated') . PHP_EOL; } elseif ($direction === 'down') { $migration->down(); if (method_exists($migration, 'afterDown')) { $migration->afterDown(); } print PHP_EOL . Color::info('Downgrade Version ' . $version . ' was successfully migrated') . PHP_EOL; } } } else { throw new CommandsException('Migration class cannot be found ' . $className . ' at ' . $filePath); } }
[ "protected", "function", "_migrateFile", "(", "$", "version", ",", "$", "filePath", ",", "$", "direction", "=", "'up'", ")", "{", "$", "classVersion", "=", "preg_replace", "(", "'/[^0-9A-Za-z]/'", ",", "''", ",", "$", "version", ")", ";", "$", "className", "=", "'Migration_'", ".", "$", "classVersion", ";", "if", "(", "file_exists", "(", "$", "filePath", ")", ")", "{", "require_once", "$", "filePath", ";", "if", "(", "class_exists", "(", "$", "className", ")", ")", "{", "$", "migration", "=", "new", "$", "className", "(", "$", "this", "->", "config", ",", "$", "version", ")", ";", "if", "(", "$", "direction", "===", "'up'", ")", "{", "$", "migration", "->", "up", "(", ")", ";", "if", "(", "method_exists", "(", "$", "migration", ",", "'afterUp'", ")", ")", "{", "$", "migration", "->", "afterUp", "(", ")", ";", "}", "print", "PHP_EOL", ".", "Color", "::", "success", "(", "'Upgrade Version '", ".", "$", "version", ".", "' was successfully migrated'", ")", ".", "PHP_EOL", ";", "}", "elseif", "(", "$", "direction", "===", "'down'", ")", "{", "$", "migration", "->", "down", "(", ")", ";", "if", "(", "method_exists", "(", "$", "migration", ",", "'afterDown'", ")", ")", "{", "$", "migration", "->", "afterDown", "(", ")", ";", "}", "print", "PHP_EOL", ".", "Color", "::", "info", "(", "'Downgrade Version '", ".", "$", "version", ".", "' was successfully migrated'", ")", ".", "PHP_EOL", ";", "}", "}", "}", "else", "{", "throw", "new", "CommandsException", "(", "'Migration class cannot be found '", ".", "$", "className", ".", "' at '", ".", "$", "filePath", ")", ";", "}", "}" ]
Migrate Single File Up or Down @param $version @param $filePath @param string $direction @throws CommandsException
[ "Migrate", "Single", "File", "Up", "or", "Down" ]
train
https://github.com/SachaMorard/phalcon-console-migration/blob/6b79ecb04f3790844eae04d33e3489a98f4f1214/Library/Phalcon/Migrations.php#L209-L234
SachaMorard/phalcon-console-migration
Library/Phalcon/Migrations.php
Migrations.generate
public function generate() { $version = date('YmdHis'); $this->_generateMigrationFile($version); print PHP_EOL . Color::success('Version ' . $version . ' was successfully generated') . PHP_EOL; }
php
public function generate() { $version = date('YmdHis'); $this->_generateMigrationFile($version); print PHP_EOL . Color::success('Version ' . $version . ' was successfully generated') . PHP_EOL; }
[ "public", "function", "generate", "(", ")", "{", "$", "version", "=", "date", "(", "'YmdHis'", ")", ";", "$", "this", "->", "_generateMigrationFile", "(", "$", "version", ")", ";", "print", "PHP_EOL", ".", "Color", "::", "success", "(", "'Version '", ".", "$", "version", ".", "' was successfully generated'", ")", ".", "PHP_EOL", ";", "}" ]
Generate Empty Migration file
[ "Generate", "Empty", "Migration", "file" ]
train
https://github.com/SachaMorard/phalcon-console-migration/blob/6b79ecb04f3790844eae04d33e3489a98f4f1214/Library/Phalcon/Migrations.php#L240-L246
SachaMorard/phalcon-console-migration
Library/Phalcon/Migrations.php
Migrations._generateMigrationFile
protected function _generateMigrationFile($version, $contentUp = "", $contentDown = "") { $classVersion = preg_replace('/[^0-9A-Za-z]/', '', $version); $className = 'Migration_' . $classVersion; $classData = "<?php use Phalcon\Migrations\MigrationScript as Migration; class " . $className . " extends Migration\n" . "{\n\n" . "\tpublic function up()\n" . "\t{\n" . $contentUp . "\n\t}" . "\n\n" . "\tpublic function down()\n" . "\t{\n" . $contentDown . "\n\t}" . "\n}\n"; $classData = str_replace("\t", " ", $classData); file_put_contents($this->migrationsDir . '/' . $version . '.php', $classData); return $classData; }
php
protected function _generateMigrationFile($version, $contentUp = "", $contentDown = "") { $classVersion = preg_replace('/[^0-9A-Za-z]/', '', $version); $className = 'Migration_' . $classVersion; $classData = "<?php use Phalcon\Migrations\MigrationScript as Migration; class " . $className . " extends Migration\n" . "{\n\n" . "\tpublic function up()\n" . "\t{\n" . $contentUp . "\n\t}" . "\n\n" . "\tpublic function down()\n" . "\t{\n" . $contentDown . "\n\t}" . "\n}\n"; $classData = str_replace("\t", " ", $classData); file_put_contents($this->migrationsDir . '/' . $version . '.php', $classData); return $classData; }
[ "protected", "function", "_generateMigrationFile", "(", "$", "version", ",", "$", "contentUp", "=", "\"\"", ",", "$", "contentDown", "=", "\"\"", ")", "{", "$", "classVersion", "=", "preg_replace", "(", "'/[^0-9A-Za-z]/'", ",", "''", ",", "$", "version", ")", ";", "$", "className", "=", "'Migration_'", ".", "$", "classVersion", ";", "$", "classData", "=", "\"<?php\n\nuse Phalcon\\Migrations\\MigrationScript as Migration;\n\nclass \"", ".", "$", "className", ".", "\" extends Migration\\n\"", ".", "\"{\\n\\n\"", ".", "\"\\tpublic function up()\\n\"", ".", "\"\\t{\\n\"", ".", "$", "contentUp", ".", "\"\\n\\t}\"", ".", "\"\\n\\n\"", ".", "\"\\tpublic function down()\\n\"", ".", "\"\\t{\\n\"", ".", "$", "contentDown", ".", "\"\\n\\t}\"", ".", "\"\\n}\\n\"", ";", "$", "classData", "=", "str_replace", "(", "\"\\t\"", ",", "\" \"", ",", "$", "classData", ")", ";", "file_put_contents", "(", "$", "this", "->", "migrationsDir", ".", "'/'", ".", "$", "version", ".", "'.php'", ",", "$", "classData", ")", ";", "return", "$", "classData", ";", "}" ]
Generate Migration file @param $version @param string $contentUp @param string $contentDown @return mixed|string
[ "Generate", "Migration", "file" ]
train
https://github.com/SachaMorard/phalcon-console-migration/blob/6b79ecb04f3790844eae04d33e3489a98f4f1214/Library/Phalcon/Migrations.php#L257-L280
SachaMorard/phalcon-console-migration
Library/Phalcon/Migrations.php
Migrations.status
public function status() { $connection = $this->getDI()->get($this->migrationAdapter); $lastMig = $connection->fetchOne('SELECT * FROM migration ORDER BY id DESC', \PDO::FETCH_ASSOC); print PHP_EOL . Color::info('Current Version : ' . $lastMig['version']) . PHP_EOL; }
php
public function status() { $connection = $this->getDI()->get($this->migrationAdapter); $lastMig = $connection->fetchOne('SELECT * FROM migration ORDER BY id DESC', \PDO::FETCH_ASSOC); print PHP_EOL . Color::info('Current Version : ' . $lastMig['version']) . PHP_EOL; }
[ "public", "function", "status", "(", ")", "{", "$", "connection", "=", "$", "this", "->", "getDI", "(", ")", "->", "get", "(", "$", "this", "->", "migrationAdapter", ")", ";", "$", "lastMig", "=", "$", "connection", "->", "fetchOne", "(", "'SELECT * FROM migration ORDER BY id DESC'", ",", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "print", "PHP_EOL", ".", "Color", "::", "info", "(", "'Current Version : '", ".", "$", "lastMig", "[", "'version'", "]", ")", ".", "PHP_EOL", ";", "}" ]
Migration Status
[ "Migration", "Status" ]
train
https://github.com/SachaMorard/phalcon-console-migration/blob/6b79ecb04f3790844eae04d33e3489a98f4f1214/Library/Phalcon/Migrations.php#L285-L292
SachaMorard/phalcon-console-migration
Library/Phalcon/Migrations.php
Migrations._morphTable
protected function _morphTable($tableName, $definition, $foreignKeys, $dbAdapter) { $ignoreDropForeignKeys = array(); /** @var \Phalcon\Db\Adapter $connection */ $connection = $this->getDI()->get($dbAdapter); if ($dbAdapter === 'dbCassandra') { $schema = $connection->getDescriptor()['keyspace']; } elseif ($dbAdapter === 'dbPostgresql') { $schema = $connection->getDescriptor()['schema']; } else { $schema = $connection->getDescriptor()['dbname']; } $sql = array(); $tableExists = $connection->tableExists($tableName, $schema); if (isset($definition['columns'])) { if (count($definition['columns']) == 0) { throw new Exception('Table must have at least one column'); } $fields = array(); foreach ($definition['columns'] as $tableColumn) { if (!is_object($tableColumn)) { throw new Exception('Table must have at least one column'); } $fields[$tableColumn->getName()] = $tableColumn; } if ($tableExists) { $localFields = array(); $description = $connection->describeColumns($tableName, $schema); foreach ($description as $field) { $localFields[$field->getName()] = $field; } foreach ($fields as $fieldName => $tableColumn) { if ($dbAdapter === 'dbPostgresql') { $schema = $connection->getDescriptor()['schema']; } if (!isset($localFields[$fieldName])) { /** * ADD COLUMN */ $rawSql = $connection->getDialect()->addColumn($tableName, $tableColumn->getSchemaName(), $tableColumn); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } else { /** * ALTER TABLE */ $changed = false; if ($localFields[$fieldName]->getType() != $tableColumn->getType()) { // If we are on MySQL DB, and the current column in DB is INT(1) // and current annotation is "boolean", we don't notify change // because when we save a boolean column in MySQL it's converted to INT(1) // It prevents executing useless DB updates on each run if ($dbAdapter !== 'dbMysql' || $localFields[$fieldName]->getType() !== \Phalcon\Db\Column::TYPE_INTEGER || $localFields[$fieldName]->getSize() !== 1 || $tableColumn->getType() !== \Phalcon\Db\Column::TYPE_BOOLEAN ) { $changed = true; } } if ($tableColumn->isNotNull() != $localFields[$fieldName]->isNotNull()) { $changed = true; } if ($tableColumn->getSize() && $tableColumn->getSize() != $localFields[$fieldName]->getSize()) { $changed = true; } if ($changed == true) { $existingForeignKeys = []; // We check if there is a foreign key constraint if ($dbAdapter === 'dbMysql') { $results = $connection->query("SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,REFERENCED_TABLE_SCHEMA,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = '" . $connection->getDescriptor()['dbname'] . "' AND REFERENCED_TABLE_NAME = '" . $tableName . "' AND REFERENCED_COLUMN_NAME = '" . $tableColumn->getName() . "'"); foreach ($results->fetchAll() as $r) { $rules = $connection->query('SELECT UPDATE_RULE, DELETE_RULE FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME="' . $r['CONSTRAINT_NAME'] . '" AND CONSTRAINT_SCHEMA ="' . $r['TABLE_SCHEMA'] . '"'); $rules = $rules->fetch(); $r['UPDATE_RULE'] = $rules['UPDATE_RULE']; $r['DELETE_RULE'] = $rules['DELETE_RULE']; /** * DROP FOREIGN KEY BECAUSE WE CHANGE THE CURRENT COLUMN */ $rawSql = $connection->getDialect()->dropForeignKey($r['TABLE_NAME'], $r['TABLE_SCHEMA'], $r['CONSTRAINT_NAME']); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; $existingForeignKeys[] = $r; } } elseif ($dbAdapter === 'dbPostgresql') { $sqlconstraint = $this->getPGSQLConstraint($tableName, $tableColumn->getName()); $results = $connection->query($sqlconstraint); foreach ($results->fetchAll() as $r) { $r['UPDATE_RULE'] = $r['on_update']; $r['DELETE_RULE'] = $r['on_delete']; $r['TABLE_NAME'] = $r['table_name']; $r['TABLE_SCHEMA'] = $r['constraint_schema']; $r['CONSTRAINT_NAME'] = $r['constraint_name']; $r['REFERENCED_TABLE_SCHEMA'] = $r['constraint_schema']; $r['REFERENCED_TABLE_NAME'] = $r['references_table']; $r['REFERENCED_COLUMN_NAME'] = $r['references_field']; $r['COLUMN_NAME'] = $r['column_name']; /** * DROP FOREIGN KEY BECAUSE WE CHANGE THE CURRENT COLUMN */ $rawSql = $connection->getDialect()->dropForeignKey($r['TABLE_NAME'], $r['TABLE_SCHEMA'], $r['CONSTRAINT_NAME']); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; $existingForeignKeys[] = $r; } } /** * ALTER TABLE */ if ($dbAdapter === 'dbPostgresql') { $rawSql = $connection->getDialect()->modifyColumn($tableName, $tableColumn->getSchemaName(), $tableColumn, $localFields[$fieldName]); } else { $rawSql = $connection->getDialect()->modifyColumn($tableName, $tableColumn->getSchemaName(), $tableColumn); } $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; if ($existingForeignKeys) { foreach ($existingForeignKeys as $r) { /** * ADD FOREIGN KEY AFTER DROP ONE (TO CHANGE IT) */ $rawSql = $connection->getDialect()->addForeignKey( $r['TABLE_NAME'], $r['TABLE_SCHEMA'], new Reference( $r['CONSTRAINT_NAME'], array( "referencedSchema" => $r['REFERENCED_TABLE_SCHEMA'], "referencedTable" => $r['REFERENCED_TABLE_NAME'], "columns" => array($r['COLUMN_NAME']), "referencedColumns" => array($r['REFERENCED_COLUMN_NAME']), 'onUpdate' => $r['UPDATE_RULE'], 'onDelete' => $r['DELETE_RULE'] ) )); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } } } } /** * DROP COLUMN (and foreign key) */ foreach ($localFields as $fieldName => $localField) { if (!isset($fields[$fieldName])) { if ($dbAdapter === 'dbMysql') { // We check if there is a foreign key constraint $results = $connection->query("SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,REFERENCED_TABLE_SCHEMA,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = '" . $schema . "' AND TABLE_NAME = '" . $tableName . "' AND COLUMN_NAME = '" . $fieldName . "'"); foreach ($results->fetchAll() as $r) { $ignoreDropForeignKeys[] = $r['CONSTRAINT_NAME']; $rawSql = $connection->getDialect()->dropForeignKey($r['TABLE_NAME'], $r['TABLE_SCHEMA'], $r['CONSTRAINT_NAME']); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } elseif ($dbAdapter === 'dbPostgresql') { $sqlconstraint = $this->getPGSQLConstraint($tableName, $fieldName); $results = $connection->query($sqlconstraint); foreach ($results->fetchAll() as $r) { $ignoreDropForeignKeys[] = $r['CONSTRAINT_NAME']; $rawSql = $connection->getDialect()->dropForeignKey($r['table_name'], $r['constraint_schema'], $r['constraint_name']); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } $rawSql = $connection->getDialect()->dropColumn($tableName, $schema, $fieldName); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } } else { /** * CREATE TABLE IF NOT EXISTS */ $rawSql = $connection->getDialect()->createTable($tableName, $schema, $definition); if ($dbAdapter === 'dbPostgresql') { $sqlInstructions = explode(';', $rawSql); foreach ($sqlInstructions as $instruction) { if ($instruction !== "" && strpos($instruction, '_pkey" ON') === false) { $sql[] = '$this->' . $dbAdapter . '->query(\'' . $instruction . '\');'; } } } else { $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } } /** * DROP FOREIGN KEY */ if ($tableExists === true && ($dbAdapter === 'dbMysql' || $dbAdapter === 'dbPostgresql')) { $actualReferences = $connection->describeReferences($tableName, $schema); /* @var $actualReference \Phalcon\Db\Reference */ foreach ($actualReferences as $actualReference) { $foreignKeyExists = false; for ($i = count($foreignKeys) - 1; $i >= 0; --$i) { if ($dbAdapter === 'dbMysql') { $rules = $connection->query('SELECT UPDATE_RULE, DELETE_RULE FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME="' . $actualReference->getName() . '" AND CONSTRAINT_SCHEMA ="' . $actualReference->getReferencedSchema() . '"'); $rules = $rules->fetch(); if ($tableName === $foreignKeys[$i]['table'] && $actualReference->getReferencedTable() === $foreignKeys[$i]['referencedTable'] && count(array_diff($actualReference->getColumns(), $foreignKeys[$i]['fields'])) === 0 && count(array_diff($actualReference->getReferencedColumns(), $foreignKeys[$i]['referencedFields'])) === 0 // TODO : réactiver cette ligne si Phalcon prend en compte la méthode : && $actualReference->getOnUpdate() === $foreignKeys[$i]['action'] && $rules['UPDATE_RULE'] === $foreignKeys[$i]['action'] // TODO : réactiver cette ligne si Phalcon prend en compte la méthode : && $actualReference->getOnDelete() === $foreignKeys[$i]['action']) { && $rules['DELETE_RULE'] === $foreignKeys[$i]['action'] ) { $foreignKeyExists = true; array_splice($foreignKeys, $i, 1); break; } } else { if ($tableName === $foreignKeys[$i]['table'] && $actualReference->getReferencedTable() === $foreignKeys[$i]['referencedTable'] && count(array_diff($actualReference->getColumns(), $foreignKeys[$i]['fields'])) === 0 && count(array_diff($actualReference->getReferencedColumns(), $foreignKeys[$i]['referencedFields'])) === 0 ) { $foreignKeyExists = true; array_splice($foreignKeys, $i, 1); break; } } } if (!$foreignKeyExists && !in_array($actualReference->getName(), $ignoreDropForeignKeys)) { $rawSql = $connection->getDialect()->dropForeignKey( $tableName, $actualReference->getReferencedSchema(), $actualReference->getName() ); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } } /** * ADD FOREIGN KEY */ if ($foreignKeys) { foreach ($foreignKeys as $foreignKey) { $rawSql = $connection->getDialect()->addForeignKey( $tableName, $connection->getDescriptor()['dbname'], new Reference( $foreignKey['name'], array( "referencedSchema" => $connection->getDescriptor()['dbname'], "referencedTable" => $foreignKey['referencedTable'], "columns" => $foreignKey['fields'], "referencedColumns" => $foreignKey['referencedFields'], 'onUpdate' => $foreignKey['action'], 'onDelete' => $foreignKey['action'] ) )); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } /** * INDEXES */ if (isset($definition['indexes'])) { if ($tableExists == true) { $indexes = array(); foreach ($definition['indexes'] as $tableIndex) { $indexes[$tableIndex->getName()] = $tableIndex; } if ($dbAdapter === 'dbPostgresql') { $rawSql = $connection->getDialect()->modifyColumn($tableName, $tableColumn->getSchemaName(), $tableColumn, $localFields[$fieldName]); } $localIndexes = array(); $actualIndexes = $connection->describeIndexes($tableName, $schema); foreach ($actualIndexes as $actualIndex) { $deleted = true; foreach ($definition['indexes'] as $tableIndex) { // hack for encoging problem $tableIndexName = $tableIndex->getName(); $actualIndexName = $actualIndex->getName(); if ($tableIndexName === $actualIndexName) { $deleted = false; $localIndexes[$actualIndex->getName()] = $actualIndex->getColumns(); break; } elseif (substr($actualIndex->getName(), 0, 3) !== 'IDX' && ($dbAdapter !== 'dbCassandra') && ($dbAdapter !== 'dbPostgresql')) { $deleted = false; break; } } if ($deleted) { $rawSql = $connection->getDialect()->dropIndex($tableName, $tableColumn->getSchemaName(), $actualIndexName); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } foreach ($definition['indexes'] as $tableIndex) { $tableIndexName = $tableIndex->getName(); if (!isset($localIndexes[$tableIndexName])) { if ($tableIndexName == 'PRIMARY') { $rawSql = $connection->getDialect()->addPrimaryKey($tableName, $tableColumn->getSchemaName(), $tableIndex); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } else { $rawSql = $connection->getDialect()->addIndex($tableName, $tableColumn->getSchemaName(), $tableIndex); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } else { $changed = false; if (count($tableIndex->getColumns()) != count($localIndexes[$tableIndexName])) { $changed = true; } else { foreach ($tableIndex->getColumns() as $columnName) { if (!in_array($columnName, $localIndexes[$tableIndexName])) { $changed = true; break; } } } if ($changed == true) { if ($tableIndex->getName() == 'PRIMARY') { $rawSql = $connection->getDialect()->dropPrimaryKey($tableName, $tableColumn->getSchemaName()); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; $rawSql = $connection->getDialect()->addPrimaryKey($tableName, $tableColumn->getSchemaName(), $tableIndex); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } } } } } return $sql; }
php
protected function _morphTable($tableName, $definition, $foreignKeys, $dbAdapter) { $ignoreDropForeignKeys = array(); /** @var \Phalcon\Db\Adapter $connection */ $connection = $this->getDI()->get($dbAdapter); if ($dbAdapter === 'dbCassandra') { $schema = $connection->getDescriptor()['keyspace']; } elseif ($dbAdapter === 'dbPostgresql') { $schema = $connection->getDescriptor()['schema']; } else { $schema = $connection->getDescriptor()['dbname']; } $sql = array(); $tableExists = $connection->tableExists($tableName, $schema); if (isset($definition['columns'])) { if (count($definition['columns']) == 0) { throw new Exception('Table must have at least one column'); } $fields = array(); foreach ($definition['columns'] as $tableColumn) { if (!is_object($tableColumn)) { throw new Exception('Table must have at least one column'); } $fields[$tableColumn->getName()] = $tableColumn; } if ($tableExists) { $localFields = array(); $description = $connection->describeColumns($tableName, $schema); foreach ($description as $field) { $localFields[$field->getName()] = $field; } foreach ($fields as $fieldName => $tableColumn) { if ($dbAdapter === 'dbPostgresql') { $schema = $connection->getDescriptor()['schema']; } if (!isset($localFields[$fieldName])) { /** * ADD COLUMN */ $rawSql = $connection->getDialect()->addColumn($tableName, $tableColumn->getSchemaName(), $tableColumn); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } else { /** * ALTER TABLE */ $changed = false; if ($localFields[$fieldName]->getType() != $tableColumn->getType()) { // If we are on MySQL DB, and the current column in DB is INT(1) // and current annotation is "boolean", we don't notify change // because when we save a boolean column in MySQL it's converted to INT(1) // It prevents executing useless DB updates on each run if ($dbAdapter !== 'dbMysql' || $localFields[$fieldName]->getType() !== \Phalcon\Db\Column::TYPE_INTEGER || $localFields[$fieldName]->getSize() !== 1 || $tableColumn->getType() !== \Phalcon\Db\Column::TYPE_BOOLEAN ) { $changed = true; } } if ($tableColumn->isNotNull() != $localFields[$fieldName]->isNotNull()) { $changed = true; } if ($tableColumn->getSize() && $tableColumn->getSize() != $localFields[$fieldName]->getSize()) { $changed = true; } if ($changed == true) { $existingForeignKeys = []; // We check if there is a foreign key constraint if ($dbAdapter === 'dbMysql') { $results = $connection->query("SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,REFERENCED_TABLE_SCHEMA,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = '" . $connection->getDescriptor()['dbname'] . "' AND REFERENCED_TABLE_NAME = '" . $tableName . "' AND REFERENCED_COLUMN_NAME = '" . $tableColumn->getName() . "'"); foreach ($results->fetchAll() as $r) { $rules = $connection->query('SELECT UPDATE_RULE, DELETE_RULE FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME="' . $r['CONSTRAINT_NAME'] . '" AND CONSTRAINT_SCHEMA ="' . $r['TABLE_SCHEMA'] . '"'); $rules = $rules->fetch(); $r['UPDATE_RULE'] = $rules['UPDATE_RULE']; $r['DELETE_RULE'] = $rules['DELETE_RULE']; /** * DROP FOREIGN KEY BECAUSE WE CHANGE THE CURRENT COLUMN */ $rawSql = $connection->getDialect()->dropForeignKey($r['TABLE_NAME'], $r['TABLE_SCHEMA'], $r['CONSTRAINT_NAME']); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; $existingForeignKeys[] = $r; } } elseif ($dbAdapter === 'dbPostgresql') { $sqlconstraint = $this->getPGSQLConstraint($tableName, $tableColumn->getName()); $results = $connection->query($sqlconstraint); foreach ($results->fetchAll() as $r) { $r['UPDATE_RULE'] = $r['on_update']; $r['DELETE_RULE'] = $r['on_delete']; $r['TABLE_NAME'] = $r['table_name']; $r['TABLE_SCHEMA'] = $r['constraint_schema']; $r['CONSTRAINT_NAME'] = $r['constraint_name']; $r['REFERENCED_TABLE_SCHEMA'] = $r['constraint_schema']; $r['REFERENCED_TABLE_NAME'] = $r['references_table']; $r['REFERENCED_COLUMN_NAME'] = $r['references_field']; $r['COLUMN_NAME'] = $r['column_name']; /** * DROP FOREIGN KEY BECAUSE WE CHANGE THE CURRENT COLUMN */ $rawSql = $connection->getDialect()->dropForeignKey($r['TABLE_NAME'], $r['TABLE_SCHEMA'], $r['CONSTRAINT_NAME']); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; $existingForeignKeys[] = $r; } } /** * ALTER TABLE */ if ($dbAdapter === 'dbPostgresql') { $rawSql = $connection->getDialect()->modifyColumn($tableName, $tableColumn->getSchemaName(), $tableColumn, $localFields[$fieldName]); } else { $rawSql = $connection->getDialect()->modifyColumn($tableName, $tableColumn->getSchemaName(), $tableColumn); } $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; if ($existingForeignKeys) { foreach ($existingForeignKeys as $r) { /** * ADD FOREIGN KEY AFTER DROP ONE (TO CHANGE IT) */ $rawSql = $connection->getDialect()->addForeignKey( $r['TABLE_NAME'], $r['TABLE_SCHEMA'], new Reference( $r['CONSTRAINT_NAME'], array( "referencedSchema" => $r['REFERENCED_TABLE_SCHEMA'], "referencedTable" => $r['REFERENCED_TABLE_NAME'], "columns" => array($r['COLUMN_NAME']), "referencedColumns" => array($r['REFERENCED_COLUMN_NAME']), 'onUpdate' => $r['UPDATE_RULE'], 'onDelete' => $r['DELETE_RULE'] ) )); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } } } } /** * DROP COLUMN (and foreign key) */ foreach ($localFields as $fieldName => $localField) { if (!isset($fields[$fieldName])) { if ($dbAdapter === 'dbMysql') { // We check if there is a foreign key constraint $results = $connection->query("SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,REFERENCED_TABLE_SCHEMA,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = '" . $schema . "' AND TABLE_NAME = '" . $tableName . "' AND COLUMN_NAME = '" . $fieldName . "'"); foreach ($results->fetchAll() as $r) { $ignoreDropForeignKeys[] = $r['CONSTRAINT_NAME']; $rawSql = $connection->getDialect()->dropForeignKey($r['TABLE_NAME'], $r['TABLE_SCHEMA'], $r['CONSTRAINT_NAME']); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } elseif ($dbAdapter === 'dbPostgresql') { $sqlconstraint = $this->getPGSQLConstraint($tableName, $fieldName); $results = $connection->query($sqlconstraint); foreach ($results->fetchAll() as $r) { $ignoreDropForeignKeys[] = $r['CONSTRAINT_NAME']; $rawSql = $connection->getDialect()->dropForeignKey($r['table_name'], $r['constraint_schema'], $r['constraint_name']); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } $rawSql = $connection->getDialect()->dropColumn($tableName, $schema, $fieldName); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } } else { /** * CREATE TABLE IF NOT EXISTS */ $rawSql = $connection->getDialect()->createTable($tableName, $schema, $definition); if ($dbAdapter === 'dbPostgresql') { $sqlInstructions = explode(';', $rawSql); foreach ($sqlInstructions as $instruction) { if ($instruction !== "" && strpos($instruction, '_pkey" ON') === false) { $sql[] = '$this->' . $dbAdapter . '->query(\'' . $instruction . '\');'; } } } else { $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } } /** * DROP FOREIGN KEY */ if ($tableExists === true && ($dbAdapter === 'dbMysql' || $dbAdapter === 'dbPostgresql')) { $actualReferences = $connection->describeReferences($tableName, $schema); /* @var $actualReference \Phalcon\Db\Reference */ foreach ($actualReferences as $actualReference) { $foreignKeyExists = false; for ($i = count($foreignKeys) - 1; $i >= 0; --$i) { if ($dbAdapter === 'dbMysql') { $rules = $connection->query('SELECT UPDATE_RULE, DELETE_RULE FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME="' . $actualReference->getName() . '" AND CONSTRAINT_SCHEMA ="' . $actualReference->getReferencedSchema() . '"'); $rules = $rules->fetch(); if ($tableName === $foreignKeys[$i]['table'] && $actualReference->getReferencedTable() === $foreignKeys[$i]['referencedTable'] && count(array_diff($actualReference->getColumns(), $foreignKeys[$i]['fields'])) === 0 && count(array_diff($actualReference->getReferencedColumns(), $foreignKeys[$i]['referencedFields'])) === 0 // TODO : réactiver cette ligne si Phalcon prend en compte la méthode : && $actualReference->getOnUpdate() === $foreignKeys[$i]['action'] && $rules['UPDATE_RULE'] === $foreignKeys[$i]['action'] // TODO : réactiver cette ligne si Phalcon prend en compte la méthode : && $actualReference->getOnDelete() === $foreignKeys[$i]['action']) { && $rules['DELETE_RULE'] === $foreignKeys[$i]['action'] ) { $foreignKeyExists = true; array_splice($foreignKeys, $i, 1); break; } } else { if ($tableName === $foreignKeys[$i]['table'] && $actualReference->getReferencedTable() === $foreignKeys[$i]['referencedTable'] && count(array_diff($actualReference->getColumns(), $foreignKeys[$i]['fields'])) === 0 && count(array_diff($actualReference->getReferencedColumns(), $foreignKeys[$i]['referencedFields'])) === 0 ) { $foreignKeyExists = true; array_splice($foreignKeys, $i, 1); break; } } } if (!$foreignKeyExists && !in_array($actualReference->getName(), $ignoreDropForeignKeys)) { $rawSql = $connection->getDialect()->dropForeignKey( $tableName, $actualReference->getReferencedSchema(), $actualReference->getName() ); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } } /** * ADD FOREIGN KEY */ if ($foreignKeys) { foreach ($foreignKeys as $foreignKey) { $rawSql = $connection->getDialect()->addForeignKey( $tableName, $connection->getDescriptor()['dbname'], new Reference( $foreignKey['name'], array( "referencedSchema" => $connection->getDescriptor()['dbname'], "referencedTable" => $foreignKey['referencedTable'], "columns" => $foreignKey['fields'], "referencedColumns" => $foreignKey['referencedFields'], 'onUpdate' => $foreignKey['action'], 'onDelete' => $foreignKey['action'] ) )); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } /** * INDEXES */ if (isset($definition['indexes'])) { if ($tableExists == true) { $indexes = array(); foreach ($definition['indexes'] as $tableIndex) { $indexes[$tableIndex->getName()] = $tableIndex; } if ($dbAdapter === 'dbPostgresql') { $rawSql = $connection->getDialect()->modifyColumn($tableName, $tableColumn->getSchemaName(), $tableColumn, $localFields[$fieldName]); } $localIndexes = array(); $actualIndexes = $connection->describeIndexes($tableName, $schema); foreach ($actualIndexes as $actualIndex) { $deleted = true; foreach ($definition['indexes'] as $tableIndex) { // hack for encoging problem $tableIndexName = $tableIndex->getName(); $actualIndexName = $actualIndex->getName(); if ($tableIndexName === $actualIndexName) { $deleted = false; $localIndexes[$actualIndex->getName()] = $actualIndex->getColumns(); break; } elseif (substr($actualIndex->getName(), 0, 3) !== 'IDX' && ($dbAdapter !== 'dbCassandra') && ($dbAdapter !== 'dbPostgresql')) { $deleted = false; break; } } if ($deleted) { $rawSql = $connection->getDialect()->dropIndex($tableName, $tableColumn->getSchemaName(), $actualIndexName); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } foreach ($definition['indexes'] as $tableIndex) { $tableIndexName = $tableIndex->getName(); if (!isset($localIndexes[$tableIndexName])) { if ($tableIndexName == 'PRIMARY') { $rawSql = $connection->getDialect()->addPrimaryKey($tableName, $tableColumn->getSchemaName(), $tableIndex); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } else { $rawSql = $connection->getDialect()->addIndex($tableName, $tableColumn->getSchemaName(), $tableIndex); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } else { $changed = false; if (count($tableIndex->getColumns()) != count($localIndexes[$tableIndexName])) { $changed = true; } else { foreach ($tableIndex->getColumns() as $columnName) { if (!in_array($columnName, $localIndexes[$tableIndexName])) { $changed = true; break; } } } if ($changed == true) { if ($tableIndex->getName() == 'PRIMARY') { $rawSql = $connection->getDialect()->dropPrimaryKey($tableName, $tableColumn->getSchemaName()); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; $rawSql = $connection->getDialect()->addPrimaryKey($tableName, $tableColumn->getSchemaName(), $tableIndex); $sql[] = '$this->' . $dbAdapter . '->query(\'' . $rawSql . '\');'; } } } } } } return $sql; }
[ "protected", "function", "_morphTable", "(", "$", "tableName", ",", "$", "definition", ",", "$", "foreignKeys", ",", "$", "dbAdapter", ")", "{", "$", "ignoreDropForeignKeys", "=", "array", "(", ")", ";", "/** @var \\Phalcon\\Db\\Adapter $connection */", "$", "connection", "=", "$", "this", "->", "getDI", "(", ")", "->", "get", "(", "$", "dbAdapter", ")", ";", "if", "(", "$", "dbAdapter", "===", "'dbCassandra'", ")", "{", "$", "schema", "=", "$", "connection", "->", "getDescriptor", "(", ")", "[", "'keyspace'", "]", ";", "}", "elseif", "(", "$", "dbAdapter", "===", "'dbPostgresql'", ")", "{", "$", "schema", "=", "$", "connection", "->", "getDescriptor", "(", ")", "[", "'schema'", "]", ";", "}", "else", "{", "$", "schema", "=", "$", "connection", "->", "getDescriptor", "(", ")", "[", "'dbname'", "]", ";", "}", "$", "sql", "=", "array", "(", ")", ";", "$", "tableExists", "=", "$", "connection", "->", "tableExists", "(", "$", "tableName", ",", "$", "schema", ")", ";", "if", "(", "isset", "(", "$", "definition", "[", "'columns'", "]", ")", ")", "{", "if", "(", "count", "(", "$", "definition", "[", "'columns'", "]", ")", "==", "0", ")", "{", "throw", "new", "Exception", "(", "'Table must have at least one column'", ")", ";", "}", "$", "fields", "=", "array", "(", ")", ";", "foreach", "(", "$", "definition", "[", "'columns'", "]", "as", "$", "tableColumn", ")", "{", "if", "(", "!", "is_object", "(", "$", "tableColumn", ")", ")", "{", "throw", "new", "Exception", "(", "'Table must have at least one column'", ")", ";", "}", "$", "fields", "[", "$", "tableColumn", "->", "getName", "(", ")", "]", "=", "$", "tableColumn", ";", "}", "if", "(", "$", "tableExists", ")", "{", "$", "localFields", "=", "array", "(", ")", ";", "$", "description", "=", "$", "connection", "->", "describeColumns", "(", "$", "tableName", ",", "$", "schema", ")", ";", "foreach", "(", "$", "description", "as", "$", "field", ")", "{", "$", "localFields", "[", "$", "field", "->", "getName", "(", ")", "]", "=", "$", "field", ";", "}", "foreach", "(", "$", "fields", "as", "$", "fieldName", "=>", "$", "tableColumn", ")", "{", "if", "(", "$", "dbAdapter", "===", "'dbPostgresql'", ")", "{", "$", "schema", "=", "$", "connection", "->", "getDescriptor", "(", ")", "[", "'schema'", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "localFields", "[", "$", "fieldName", "]", ")", ")", "{", "/**\n * ADD COLUMN\n */", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "addColumn", "(", "$", "tableName", ",", "$", "tableColumn", "->", "getSchemaName", "(", ")", ",", "$", "tableColumn", ")", ";", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "}", "else", "{", "/**\n * ALTER TABLE\n */", "$", "changed", "=", "false", ";", "if", "(", "$", "localFields", "[", "$", "fieldName", "]", "->", "getType", "(", ")", "!=", "$", "tableColumn", "->", "getType", "(", ")", ")", "{", "// If we are on MySQL DB, and the current column in DB is INT(1)", "// and current annotation is \"boolean\", we don't notify change", "// because when we save a boolean column in MySQL it's converted to INT(1)", "// It prevents executing useless DB updates on each run", "if", "(", "$", "dbAdapter", "!==", "'dbMysql'", "||", "$", "localFields", "[", "$", "fieldName", "]", "->", "getType", "(", ")", "!==", "\\", "Phalcon", "\\", "Db", "\\", "Column", "::", "TYPE_INTEGER", "||", "$", "localFields", "[", "$", "fieldName", "]", "->", "getSize", "(", ")", "!==", "1", "||", "$", "tableColumn", "->", "getType", "(", ")", "!==", "\\", "Phalcon", "\\", "Db", "\\", "Column", "::", "TYPE_BOOLEAN", ")", "{", "$", "changed", "=", "true", ";", "}", "}", "if", "(", "$", "tableColumn", "->", "isNotNull", "(", ")", "!=", "$", "localFields", "[", "$", "fieldName", "]", "->", "isNotNull", "(", ")", ")", "{", "$", "changed", "=", "true", ";", "}", "if", "(", "$", "tableColumn", "->", "getSize", "(", ")", "&&", "$", "tableColumn", "->", "getSize", "(", ")", "!=", "$", "localFields", "[", "$", "fieldName", "]", "->", "getSize", "(", ")", ")", "{", "$", "changed", "=", "true", ";", "}", "if", "(", "$", "changed", "==", "true", ")", "{", "$", "existingForeignKeys", "=", "[", "]", ";", "// We check if there is a foreign key constraint", "if", "(", "$", "dbAdapter", "===", "'dbMysql'", ")", "{", "$", "results", "=", "$", "connection", "->", "query", "(", "\"SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,REFERENCED_TABLE_SCHEMA,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = '\"", ".", "$", "connection", "->", "getDescriptor", "(", ")", "[", "'dbname'", "]", ".", "\"' AND REFERENCED_TABLE_NAME = '\"", ".", "$", "tableName", ".", "\"' AND REFERENCED_COLUMN_NAME = '\"", ".", "$", "tableColumn", "->", "getName", "(", ")", ".", "\"'\"", ")", ";", "foreach", "(", "$", "results", "->", "fetchAll", "(", ")", "as", "$", "r", ")", "{", "$", "rules", "=", "$", "connection", "->", "query", "(", "'SELECT UPDATE_RULE, DELETE_RULE FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME=\"'", ".", "$", "r", "[", "'CONSTRAINT_NAME'", "]", ".", "'\" AND CONSTRAINT_SCHEMA =\"'", ".", "$", "r", "[", "'TABLE_SCHEMA'", "]", ".", "'\"'", ")", ";", "$", "rules", "=", "$", "rules", "->", "fetch", "(", ")", ";", "$", "r", "[", "'UPDATE_RULE'", "]", "=", "$", "rules", "[", "'UPDATE_RULE'", "]", ";", "$", "r", "[", "'DELETE_RULE'", "]", "=", "$", "rules", "[", "'DELETE_RULE'", "]", ";", "/**\n * DROP FOREIGN KEY BECAUSE WE CHANGE THE CURRENT COLUMN\n */", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "dropForeignKey", "(", "$", "r", "[", "'TABLE_NAME'", "]", ",", "$", "r", "[", "'TABLE_SCHEMA'", "]", ",", "$", "r", "[", "'CONSTRAINT_NAME'", "]", ")", ";", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "$", "existingForeignKeys", "[", "]", "=", "$", "r", ";", "}", "}", "elseif", "(", "$", "dbAdapter", "===", "'dbPostgresql'", ")", "{", "$", "sqlconstraint", "=", "$", "this", "->", "getPGSQLConstraint", "(", "$", "tableName", ",", "$", "tableColumn", "->", "getName", "(", ")", ")", ";", "$", "results", "=", "$", "connection", "->", "query", "(", "$", "sqlconstraint", ")", ";", "foreach", "(", "$", "results", "->", "fetchAll", "(", ")", "as", "$", "r", ")", "{", "$", "r", "[", "'UPDATE_RULE'", "]", "=", "$", "r", "[", "'on_update'", "]", ";", "$", "r", "[", "'DELETE_RULE'", "]", "=", "$", "r", "[", "'on_delete'", "]", ";", "$", "r", "[", "'TABLE_NAME'", "]", "=", "$", "r", "[", "'table_name'", "]", ";", "$", "r", "[", "'TABLE_SCHEMA'", "]", "=", "$", "r", "[", "'constraint_schema'", "]", ";", "$", "r", "[", "'CONSTRAINT_NAME'", "]", "=", "$", "r", "[", "'constraint_name'", "]", ";", "$", "r", "[", "'REFERENCED_TABLE_SCHEMA'", "]", "=", "$", "r", "[", "'constraint_schema'", "]", ";", "$", "r", "[", "'REFERENCED_TABLE_NAME'", "]", "=", "$", "r", "[", "'references_table'", "]", ";", "$", "r", "[", "'REFERENCED_COLUMN_NAME'", "]", "=", "$", "r", "[", "'references_field'", "]", ";", "$", "r", "[", "'COLUMN_NAME'", "]", "=", "$", "r", "[", "'column_name'", "]", ";", "/**\n * DROP FOREIGN KEY BECAUSE WE CHANGE THE CURRENT COLUMN\n */", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "dropForeignKey", "(", "$", "r", "[", "'TABLE_NAME'", "]", ",", "$", "r", "[", "'TABLE_SCHEMA'", "]", ",", "$", "r", "[", "'CONSTRAINT_NAME'", "]", ")", ";", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "$", "existingForeignKeys", "[", "]", "=", "$", "r", ";", "}", "}", "/**\n * ALTER TABLE\n */", "if", "(", "$", "dbAdapter", "===", "'dbPostgresql'", ")", "{", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "modifyColumn", "(", "$", "tableName", ",", "$", "tableColumn", "->", "getSchemaName", "(", ")", ",", "$", "tableColumn", ",", "$", "localFields", "[", "$", "fieldName", "]", ")", ";", "}", "else", "{", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "modifyColumn", "(", "$", "tableName", ",", "$", "tableColumn", "->", "getSchemaName", "(", ")", ",", "$", "tableColumn", ")", ";", "}", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "if", "(", "$", "existingForeignKeys", ")", "{", "foreach", "(", "$", "existingForeignKeys", "as", "$", "r", ")", "{", "/**\n * ADD FOREIGN KEY AFTER DROP ONE (TO CHANGE IT)\n */", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "addForeignKey", "(", "$", "r", "[", "'TABLE_NAME'", "]", ",", "$", "r", "[", "'TABLE_SCHEMA'", "]", ",", "new", "Reference", "(", "$", "r", "[", "'CONSTRAINT_NAME'", "]", ",", "array", "(", "\"referencedSchema\"", "=>", "$", "r", "[", "'REFERENCED_TABLE_SCHEMA'", "]", ",", "\"referencedTable\"", "=>", "$", "r", "[", "'REFERENCED_TABLE_NAME'", "]", ",", "\"columns\"", "=>", "array", "(", "$", "r", "[", "'COLUMN_NAME'", "]", ")", ",", "\"referencedColumns\"", "=>", "array", "(", "$", "r", "[", "'REFERENCED_COLUMN_NAME'", "]", ")", ",", "'onUpdate'", "=>", "$", "r", "[", "'UPDATE_RULE'", "]", ",", "'onDelete'", "=>", "$", "r", "[", "'DELETE_RULE'", "]", ")", ")", ")", ";", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "}", "}", "}", "}", "}", "/**\n * DROP COLUMN (and foreign key)\n */", "foreach", "(", "$", "localFields", "as", "$", "fieldName", "=>", "$", "localField", ")", "{", "if", "(", "!", "isset", "(", "$", "fields", "[", "$", "fieldName", "]", ")", ")", "{", "if", "(", "$", "dbAdapter", "===", "'dbMysql'", ")", "{", "// We check if there is a foreign key constraint", "$", "results", "=", "$", "connection", "->", "query", "(", "\"SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,REFERENCED_TABLE_SCHEMA,REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = '\"", ".", "$", "schema", ".", "\"' AND TABLE_NAME = '\"", ".", "$", "tableName", ".", "\"' AND COLUMN_NAME = '\"", ".", "$", "fieldName", ".", "\"'\"", ")", ";", "foreach", "(", "$", "results", "->", "fetchAll", "(", ")", "as", "$", "r", ")", "{", "$", "ignoreDropForeignKeys", "[", "]", "=", "$", "r", "[", "'CONSTRAINT_NAME'", "]", ";", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "dropForeignKey", "(", "$", "r", "[", "'TABLE_NAME'", "]", ",", "$", "r", "[", "'TABLE_SCHEMA'", "]", ",", "$", "r", "[", "'CONSTRAINT_NAME'", "]", ")", ";", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "}", "}", "elseif", "(", "$", "dbAdapter", "===", "'dbPostgresql'", ")", "{", "$", "sqlconstraint", "=", "$", "this", "->", "getPGSQLConstraint", "(", "$", "tableName", ",", "$", "fieldName", ")", ";", "$", "results", "=", "$", "connection", "->", "query", "(", "$", "sqlconstraint", ")", ";", "foreach", "(", "$", "results", "->", "fetchAll", "(", ")", "as", "$", "r", ")", "{", "$", "ignoreDropForeignKeys", "[", "]", "=", "$", "r", "[", "'CONSTRAINT_NAME'", "]", ";", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "dropForeignKey", "(", "$", "r", "[", "'table_name'", "]", ",", "$", "r", "[", "'constraint_schema'", "]", ",", "$", "r", "[", "'constraint_name'", "]", ")", ";", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "}", "}", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "dropColumn", "(", "$", "tableName", ",", "$", "schema", ",", "$", "fieldName", ")", ";", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "}", "}", "}", "else", "{", "/**\n * CREATE TABLE IF NOT EXISTS\n */", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "createTable", "(", "$", "tableName", ",", "$", "schema", ",", "$", "definition", ")", ";", "if", "(", "$", "dbAdapter", "===", "'dbPostgresql'", ")", "{", "$", "sqlInstructions", "=", "explode", "(", "';'", ",", "$", "rawSql", ")", ";", "foreach", "(", "$", "sqlInstructions", "as", "$", "instruction", ")", "{", "if", "(", "$", "instruction", "!==", "\"\"", "&&", "strpos", "(", "$", "instruction", ",", "'_pkey\" ON'", ")", "===", "false", ")", "{", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "instruction", ".", "'\\');'", ";", "}", "}", "}", "else", "{", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "}", "}", "}", "/**\n * DROP FOREIGN KEY\n */", "if", "(", "$", "tableExists", "===", "true", "&&", "(", "$", "dbAdapter", "===", "'dbMysql'", "||", "$", "dbAdapter", "===", "'dbPostgresql'", ")", ")", "{", "$", "actualReferences", "=", "$", "connection", "->", "describeReferences", "(", "$", "tableName", ",", "$", "schema", ")", ";", "/* @var $actualReference \\Phalcon\\Db\\Reference */", "foreach", "(", "$", "actualReferences", "as", "$", "actualReference", ")", "{", "$", "foreignKeyExists", "=", "false", ";", "for", "(", "$", "i", "=", "count", "(", "$", "foreignKeys", ")", "-", "1", ";", "$", "i", ">=", "0", ";", "--", "$", "i", ")", "{", "if", "(", "$", "dbAdapter", "===", "'dbMysql'", ")", "{", "$", "rules", "=", "$", "connection", "->", "query", "(", "'SELECT UPDATE_RULE, DELETE_RULE FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME=\"'", ".", "$", "actualReference", "->", "getName", "(", ")", ".", "'\" AND CONSTRAINT_SCHEMA =\"'", ".", "$", "actualReference", "->", "getReferencedSchema", "(", ")", ".", "'\"'", ")", ";", "$", "rules", "=", "$", "rules", "->", "fetch", "(", ")", ";", "if", "(", "$", "tableName", "===", "$", "foreignKeys", "[", "$", "i", "]", "[", "'table'", "]", "&&", "$", "actualReference", "->", "getReferencedTable", "(", ")", "===", "$", "foreignKeys", "[", "$", "i", "]", "[", "'referencedTable'", "]", "&&", "count", "(", "array_diff", "(", "$", "actualReference", "->", "getColumns", "(", ")", ",", "$", "foreignKeys", "[", "$", "i", "]", "[", "'fields'", "]", ")", ")", "===", "0", "&&", "count", "(", "array_diff", "(", "$", "actualReference", "->", "getReferencedColumns", "(", ")", ",", "$", "foreignKeys", "[", "$", "i", "]", "[", "'referencedFields'", "]", ")", ")", "===", "0", "// TODO : réactiver cette ligne si Phalcon prend en compte la méthode : && $actualReference->getOnUpdate() === $foreignKeys[$i]['action']", "&&", "$", "rules", "[", "'UPDATE_RULE'", "]", "===", "$", "foreignKeys", "[", "$", "i", "]", "[", "'action'", "]", "// TODO : réactiver cette ligne si Phalcon prend en compte la méthode : && $actualReference->getOnDelete() === $foreignKeys[$i]['action']) {", "&&", "$", "rules", "[", "'DELETE_RULE'", "]", "===", "$", "foreignKeys", "[", "$", "i", "]", "[", "'action'", "]", ")", "{", "$", "foreignKeyExists", "=", "true", ";", "array_splice", "(", "$", "foreignKeys", ",", "$", "i", ",", "1", ")", ";", "break", ";", "}", "}", "else", "{", "if", "(", "$", "tableName", "===", "$", "foreignKeys", "[", "$", "i", "]", "[", "'table'", "]", "&&", "$", "actualReference", "->", "getReferencedTable", "(", ")", "===", "$", "foreignKeys", "[", "$", "i", "]", "[", "'referencedTable'", "]", "&&", "count", "(", "array_diff", "(", "$", "actualReference", "->", "getColumns", "(", ")", ",", "$", "foreignKeys", "[", "$", "i", "]", "[", "'fields'", "]", ")", ")", "===", "0", "&&", "count", "(", "array_diff", "(", "$", "actualReference", "->", "getReferencedColumns", "(", ")", ",", "$", "foreignKeys", "[", "$", "i", "]", "[", "'referencedFields'", "]", ")", ")", "===", "0", ")", "{", "$", "foreignKeyExists", "=", "true", ";", "array_splice", "(", "$", "foreignKeys", ",", "$", "i", ",", "1", ")", ";", "break", ";", "}", "}", "}", "if", "(", "!", "$", "foreignKeyExists", "&&", "!", "in_array", "(", "$", "actualReference", "->", "getName", "(", ")", ",", "$", "ignoreDropForeignKeys", ")", ")", "{", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "dropForeignKey", "(", "$", "tableName", ",", "$", "actualReference", "->", "getReferencedSchema", "(", ")", ",", "$", "actualReference", "->", "getName", "(", ")", ")", ";", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "}", "}", "}", "/**\n * ADD FOREIGN KEY\n */", "if", "(", "$", "foreignKeys", ")", "{", "foreach", "(", "$", "foreignKeys", "as", "$", "foreignKey", ")", "{", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "addForeignKey", "(", "$", "tableName", ",", "$", "connection", "->", "getDescriptor", "(", ")", "[", "'dbname'", "]", ",", "new", "Reference", "(", "$", "foreignKey", "[", "'name'", "]", ",", "array", "(", "\"referencedSchema\"", "=>", "$", "connection", "->", "getDescriptor", "(", ")", "[", "'dbname'", "]", ",", "\"referencedTable\"", "=>", "$", "foreignKey", "[", "'referencedTable'", "]", ",", "\"columns\"", "=>", "$", "foreignKey", "[", "'fields'", "]", ",", "\"referencedColumns\"", "=>", "$", "foreignKey", "[", "'referencedFields'", "]", ",", "'onUpdate'", "=>", "$", "foreignKey", "[", "'action'", "]", ",", "'onDelete'", "=>", "$", "foreignKey", "[", "'action'", "]", ")", ")", ")", ";", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "}", "}", "/**\n * INDEXES\n */", "if", "(", "isset", "(", "$", "definition", "[", "'indexes'", "]", ")", ")", "{", "if", "(", "$", "tableExists", "==", "true", ")", "{", "$", "indexes", "=", "array", "(", ")", ";", "foreach", "(", "$", "definition", "[", "'indexes'", "]", "as", "$", "tableIndex", ")", "{", "$", "indexes", "[", "$", "tableIndex", "->", "getName", "(", ")", "]", "=", "$", "tableIndex", ";", "}", "if", "(", "$", "dbAdapter", "===", "'dbPostgresql'", ")", "{", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "modifyColumn", "(", "$", "tableName", ",", "$", "tableColumn", "->", "getSchemaName", "(", ")", ",", "$", "tableColumn", ",", "$", "localFields", "[", "$", "fieldName", "]", ")", ";", "}", "$", "localIndexes", "=", "array", "(", ")", ";", "$", "actualIndexes", "=", "$", "connection", "->", "describeIndexes", "(", "$", "tableName", ",", "$", "schema", ")", ";", "foreach", "(", "$", "actualIndexes", "as", "$", "actualIndex", ")", "{", "$", "deleted", "=", "true", ";", "foreach", "(", "$", "definition", "[", "'indexes'", "]", "as", "$", "tableIndex", ")", "{", "// hack for encoging problem", "$", "tableIndexName", "=", "$", "tableIndex", "->", "getName", "(", ")", ";", "$", "actualIndexName", "=", "$", "actualIndex", "->", "getName", "(", ")", ";", "if", "(", "$", "tableIndexName", "===", "$", "actualIndexName", ")", "{", "$", "deleted", "=", "false", ";", "$", "localIndexes", "[", "$", "actualIndex", "->", "getName", "(", ")", "]", "=", "$", "actualIndex", "->", "getColumns", "(", ")", ";", "break", ";", "}", "elseif", "(", "substr", "(", "$", "actualIndex", "->", "getName", "(", ")", ",", "0", ",", "3", ")", "!==", "'IDX'", "&&", "(", "$", "dbAdapter", "!==", "'dbCassandra'", ")", "&&", "(", "$", "dbAdapter", "!==", "'dbPostgresql'", ")", ")", "{", "$", "deleted", "=", "false", ";", "break", ";", "}", "}", "if", "(", "$", "deleted", ")", "{", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "dropIndex", "(", "$", "tableName", ",", "$", "tableColumn", "->", "getSchemaName", "(", ")", ",", "$", "actualIndexName", ")", ";", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "}", "}", "foreach", "(", "$", "definition", "[", "'indexes'", "]", "as", "$", "tableIndex", ")", "{", "$", "tableIndexName", "=", "$", "tableIndex", "->", "getName", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "localIndexes", "[", "$", "tableIndexName", "]", ")", ")", "{", "if", "(", "$", "tableIndexName", "==", "'PRIMARY'", ")", "{", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "addPrimaryKey", "(", "$", "tableName", ",", "$", "tableColumn", "->", "getSchemaName", "(", ")", ",", "$", "tableIndex", ")", ";", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "}", "else", "{", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "addIndex", "(", "$", "tableName", ",", "$", "tableColumn", "->", "getSchemaName", "(", ")", ",", "$", "tableIndex", ")", ";", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "}", "}", "else", "{", "$", "changed", "=", "false", ";", "if", "(", "count", "(", "$", "tableIndex", "->", "getColumns", "(", ")", ")", "!=", "count", "(", "$", "localIndexes", "[", "$", "tableIndexName", "]", ")", ")", "{", "$", "changed", "=", "true", ";", "}", "else", "{", "foreach", "(", "$", "tableIndex", "->", "getColumns", "(", ")", "as", "$", "columnName", ")", "{", "if", "(", "!", "in_array", "(", "$", "columnName", ",", "$", "localIndexes", "[", "$", "tableIndexName", "]", ")", ")", "{", "$", "changed", "=", "true", ";", "break", ";", "}", "}", "}", "if", "(", "$", "changed", "==", "true", ")", "{", "if", "(", "$", "tableIndex", "->", "getName", "(", ")", "==", "'PRIMARY'", ")", "{", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "dropPrimaryKey", "(", "$", "tableName", ",", "$", "tableColumn", "->", "getSchemaName", "(", ")", ")", ";", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "$", "rawSql", "=", "$", "connection", "->", "getDialect", "(", ")", "->", "addPrimaryKey", "(", "$", "tableName", ",", "$", "tableColumn", "->", "getSchemaName", "(", ")", ",", "$", "tableIndex", ")", ";", "$", "sql", "[", "]", "=", "'$this->'", ".", "$", "dbAdapter", ".", "'->query(\\''", ".", "$", "rawSql", ".", "'\\');'", ";", "}", "}", "}", "}", "}", "}", "return", "$", "sql", ";", "}" ]
Look for table definition modifications and apply to real table @param $tableName @param $definition @param $foreignKeys @return array @throws Exception
[ "Look", "for", "table", "definition", "modifications", "and", "apply", "to", "real", "table" ]
train
https://github.com/SachaMorard/phalcon-console-migration/blob/6b79ecb04f3790844eae04d33e3489a98f4f1214/Library/Phalcon/Migrations.php#L605-L959
VincentChalnot/SidusAdminBundle
Templating/TemplatingHelper.php
TemplatingHelper.renderListAction
public function renderListAction( Action $action, DataGrid $dataGrid, array $viewParameters = [] ): Response { $viewParameters = array_merge( $this->getViewParameters($action), ['datagrid' => $dataGrid], $viewParameters ); return $this->renderAction($action, $viewParameters); }
php
public function renderListAction( Action $action, DataGrid $dataGrid, array $viewParameters = [] ): Response { $viewParameters = array_merge( $this->getViewParameters($action), ['datagrid' => $dataGrid], $viewParameters ); return $this->renderAction($action, $viewParameters); }
[ "public", "function", "renderListAction", "(", "Action", "$", "action", ",", "DataGrid", "$", "dataGrid", ",", "array", "$", "viewParameters", "=", "[", "]", ")", ":", "Response", "{", "$", "viewParameters", "=", "array_merge", "(", "$", "this", "->", "getViewParameters", "(", "$", "action", ")", ",", "[", "'datagrid'", "=>", "$", "dataGrid", "]", ",", "$", "viewParameters", ")", ";", "return", "$", "this", "->", "renderAction", "(", "$", "action", ",", "$", "viewParameters", ")", ";", "}" ]
@param Action $action @param DataGrid $dataGrid @param array $viewParameters @return Response
[ "@param", "Action", "$action", "@param", "DataGrid", "$dataGrid", "@param", "array", "$viewParameters" ]
train
https://github.com/VincentChalnot/SidusAdminBundle/blob/3366f3f1525435860cf275ed2f1f0b58cf6eea18/Templating/TemplatingHelper.php#L61-L73
VincentChalnot/SidusAdminBundle
Templating/TemplatingHelper.php
TemplatingHelper.getViewParameters
public function getViewParameters( Action $action, FormInterface $form = null, $data = null, array $listRouteParameters = [] ): array { $parameters = [ 'listPath' => $this->routingHelper->getAdminListPath($action->getAdmin(), $listRouteParameters), 'admin' => $action->getAdmin(), ]; if ($form) { $parameters['form'] = $form->createView(); } if ($data) { $parameters['data'] = $data; } return $parameters; }
php
public function getViewParameters( Action $action, FormInterface $form = null, $data = null, array $listRouteParameters = [] ): array { $parameters = [ 'listPath' => $this->routingHelper->getAdminListPath($action->getAdmin(), $listRouteParameters), 'admin' => $action->getAdmin(), ]; if ($form) { $parameters['form'] = $form->createView(); } if ($data) { $parameters['data'] = $data; } return $parameters; }
[ "public", "function", "getViewParameters", "(", "Action", "$", "action", ",", "FormInterface", "$", "form", "=", "null", ",", "$", "data", "=", "null", ",", "array", "$", "listRouteParameters", "=", "[", "]", ")", ":", "array", "{", "$", "parameters", "=", "[", "'listPath'", "=>", "$", "this", "->", "routingHelper", "->", "getAdminListPath", "(", "$", "action", "->", "getAdmin", "(", ")", ",", "$", "listRouteParameters", ")", ",", "'admin'", "=>", "$", "action", "->", "getAdmin", "(", ")", ",", "]", ";", "if", "(", "$", "form", ")", "{", "$", "parameters", "[", "'form'", "]", "=", "$", "form", "->", "createView", "(", ")", ";", "}", "if", "(", "$", "data", ")", "{", "$", "parameters", "[", "'data'", "]", "=", "$", "data", ";", "}", "return", "$", "parameters", ";", "}" ]
@param Action $action @param FormInterface $form @param mixed $data @param array $listRouteParameters @return array
[ "@param", "Action", "$action", "@param", "FormInterface", "$form", "@param", "mixed", "$data", "@param", "array", "$listRouteParameters" ]
train
https://github.com/VincentChalnot/SidusAdminBundle/blob/3366f3f1525435860cf275ed2f1f0b58cf6eea18/Templating/TemplatingHelper.php#L102-L121
webforge-labs/psc-cms
lib/Psc/Doctrine/NestedSetsFixture.php
NestedSetsFixture.load
public function load(ObjectManager $em) { foreach ($this->examples as $list) { list($example, $context) = $list; $fixture = new NestedSetFixture($example, $context); $fixture->load($em); } }
php
public function load(ObjectManager $em) { foreach ($this->examples as $list) { list($example, $context) = $list; $fixture = new NestedSetFixture($example, $context); $fixture->load($em); } }
[ "public", "function", "load", "(", "ObjectManager", "$", "em", ")", "{", "foreach", "(", "$", "this", "->", "examples", "as", "$", "list", ")", "{", "list", "(", "$", "example", ",", "$", "context", ")", "=", "$", "list", ";", "$", "fixture", "=", "new", "NestedSetFixture", "(", "$", "example", ",", "$", "context", ")", ";", "$", "fixture", "->", "load", "(", "$", "em", ")", ";", "}", "}" ]
Load data fixtures with the passed EntityManager @param Doctrine\Common\Persistence\ObjectManager $manager
[ "Load", "data", "fixtures", "with", "the", "passed", "EntityManager" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Doctrine/NestedSetsFixture.php#L27-L34
PeekAndPoke/psi
src/Operation/FullSet/SortOperation.php
SortOperation.apply
public function apply(\Iterator $set) { $data = iterator_to_array($set); sort($data, $this->sortFlags); return new \ArrayIterator($data); }
php
public function apply(\Iterator $set) { $data = iterator_to_array($set); sort($data, $this->sortFlags); return new \ArrayIterator($data); }
[ "public", "function", "apply", "(", "\\", "Iterator", "$", "set", ")", "{", "$", "data", "=", "iterator_to_array", "(", "$", "set", ")", ";", "sort", "(", "$", "data", ",", "$", "this", "->", "sortFlags", ")", ";", "return", "new", "\\", "ArrayIterator", "(", "$", "data", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/PeekAndPoke/psi/blob/cfd45d995d3a2c2ea6ba5b1ce7b5fcc71179456f/src/Operation/FullSet/SortOperation.php#L20-L27
OpenClassrooms/ServiceProxy
src/ServiceProxyBuilder.php
ServiceProxyBuilder.build
public function build() { $proxy = $this->proxyFactory->createProxy($this->class); if ($proxy instanceof ServiceProxyCacheInterface) { if (null === $this->cacheProvider) { throw new InvalidCacheProviderException(); } $proxy->proxy_setCacheProvider($this->cacheProvider); } return $proxy; }
php
public function build() { $proxy = $this->proxyFactory->createProxy($this->class); if ($proxy instanceof ServiceProxyCacheInterface) { if (null === $this->cacheProvider) { throw new InvalidCacheProviderException(); } $proxy->proxy_setCacheProvider($this->cacheProvider); } return $proxy; }
[ "public", "function", "build", "(", ")", "{", "$", "proxy", "=", "$", "this", "->", "proxyFactory", "->", "createProxy", "(", "$", "this", "->", "class", ")", ";", "if", "(", "$", "proxy", "instanceof", "ServiceProxyCacheInterface", ")", "{", "if", "(", "null", "===", "$", "this", "->", "cacheProvider", ")", "{", "throw", "new", "InvalidCacheProviderException", "(", ")", ";", "}", "$", "proxy", "->", "proxy_setCacheProvider", "(", "$", "this", "->", "cacheProvider", ")", ";", "}", "return", "$", "proxy", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/OpenClassrooms/ServiceProxy/blob/31f9f8be8f064b4ca36873df83fc3833f53da438/src/ServiceProxyBuilder.php#L53-L64
redaigbaria/oauth2
src/Grant/PasswordGrant.php
PasswordGrant.getVerifyCredentialsCallback
protected function getVerifyCredentialsCallback() { if (is_null($this->callback) || !is_callable($this->callback)) { throw new Exception\ServerErrorException('Null or non-callable callback set on Password grant'); } return $this->callback; }
php
protected function getVerifyCredentialsCallback() { if (is_null($this->callback) || !is_callable($this->callback)) { throw new Exception\ServerErrorException('Null or non-callable callback set on Password grant'); } return $this->callback; }
[ "protected", "function", "getVerifyCredentialsCallback", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "callback", ")", "||", "!", "is_callable", "(", "$", "this", "->", "callback", ")", ")", "{", "throw", "new", "Exception", "\\", "ServerErrorException", "(", "'Null or non-callable callback set on Password grant'", ")", ";", "}", "return", "$", "this", "->", "callback", ";", "}" ]
Return the callback function @return callable @throws
[ "Return", "the", "callback", "function" ]
train
https://github.com/redaigbaria/oauth2/blob/54cca4aaaff6a095cbf1c8010f2fe2cc7de4e45a/src/Grant/PasswordGrant.php#L74-L81
redaigbaria/oauth2
src/Grant/PasswordGrant.php
PasswordGrant.completeFlow
public function completeFlow() { // Get the required params $clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser()); if (is_null($clientId)) { throw new Exception\InvalidRequestException('client_id'); } $clientSecret = $this->server->getRequest()->request->get('client_secret', $this->server->getRequest()->getPassword()); if (is_null($clientSecret)) { throw new Exception\InvalidRequestException('client_secret'); } // Validate client ID and client secret $client = $this->server->getClientStorage()->get( $clientId, $clientSecret, null, $this->getIdentifier() ); if (($client instanceof ClientEntity) === false) { $this->server->getEventEmitter()->emit(new Event\ClientAuthenticationFailedEvent($this->server->getRequest())); throw new Exception\InvalidClientException(); } $request = $this->server->getRequest()->request; if(is_null($request->get('facebook_token') && is_null($request->get("device_id")))) { $username = $request->get('username', $request->get('email',null)); if (is_null($username)) { throw new Exception\InvalidRequestException('username'); } $password = $this->server->getRequest()->request->get('password', null); if (is_null($password)) { throw new Exception\InvalidRequestException('password'); } } // Check if user's username and password are correct $userId = call_user_func($this->getVerifyCredentialsCallback(), isset($username) ? $username : null, isset($password) ? $password: null); if ($userId === false) { $this->server->getEventEmitter()->emit(new Event\UserAuthenticationFailedEvent($this->server->getRequest())); throw new Exception\InvalidCredentialsException(); } // Validate any scopes that are in the request $scopeParam = $this->server->getRequest()->request->get('scope', ''); $scopes = $this->validateScopes($scopeParam, $client); // Create a new session $session = new SessionEntity($this->server); $session->setOwner('user', $userId); $session->associateClient($client); // Generate an access token $accessToken = new AccessTokenEntity($this->server); $accessToken->setId(SecureKey::generate()); $accessToken->setExpireTime($this->getAccessTokenTTL() + time()); // Associate scopes with the session and access token foreach ($scopes as $scope) { $session->associateScope($scope); } foreach ($session->getScopes() as $scope) { $accessToken->associateScope($scope); } $this->server->getTokenType()->setSession($session); $this->server->getTokenType()->setParam('access_token', $accessToken->getId()); $this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL()); // Associate a refresh token if set if ($this->server->hasGrantType('refresh_token')) { $refreshToken = new RefreshTokenEntity($this->server); $refreshToken->setId(SecureKey::generate()); $refreshToken->setExpireTime($this->server->getGrantType('refresh_token')->getRefreshTokenTTL() + time()); $this->server->getTokenType()->setParam('refresh_token', $refreshToken->getId()); } // Save everything $session->save(); $accessToken->setSession($session); $accessToken->save(); if ($this->server->hasGrantType('refresh_token')) { $refreshToken->setAccessToken($accessToken); $refreshToken->save(); } return $this->server->getTokenType()->generateResponse(); }
php
public function completeFlow() { // Get the required params $clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser()); if (is_null($clientId)) { throw new Exception\InvalidRequestException('client_id'); } $clientSecret = $this->server->getRequest()->request->get('client_secret', $this->server->getRequest()->getPassword()); if (is_null($clientSecret)) { throw new Exception\InvalidRequestException('client_secret'); } // Validate client ID and client secret $client = $this->server->getClientStorage()->get( $clientId, $clientSecret, null, $this->getIdentifier() ); if (($client instanceof ClientEntity) === false) { $this->server->getEventEmitter()->emit(new Event\ClientAuthenticationFailedEvent($this->server->getRequest())); throw new Exception\InvalidClientException(); } $request = $this->server->getRequest()->request; if(is_null($request->get('facebook_token') && is_null($request->get("device_id")))) { $username = $request->get('username', $request->get('email',null)); if (is_null($username)) { throw new Exception\InvalidRequestException('username'); } $password = $this->server->getRequest()->request->get('password', null); if (is_null($password)) { throw new Exception\InvalidRequestException('password'); } } // Check if user's username and password are correct $userId = call_user_func($this->getVerifyCredentialsCallback(), isset($username) ? $username : null, isset($password) ? $password: null); if ($userId === false) { $this->server->getEventEmitter()->emit(new Event\UserAuthenticationFailedEvent($this->server->getRequest())); throw new Exception\InvalidCredentialsException(); } // Validate any scopes that are in the request $scopeParam = $this->server->getRequest()->request->get('scope', ''); $scopes = $this->validateScopes($scopeParam, $client); // Create a new session $session = new SessionEntity($this->server); $session->setOwner('user', $userId); $session->associateClient($client); // Generate an access token $accessToken = new AccessTokenEntity($this->server); $accessToken->setId(SecureKey::generate()); $accessToken->setExpireTime($this->getAccessTokenTTL() + time()); // Associate scopes with the session and access token foreach ($scopes as $scope) { $session->associateScope($scope); } foreach ($session->getScopes() as $scope) { $accessToken->associateScope($scope); } $this->server->getTokenType()->setSession($session); $this->server->getTokenType()->setParam('access_token', $accessToken->getId()); $this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL()); // Associate a refresh token if set if ($this->server->hasGrantType('refresh_token')) { $refreshToken = new RefreshTokenEntity($this->server); $refreshToken->setId(SecureKey::generate()); $refreshToken->setExpireTime($this->server->getGrantType('refresh_token')->getRefreshTokenTTL() + time()); $this->server->getTokenType()->setParam('refresh_token', $refreshToken->getId()); } // Save everything $session->save(); $accessToken->setSession($session); $accessToken->save(); if ($this->server->hasGrantType('refresh_token')) { $refreshToken->setAccessToken($accessToken); $refreshToken->save(); } return $this->server->getTokenType()->generateResponse(); }
[ "public", "function", "completeFlow", "(", ")", "{", "// Get the required params\r", "$", "clientId", "=", "$", "this", "->", "server", "->", "getRequest", "(", ")", "->", "request", "->", "get", "(", "'client_id'", ",", "$", "this", "->", "server", "->", "getRequest", "(", ")", "->", "getUser", "(", ")", ")", ";", "if", "(", "is_null", "(", "$", "clientId", ")", ")", "{", "throw", "new", "Exception", "\\", "InvalidRequestException", "(", "'client_id'", ")", ";", "}", "$", "clientSecret", "=", "$", "this", "->", "server", "->", "getRequest", "(", ")", "->", "request", "->", "get", "(", "'client_secret'", ",", "$", "this", "->", "server", "->", "getRequest", "(", ")", "->", "getPassword", "(", ")", ")", ";", "if", "(", "is_null", "(", "$", "clientSecret", ")", ")", "{", "throw", "new", "Exception", "\\", "InvalidRequestException", "(", "'client_secret'", ")", ";", "}", "// Validate client ID and client secret\r", "$", "client", "=", "$", "this", "->", "server", "->", "getClientStorage", "(", ")", "->", "get", "(", "$", "clientId", ",", "$", "clientSecret", ",", "null", ",", "$", "this", "->", "getIdentifier", "(", ")", ")", ";", "if", "(", "(", "$", "client", "instanceof", "ClientEntity", ")", "===", "false", ")", "{", "$", "this", "->", "server", "->", "getEventEmitter", "(", ")", "->", "emit", "(", "new", "Event", "\\", "ClientAuthenticationFailedEvent", "(", "$", "this", "->", "server", "->", "getRequest", "(", ")", ")", ")", ";", "throw", "new", "Exception", "\\", "InvalidClientException", "(", ")", ";", "}", "$", "request", "=", "$", "this", "->", "server", "->", "getRequest", "(", ")", "->", "request", ";", "if", "(", "is_null", "(", "$", "request", "->", "get", "(", "'facebook_token'", ")", "&&", "is_null", "(", "$", "request", "->", "get", "(", "\"device_id\"", ")", ")", ")", ")", "{", "$", "username", "=", "$", "request", "->", "get", "(", "'username'", ",", "$", "request", "->", "get", "(", "'email'", ",", "null", ")", ")", ";", "if", "(", "is_null", "(", "$", "username", ")", ")", "{", "throw", "new", "Exception", "\\", "InvalidRequestException", "(", "'username'", ")", ";", "}", "$", "password", "=", "$", "this", "->", "server", "->", "getRequest", "(", ")", "->", "request", "->", "get", "(", "'password'", ",", "null", ")", ";", "if", "(", "is_null", "(", "$", "password", ")", ")", "{", "throw", "new", "Exception", "\\", "InvalidRequestException", "(", "'password'", ")", ";", "}", "}", "// Check if user's username and password are correct\r", "$", "userId", "=", "call_user_func", "(", "$", "this", "->", "getVerifyCredentialsCallback", "(", ")", ",", "isset", "(", "$", "username", ")", "?", "$", "username", ":", "null", ",", "isset", "(", "$", "password", ")", "?", "$", "password", ":", "null", ")", ";", "if", "(", "$", "userId", "===", "false", ")", "{", "$", "this", "->", "server", "->", "getEventEmitter", "(", ")", "->", "emit", "(", "new", "Event", "\\", "UserAuthenticationFailedEvent", "(", "$", "this", "->", "server", "->", "getRequest", "(", ")", ")", ")", ";", "throw", "new", "Exception", "\\", "InvalidCredentialsException", "(", ")", ";", "}", "// Validate any scopes that are in the request\r", "$", "scopeParam", "=", "$", "this", "->", "server", "->", "getRequest", "(", ")", "->", "request", "->", "get", "(", "'scope'", ",", "''", ")", ";", "$", "scopes", "=", "$", "this", "->", "validateScopes", "(", "$", "scopeParam", ",", "$", "client", ")", ";", "// Create a new session\r", "$", "session", "=", "new", "SessionEntity", "(", "$", "this", "->", "server", ")", ";", "$", "session", "->", "setOwner", "(", "'user'", ",", "$", "userId", ")", ";", "$", "session", "->", "associateClient", "(", "$", "client", ")", ";", "// Generate an access token\r", "$", "accessToken", "=", "new", "AccessTokenEntity", "(", "$", "this", "->", "server", ")", ";", "$", "accessToken", "->", "setId", "(", "SecureKey", "::", "generate", "(", ")", ")", ";", "$", "accessToken", "->", "setExpireTime", "(", "$", "this", "->", "getAccessTokenTTL", "(", ")", "+", "time", "(", ")", ")", ";", "// Associate scopes with the session and access token\r", "foreach", "(", "$", "scopes", "as", "$", "scope", ")", "{", "$", "session", "->", "associateScope", "(", "$", "scope", ")", ";", "}", "foreach", "(", "$", "session", "->", "getScopes", "(", ")", "as", "$", "scope", ")", "{", "$", "accessToken", "->", "associateScope", "(", "$", "scope", ")", ";", "}", "$", "this", "->", "server", "->", "getTokenType", "(", ")", "->", "setSession", "(", "$", "session", ")", ";", "$", "this", "->", "server", "->", "getTokenType", "(", ")", "->", "setParam", "(", "'access_token'", ",", "$", "accessToken", "->", "getId", "(", ")", ")", ";", "$", "this", "->", "server", "->", "getTokenType", "(", ")", "->", "setParam", "(", "'expires_in'", ",", "$", "this", "->", "getAccessTokenTTL", "(", ")", ")", ";", "// Associate a refresh token if set\r", "if", "(", "$", "this", "->", "server", "->", "hasGrantType", "(", "'refresh_token'", ")", ")", "{", "$", "refreshToken", "=", "new", "RefreshTokenEntity", "(", "$", "this", "->", "server", ")", ";", "$", "refreshToken", "->", "setId", "(", "SecureKey", "::", "generate", "(", ")", ")", ";", "$", "refreshToken", "->", "setExpireTime", "(", "$", "this", "->", "server", "->", "getGrantType", "(", "'refresh_token'", ")", "->", "getRefreshTokenTTL", "(", ")", "+", "time", "(", ")", ")", ";", "$", "this", "->", "server", "->", "getTokenType", "(", ")", "->", "setParam", "(", "'refresh_token'", ",", "$", "refreshToken", "->", "getId", "(", ")", ")", ";", "}", "// Save everything\r", "$", "session", "->", "save", "(", ")", ";", "$", "accessToken", "->", "setSession", "(", "$", "session", ")", ";", "$", "accessToken", "->", "save", "(", ")", ";", "if", "(", "$", "this", "->", "server", "->", "hasGrantType", "(", "'refresh_token'", ")", ")", "{", "$", "refreshToken", "->", "setAccessToken", "(", "$", "accessToken", ")", ";", "$", "refreshToken", "->", "save", "(", ")", ";", "}", "return", "$", "this", "->", "server", "->", "getTokenType", "(", ")", "->", "generateResponse", "(", ")", ";", "}" ]
Complete the password grant @return array @throws
[ "Complete", "the", "password", "grant" ]
train
https://github.com/redaigbaria/oauth2/blob/54cca4aaaff6a095cbf1c8010f2fe2cc7de4e45a/src/Grant/PasswordGrant.php#L90-L184
redaigbaria/oauth2
src/Entity/RefreshTokenEntity.php
RefreshTokenEntity.getAccessToken
public function getAccessToken() { if (! $this->accessTokenEntity instanceof AccessTokenEntity) { $this->accessTokenEntity = $this->server->getAccessTokenStorage()->get($this->accessTokenId); } return $this->accessTokenEntity; }
php
public function getAccessToken() { if (! $this->accessTokenEntity instanceof AccessTokenEntity) { $this->accessTokenEntity = $this->server->getAccessTokenStorage()->get($this->accessTokenId); } return $this->accessTokenEntity; }
[ "public", "function", "getAccessToken", "(", ")", "{", "if", "(", "!", "$", "this", "->", "accessTokenEntity", "instanceof", "AccessTokenEntity", ")", "{", "$", "this", "->", "accessTokenEntity", "=", "$", "this", "->", "server", "->", "getAccessTokenStorage", "(", ")", "->", "get", "(", "$", "this", "->", "accessTokenId", ")", ";", "}", "return", "$", "this", "->", "accessTokenEntity", ";", "}" ]
Return access token @return AccessTokenEntity
[ "Return", "access", "token" ]
train
https://github.com/redaigbaria/oauth2/blob/54cca4aaaff6a095cbf1c8010f2fe2cc7de4e45a/src/Entity/RefreshTokenEntity.php#L66-L73
redaigbaria/oauth2
src/Entity/RefreshTokenEntity.php
RefreshTokenEntity.save
public function save() { $this->server->getRefreshTokenStorage()->create( $this->getId(), $this->getExpireTime(), $this->getAccessToken()->getId() ); }
php
public function save() { $this->server->getRefreshTokenStorage()->create( $this->getId(), $this->getExpireTime(), $this->getAccessToken()->getId() ); }
[ "public", "function", "save", "(", ")", "{", "$", "this", "->", "server", "->", "getRefreshTokenStorage", "(", ")", "->", "create", "(", "$", "this", "->", "getId", "(", ")", ",", "$", "this", "->", "getExpireTime", "(", ")", ",", "$", "this", "->", "getAccessToken", "(", ")", "->", "getId", "(", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/redaigbaria/oauth2/blob/54cca4aaaff6a095cbf1c8010f2fe2cc7de4e45a/src/Entity/RefreshTokenEntity.php#L78-L85
teneleven/GeolocatorBundle
Form/Type/GeocodedAddressType.php
GeocodedAddressType.buildForm
public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addModelTransformer($this->transformer); parent::buildForm($builder, $options); }
php
public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addModelTransformer($this->transformer); parent::buildForm($builder, $options); }
[ "public", "function", "buildForm", "(", "FormBuilderInterface", "$", "builder", ",", "array", "$", "options", ")", "{", "$", "builder", "->", "addModelTransformer", "(", "$", "this", "->", "transformer", ")", ";", "parent", "::", "buildForm", "(", "$", "builder", ",", "$", "options", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/teneleven/GeolocatorBundle/blob/4ead8e783a91577f2a67aa302b79641d4b9e99ad/Form/Type/GeocodedAddressType.php#L44-L49
nyeholt/silverstripe-external-content
thirdparty/Zend/Validate/Abstract.php
Zend_Validate_Abstract.setDefaultTranslator
public static function setDefaultTranslator($translator = null) { if ((null === $translator) || ($translator instanceof Zend_Translate_Adapter)) { self::$_defaultTranslator = $translator; } elseif ($translator instanceof Zend_Translate) { self::$_defaultTranslator = $translator->getAdapter(); } else { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Invalid translator specified'); } }
php
public static function setDefaultTranslator($translator = null) { if ((null === $translator) || ($translator instanceof Zend_Translate_Adapter)) { self::$_defaultTranslator = $translator; } elseif ($translator instanceof Zend_Translate) { self::$_defaultTranslator = $translator->getAdapter(); } else { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Invalid translator specified'); } }
[ "public", "static", "function", "setDefaultTranslator", "(", "$", "translator", "=", "null", ")", "{", "if", "(", "(", "null", "===", "$", "translator", ")", "||", "(", "$", "translator", "instanceof", "Zend_Translate_Adapter", ")", ")", "{", "self", "::", "$", "_defaultTranslator", "=", "$", "translator", ";", "}", "elseif", "(", "$", "translator", "instanceof", "Zend_Translate", ")", "{", "self", "::", "$", "_defaultTranslator", "=", "$", "translator", "->", "getAdapter", "(", ")", ";", "}", "else", "{", "require_once", "'Zend/Validate/Exception.php'", ";", "throw", "new", "Zend_Validate_Exception", "(", "'Invalid translator specified'", ")", ";", "}", "}" ]
Set default translation object for all validate objects @param Zend_Translate|Zend_Translate_Adapter|null $translator @return void
[ "Set", "default", "translation", "object", "for", "all", "validate", "objects" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Validate/Abstract.php#L343-L353
nyeholt/silverstripe-external-content
thirdparty/Zend/Validate/Abstract.php
Zend_Validate_Abstract.getDefaultTranslator
public static function getDefaultTranslator() { if (null === self::$_defaultTranslator) { require_once 'Zend/Registry.php'; if (Zend_Registry::isRegistered('Zend_Translate')) { $translator = Zend_Registry::get('Zend_Translate'); if ($translator instanceof Zend_Translate_Adapter) { return $translator; } elseif ($translator instanceof Zend_Translate) { return $translator->getAdapter(); } } } return self::$_defaultTranslator; }
php
public static function getDefaultTranslator() { if (null === self::$_defaultTranslator) { require_once 'Zend/Registry.php'; if (Zend_Registry::isRegistered('Zend_Translate')) { $translator = Zend_Registry::get('Zend_Translate'); if ($translator instanceof Zend_Translate_Adapter) { return $translator; } elseif ($translator instanceof Zend_Translate) { return $translator->getAdapter(); } } } return self::$_defaultTranslator; }
[ "public", "static", "function", "getDefaultTranslator", "(", ")", "{", "if", "(", "null", "===", "self", "::", "$", "_defaultTranslator", ")", "{", "require_once", "'Zend/Registry.php'", ";", "if", "(", "Zend_Registry", "::", "isRegistered", "(", "'Zend_Translate'", ")", ")", "{", "$", "translator", "=", "Zend_Registry", "::", "get", "(", "'Zend_Translate'", ")", ";", "if", "(", "$", "translator", "instanceof", "Zend_Translate_Adapter", ")", "{", "return", "$", "translator", ";", "}", "elseif", "(", "$", "translator", "instanceof", "Zend_Translate", ")", "{", "return", "$", "translator", "->", "getAdapter", "(", ")", ";", "}", "}", "}", "return", "self", "::", "$", "_defaultTranslator", ";", "}" ]
Get default translation object for all validate objects @return Zend_Translate_Adapter|null
[ "Get", "default", "translation", "object", "for", "all", "validate", "objects" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Validate/Abstract.php#L360-L375
factorio-item-browser/export-data
src/Entity/Item.php
Item.writeData
public function writeData(): array { $dataBuilder = new DataBuilder(); $dataBuilder->setString('t', $this->type, '') ->setString('n', $this->name, '') ->setArray('l', $this->labels->writeData(), null, []) ->setArray('d', $this->descriptions->writeData(), null, []) ->setInteger('r', $this->providesRecipeLocalisation ? 1 : 0, 0) ->setInteger('m', $this->providesMachineLocalisation ? 1 : 0, 0) ->setString('i', $this->iconHash, '') ->setInteger('e', $this->isNew ? 1 : 0, 1); return $dataBuilder->getData(); }
php
public function writeData(): array { $dataBuilder = new DataBuilder(); $dataBuilder->setString('t', $this->type, '') ->setString('n', $this->name, '') ->setArray('l', $this->labels->writeData(), null, []) ->setArray('d', $this->descriptions->writeData(), null, []) ->setInteger('r', $this->providesRecipeLocalisation ? 1 : 0, 0) ->setInteger('m', $this->providesMachineLocalisation ? 1 : 0, 0) ->setString('i', $this->iconHash, '') ->setInteger('e', $this->isNew ? 1 : 0, 1); return $dataBuilder->getData(); }
[ "public", "function", "writeData", "(", ")", ":", "array", "{", "$", "dataBuilder", "=", "new", "DataBuilder", "(", ")", ";", "$", "dataBuilder", "->", "setString", "(", "'t'", ",", "$", "this", "->", "type", ",", "''", ")", "->", "setString", "(", "'n'", ",", "$", "this", "->", "name", ",", "''", ")", "->", "setArray", "(", "'l'", ",", "$", "this", "->", "labels", "->", "writeData", "(", ")", ",", "null", ",", "[", "]", ")", "->", "setArray", "(", "'d'", ",", "$", "this", "->", "descriptions", "->", "writeData", "(", ")", ",", "null", ",", "[", "]", ")", "->", "setInteger", "(", "'r'", ",", "$", "this", "->", "providesRecipeLocalisation", "?", "1", ":", "0", ",", "0", ")", "->", "setInteger", "(", "'m'", ",", "$", "this", "->", "providesMachineLocalisation", "?", "1", ":", "0", ",", "0", ")", "->", "setString", "(", "'i'", ",", "$", "this", "->", "iconHash", ",", "''", ")", "->", "setInteger", "(", "'e'", ",", "$", "this", "->", "isNew", "?", "1", ":", "0", ",", "1", ")", ";", "return", "$", "dataBuilder", "->", "getData", "(", ")", ";", "}" ]
Writes the entity data to an array. @return array
[ "Writes", "the", "entity", "data", "to", "an", "array", "." ]
train
https://github.com/factorio-item-browser/export-data/blob/1413b2eed0fbfed0521457ac7ef0d668ac30c212/src/Entity/Item.php#L249-L261
factorio-item-browser/export-data
src/Entity/Item.php
Item.readData
public function readData(DataContainer $data) { $this->type = $data->getString('t', ''); $this->name = $data->getString('n', ''); $this->labels->readData($data->getObject('l')); $this->descriptions->readData($data->getObject('d')); $this->providesRecipeLocalisation = $data->getInteger('r', 0) === 1; $this->providesMachineLocalisation = $data->getInteger('m', 0) === 1; $this->iconHash = $data->getString('i'); $this->isNew = $data->getInteger('e', 1) === 1; return $this; }
php
public function readData(DataContainer $data) { $this->type = $data->getString('t', ''); $this->name = $data->getString('n', ''); $this->labels->readData($data->getObject('l')); $this->descriptions->readData($data->getObject('d')); $this->providesRecipeLocalisation = $data->getInteger('r', 0) === 1; $this->providesMachineLocalisation = $data->getInteger('m', 0) === 1; $this->iconHash = $data->getString('i'); $this->isNew = $data->getInteger('e', 1) === 1; return $this; }
[ "public", "function", "readData", "(", "DataContainer", "$", "data", ")", "{", "$", "this", "->", "type", "=", "$", "data", "->", "getString", "(", "'t'", ",", "''", ")", ";", "$", "this", "->", "name", "=", "$", "data", "->", "getString", "(", "'n'", ",", "''", ")", ";", "$", "this", "->", "labels", "->", "readData", "(", "$", "data", "->", "getObject", "(", "'l'", ")", ")", ";", "$", "this", "->", "descriptions", "->", "readData", "(", "$", "data", "->", "getObject", "(", "'d'", ")", ")", ";", "$", "this", "->", "providesRecipeLocalisation", "=", "$", "data", "->", "getInteger", "(", "'r'", ",", "0", ")", "===", "1", ";", "$", "this", "->", "providesMachineLocalisation", "=", "$", "data", "->", "getInteger", "(", "'m'", ",", "0", ")", "===", "1", ";", "$", "this", "->", "iconHash", "=", "$", "data", "->", "getString", "(", "'i'", ")", ";", "$", "this", "->", "isNew", "=", "$", "data", "->", "getInteger", "(", "'e'", ",", "1", ")", "===", "1", ";", "return", "$", "this", ";", "}" ]
Reads the entity data. @param DataContainer $data @return $this
[ "Reads", "the", "entity", "data", "." ]
train
https://github.com/factorio-item-browser/export-data/blob/1413b2eed0fbfed0521457ac7ef0d668ac30c212/src/Entity/Item.php#L268-L279
factorio-item-browser/export-data
src/Entity/Item.php
Item.calculateHash
public function calculateHash(): string { return EntityUtils::calculateHashOfArray([ $this->type, $this->name, $this->labels->calculateHash(), $this->descriptions->calculateHash(), $this->providesRecipeLocalisation, $this->providesMachineLocalisation, $this->iconHash, $this->isNew, ]); }
php
public function calculateHash(): string { return EntityUtils::calculateHashOfArray([ $this->type, $this->name, $this->labels->calculateHash(), $this->descriptions->calculateHash(), $this->providesRecipeLocalisation, $this->providesMachineLocalisation, $this->iconHash, $this->isNew, ]); }
[ "public", "function", "calculateHash", "(", ")", ":", "string", "{", "return", "EntityUtils", "::", "calculateHashOfArray", "(", "[", "$", "this", "->", "type", ",", "$", "this", "->", "name", ",", "$", "this", "->", "labels", "->", "calculateHash", "(", ")", ",", "$", "this", "->", "descriptions", "->", "calculateHash", "(", ")", ",", "$", "this", "->", "providesRecipeLocalisation", ",", "$", "this", "->", "providesMachineLocalisation", ",", "$", "this", "->", "iconHash", ",", "$", "this", "->", "isNew", ",", "]", ")", ";", "}" ]
Calculates a hash value representing the entity. @return string
[ "Calculates", "a", "hash", "value", "representing", "the", "entity", "." ]
train
https://github.com/factorio-item-browser/export-data/blob/1413b2eed0fbfed0521457ac7ef0d668ac30c212/src/Entity/Item.php#L285-L297
periaptio/empress-generator
src/Syntax/AddToTable.php
AddToTable.getItem
protected function getItem($field) { $property = $field['field']; // If the field is an array, // make it an array in the Migration if (is_array($property)) { $property = "['". implode("','", $property) ."']"; } else { $property = $property ? "'$property'" : null; } $type = $field['type']; $output = sprintf( "\$table->%s(%s)", $type, $property ); // If we have args, then it needs // to be formatted a bit differently if (isset($field['args'])) { $output = sprintf( "\$table->%s(%s, %s)", $type, $property, $field['args'] ); } if (isset($field['decorators'])) { $output .= $this->addDecorators($field['decorators']); } return $output . ';'; }
php
protected function getItem($field) { $property = $field['field']; // If the field is an array, // make it an array in the Migration if (is_array($property)) { $property = "['". implode("','", $property) ."']"; } else { $property = $property ? "'$property'" : null; } $type = $field['type']; $output = sprintf( "\$table->%s(%s)", $type, $property ); // If we have args, then it needs // to be formatted a bit differently if (isset($field['args'])) { $output = sprintf( "\$table->%s(%s, %s)", $type, $property, $field['args'] ); } if (isset($field['decorators'])) { $output .= $this->addDecorators($field['decorators']); } return $output . ';'; }
[ "protected", "function", "getItem", "(", "$", "field", ")", "{", "$", "property", "=", "$", "field", "[", "'field'", "]", ";", "// If the field is an array,", "// make it an array in the Migration", "if", "(", "is_array", "(", "$", "property", ")", ")", "{", "$", "property", "=", "\"['\"", ".", "implode", "(", "\"','\"", ",", "$", "property", ")", ".", "\"']\"", ";", "}", "else", "{", "$", "property", "=", "$", "property", "?", "\"'$property'\"", ":", "null", ";", "}", "$", "type", "=", "$", "field", "[", "'type'", "]", ";", "$", "output", "=", "sprintf", "(", "\"\\$table->%s(%s)\"", ",", "$", "type", ",", "$", "property", ")", ";", "// If we have args, then it needs", "// to be formatted a bit differently", "if", "(", "isset", "(", "$", "field", "[", "'args'", "]", ")", ")", "{", "$", "output", "=", "sprintf", "(", "\"\\$table->%s(%s, %s)\"", ",", "$", "type", ",", "$", "property", ",", "$", "field", "[", "'args'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "field", "[", "'decorators'", "]", ")", ")", "{", "$", "output", ".=", "$", "this", "->", "addDecorators", "(", "$", "field", "[", "'decorators'", "]", ")", ";", "}", "return", "$", "output", ".", "';'", ";", "}" ]
Return string for adding a column @param array $field @return string
[ "Return", "string", "for", "adding", "a", "column" ]
train
https://github.com/periaptio/empress-generator/blob/749fb4b12755819e9c97377ebfb446ee0822168a/src/Syntax/AddToTable.php#L16-L50
webforge-labs/psc-cms
lib/Psc/URL/Service/Handler.php
Handler.process
public function process(Request $request) { // required $service = $this->getRegisteredService($request->getPart(1)); $call = new Call(mb_strtolower($request->getMethod())); // identifier ist optional if (($identifier = $request->getPart(2)) !== NULL) { $call->addParameter($identifier); /* alle Subs weitergeben als weitere Parameter */ foreach ($request->getPartsFrom(3) as $p) { $call->addParameter($p); } } else { $call->setName('index'); } if ($request->getMethod() === Request::POST || $request->getMethod() === Request::PUT) { $call->addParameter($request->getBody()); } $this->call = $call; $this->service = $service; return $this->call(); }
php
public function process(Request $request) { // required $service = $this->getRegisteredService($request->getPart(1)); $call = new Call(mb_strtolower($request->getMethod())); // identifier ist optional if (($identifier = $request->getPart(2)) !== NULL) { $call->addParameter($identifier); /* alle Subs weitergeben als weitere Parameter */ foreach ($request->getPartsFrom(3) as $p) { $call->addParameter($p); } } else { $call->setName('index'); } if ($request->getMethod() === Request::POST || $request->getMethod() === Request::PUT) { $call->addParameter($request->getBody()); } $this->call = $call; $this->service = $service; return $this->call(); }
[ "public", "function", "process", "(", "Request", "$", "request", ")", "{", "// required", "$", "service", "=", "$", "this", "->", "getRegisteredService", "(", "$", "request", "->", "getPart", "(", "1", ")", ")", ";", "$", "call", "=", "new", "Call", "(", "mb_strtolower", "(", "$", "request", "->", "getMethod", "(", ")", ")", ")", ";", "// identifier ist optional", "if", "(", "(", "$", "identifier", "=", "$", "request", "->", "getPart", "(", "2", ")", ")", "!==", "NULL", ")", "{", "$", "call", "->", "addParameter", "(", "$", "identifier", ")", ";", "/* alle Subs weitergeben als weitere Parameter */", "foreach", "(", "$", "request", "->", "getPartsFrom", "(", "3", ")", "as", "$", "p", ")", "{", "$", "call", "->", "addParameter", "(", "$", "p", ")", ";", "}", "}", "else", "{", "$", "call", "->", "setName", "(", "'index'", ")", ";", "}", "if", "(", "$", "request", "->", "getMethod", "(", ")", "===", "Request", "::", "POST", "||", "$", "request", "->", "getMethod", "(", ")", "===", "Request", "::", "PUT", ")", "{", "$", "call", "->", "addParameter", "(", "$", "request", "->", "getBody", "(", ")", ")", ";", "}", "$", "this", "->", "call", "=", "$", "call", ";", "$", "this", "->", "service", "=", "$", "service", ";", "return", "$", "this", "->", "call", "(", ")", ";", "}" ]
Führt den Request aus Gibt die Ausgabe des Calls vom Controller zurück wenn man den Request nicht selbst erstellen will, kann man \Psc\URL\Service\Request::infer(); benutzen.
[ "Führt", "den", "Request", "aus" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/URL/Service/Handler.php#L47-L72
webforge-labs/psc-cms
lib/Psc/URL/Service/Handler.php
Handler.call
protected function call() { if (isset($this->service) && isset($this->call)) { return $this->service->process($this->call); } }
php
protected function call() { if (isset($this->service) && isset($this->call)) { return $this->service->process($this->call); } }
[ "protected", "function", "call", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "service", ")", "&&", "isset", "(", "$", "this", "->", "call", ")", ")", "{", "return", "$", "this", "->", "service", "->", "process", "(", "$", "this", "->", "call", ")", ";", "}", "}" ]
Gibt die Rückgabe des process() von Controller zurück
[ "Gibt", "die", "Rückgabe", "des", "process", "()", "von", "Controller", "zurück" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/URL/Service/Handler.php#L77-L81
dms-org/package.blog
src/Infrastructure/Persistence/BlogArticleCommentMapper.php
BlogArticleCommentMapper.define
protected function define(MapperDefinition $map) { $map->type(BlogArticleComment::class); $map->toTable('article_comments'); $map->idToPrimaryKey('id'); $map->column($map->getOrm()->getNamespace() . 'article_id')->asUnsignedInt(); $map->relation(BlogArticleComment::ARTICLE) ->to(BlogArticle::class) ->manyToOne() ->withBidirectionalRelation(BlogArticle::COMMENTS) ->withRelatedIdAs($map->getOrm()->getNamespace() . 'article_id'); $map->property(BlogArticleComment::AUTHOR_NAME)->to('author_name')->asVarchar(255); $map->embedded(BlogArticleComment::AUTHOR_EMAIL) ->using(new EmailAddressMapper('author_email')); $map->property(BlogArticleComment::CONTENT)->to('content')->asText(); $map->embedded(BlogArticleComment::POSTED_AT) ->using(new DateTimeMapper('posted_at')); MetadataMapper::mapMetadataToJsonColumn($map, 'metadata'); }
php
protected function define(MapperDefinition $map) { $map->type(BlogArticleComment::class); $map->toTable('article_comments'); $map->idToPrimaryKey('id'); $map->column($map->getOrm()->getNamespace() . 'article_id')->asUnsignedInt(); $map->relation(BlogArticleComment::ARTICLE) ->to(BlogArticle::class) ->manyToOne() ->withBidirectionalRelation(BlogArticle::COMMENTS) ->withRelatedIdAs($map->getOrm()->getNamespace() . 'article_id'); $map->property(BlogArticleComment::AUTHOR_NAME)->to('author_name')->asVarchar(255); $map->embedded(BlogArticleComment::AUTHOR_EMAIL) ->using(new EmailAddressMapper('author_email')); $map->property(BlogArticleComment::CONTENT)->to('content')->asText(); $map->embedded(BlogArticleComment::POSTED_AT) ->using(new DateTimeMapper('posted_at')); MetadataMapper::mapMetadataToJsonColumn($map, 'metadata'); }
[ "protected", "function", "define", "(", "MapperDefinition", "$", "map", ")", "{", "$", "map", "->", "type", "(", "BlogArticleComment", "::", "class", ")", ";", "$", "map", "->", "toTable", "(", "'article_comments'", ")", ";", "$", "map", "->", "idToPrimaryKey", "(", "'id'", ")", ";", "$", "map", "->", "column", "(", "$", "map", "->", "getOrm", "(", ")", "->", "getNamespace", "(", ")", ".", "'article_id'", ")", "->", "asUnsignedInt", "(", ")", ";", "$", "map", "->", "relation", "(", "BlogArticleComment", "::", "ARTICLE", ")", "->", "to", "(", "BlogArticle", "::", "class", ")", "->", "manyToOne", "(", ")", "->", "withBidirectionalRelation", "(", "BlogArticle", "::", "COMMENTS", ")", "->", "withRelatedIdAs", "(", "$", "map", "->", "getOrm", "(", ")", "->", "getNamespace", "(", ")", ".", "'article_id'", ")", ";", "$", "map", "->", "property", "(", "BlogArticleComment", "::", "AUTHOR_NAME", ")", "->", "to", "(", "'author_name'", ")", "->", "asVarchar", "(", "255", ")", ";", "$", "map", "->", "embedded", "(", "BlogArticleComment", "::", "AUTHOR_EMAIL", ")", "->", "using", "(", "new", "EmailAddressMapper", "(", "'author_email'", ")", ")", ";", "$", "map", "->", "property", "(", "BlogArticleComment", "::", "CONTENT", ")", "->", "to", "(", "'content'", ")", "->", "asText", "(", ")", ";", "$", "map", "->", "embedded", "(", "BlogArticleComment", "::", "POSTED_AT", ")", "->", "using", "(", "new", "DateTimeMapper", "(", "'posted_at'", ")", ")", ";", "MetadataMapper", "::", "mapMetadataToJsonColumn", "(", "$", "map", ",", "'metadata'", ")", ";", "}" ]
Defines the entity mapper @param MapperDefinition $map @return void
[ "Defines", "the", "entity", "mapper" ]
train
https://github.com/dms-org/package.blog/blob/1500f6fad20d81289a0dfa617fc1c54699f01e16/src/Infrastructure/Persistence/BlogArticleCommentMapper.php#L38-L64
phpmob/changmin
src/PhpMob/ChangMinBundle/Form/Type/AdminUserType.php
AdminUserType.buildForm
public function buildForm(FormBuilderInterface $builder, array $options): void { parent::buildForm($builder, $options); $builder ->add('localeCode', LocaleType::class, [ 'required' => false, 'label' => 'changmin.form.admin_user.locale_code', ]) ->add('picture', AdminUserPictureType::class, [ 'required' => false, 'label' => 'changmin.form.admin_user.picture', ]) ; }
php
public function buildForm(FormBuilderInterface $builder, array $options): void { parent::buildForm($builder, $options); $builder ->add('localeCode', LocaleType::class, [ 'required' => false, 'label' => 'changmin.form.admin_user.locale_code', ]) ->add('picture', AdminUserPictureType::class, [ 'required' => false, 'label' => 'changmin.form.admin_user.picture', ]) ; }
[ "public", "function", "buildForm", "(", "FormBuilderInterface", "$", "builder", ",", "array", "$", "options", ")", ":", "void", "{", "parent", "::", "buildForm", "(", "$", "builder", ",", "$", "options", ")", ";", "$", "builder", "->", "add", "(", "'localeCode'", ",", "LocaleType", "::", "class", ",", "[", "'required'", "=>", "false", ",", "'label'", "=>", "'changmin.form.admin_user.locale_code'", ",", "]", ")", "->", "add", "(", "'picture'", ",", "AdminUserPictureType", "::", "class", ",", "[", "'required'", "=>", "false", ",", "'label'", "=>", "'changmin.form.admin_user.picture'", ",", "]", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/phpmob/changmin/blob/bfebb1561229094d1c138574abab75f2f1d17d66/src/PhpMob/ChangMinBundle/Form/Type/AdminUserType.php#L26-L40
slashworks/control-bundle
src/Slashworks/BackendBundle/Controller/SecurityController.php
SecurityController.loginAction
public function loginAction(Request $request) { if ($this->container->getParameter('database_password') === null) { return $this->redirect($this->generateUrl('install_license')); } else { $request = $this->getRequest(); $session = $request->getSession(); // get the login error if there is one if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) { $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR); } else { $error = $session->get(SecurityContext::AUTHENTICATION_ERROR); } return $this->render('SlashworksBackendBundle:Security:login.html.twig', array( 'last_username' => $session->get(SecurityContext::LAST_USERNAME), 'error' => $error, )); } }
php
public function loginAction(Request $request) { if ($this->container->getParameter('database_password') === null) { return $this->redirect($this->generateUrl('install_license')); } else { $request = $this->getRequest(); $session = $request->getSession(); // get the login error if there is one if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) { $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR); } else { $error = $session->get(SecurityContext::AUTHENTICATION_ERROR); } return $this->render('SlashworksBackendBundle:Security:login.html.twig', array( 'last_username' => $session->get(SecurityContext::LAST_USERNAME), 'error' => $error, )); } }
[ "public", "function", "loginAction", "(", "Request", "$", "request", ")", "{", "if", "(", "$", "this", "->", "container", "->", "getParameter", "(", "'database_password'", ")", "===", "null", ")", "{", "return", "$", "this", "->", "redirect", "(", "$", "this", "->", "generateUrl", "(", "'install_license'", ")", ")", ";", "}", "else", "{", "$", "request", "=", "$", "this", "->", "getRequest", "(", ")", ";", "$", "session", "=", "$", "request", "->", "getSession", "(", ")", ";", "// get the login error if there is one", "if", "(", "$", "request", "->", "attributes", "->", "has", "(", "SecurityContext", "::", "AUTHENTICATION_ERROR", ")", ")", "{", "$", "error", "=", "$", "request", "->", "attributes", "->", "get", "(", "SecurityContext", "::", "AUTHENTICATION_ERROR", ")", ";", "}", "else", "{", "$", "error", "=", "$", "session", "->", "get", "(", "SecurityContext", "::", "AUTHENTICATION_ERROR", ")", ";", "}", "return", "$", "this", "->", "render", "(", "'SlashworksBackendBundle:Security:login.html.twig'", ",", "array", "(", "'last_username'", "=>", "$", "session", "->", "get", "(", "SecurityContext", "::", "LAST_USERNAME", ")", ",", "'error'", "=>", "$", "error", ",", ")", ")", ";", "}", "}" ]
@param \Symfony\Component\HttpFoundation\Request $request @return \Symfony\Component\HttpFoundation\Response
[ "@param", "\\", "Symfony", "\\", "Component", "\\", "HttpFoundation", "\\", "Request", "$request" ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/BackendBundle/Controller/SecurityController.php#L41-L63
ClanCats/Core
src/bundles/UI/Builder/Bootstrap.php
Builder_Bootstrap.build_alert
public function build_alert( $alerts ) { return HTML::tag( 'div', function() use( $alerts ) { // loop trough all alert types foreach( $alerts as $type => $items ) { foreach( $items as $alert ) { $alert = implode( "<br>\n", $alert ); // close button $close = HTML::tag( 'button', '&times;' ) ->add_class( 'close' ) ->type( 'button' ) ->data( 'dismiss', 'alert' ); // alert div echo HTML::tag( 'div', $close.$alert ) ->add_class( 'alert fade in' ) ->add_class( 'alert-'.$type ); } } })->add_class( 'ui-alert-container' ); }
php
public function build_alert( $alerts ) { return HTML::tag( 'div', function() use( $alerts ) { // loop trough all alert types foreach( $alerts as $type => $items ) { foreach( $items as $alert ) { $alert = implode( "<br>\n", $alert ); // close button $close = HTML::tag( 'button', '&times;' ) ->add_class( 'close' ) ->type( 'button' ) ->data( 'dismiss', 'alert' ); // alert div echo HTML::tag( 'div', $close.$alert ) ->add_class( 'alert fade in' ) ->add_class( 'alert-'.$type ); } } })->add_class( 'ui-alert-container' ); }
[ "public", "function", "build_alert", "(", "$", "alerts", ")", "{", "return", "HTML", "::", "tag", "(", "'div'", ",", "function", "(", ")", "use", "(", "$", "alerts", ")", "{", "// loop trough all alert types", "foreach", "(", "$", "alerts", "as", "$", "type", "=>", "$", "items", ")", "{", "foreach", "(", "$", "items", "as", "$", "alert", ")", "{", "$", "alert", "=", "implode", "(", "\"<br>\\n\"", ",", "$", "alert", ")", ";", "// close button", "$", "close", "=", "HTML", "::", "tag", "(", "'button'", ",", "'&times;'", ")", "->", "add_class", "(", "'close'", ")", "->", "type", "(", "'button'", ")", "->", "data", "(", "'dismiss'", ",", "'alert'", ")", ";", "// alert div", "echo", "HTML", "::", "tag", "(", "'div'", ",", "$", "close", ".", "$", "alert", ")", "->", "add_class", "(", "'alert fade in'", ")", "->", "add_class", "(", "'alert-'", ".", "$", "type", ")", ";", "}", "}", "}", ")", "->", "add_class", "(", "'ui-alert-container'", ")", ";", "}" ]
Build the UI alerts @param array $alerts @return UI\HTML
[ "Build", "the", "UI", "alerts" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/bundles/UI/Builder/Bootstrap.php#L74-L98
fyuze/framework
src/Fyuze/Kernel/Services/Database.php
Database.services
public function services() { $this->registry->add('db', function () { $config = $this->registry->make('config')->get('database'); $default = $config['connections'][$config['default']]; return new Db(Factory::create(array_merge($default, ['fetch' => $config['fetch']]))); }); }
php
public function services() { $this->registry->add('db', function () { $config = $this->registry->make('config')->get('database'); $default = $config['connections'][$config['default']]; return new Db(Factory::create(array_merge($default, ['fetch' => $config['fetch']]))); }); }
[ "public", "function", "services", "(", ")", "{", "$", "this", "->", "registry", "->", "add", "(", "'db'", ",", "function", "(", ")", "{", "$", "config", "=", "$", "this", "->", "registry", "->", "make", "(", "'config'", ")", "->", "get", "(", "'database'", ")", ";", "$", "default", "=", "$", "config", "[", "'connections'", "]", "[", "$", "config", "[", "'default'", "]", "]", ";", "return", "new", "Db", "(", "Factory", "::", "create", "(", "array_merge", "(", "$", "default", ",", "[", "'fetch'", "=>", "$", "config", "[", "'fetch'", "]", "]", ")", ")", ")", ";", "}", ")", ";", "}" ]
Database services
[ "Database", "services" ]
train
https://github.com/fyuze/framework/blob/89b3984f7225e24bfcdafb090ee197275b3222c9/src/Fyuze/Kernel/Services/Database.php#L13-L23
SergioMadness/taxes-laravel
src/services/TaxFacade.php
TaxFacade.setCurrentDriver
public function setCurrentDriver(string $name): ITaxFacade { $this->currentDriverName = $name; $this->makeCurrentDriver($name); return $this; }
php
public function setCurrentDriver(string $name): ITaxFacade { $this->currentDriverName = $name; $this->makeCurrentDriver($name); return $this; }
[ "public", "function", "setCurrentDriver", "(", "string", "$", "name", ")", ":", "ITaxFacade", "{", "$", "this", "->", "currentDriverName", "=", "$", "name", ";", "$", "this", "->", "makeCurrentDriver", "(", "$", "name", ")", ";", "return", "$", "this", ";", "}" ]
Set current driver @param string $name @return ITaxFacade
[ "Set", "current", "driver" ]
train
https://github.com/SergioMadness/taxes-laravel/blob/ca33644d924700e858ecbfcf3c311bac7d3ffd26/src/services/TaxFacade.php#L41-L48
SergioMadness/taxes-laravel
src/services/TaxFacade.php
TaxFacade.makeCurrentDriver
protected function makeCurrentDriver(string $name): ITaxFacade { $this->currentDriver = app($this->getDriver($name), [ 'config' => config('taxes.' . $name), ]); return $this; }
php
protected function makeCurrentDriver(string $name): ITaxFacade { $this->currentDriver = app($this->getDriver($name), [ 'config' => config('taxes.' . $name), ]); return $this; }
[ "protected", "function", "makeCurrentDriver", "(", "string", "$", "name", ")", ":", "ITaxFacade", "{", "$", "this", "->", "currentDriver", "=", "app", "(", "$", "this", "->", "getDriver", "(", "$", "name", ")", ",", "[", "'config'", "=>", "config", "(", "'taxes.'", ".", "$", "name", ")", ",", "]", ")", ";", "return", "$", "this", ";", "}" ]
Build driver @param string $name @return $this
[ "Build", "driver" ]
train
https://github.com/SergioMadness/taxes-laravel/blob/ca33644d924700e858ecbfcf3c311bac7d3ffd26/src/services/TaxFacade.php#L57-L64
SergioMadness/taxes-laravel
src/services/TaxFacade.php
TaxFacade.registerDriver
public function registerDriver(string $alias, string $className): ITaxFacade { $this->drivers[$alias] = $className; return $this; }
php
public function registerDriver(string $alias, string $className): ITaxFacade { $this->drivers[$alias] = $className; return $this; }
[ "public", "function", "registerDriver", "(", "string", "$", "alias", ",", "string", "$", "className", ")", ":", "ITaxFacade", "{", "$", "this", "->", "drivers", "[", "$", "alias", "]", "=", "$", "className", ";", "return", "$", "this", ";", "}" ]
Register driver @param string $alias @param string $className @return ITaxFacade
[ "Register", "driver" ]
train
https://github.com/SergioMadness/taxes-laravel/blob/ca33644d924700e858ecbfcf3c311bac7d3ffd26/src/services/TaxFacade.php#L116-L121
SergioMadness/taxes-laravel
src/services/TaxFacade.php
TaxFacade.driverInstance
public function driverInstance(string $driver): ?ITaxFacade { if (($driverClass = $this->getDriver($driver)) !== null) { return app($driverClass, [ 'config' => config('taxes.' . $driverClass), ]); } return null; }
php
public function driverInstance(string $driver): ?ITaxFacade { if (($driverClass = $this->getDriver($driver)) !== null) { return app($driverClass, [ 'config' => config('taxes.' . $driverClass), ]); } return null; }
[ "public", "function", "driverInstance", "(", "string", "$", "driver", ")", ":", "?", "ITaxFacade", "{", "if", "(", "(", "$", "driverClass", "=", "$", "this", "->", "getDriver", "(", "$", "driver", ")", ")", "!==", "null", ")", "{", "return", "app", "(", "$", "driverClass", ",", "[", "'config'", "=>", "config", "(", "'taxes.'", ".", "$", "driverClass", ")", ",", "]", ")", ";", "}", "return", "null", ";", "}" ]
Build driver by name @param string $driver @return null|ITaxFacade
[ "Build", "driver", "by", "name" ]
train
https://github.com/SergioMadness/taxes-laravel/blob/ca33644d924700e858ecbfcf3c311bac7d3ffd26/src/services/TaxFacade.php#L140-L149
SergioMadness/taxes-laravel
src/services/TaxFacade.php
TaxFacade.sendReceipt
public function sendReceipt(Receipt $receipt) { $driver = $this->getCurrentDriver(); return $driver !== null ? $driver->sendReceipt($receipt) : null; }
php
public function sendReceipt(Receipt $receipt) { $driver = $this->getCurrentDriver(); return $driver !== null ? $driver->sendReceipt($receipt) : null; }
[ "public", "function", "sendReceipt", "(", "Receipt", "$", "receipt", ")", "{", "$", "driver", "=", "$", "this", "->", "getCurrentDriver", "(", ")", ";", "return", "$", "driver", "!==", "null", "?", "$", "driver", "->", "sendReceipt", "(", "$", "receipt", ")", ":", "null", ";", "}" ]
Send receipt @param Receipt $receipt @return mixed
[ "Send", "receipt" ]
train
https://github.com/SergioMadness/taxes-laravel/blob/ca33644d924700e858ecbfcf3c311bac7d3ffd26/src/services/TaxFacade.php#L158-L163
nyeholt/silverstripe-external-content
thirdparty/Zend/Validate/File/MimeType.php
Zend_Validate_File_MimeType.setMagicFile
public function setMagicFile($file) { if (empty($file)) { $this->_magicfile = null; } else if (!is_readable($file)) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('The given magicfile can not be read'); } else { $this->_magicfile = (string) $file; } return $this; }
php
public function setMagicFile($file) { if (empty($file)) { $this->_magicfile = null; } else if (!is_readable($file)) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('The given magicfile can not be read'); } else { $this->_magicfile = (string) $file; } return $this; }
[ "public", "function", "setMagicFile", "(", "$", "file", ")", "{", "if", "(", "empty", "(", "$", "file", ")", ")", "{", "$", "this", "->", "_magicfile", "=", "null", ";", "}", "else", "if", "(", "!", "is_readable", "(", "$", "file", ")", ")", "{", "require_once", "'Zend/Validate/Exception.php'", ";", "throw", "new", "Zend_Validate_Exception", "(", "'The given magicfile can not be read'", ")", ";", "}", "else", "{", "$", "this", "->", "_magicfile", "=", "(", "string", ")", "$", "file", ";", "}", "return", "$", "this", ";", "}" ]
Sets the magicfile to use if null, the MAGIC constant from php is used @param string $file @return Zend_Validate_File_MimeType Provides fluid interface
[ "Sets", "the", "magicfile", "to", "use", "if", "null", "the", "MAGIC", "constant", "from", "php", "is", "used" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Validate/File/MimeType.php#L125-L137
steeffeen/FancyManiaLinks
FML/Elements/TemplateScript.php
TemplateScript.getScriptText
public function getScriptText($parameters = null) { if (!$parameters) { $parameters = $this->parameters; } ob_start(); include $this->filePath; $scriptText = ob_get_contents(); ob_end_clean(); return $scriptText; }
php
public function getScriptText($parameters = null) { if (!$parameters) { $parameters = $this->parameters; } ob_start(); include $this->filePath; $scriptText = ob_get_contents(); ob_end_clean(); return $scriptText; }
[ "public", "function", "getScriptText", "(", "$", "parameters", "=", "null", ")", "{", "if", "(", "!", "$", "parameters", ")", "{", "$", "parameters", "=", "$", "this", "->", "parameters", ";", "}", "ob_start", "(", ")", ";", "include", "$", "this", "->", "filePath", ";", "$", "scriptText", "=", "ob_get_contents", "(", ")", ";", "ob_end_clean", "(", ")", ";", "return", "$", "scriptText", ";", "}" ]
Get the compiled script text @param mixed $parameters (optional) Parameters @return string
[ "Get", "the", "compiled", "script", "text" ]
train
https://github.com/steeffeen/FancyManiaLinks/blob/227b0759306f0a3c75873ba50276e4163a93bfa6/FML/Elements/TemplateScript.php#L111-L126
teneleven/GeolocatorBundle
Provider/LocationProvider.php
LocationProvider.findLocations
public function findLocations(Form $form) { $searchCenter = $form->get('location')->getData(); $results = $this->getQueryBuilder($searchCenter) ->orderBy('distance') ->getQuery() ->execute(); return $this->decorateResults($searchCenter, $results); }
php
public function findLocations(Form $form) { $searchCenter = $form->get('location')->getData(); $results = $this->getQueryBuilder($searchCenter) ->orderBy('distance') ->getQuery() ->execute(); return $this->decorateResults($searchCenter, $results); }
[ "public", "function", "findLocations", "(", "Form", "$", "form", ")", "{", "$", "searchCenter", "=", "$", "form", "->", "get", "(", "'location'", ")", "->", "getData", "(", ")", ";", "$", "results", "=", "$", "this", "->", "getQueryBuilder", "(", "$", "searchCenter", ")", "->", "orderBy", "(", "'distance'", ")", "->", "getQuery", "(", ")", "->", "execute", "(", ")", ";", "return", "$", "this", "->", "decorateResults", "(", "$", "searchCenter", ",", "$", "results", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/teneleven/GeolocatorBundle/blob/4ead8e783a91577f2a67aa302b79641d4b9e99ad/Provider/LocationProvider.php#L62-L72
teneleven/GeolocatorBundle
Provider/LocationProvider.php
LocationProvider.decorateResults
protected function decorateResults(Coordinates $searchCenter, array $results) { $search = new Search(); $search->setCenter($searchCenter); foreach ($results as $result) { $distanceInMiles = UnitConverter::kmToMiles($result['distance']); $search->addResult(new Result($result[0], $distanceInMiles)); } return $search; }
php
protected function decorateResults(Coordinates $searchCenter, array $results) { $search = new Search(); $search->setCenter($searchCenter); foreach ($results as $result) { $distanceInMiles = UnitConverter::kmToMiles($result['distance']); $search->addResult(new Result($result[0], $distanceInMiles)); } return $search; }
[ "protected", "function", "decorateResults", "(", "Coordinates", "$", "searchCenter", ",", "array", "$", "results", ")", "{", "$", "search", "=", "new", "Search", "(", ")", ";", "$", "search", "->", "setCenter", "(", "$", "searchCenter", ")", ";", "foreach", "(", "$", "results", "as", "$", "result", ")", "{", "$", "distanceInMiles", "=", "UnitConverter", "::", "kmToMiles", "(", "$", "result", "[", "'distance'", "]", ")", ";", "$", "search", "->", "addResult", "(", "new", "Result", "(", "$", "result", "[", "0", "]", ",", "$", "distanceInMiles", ")", ")", ";", "}", "return", "$", "search", ";", "}" ]
Helper method to decorate search results @param Coordinates $searchCenter @param array $results @return Search
[ "Helper", "method", "to", "decorate", "search", "results" ]
train
https://github.com/teneleven/GeolocatorBundle/blob/4ead8e783a91577f2a67aa302b79641d4b9e99ad/Provider/LocationProvider.php#L110-L121
PeekAndPoke/psi
src/Operation/Terminal/GetRandomOperation.php
GetRandomOperation.apply
public function apply(\Iterator $set) { $data = array_values(iterator_to_array($set)); $count = count($data); if ($count === 0) { return $this->default; } return $data[mt_rand(0, $count - 1)]; }
php
public function apply(\Iterator $set) { $data = array_values(iterator_to_array($set)); $count = count($data); if ($count === 0) { return $this->default; } return $data[mt_rand(0, $count - 1)]; }
[ "public", "function", "apply", "(", "\\", "Iterator", "$", "set", ")", "{", "$", "data", "=", "array_values", "(", "iterator_to_array", "(", "$", "set", ")", ")", ";", "$", "count", "=", "count", "(", "$", "data", ")", ";", "if", "(", "$", "count", "===", "0", ")", "{", "return", "$", "this", "->", "default", ";", "}", "return", "$", "data", "[", "mt_rand", "(", "0", ",", "$", "count", "-", "1", ")", "]", ";", "}" ]
@param \Iterator $set @return mixed
[ "@param", "\\", "Iterator", "$set" ]
train
https://github.com/PeekAndPoke/psi/blob/cfd45d995d3a2c2ea6ba5b1ce7b5fcc71179456f/src/Operation/Terminal/GetRandomOperation.php#L35-L45
CakeCMS/Core
src/Nav.php
Nav.activeMenu
public static function activeMenu($menu = null) { if ($menu === null) { $activeMenu = self::$_activeMenu; } else { $activeMenu = $menu; } if (!array_key_exists($activeMenu, self::$_items)) { self::$_items[$activeMenu] = []; } self::$_activeMenu = $activeMenu; return $activeMenu; }
php
public static function activeMenu($menu = null) { if ($menu === null) { $activeMenu = self::$_activeMenu; } else { $activeMenu = $menu; } if (!array_key_exists($activeMenu, self::$_items)) { self::$_items[$activeMenu] = []; } self::$_activeMenu = $activeMenu; return $activeMenu; }
[ "public", "static", "function", "activeMenu", "(", "$", "menu", "=", "null", ")", "{", "if", "(", "$", "menu", "===", "null", ")", "{", "$", "activeMenu", "=", "self", "::", "$", "_activeMenu", ";", "}", "else", "{", "$", "activeMenu", "=", "$", "menu", ";", "}", "if", "(", "!", "array_key_exists", "(", "$", "activeMenu", ",", "self", "::", "$", "_items", ")", ")", "{", "self", "::", "$", "_items", "[", "$", "activeMenu", "]", "=", "[", "]", ";", "}", "self", "::", "$", "_activeMenu", "=", "$", "activeMenu", ";", "return", "$", "activeMenu", ";", "}" ]
Getter/setter for activeMenu @param null $menu @return null|string
[ "Getter", "/", "setter", "for", "activeMenu" ]
train
https://github.com/CakeCMS/Core/blob/f9cba7aa0043a10e5c35bd45fbad158688a09a96/src/Nav.php#L67-L81
CakeCMS/Core
src/Nav.php
Nav.add
public static function add($menu, $path, $options = []) { // Juggle argument for backward compatibility if (is_array($path)) { $options = $path; $path = $menu; $menu = self::activeMenu(); } else { self::activeMenu($menu); } $pathE = explode('.', $path); $pathE = array_splice($pathE, 0, count($pathE) - 2); $parent = join('.', $pathE); if (!empty($parent) && !Hash::check(self::$_items[$menu], $parent)) { $title = Inflector::humanize(end($pathE)); $opt = ['title' => $title]; self::_setupOptions($opt); self::add($parent, $opt); } self::_setupOptions($options); $current = Hash::extract(self::$_items[$menu], $path); if (!empty($current)) { self::_replace(self::$_items[$menu], $path, $options); } else { self::$_items[$menu] = Hash::insert(self::$_items[$menu], $path, $options); } }
php
public static function add($menu, $path, $options = []) { // Juggle argument for backward compatibility if (is_array($path)) { $options = $path; $path = $menu; $menu = self::activeMenu(); } else { self::activeMenu($menu); } $pathE = explode('.', $path); $pathE = array_splice($pathE, 0, count($pathE) - 2); $parent = join('.', $pathE); if (!empty($parent) && !Hash::check(self::$_items[$menu], $parent)) { $title = Inflector::humanize(end($pathE)); $opt = ['title' => $title]; self::_setupOptions($opt); self::add($parent, $opt); } self::_setupOptions($options); $current = Hash::extract(self::$_items[$menu], $path); if (!empty($current)) { self::_replace(self::$_items[$menu], $path, $options); } else { self::$_items[$menu] = Hash::insert(self::$_items[$menu], $path, $options); } }
[ "public", "static", "function", "add", "(", "$", "menu", ",", "$", "path", ",", "$", "options", "=", "[", "]", ")", "{", "// Juggle argument for backward compatibility", "if", "(", "is_array", "(", "$", "path", ")", ")", "{", "$", "options", "=", "$", "path", ";", "$", "path", "=", "$", "menu", ";", "$", "menu", "=", "self", "::", "activeMenu", "(", ")", ";", "}", "else", "{", "self", "::", "activeMenu", "(", "$", "menu", ")", ";", "}", "$", "pathE", "=", "explode", "(", "'.'", ",", "$", "path", ")", ";", "$", "pathE", "=", "array_splice", "(", "$", "pathE", ",", "0", ",", "count", "(", "$", "pathE", ")", "-", "2", ")", ";", "$", "parent", "=", "join", "(", "'.'", ",", "$", "pathE", ")", ";", "if", "(", "!", "empty", "(", "$", "parent", ")", "&&", "!", "Hash", "::", "check", "(", "self", "::", "$", "_items", "[", "$", "menu", "]", ",", "$", "parent", ")", ")", "{", "$", "title", "=", "Inflector", "::", "humanize", "(", "end", "(", "$", "pathE", ")", ")", ";", "$", "opt", "=", "[", "'title'", "=>", "$", "title", "]", ";", "self", "::", "_setupOptions", "(", "$", "opt", ")", ";", "self", "::", "add", "(", "$", "parent", ",", "$", "opt", ")", ";", "}", "self", "::", "_setupOptions", "(", "$", "options", ")", ";", "$", "current", "=", "Hash", "::", "extract", "(", "self", "::", "$", "_items", "[", "$", "menu", "]", ",", "$", "path", ")", ";", "if", "(", "!", "empty", "(", "$", "current", ")", ")", "{", "self", "::", "_replace", "(", "self", "::", "$", "_items", "[", "$", "menu", "]", ",", "$", "path", ",", "$", "options", ")", ";", "}", "else", "{", "self", "::", "$", "_items", "[", "$", "menu", "]", "=", "Hash", "::", "insert", "(", "self", "::", "$", "_items", "[", "$", "menu", "]", ",", "$", "path", ",", "$", "options", ")", ";", "}", "}" ]
Add a menu item. @param $menu @param $path @param array $options
[ "Add", "a", "menu", "item", "." ]
train
https://github.com/CakeCMS/Core/blob/f9cba7aa0043a10e5c35bd45fbad158688a09a96/src/Nav.php#L90-L120
CakeCMS/Core
src/Nav.php
Nav.items
public static function items($menu = 'sidebar', $items = null) { if (!is_string($menu)) { throw new \UnexpectedValueException('Menu id is not a string'); } if (!empty($items)) { self::$_items[$menu] = $items; } if (!array_key_exists($menu, self::$_items)) { Log::error('Invalid menu: ' . $menu); return []; } return self::$_items[$menu]; }
php
public static function items($menu = 'sidebar', $items = null) { if (!is_string($menu)) { throw new \UnexpectedValueException('Menu id is not a string'); } if (!empty($items)) { self::$_items[$menu] = $items; } if (!array_key_exists($menu, self::$_items)) { Log::error('Invalid menu: ' . $menu); return []; } return self::$_items[$menu]; }
[ "public", "static", "function", "items", "(", "$", "menu", "=", "'sidebar'", ",", "$", "items", "=", "null", ")", "{", "if", "(", "!", "is_string", "(", "$", "menu", ")", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "'Menu id is not a string'", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "items", ")", ")", "{", "self", "::", "$", "_items", "[", "$", "menu", "]", "=", "$", "items", ";", "}", "if", "(", "!", "array_key_exists", "(", "$", "menu", ",", "self", "::", "$", "_items", ")", ")", "{", "Log", "::", "error", "(", "'Invalid menu: '", ".", "$", "menu", ")", ";", "return", "[", "]", ";", "}", "return", "self", "::", "$", "_items", "[", "$", "menu", "]", ";", "}" ]
Sets or returns menu data in array. @param string $menu @param null $items @return array
[ "Sets", "or", "returns", "menu", "data", "in", "array", "." ]
train
https://github.com/CakeCMS/Core/blob/f9cba7aa0043a10e5c35bd45fbad158688a09a96/src/Nav.php#L154-L170
CakeCMS/Core
src/Nav.php
Nav._clear
protected static function _clear($menu) { if (array_key_exists($menu, self::$_items)) { self::$_items[$menu] = []; } else { throw new \UnexpectedValueException('Invalid menu: ' . $menu); } }
php
protected static function _clear($menu) { if (array_key_exists($menu, self::$_items)) { self::$_items[$menu] = []; } else { throw new \UnexpectedValueException('Invalid menu: ' . $menu); } }
[ "protected", "static", "function", "_clear", "(", "$", "menu", ")", "{", "if", "(", "array_key_exists", "(", "$", "menu", ",", "self", "::", "$", "_items", ")", ")", "{", "self", "::", "$", "_items", "[", "$", "menu", "]", "=", "[", "]", ";", "}", "else", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "'Invalid menu: '", ".", "$", "menu", ")", ";", "}", "}" ]
Clear menu items. @param $menu @throws \UnexpectedValueException
[ "Clear", "menu", "items", "." ]
train
https://github.com/CakeCMS/Core/blob/f9cba7aa0043a10e5c35bd45fbad158688a09a96/src/Nav.php#L199-L206
CakeCMS/Core
src/Nav.php
Nav._merge
protected static function _merge($firstArray, $secondArray) { $merged = Hash::merge($firstArray, $secondArray); foreach ($merged as $key => $val) { if (is_array($val) && is_int(key($val))) { $merged[$key] = array_unique($val); } } return $merged; }
php
protected static function _merge($firstArray, $secondArray) { $merged = Hash::merge($firstArray, $secondArray); foreach ($merged as $key => $val) { if (is_array($val) && is_int(key($val))) { $merged[$key] = array_unique($val); } } return $merged; }
[ "protected", "static", "function", "_merge", "(", "$", "firstArray", ",", "$", "secondArray", ")", "{", "$", "merged", "=", "Hash", "::", "merge", "(", "$", "firstArray", ",", "$", "secondArray", ")", ";", "foreach", "(", "$", "merged", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "is_array", "(", "$", "val", ")", "&&", "is_int", "(", "key", "(", "$", "val", ")", ")", ")", "{", "$", "merged", "[", "$", "key", "]", "=", "array_unique", "(", "$", "val", ")", ";", "}", "}", "return", "$", "merged", ";", "}" ]
Merge $firstArray with $secondArray. Similar to Hash::merge, except duplicates are removed @param array $firstArray @param array $secondArray @return array
[ "Merge", "$firstArray", "with", "$secondArray", "." ]
train
https://github.com/CakeCMS/Core/blob/f9cba7aa0043a10e5c35bd45fbad158688a09a96/src/Nav.php#L216-L225
CakeCMS/Core
src/Nav.php
Nav._replace
protected static function _replace(&$target, $path, $options) { $pathE = explode('.', $path); $path = array_shift($pathE); $fragment = join('.', $pathE); if (!empty($pathE)) { self::_replace($target[$path], $fragment, $options); } else { $target[$path] = self::_merge($target[$path], $options); } }
php
protected static function _replace(&$target, $path, $options) { $pathE = explode('.', $path); $path = array_shift($pathE); $fragment = join('.', $pathE); if (!empty($pathE)) { self::_replace($target[$path], $fragment, $options); } else { $target[$path] = self::_merge($target[$path], $options); } }
[ "protected", "static", "function", "_replace", "(", "&", "$", "target", ",", "$", "path", ",", "$", "options", ")", "{", "$", "pathE", "=", "explode", "(", "'.'", ",", "$", "path", ")", ";", "$", "path", "=", "array_shift", "(", "$", "pathE", ")", ";", "$", "fragment", "=", "join", "(", "'.'", ",", "$", "pathE", ")", ";", "if", "(", "!", "empty", "(", "$", "pathE", ")", ")", "{", "self", "::", "_replace", "(", "$", "target", "[", "$", "path", "]", ",", "$", "fragment", ",", "$", "options", ")", ";", "}", "else", "{", "$", "target", "[", "$", "path", "]", "=", "self", "::", "_merge", "(", "$", "target", "[", "$", "path", "]", ",", "$", "options", ")", ";", "}", "}" ]
Replace a menu element. @param array $target pointer to start of array @param string $path path to search for in dot separated format @param array $options data to replace with @return void
[ "Replace", "a", "menu", "element", "." ]
train
https://github.com/CakeCMS/Core/blob/f9cba7aa0043a10e5c35bd45fbad158688a09a96/src/Nav.php#L235-L246
CakeCMS/Core
src/Nav.php
Nav._setupOptions
protected static function _setupOptions(&$options) { $options = self::_merge(self::$_defaults, $options); foreach ($options['children'] as &$child) { self::_setupOptions($child); } }
php
protected static function _setupOptions(&$options) { $options = self::_merge(self::$_defaults, $options); foreach ($options['children'] as &$child) { self::_setupOptions($child); } }
[ "protected", "static", "function", "_setupOptions", "(", "&", "$", "options", ")", "{", "$", "options", "=", "self", "::", "_merge", "(", "self", "::", "$", "_defaults", ",", "$", "options", ")", ";", "foreach", "(", "$", "options", "[", "'children'", "]", "as", "&", "$", "child", ")", "{", "self", "::", "_setupOptions", "(", "$", "child", ")", ";", "}", "}" ]
Setup options. @param array $options @return void
[ "Setup", "options", "." ]
train
https://github.com/CakeCMS/Core/blob/f9cba7aa0043a10e5c35bd45fbad158688a09a96/src/Nav.php#L254-L260
ClanCats/Core
src/classes/CCCli.php
CCCli.write
public static function write( $str, $color = null, $background = null ) { if ( !is_null( $color ) ) { $str = static::color( $str, $color, $background ); } fwrite( STDOUT, $str ); }
php
public static function write( $str, $color = null, $background = null ) { if ( !is_null( $color ) ) { $str = static::color( $str, $color, $background ); } fwrite( STDOUT, $str ); }
[ "public", "static", "function", "write", "(", "$", "str", ",", "$", "color", "=", "null", ",", "$", "background", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "color", ")", ")", "{", "$", "str", "=", "static", "::", "color", "(", "$", "str", ",", "$", "color", ",", "$", "background", ")", ";", "}", "fwrite", "(", "STDOUT", ",", "$", "str", ")", ";", "}" ]
Write to the standard output device @param string $str @return void
[ "Write", "to", "the", "standard", "output", "device" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCCli.php#L80-L88
ClanCats/Core
src/classes/CCCli.php
CCCli.line
public static function line( $str, $color = null, $background = null ) { if ( is_array( $str ) ) { $str = implode( PHP_EOL, $str ); } static::write( $str.PHP_EOL, $color, $background ); }
php
public static function line( $str, $color = null, $background = null ) { if ( is_array( $str ) ) { $str = implode( PHP_EOL, $str ); } static::write( $str.PHP_EOL, $color, $background ); }
[ "public", "static", "function", "line", "(", "$", "str", ",", "$", "color", "=", "null", ",", "$", "background", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "str", ")", ")", "{", "$", "str", "=", "implode", "(", "PHP_EOL", ",", "$", "str", ")", ";", "}", "static", "::", "write", "(", "$", "str", ".", "PHP_EOL", ",", "$", "color", ",", "$", "background", ")", ";", "}" ]
Write to the standard output device with an end of line. @param string $str @return void
[ "Write", "to", "the", "standard", "output", "device", "with", "an", "end", "of", "line", "." ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCCli.php#L96-L104
ClanCats/Core
src/classes/CCCli.php
CCCli.color
public static function color( $str, $color, $background = null ) { // ANSI escape codes are not available on Windows CMD // So we return the string unmodified if ( static::is_windows() ) { return $str; } $out = "\033[".static::$colors[$color]."m"; if ( !is_null( $background ) ) { $out .= "\033[".static::$background_colors[$background]."m"; } return $out.$str."\033[0m"; }
php
public static function color( $str, $color, $background = null ) { // ANSI escape codes are not available on Windows CMD // So we return the string unmodified if ( static::is_windows() ) { return $str; } $out = "\033[".static::$colors[$color]."m"; if ( !is_null( $background ) ) { $out .= "\033[".static::$background_colors[$background]."m"; } return $out.$str."\033[0m"; }
[ "public", "static", "function", "color", "(", "$", "str", ",", "$", "color", ",", "$", "background", "=", "null", ")", "{", "// ANSI escape codes are not available on Windows CMD", "// So we return the string unmodified", "if", "(", "static", "::", "is_windows", "(", ")", ")", "{", "return", "$", "str", ";", "}", "$", "out", "=", "\"\\033[\"", ".", "static", "::", "$", "colors", "[", "$", "color", "]", ".", "\"m\"", ";", "if", "(", "!", "is_null", "(", "$", "background", ")", ")", "{", "$", "out", ".=", "\"\\033[\"", ".", "static", "::", "$", "background_colors", "[", "$", "background", "]", ".", "\"m\"", ";", "}", "return", "$", "out", ".", "$", "str", ".", "\"\\033[0m\"", ";", "}" ]
Add color to string Check the available colors at the top $colors & $background_colors @param string $str @param string $color @param string $background @return string
[ "Add", "color", "to", "string", "Check", "the", "available", "colors", "at", "the", "top", "$colors", "&", "$background_colors" ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCCli.php#L177-L194
ClanCats/Core
src/classes/CCCli.php
CCCli.confirm
public static function confirm( $question, $strict = false ) { $question .= ' [yes/no]: '; if ( $strict ) { do { $res = strtolower( static::read( $question ) ); } while ( $res !== 'yes' && $res !== 'no' ); return ( $res == 'yes' ) ? true : false; } do { $res = strtolower( static::read( $question ) ); } while ( empty( $res ) ); $positives = array( 'yes', 'y', 'ya', 'ye', 'yeah', 'yup', 'jep', 'jap', 'ja', 'si', 'sim', 'true', 'hai', 'oui', 'no problemo', ); return in_array( $res, $positives ); }
php
public static function confirm( $question, $strict = false ) { $question .= ' [yes/no]: '; if ( $strict ) { do { $res = strtolower( static::read( $question ) ); } while ( $res !== 'yes' && $res !== 'no' ); return ( $res == 'yes' ) ? true : false; } do { $res = strtolower( static::read( $question ) ); } while ( empty( $res ) ); $positives = array( 'yes', 'y', 'ya', 'ye', 'yeah', 'yup', 'jep', 'jap', 'ja', 'si', 'sim', 'true', 'hai', 'oui', 'no problemo', ); return in_array( $res, $positives ); }
[ "public", "static", "function", "confirm", "(", "$", "question", ",", "$", "strict", "=", "false", ")", "{", "$", "question", ".=", "' [yes/no]: '", ";", "if", "(", "$", "strict", ")", "{", "do", "{", "$", "res", "=", "strtolower", "(", "static", "::", "read", "(", "$", "question", ")", ")", ";", "}", "while", "(", "$", "res", "!==", "'yes'", "&&", "$", "res", "!==", "'no'", ")", ";", "return", "(", "$", "res", "==", "'yes'", ")", "?", "true", ":", "false", ";", "}", "do", "{", "$", "res", "=", "strtolower", "(", "static", "::", "read", "(", "$", "question", ")", ")", ";", "}", "while", "(", "empty", "(", "$", "res", ")", ")", ";", "$", "positives", "=", "array", "(", "'yes'", ",", "'y'", ",", "'ya'", ",", "'ye'", ",", "'yeah'", ",", "'yup'", ",", "'jep'", ",", "'jap'", ",", "'ja'", ",", "'si'", ",", "'sim'", ",", "'true'", ",", "'hai'", ",", "'oui'", ",", "'no problemo'", ",", ")", ";", "return", "in_array", "(", "$", "res", ",", "$", "positives", ")", ";", "}" ]
Get a bool value from the user This will write the question down and waiting for a yes or no. When strict is true, it wil only accept yes or no. And not y, n, jep etc. @param string $question @param bool $strict @return bool
[ "Get", "a", "bool", "value", "from", "the", "user", "This", "will", "write", "the", "question", "down", "and", "waiting", "for", "a", "yes", "or", "no", "." ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCCli.php#L221-L253
ClanCats/Core
src/classes/CCCli.php
CCCli.read
public static function read( $prefix = '' ) { if ( !static::is_windows() ) { $line = readline( $prefix ); readline_add_history( $line ); } else { static::write( $prefix ); $line = trim( fgets( STDIN ) ); } return $line; }
php
public static function read( $prefix = '' ) { if ( !static::is_windows() ) { $line = readline( $prefix ); readline_add_history( $line ); } else { static::write( $prefix ); $line = trim( fgets( STDIN ) ); } return $line; }
[ "public", "static", "function", "read", "(", "$", "prefix", "=", "''", ")", "{", "if", "(", "!", "static", "::", "is_windows", "(", ")", ")", "{", "$", "line", "=", "readline", "(", "$", "prefix", ")", ";", "readline_add_history", "(", "$", "line", ")", ";", "}", "else", "{", "static", "::", "write", "(", "$", "prefix", ")", ";", "$", "line", "=", "trim", "(", "fgets", "(", "STDIN", ")", ")", ";", "}", "return", "$", "line", ";", "}" ]
Read from comman line Because windows does not support readline we use normal fgets in that case. @param string $prefix The prefix will be printet before the user can respond. @return string
[ "Read", "from", "comman", "line", "Because", "windows", "does", "not", "support", "readline", "we", "use", "normal", "fgets", "in", "that", "case", "." ]
train
https://github.com/ClanCats/Core/blob/9f6ec72c1a439de4b253d0223f1029f7f85b6ef8/src/classes/CCCli.php#L262-L276
Sedona-Solutions/sedona-sbo
src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php
BaseCrudController.getUrl
protected function getUrl($entity, $mode) { return $this->generateUrl($this->route_name.$mode, array('id' => $entity->getId())); }
php
protected function getUrl($entity, $mode) { return $this->generateUrl($this->route_name.$mode, array('id' => $entity->getId())); }
[ "protected", "function", "getUrl", "(", "$", "entity", ",", "$", "mode", ")", "{", "return", "$", "this", "->", "generateUrl", "(", "$", "this", "->", "route_name", ".", "$", "mode", ",", "array", "(", "'id'", "=>", "$", "entity", "->", "getId", "(", ")", ")", ")", ";", "}" ]
@param $entity @param $mode @return string
[ "@param", "$entity", "@param", "$mode" ]
train
https://github.com/Sedona-Solutions/sedona-sbo/blob/8548be4170d191cb1a3e263577aaaab49f04d5ce/src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php#L90-L93
Sedona-Solutions/sedona-sbo
src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php
BaseCrudController.manageEdit
protected function manageEdit($entity, Request $request, $formTypeFQCN) { $form = $this->createForm($formTypeFQCN, $entity, array( 'action' => $this->getEditUrl($entity), 'method' => 'POST', )); $form ->add('save', SubmitType::class, array('attr' => array('class' => 'btn btn-primary'))) ->add('delete', SubmitType::class, array('attr' => array('class' => 'btn btn-danger'))); $form->handleRequest($request); if ($form->isSubmitted()) { if ($form->get('save')->isClicked()) { if ($form->isValid()) { return $this->crudManage($entity, AdminCrudEvent::UPDATE); } } elseif ($form->get('delete')->isClicked()) { return $this->crudManage($entity, AdminCrudEvent::DELETE); } } return $this->render( $this->getEditTemplate(), array( 'entity' => $entity, 'form' => $form->createView(), )); }
php
protected function manageEdit($entity, Request $request, $formTypeFQCN) { $form = $this->createForm($formTypeFQCN, $entity, array( 'action' => $this->getEditUrl($entity), 'method' => 'POST', )); $form ->add('save', SubmitType::class, array('attr' => array('class' => 'btn btn-primary'))) ->add('delete', SubmitType::class, array('attr' => array('class' => 'btn btn-danger'))); $form->handleRequest($request); if ($form->isSubmitted()) { if ($form->get('save')->isClicked()) { if ($form->isValid()) { return $this->crudManage($entity, AdminCrudEvent::UPDATE); } } elseif ($form->get('delete')->isClicked()) { return $this->crudManage($entity, AdminCrudEvent::DELETE); } } return $this->render( $this->getEditTemplate(), array( 'entity' => $entity, 'form' => $form->createView(), )); }
[ "protected", "function", "manageEdit", "(", "$", "entity", ",", "Request", "$", "request", ",", "$", "formTypeFQCN", ")", "{", "$", "form", "=", "$", "this", "->", "createForm", "(", "$", "formTypeFQCN", ",", "$", "entity", ",", "array", "(", "'action'", "=>", "$", "this", "->", "getEditUrl", "(", "$", "entity", ")", ",", "'method'", "=>", "'POST'", ",", ")", ")", ";", "$", "form", "->", "add", "(", "'save'", ",", "SubmitType", "::", "class", ",", "array", "(", "'attr'", "=>", "array", "(", "'class'", "=>", "'btn btn-primary'", ")", ")", ")", "->", "add", "(", "'delete'", ",", "SubmitType", "::", "class", ",", "array", "(", "'attr'", "=>", "array", "(", "'class'", "=>", "'btn btn-danger'", ")", ")", ")", ";", "$", "form", "->", "handleRequest", "(", "$", "request", ")", ";", "if", "(", "$", "form", "->", "isSubmitted", "(", ")", ")", "{", "if", "(", "$", "form", "->", "get", "(", "'save'", ")", "->", "isClicked", "(", ")", ")", "{", "if", "(", "$", "form", "->", "isValid", "(", ")", ")", "{", "return", "$", "this", "->", "crudManage", "(", "$", "entity", ",", "AdminCrudEvent", "::", "UPDATE", ")", ";", "}", "}", "elseif", "(", "$", "form", "->", "get", "(", "'delete'", ")", "->", "isClicked", "(", ")", ")", "{", "return", "$", "this", "->", "crudManage", "(", "$", "entity", ",", "AdminCrudEvent", "::", "DELETE", ")", ";", "}", "}", "return", "$", "this", "->", "render", "(", "$", "this", "->", "getEditTemplate", "(", ")", ",", "array", "(", "'entity'", "=>", "$", "entity", ",", "'form'", "=>", "$", "form", "->", "createView", "(", ")", ",", ")", ")", ";", "}" ]
Generic edit controller helper. @param $entity @param Request $request @return string|\Symfony\Component\HttpFoundation\RedirectResponse
[ "Generic", "edit", "controller", "helper", "." ]
train
https://github.com/Sedona-Solutions/sedona-sbo/blob/8548be4170d191cb1a3e263577aaaab49f04d5ce/src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php#L103-L132
Sedona-Solutions/sedona-sbo
src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php
BaseCrudController.manageNew
protected function manageNew($entity, Request $request, $formTypeFQCN) { $form = $this->createForm($formTypeFQCN, $entity, array( 'action' => $this->getNewUrl($entity), 'method' => 'POST', )); $form ->add('create', submitType::class, array('attr' => array('class' => 'btn btn-primary'))); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { return $this->crudManage($entity, AdminCrudEvent::CREATE); } return $this->render( $this->getNewTemplate(), array( 'entity' => $entity, 'form' => $form->createView(), )); }
php
protected function manageNew($entity, Request $request, $formTypeFQCN) { $form = $this->createForm($formTypeFQCN, $entity, array( 'action' => $this->getNewUrl($entity), 'method' => 'POST', )); $form ->add('create', submitType::class, array('attr' => array('class' => 'btn btn-primary'))); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { return $this->crudManage($entity, AdminCrudEvent::CREATE); } return $this->render( $this->getNewTemplate(), array( 'entity' => $entity, 'form' => $form->createView(), )); }
[ "protected", "function", "manageNew", "(", "$", "entity", ",", "Request", "$", "request", ",", "$", "formTypeFQCN", ")", "{", "$", "form", "=", "$", "this", "->", "createForm", "(", "$", "formTypeFQCN", ",", "$", "entity", ",", "array", "(", "'action'", "=>", "$", "this", "->", "getNewUrl", "(", "$", "entity", ")", ",", "'method'", "=>", "'POST'", ",", ")", ")", ";", "$", "form", "->", "add", "(", "'create'", ",", "submitType", "::", "class", ",", "array", "(", "'attr'", "=>", "array", "(", "'class'", "=>", "'btn btn-primary'", ")", ")", ")", ";", "$", "form", "->", "handleRequest", "(", "$", "request", ")", ";", "if", "(", "$", "form", "->", "isSubmitted", "(", ")", "&&", "$", "form", "->", "isValid", "(", ")", ")", "{", "return", "$", "this", "->", "crudManage", "(", "$", "entity", ",", "AdminCrudEvent", "::", "CREATE", ")", ";", "}", "return", "$", "this", "->", "render", "(", "$", "this", "->", "getNewTemplate", "(", ")", ",", "array", "(", "'entity'", "=>", "$", "entity", ",", "'form'", "=>", "$", "form", "->", "createView", "(", ")", ",", ")", ")", ";", "}" ]
Generic new controller helper. @param $entity @param Request $request @return string|\Symfony\Component\HttpFoundation\RedirectResponse
[ "Generic", "new", "controller", "helper", "." ]
train
https://github.com/Sedona-Solutions/sedona-sbo/blob/8548be4170d191cb1a3e263577aaaab49f04d5ce/src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php#L142-L164
Sedona-Solutions/sedona-sbo
src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php
BaseCrudController.crudManage
protected function crudManage($entity, $action) { // Before, send preAction $event = $this->dispatchPreActionCrudEvent($entity, $action); $em = $this->getDoctrine()->getManager(); // Update entity according to action (can be changed in event) switch ($event->getAction()) { case AdminCrudEvent::CREATE; $em->persist($entity); break; case AdminCrudEvent::DELETE; $em->remove($entity); break; } if ($action > AdminCrudEvent::DONT_TOUCH) { $em->flush(); } // Send postAction Event $event = $this->dispatchPostActionCrudEvent($entity, $action); switch ($event->getAction()) { case AdminCrudEvent::CREATE; $this->addFlashMessage('success', $this->getFlashCreatedMessage()); break; case AdminCrudEvent::DELETE; $this->addFlashMessage('success', $this->getFlashDeletedMessage()); return $this->redirect($this->getListUrl()); break; case AdminCrudEvent::UPDATE; $this->addFlashMessage('success', $this->getFlashSavedMessage()); break; } return $this->redirect($this->getShowUrl($entity)); }
php
protected function crudManage($entity, $action) { // Before, send preAction $event = $this->dispatchPreActionCrudEvent($entity, $action); $em = $this->getDoctrine()->getManager(); // Update entity according to action (can be changed in event) switch ($event->getAction()) { case AdminCrudEvent::CREATE; $em->persist($entity); break; case AdminCrudEvent::DELETE; $em->remove($entity); break; } if ($action > AdminCrudEvent::DONT_TOUCH) { $em->flush(); } // Send postAction Event $event = $this->dispatchPostActionCrudEvent($entity, $action); switch ($event->getAction()) { case AdminCrudEvent::CREATE; $this->addFlashMessage('success', $this->getFlashCreatedMessage()); break; case AdminCrudEvent::DELETE; $this->addFlashMessage('success', $this->getFlashDeletedMessage()); return $this->redirect($this->getListUrl()); break; case AdminCrudEvent::UPDATE; $this->addFlashMessage('success', $this->getFlashSavedMessage()); break; } return $this->redirect($this->getShowUrl($entity)); }
[ "protected", "function", "crudManage", "(", "$", "entity", ",", "$", "action", ")", "{", "// Before, send preAction", "$", "event", "=", "$", "this", "->", "dispatchPreActionCrudEvent", "(", "$", "entity", ",", "$", "action", ")", ";", "$", "em", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getManager", "(", ")", ";", "// Update entity according to action (can be changed in event)", "switch", "(", "$", "event", "->", "getAction", "(", ")", ")", "{", "case", "AdminCrudEvent", "::", "CREATE", ";", "$", "em", "->", "persist", "(", "$", "entity", ")", ";", "break", ";", "case", "AdminCrudEvent", "::", "DELETE", ";", "$", "em", "->", "remove", "(", "$", "entity", ")", ";", "break", ";", "}", "if", "(", "$", "action", ">", "AdminCrudEvent", "::", "DONT_TOUCH", ")", "{", "$", "em", "->", "flush", "(", ")", ";", "}", "// Send postAction Event", "$", "event", "=", "$", "this", "->", "dispatchPostActionCrudEvent", "(", "$", "entity", ",", "$", "action", ")", ";", "switch", "(", "$", "event", "->", "getAction", "(", ")", ")", "{", "case", "AdminCrudEvent", "::", "CREATE", ";", "$", "this", "->", "addFlashMessage", "(", "'success'", ",", "$", "this", "->", "getFlashCreatedMessage", "(", ")", ")", ";", "break", ";", "case", "AdminCrudEvent", "::", "DELETE", ";", "$", "this", "->", "addFlashMessage", "(", "'success'", ",", "$", "this", "->", "getFlashDeletedMessage", "(", ")", ")", ";", "return", "$", "this", "->", "redirect", "(", "$", "this", "->", "getListUrl", "(", ")", ")", ";", "break", ";", "case", "AdminCrudEvent", "::", "UPDATE", ";", "$", "this", "->", "addFlashMessage", "(", "'success'", ",", "$", "this", "->", "getFlashSavedMessage", "(", ")", ")", ";", "break", ";", "}", "return", "$", "this", "->", "redirect", "(", "$", "this", "->", "getShowUrl", "(", "$", "entity", ")", ")", ";", "}" ]
Manage full action: send events, manage entity, send flash messages. @param $entity @param $action @return \Symfony\Component\HttpFoundation\RedirectResponse
[ "Manage", "full", "action", ":", "send", "events", "manage", "entity", "send", "flash", "messages", "." ]
train
https://github.com/Sedona-Solutions/sedona-sbo/blob/8548be4170d191cb1a3e263577aaaab49f04d5ce/src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php#L174-L212
Sedona-Solutions/sedona-sbo
src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php
BaseCrudController.dispatchCrudEvent
protected function dispatchCrudEvent($entity, $action, $eventName) { $event = new AdminCrudEvent($entity, $action, $this->getUser()); $this->get('event_dispatcher')->dispatch($eventName, $event); return $event; }
php
protected function dispatchCrudEvent($entity, $action, $eventName) { $event = new AdminCrudEvent($entity, $action, $this->getUser()); $this->get('event_dispatcher')->dispatch($eventName, $event); return $event; }
[ "protected", "function", "dispatchCrudEvent", "(", "$", "entity", ",", "$", "action", ",", "$", "eventName", ")", "{", "$", "event", "=", "new", "AdminCrudEvent", "(", "$", "entity", ",", "$", "action", ",", "$", "this", "->", "getUser", "(", ")", ")", ";", "$", "this", "->", "get", "(", "'event_dispatcher'", ")", "->", "dispatch", "(", "$", "eventName", ",", "$", "event", ")", ";", "return", "$", "event", ";", "}" ]
Generic Event dispatcher. @param $entity @param $action @param $eventName @return AdminCrudEvent
[ "Generic", "Event", "dispatcher", "." ]
train
https://github.com/Sedona-Solutions/sedona-sbo/blob/8548be4170d191cb1a3e263577aaaab49f04d5ce/src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php#L249-L255
Sedona-Solutions/sedona-sbo
src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php
BaseCrudController.dispatchAssociationActionEvent
protected function dispatchAssociationActionEvent($entity, $action, $target, $eventName) { $event = new AdminAssociationActionEvent($entity, $action, $target, $this->getUser()); $this->get('event_dispatcher')->dispatch($eventName, $event); return $event; }
php
protected function dispatchAssociationActionEvent($entity, $action, $target, $eventName) { $event = new AdminAssociationActionEvent($entity, $action, $target, $this->getUser()); $this->get('event_dispatcher')->dispatch($eventName, $event); return $event; }
[ "protected", "function", "dispatchAssociationActionEvent", "(", "$", "entity", ",", "$", "action", ",", "$", "target", ",", "$", "eventName", ")", "{", "$", "event", "=", "new", "AdminAssociationActionEvent", "(", "$", "entity", ",", "$", "action", ",", "$", "target", ",", "$", "this", "->", "getUser", "(", ")", ")", ";", "$", "this", "->", "get", "(", "'event_dispatcher'", ")", "->", "dispatch", "(", "$", "eventName", ",", "$", "event", ")", ";", "return", "$", "event", ";", "}" ]
Generic Association Action dispatcher. @param $entity @param $action @param $target @param $eventName @return AdminAssociationActionEvent
[ "Generic", "Association", "Action", "dispatcher", "." ]
train
https://github.com/Sedona-Solutions/sedona-sbo/blob/8548be4170d191cb1a3e263577aaaab49f04d5ce/src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php#L293-L299
Sedona-Solutions/sedona-sbo
src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php
BaseCrudController.manageIndex
protected function manageIndex() { $postDatatable = $this->get($this->route_name.'_datatable'); $postDatatable->buildDatatable(); return $this->render($this->getIndexTemplate(), array( 'datatable' => $postDatatable, )); }
php
protected function manageIndex() { $postDatatable = $this->get($this->route_name.'_datatable'); $postDatatable->buildDatatable(); return $this->render($this->getIndexTemplate(), array( 'datatable' => $postDatatable, )); }
[ "protected", "function", "manageIndex", "(", ")", "{", "$", "postDatatable", "=", "$", "this", "->", "get", "(", "$", "this", "->", "route_name", ".", "'_datatable'", ")", ";", "$", "postDatatable", "->", "buildDatatable", "(", ")", ";", "return", "$", "this", "->", "render", "(", "$", "this", "->", "getIndexTemplate", "(", ")", ",", "array", "(", "'datatable'", "=>", "$", "postDatatable", ",", ")", ")", ";", "}" ]
Generic index controller helper. @return Response
[ "Generic", "index", "controller", "helper", "." ]
train
https://github.com/Sedona-Solutions/sedona-sbo/blob/8548be4170d191cb1a3e263577aaaab49f04d5ce/src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php#L320-L328
Sedona-Solutions/sedona-sbo
src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php
BaseCrudController.manageFieldIndex
protected function manageFieldIndex($entity, $field) { if ($entity == null || $field == null || $this->has($this->route_name.'_'.$field.'_datatable') == false) { throw new \Exception('All the parameters are not correctly set'); } $postDatatable = $this->get($this->route_name.'_'.$field.'_datatable'); $postDatatable->buildDatatable(['entity' => $entity]); return $this->render($this->getIndexTemplate(strtolower($field)), array( 'datatable' => $postDatatable, 'entity' => $entity, )); }
php
protected function manageFieldIndex($entity, $field) { if ($entity == null || $field == null || $this->has($this->route_name.'_'.$field.'_datatable') == false) { throw new \Exception('All the parameters are not correctly set'); } $postDatatable = $this->get($this->route_name.'_'.$field.'_datatable'); $postDatatable->buildDatatable(['entity' => $entity]); return $this->render($this->getIndexTemplate(strtolower($field)), array( 'datatable' => $postDatatable, 'entity' => $entity, )); }
[ "protected", "function", "manageFieldIndex", "(", "$", "entity", ",", "$", "field", ")", "{", "if", "(", "$", "entity", "==", "null", "||", "$", "field", "==", "null", "||", "$", "this", "->", "has", "(", "$", "this", "->", "route_name", ".", "'_'", ".", "$", "field", ".", "'_datatable'", ")", "==", "false", ")", "{", "throw", "new", "\\", "Exception", "(", "'All the parameters are not correctly set'", ")", ";", "}", "$", "postDatatable", "=", "$", "this", "->", "get", "(", "$", "this", "->", "route_name", ".", "'_'", ".", "$", "field", ".", "'_datatable'", ")", ";", "$", "postDatatable", "->", "buildDatatable", "(", "[", "'entity'", "=>", "$", "entity", "]", ")", ";", "return", "$", "this", "->", "render", "(", "$", "this", "->", "getIndexTemplate", "(", "strtolower", "(", "$", "field", ")", ")", ",", "array", "(", "'datatable'", "=>", "$", "postDatatable", ",", "'entity'", "=>", "$", "entity", ",", ")", ")", ";", "}" ]
Generic index controller helper. @param $entity @param $field @return Response @throws \Exception
[ "Generic", "index", "controller", "helper", "." ]
train
https://github.com/Sedona-Solutions/sedona-sbo/blob/8548be4170d191cb1a3e263577aaaab49f04d5ce/src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php#L340-L352
Sedona-Solutions/sedona-sbo
src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php
BaseCrudController.manageFieldDatatableJson
protected function manageFieldDatatableJson($entity, $field, $reversedField, $type = 'one') { if ($entity == null || $field == null || $this->has($this->route_name.'_'.$field.'_datatable') == false) { throw new \Exception('All the parameters are not correctly set'); } $postDatatable = $this->get($this->route_name.'_'.$field.'_datatable'); $postDatatable->buildDatatable(['entity' => $entity]); if (method_exists($postDatatable, 'addLineFormatter') && method_exists($entity, 'getId')) { $postDatatable->addLineFormatter(function ($ligne) use ($entity) { $ligne['entity_id'] = $entity->getId(); return $ligne; }); } $datatable = $this->get('sg_datatables.query')->getQueryFrom($postDatatable); $entityName = $this->entity_name; if ($type === 'one') { $datatable->addWhereAll(function (QueryBuilder $qb) use ($entity, $entityName, $reversedField) { $qb ->andWhere($qb->getRootAliases()[0].'.'.$reversedField." = :$entityName") ->setParameter("$entityName", $entity) ; }); } elseif ($type === 'many') { $datatable->addWhereAll(function (QueryBuilder $qb) use ($entity, $entityName, $reversedField) { $qb ->join($qb->getRootAliases()[0].'.'.$reversedField, 'reverseField') ->andWhere('reverseField.id = :'.$entityName.'_id') ->setParameter($entityName.'_id', $entity->getId()) ; }); } return $datatable->getResponse(); }
php
protected function manageFieldDatatableJson($entity, $field, $reversedField, $type = 'one') { if ($entity == null || $field == null || $this->has($this->route_name.'_'.$field.'_datatable') == false) { throw new \Exception('All the parameters are not correctly set'); } $postDatatable = $this->get($this->route_name.'_'.$field.'_datatable'); $postDatatable->buildDatatable(['entity' => $entity]); if (method_exists($postDatatable, 'addLineFormatter') && method_exists($entity, 'getId')) { $postDatatable->addLineFormatter(function ($ligne) use ($entity) { $ligne['entity_id'] = $entity->getId(); return $ligne; }); } $datatable = $this->get('sg_datatables.query')->getQueryFrom($postDatatable); $entityName = $this->entity_name; if ($type === 'one') { $datatable->addWhereAll(function (QueryBuilder $qb) use ($entity, $entityName, $reversedField) { $qb ->andWhere($qb->getRootAliases()[0].'.'.$reversedField." = :$entityName") ->setParameter("$entityName", $entity) ; }); } elseif ($type === 'many') { $datatable->addWhereAll(function (QueryBuilder $qb) use ($entity, $entityName, $reversedField) { $qb ->join($qb->getRootAliases()[0].'.'.$reversedField, 'reverseField') ->andWhere('reverseField.id = :'.$entityName.'_id') ->setParameter($entityName.'_id', $entity->getId()) ; }); } return $datatable->getResponse(); }
[ "protected", "function", "manageFieldDatatableJson", "(", "$", "entity", ",", "$", "field", ",", "$", "reversedField", ",", "$", "type", "=", "'one'", ")", "{", "if", "(", "$", "entity", "==", "null", "||", "$", "field", "==", "null", "||", "$", "this", "->", "has", "(", "$", "this", "->", "route_name", ".", "'_'", ".", "$", "field", ".", "'_datatable'", ")", "==", "false", ")", "{", "throw", "new", "\\", "Exception", "(", "'All the parameters are not correctly set'", ")", ";", "}", "$", "postDatatable", "=", "$", "this", "->", "get", "(", "$", "this", "->", "route_name", ".", "'_'", ".", "$", "field", ".", "'_datatable'", ")", ";", "$", "postDatatable", "->", "buildDatatable", "(", "[", "'entity'", "=>", "$", "entity", "]", ")", ";", "if", "(", "method_exists", "(", "$", "postDatatable", ",", "'addLineFormatter'", ")", "&&", "method_exists", "(", "$", "entity", ",", "'getId'", ")", ")", "{", "$", "postDatatable", "->", "addLineFormatter", "(", "function", "(", "$", "ligne", ")", "use", "(", "$", "entity", ")", "{", "$", "ligne", "[", "'entity_id'", "]", "=", "$", "entity", "->", "getId", "(", ")", ";", "return", "$", "ligne", ";", "}", ")", ";", "}", "$", "datatable", "=", "$", "this", "->", "get", "(", "'sg_datatables.query'", ")", "->", "getQueryFrom", "(", "$", "postDatatable", ")", ";", "$", "entityName", "=", "$", "this", "->", "entity_name", ";", "if", "(", "$", "type", "===", "'one'", ")", "{", "$", "datatable", "->", "addWhereAll", "(", "function", "(", "QueryBuilder", "$", "qb", ")", "use", "(", "$", "entity", ",", "$", "entityName", ",", "$", "reversedField", ")", "{", "$", "qb", "->", "andWhere", "(", "$", "qb", "->", "getRootAliases", "(", ")", "[", "0", "]", ".", "'.'", ".", "$", "reversedField", ".", "\" = :$entityName\"", ")", "->", "setParameter", "(", "\"$entityName\"", ",", "$", "entity", ")", ";", "}", ")", ";", "}", "elseif", "(", "$", "type", "===", "'many'", ")", "{", "$", "datatable", "->", "addWhereAll", "(", "function", "(", "QueryBuilder", "$", "qb", ")", "use", "(", "$", "entity", ",", "$", "entityName", ",", "$", "reversedField", ")", "{", "$", "qb", "->", "join", "(", "$", "qb", "->", "getRootAliases", "(", ")", "[", "0", "]", ".", "'.'", ".", "$", "reversedField", ",", "'reverseField'", ")", "->", "andWhere", "(", "'reverseField.id = :'", ".", "$", "entityName", ".", "'_id'", ")", "->", "setParameter", "(", "$", "entityName", ".", "'_id'", ",", "$", "entity", "->", "getId", "(", ")", ")", ";", "}", ")", ";", "}", "return", "$", "datatable", "->", "getResponse", "(", ")", ";", "}" ]
@param $entity @param $field @param $reversedField @return Response @throws \Exception
[ "@param", "$entity", "@param", "$field", "@param", "$reversedField" ]
train
https://github.com/Sedona-Solutions/sedona-sbo/blob/8548be4170d191cb1a3e263577aaaab49f04d5ce/src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php#L387-L426
Sedona-Solutions/sedona-sbo
src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php
BaseCrudController.searchSelect2
protected function searchSelect2(Request $request, $class, $fieldSearchFunction = 'title', $renderResult = null) { // 3rd parameter: use the following code to have a more flexible search // $querySearch = function(\Doctrine\ORM\QueryBuilder $queryBuilder, $query) { // $queryBuilder // ->andWhere("o.{{ property }} LIKE :{{ property }}") // ->setParameter("{{ property }}","%$query%"); // }; // 4th parameter: use the following code to customize rendering of select2 // $twig = $this->get('twig'); // $html = $this->bundle_name.":Admin/".strtolower(substr($class,strripos($class,'\\')+1)).":renderResultSelect2.html.twig"; // $appendResult = function( $entity, $query) use ($twig, $html) { // return [ // 'renderValue' => $twig->render($html, ['entity' => $entity, 'query' => $query]), // 'text' => $entity->__toString(), // 'id' => $entity->getId() // ]; // }; $query = $request->get('q', null); $limit = (int) $request->get('page_limit', 10); $page = (int) $request->get('page', 1); $res = ['term' => $query, 'more' => false, 'results' => []]; // creation du queryBulider $queryBuilder = $this->get('doctrine.orm.entity_manager') ->getRepository($class) ->createQueryBuilder('o') ; // add filters if (is_string($fieldSearchFunction)) { $queryBuilder ->andWhere("o.$fieldSearchFunction LIKE :$fieldSearchFunction") ->setParameter("$fieldSearchFunction", "%$query%") ->orderBy("o.$fieldSearchFunction") ; } elseif (is_callable($fieldSearchFunction)) { $fieldSearchFunction($queryBuilder, $query); } // page & limit if (is_int($page) && $page > 0 && is_int($limit) && $limit > 0) { $queryBuilder = $queryBuilder ->setFirstResult(($page - 1) * $limit) ->setMaxResults($limit + 1) ; } // get results $result = $queryBuilder ->getQuery() ->getResult() ; if ($renderResult == null) { $getter = is_string($fieldSearchFunction) ? $this->getGetter($fieldSearchFunction) : '__toString'; $renderResult = function ($entity, $query) use ($getter) { return [ 'text' => $entity->$getter(), 'id' => $entity->getId(), ]; }; } // create response foreach ($result as $object) { $res['results'][] = $renderResult($object, $query); } // check if not more result if (count($result) > $limit) { $res['more'] = true; $res['results'] = array_slice($res['results'], 0, $limit); } $response = new JsonResponse($res); $response->setCallback($request->get('callback')); // send data into JSON return $response; }
php
protected function searchSelect2(Request $request, $class, $fieldSearchFunction = 'title', $renderResult = null) { // 3rd parameter: use the following code to have a more flexible search // $querySearch = function(\Doctrine\ORM\QueryBuilder $queryBuilder, $query) { // $queryBuilder // ->andWhere("o.{{ property }} LIKE :{{ property }}") // ->setParameter("{{ property }}","%$query%"); // }; // 4th parameter: use the following code to customize rendering of select2 // $twig = $this->get('twig'); // $html = $this->bundle_name.":Admin/".strtolower(substr($class,strripos($class,'\\')+1)).":renderResultSelect2.html.twig"; // $appendResult = function( $entity, $query) use ($twig, $html) { // return [ // 'renderValue' => $twig->render($html, ['entity' => $entity, 'query' => $query]), // 'text' => $entity->__toString(), // 'id' => $entity->getId() // ]; // }; $query = $request->get('q', null); $limit = (int) $request->get('page_limit', 10); $page = (int) $request->get('page', 1); $res = ['term' => $query, 'more' => false, 'results' => []]; // creation du queryBulider $queryBuilder = $this->get('doctrine.orm.entity_manager') ->getRepository($class) ->createQueryBuilder('o') ; // add filters if (is_string($fieldSearchFunction)) { $queryBuilder ->andWhere("o.$fieldSearchFunction LIKE :$fieldSearchFunction") ->setParameter("$fieldSearchFunction", "%$query%") ->orderBy("o.$fieldSearchFunction") ; } elseif (is_callable($fieldSearchFunction)) { $fieldSearchFunction($queryBuilder, $query); } // page & limit if (is_int($page) && $page > 0 && is_int($limit) && $limit > 0) { $queryBuilder = $queryBuilder ->setFirstResult(($page - 1) * $limit) ->setMaxResults($limit + 1) ; } // get results $result = $queryBuilder ->getQuery() ->getResult() ; if ($renderResult == null) { $getter = is_string($fieldSearchFunction) ? $this->getGetter($fieldSearchFunction) : '__toString'; $renderResult = function ($entity, $query) use ($getter) { return [ 'text' => $entity->$getter(), 'id' => $entity->getId(), ]; }; } // create response foreach ($result as $object) { $res['results'][] = $renderResult($object, $query); } // check if not more result if (count($result) > $limit) { $res['more'] = true; $res['results'] = array_slice($res['results'], 0, $limit); } $response = new JsonResponse($res); $response->setCallback($request->get('callback')); // send data into JSON return $response; }
[ "protected", "function", "searchSelect2", "(", "Request", "$", "request", ",", "$", "class", ",", "$", "fieldSearchFunction", "=", "'title'", ",", "$", "renderResult", "=", "null", ")", "{", "// 3rd parameter: use the following code to have a more flexible search", "// $querySearch = function(\\Doctrine\\ORM\\QueryBuilder $queryBuilder, $query) {", "// $queryBuilder", "// ->andWhere(\"o.{{ property }} LIKE :{{ property }}\")", "// ->setParameter(\"{{ property }}\",\"%$query%\");", "// };", "// 4th parameter: use the following code to customize rendering of select2", "// $twig = $this->get('twig');", "// $html = $this->bundle_name.\":Admin/\".strtolower(substr($class,strripos($class,'\\\\')+1)).\":renderResultSelect2.html.twig\";", "// $appendResult = function( $entity, $query) use ($twig, $html) {", "// return [", "// 'renderValue' => $twig->render($html, ['entity' => $entity, 'query' => $query]),", "// 'text' => $entity->__toString(),", "// 'id' => $entity->getId()", "// ];", "// };", "$", "query", "=", "$", "request", "->", "get", "(", "'q'", ",", "null", ")", ";", "$", "limit", "=", "(", "int", ")", "$", "request", "->", "get", "(", "'page_limit'", ",", "10", ")", ";", "$", "page", "=", "(", "int", ")", "$", "request", "->", "get", "(", "'page'", ",", "1", ")", ";", "$", "res", "=", "[", "'term'", "=>", "$", "query", ",", "'more'", "=>", "false", ",", "'results'", "=>", "[", "]", "]", ";", "// creation du queryBulider", "$", "queryBuilder", "=", "$", "this", "->", "get", "(", "'doctrine.orm.entity_manager'", ")", "->", "getRepository", "(", "$", "class", ")", "->", "createQueryBuilder", "(", "'o'", ")", ";", "// add filters", "if", "(", "is_string", "(", "$", "fieldSearchFunction", ")", ")", "{", "$", "queryBuilder", "->", "andWhere", "(", "\"o.$fieldSearchFunction LIKE :$fieldSearchFunction\"", ")", "->", "setParameter", "(", "\"$fieldSearchFunction\"", ",", "\"%$query%\"", ")", "->", "orderBy", "(", "\"o.$fieldSearchFunction\"", ")", ";", "}", "elseif", "(", "is_callable", "(", "$", "fieldSearchFunction", ")", ")", "{", "$", "fieldSearchFunction", "(", "$", "queryBuilder", ",", "$", "query", ")", ";", "}", "// page & limit", "if", "(", "is_int", "(", "$", "page", ")", "&&", "$", "page", ">", "0", "&&", "is_int", "(", "$", "limit", ")", "&&", "$", "limit", ">", "0", ")", "{", "$", "queryBuilder", "=", "$", "queryBuilder", "->", "setFirstResult", "(", "(", "$", "page", "-", "1", ")", "*", "$", "limit", ")", "->", "setMaxResults", "(", "$", "limit", "+", "1", ")", ";", "}", "// get results", "$", "result", "=", "$", "queryBuilder", "->", "getQuery", "(", ")", "->", "getResult", "(", ")", ";", "if", "(", "$", "renderResult", "==", "null", ")", "{", "$", "getter", "=", "is_string", "(", "$", "fieldSearchFunction", ")", "?", "$", "this", "->", "getGetter", "(", "$", "fieldSearchFunction", ")", ":", "'__toString'", ";", "$", "renderResult", "=", "function", "(", "$", "entity", ",", "$", "query", ")", "use", "(", "$", "getter", ")", "{", "return", "[", "'text'", "=>", "$", "entity", "->", "$", "getter", "(", ")", ",", "'id'", "=>", "$", "entity", "->", "getId", "(", ")", ",", "]", ";", "}", ";", "}", "// create response", "foreach", "(", "$", "result", "as", "$", "object", ")", "{", "$", "res", "[", "'results'", "]", "[", "]", "=", "$", "renderResult", "(", "$", "object", ",", "$", "query", ")", ";", "}", "// check if not more result", "if", "(", "count", "(", "$", "result", ")", ">", "$", "limit", ")", "{", "$", "res", "[", "'more'", "]", "=", "true", ";", "$", "res", "[", "'results'", "]", "=", "array_slice", "(", "$", "res", "[", "'results'", "]", ",", "0", ",", "$", "limit", ")", ";", "}", "$", "response", "=", "new", "JsonResponse", "(", "$", "res", ")", ";", "$", "response", "->", "setCallback", "(", "$", "request", "->", "get", "(", "'callback'", ")", ")", ";", "// send data into JSON", "return", "$", "response", ";", "}" ]
@param Request $request @param $class @param closure|string $filerFunction @param closure|null $renderResult @return JsonResponse
[ "@param", "Request", "$request", "@param", "$class", "@param", "closure|string", "$filerFunction", "@param", "closure|null", "$renderResult" ]
train
https://github.com/Sedona-Solutions/sedona-sbo/blob/8548be4170d191cb1a3e263577aaaab49f04d5ce/src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php#L448-L531
Sedona-Solutions/sedona-sbo
src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php
BaseCrudController.manageSearchFieldMany
protected function manageSearchFieldMany(Request $request, $entity, $fieldClass, $field, $fieldSearch) { $twig = $this->get('twig'); $getTitle = $this->getGetter($fieldSearch); $querySearch = function (\Doctrine\ORM\QueryBuilder $queryBuilder, $query) use ($entity, $field, $fieldSearch, $fieldClass) { $subQuery = $queryBuilder->getEntityManager()->createQueryBuilder(); $subQuery ->select('field.id') ->from(get_class($entity), 'entity') ->join('entity.'.$field, 'field') ->where('entity.id = :entity_id') ->setParameter('entity_id', $entity->getId()) ; $queryBuilder ->andWhere($queryBuilder->expr()->notIn('o.id', $subQuery->getDql())) ->setParameter('entity_id', $entity->getId()) ->andWhere('o.'.$fieldSearch.' LIKE :'.$fieldSearch) ->setParameter($fieldSearch, "%$query%") ->orderBy('o.'.$fieldSearch) ; }; $fieldClassName = substr($fieldClass, strripos($fieldClass, '\\') + 1); if ($this->get('templating')->exists($this->bundle_name.':Admin/'.$fieldClassName.':'.'renderResultSelect2.html.twig')) { $appendResult = function ($subentity, $query) use ($entity, $field, $twig, $getTitle, $fieldClassName) { return [ 'renderValue' => $twig->render($this->bundle_name.':Admin/'.$fieldClassName.':'.'renderResultSelect2.html.twig', ['entity' => $subentity, 'query' => $query]), 'confirme' => $this->generateUrl($this->route_name.'_'.strtolower($field).'_add', ['id' => $entity->getId(), strtolower($fieldClassName).'_id' => $subentity->getId()]), 'text' => $subentity->$getTitle(), 'id' => $subentity->getId(), ]; }; } else { $appendResult = function ($subentity, $query) use ($entity, $field, $twig, $getTitle, $fieldClassName) { return [ 'confirme' => $this->generateUrl($this->route_name.'_'.strtolower($field).'_add', ['id' => $entity->getId(), strtolower($fieldClassName).'_id' => $subentity->getId()]), 'text' => $subentity->$getTitle(), 'id' => $subentity->getId(), ]; }; } return $this->searchSelect2($request, $fieldClass, $querySearch, $appendResult); }
php
protected function manageSearchFieldMany(Request $request, $entity, $fieldClass, $field, $fieldSearch) { $twig = $this->get('twig'); $getTitle = $this->getGetter($fieldSearch); $querySearch = function (\Doctrine\ORM\QueryBuilder $queryBuilder, $query) use ($entity, $field, $fieldSearch, $fieldClass) { $subQuery = $queryBuilder->getEntityManager()->createQueryBuilder(); $subQuery ->select('field.id') ->from(get_class($entity), 'entity') ->join('entity.'.$field, 'field') ->where('entity.id = :entity_id') ->setParameter('entity_id', $entity->getId()) ; $queryBuilder ->andWhere($queryBuilder->expr()->notIn('o.id', $subQuery->getDql())) ->setParameter('entity_id', $entity->getId()) ->andWhere('o.'.$fieldSearch.' LIKE :'.$fieldSearch) ->setParameter($fieldSearch, "%$query%") ->orderBy('o.'.$fieldSearch) ; }; $fieldClassName = substr($fieldClass, strripos($fieldClass, '\\') + 1); if ($this->get('templating')->exists($this->bundle_name.':Admin/'.$fieldClassName.':'.'renderResultSelect2.html.twig')) { $appendResult = function ($subentity, $query) use ($entity, $field, $twig, $getTitle, $fieldClassName) { return [ 'renderValue' => $twig->render($this->bundle_name.':Admin/'.$fieldClassName.':'.'renderResultSelect2.html.twig', ['entity' => $subentity, 'query' => $query]), 'confirme' => $this->generateUrl($this->route_name.'_'.strtolower($field).'_add', ['id' => $entity->getId(), strtolower($fieldClassName).'_id' => $subentity->getId()]), 'text' => $subentity->$getTitle(), 'id' => $subentity->getId(), ]; }; } else { $appendResult = function ($subentity, $query) use ($entity, $field, $twig, $getTitle, $fieldClassName) { return [ 'confirme' => $this->generateUrl($this->route_name.'_'.strtolower($field).'_add', ['id' => $entity->getId(), strtolower($fieldClassName).'_id' => $subentity->getId()]), 'text' => $subentity->$getTitle(), 'id' => $subentity->getId(), ]; }; } return $this->searchSelect2($request, $fieldClass, $querySearch, $appendResult); }
[ "protected", "function", "manageSearchFieldMany", "(", "Request", "$", "request", ",", "$", "entity", ",", "$", "fieldClass", ",", "$", "field", ",", "$", "fieldSearch", ")", "{", "$", "twig", "=", "$", "this", "->", "get", "(", "'twig'", ")", ";", "$", "getTitle", "=", "$", "this", "->", "getGetter", "(", "$", "fieldSearch", ")", ";", "$", "querySearch", "=", "function", "(", "\\", "Doctrine", "\\", "ORM", "\\", "QueryBuilder", "$", "queryBuilder", ",", "$", "query", ")", "use", "(", "$", "entity", ",", "$", "field", ",", "$", "fieldSearch", ",", "$", "fieldClass", ")", "{", "$", "subQuery", "=", "$", "queryBuilder", "->", "getEntityManager", "(", ")", "->", "createQueryBuilder", "(", ")", ";", "$", "subQuery", "->", "select", "(", "'field.id'", ")", "->", "from", "(", "get_class", "(", "$", "entity", ")", ",", "'entity'", ")", "->", "join", "(", "'entity.'", ".", "$", "field", ",", "'field'", ")", "->", "where", "(", "'entity.id = :entity_id'", ")", "->", "setParameter", "(", "'entity_id'", ",", "$", "entity", "->", "getId", "(", ")", ")", ";", "$", "queryBuilder", "->", "andWhere", "(", "$", "queryBuilder", "->", "expr", "(", ")", "->", "notIn", "(", "'o.id'", ",", "$", "subQuery", "->", "getDql", "(", ")", ")", ")", "->", "setParameter", "(", "'entity_id'", ",", "$", "entity", "->", "getId", "(", ")", ")", "->", "andWhere", "(", "'o.'", ".", "$", "fieldSearch", ".", "' LIKE :'", ".", "$", "fieldSearch", ")", "->", "setParameter", "(", "$", "fieldSearch", ",", "\"%$query%\"", ")", "->", "orderBy", "(", "'o.'", ".", "$", "fieldSearch", ")", ";", "}", ";", "$", "fieldClassName", "=", "substr", "(", "$", "fieldClass", ",", "strripos", "(", "$", "fieldClass", ",", "'\\\\'", ")", "+", "1", ")", ";", "if", "(", "$", "this", "->", "get", "(", "'templating'", ")", "->", "exists", "(", "$", "this", "->", "bundle_name", ".", "':Admin/'", ".", "$", "fieldClassName", ".", "':'", ".", "'renderResultSelect2.html.twig'", ")", ")", "{", "$", "appendResult", "=", "function", "(", "$", "subentity", ",", "$", "query", ")", "use", "(", "$", "entity", ",", "$", "field", ",", "$", "twig", ",", "$", "getTitle", ",", "$", "fieldClassName", ")", "{", "return", "[", "'renderValue'", "=>", "$", "twig", "->", "render", "(", "$", "this", "->", "bundle_name", ".", "':Admin/'", ".", "$", "fieldClassName", ".", "':'", ".", "'renderResultSelect2.html.twig'", ",", "[", "'entity'", "=>", "$", "subentity", ",", "'query'", "=>", "$", "query", "]", ")", ",", "'confirme'", "=>", "$", "this", "->", "generateUrl", "(", "$", "this", "->", "route_name", ".", "'_'", ".", "strtolower", "(", "$", "field", ")", ".", "'_add'", ",", "[", "'id'", "=>", "$", "entity", "->", "getId", "(", ")", ",", "strtolower", "(", "$", "fieldClassName", ")", ".", "'_id'", "=>", "$", "subentity", "->", "getId", "(", ")", "]", ")", ",", "'text'", "=>", "$", "subentity", "->", "$", "getTitle", "(", ")", ",", "'id'", "=>", "$", "subentity", "->", "getId", "(", ")", ",", "]", ";", "}", ";", "}", "else", "{", "$", "appendResult", "=", "function", "(", "$", "subentity", ",", "$", "query", ")", "use", "(", "$", "entity", ",", "$", "field", ",", "$", "twig", ",", "$", "getTitle", ",", "$", "fieldClassName", ")", "{", "return", "[", "'confirme'", "=>", "$", "this", "->", "generateUrl", "(", "$", "this", "->", "route_name", ".", "'_'", ".", "strtolower", "(", "$", "field", ")", ".", "'_add'", ",", "[", "'id'", "=>", "$", "entity", "->", "getId", "(", ")", ",", "strtolower", "(", "$", "fieldClassName", ")", ".", "'_id'", "=>", "$", "subentity", "->", "getId", "(", ")", "]", ")", ",", "'text'", "=>", "$", "subentity", "->", "$", "getTitle", "(", ")", ",", "'id'", "=>", "$", "subentity", "->", "getId", "(", ")", ",", "]", ";", "}", ";", "}", "return", "$", "this", "->", "searchSelect2", "(", "$", "request", ",", "$", "fieldClass", ",", "$", "querySearch", ",", "$", "appendResult", ")", ";", "}" ]
Manage search to add in datatable. @param Request $request @param $entity @param $fieldClass @param $field @param $fieldSearch @return JsonResponse
[ "Manage", "search", "to", "add", "in", "datatable", "." ]
train
https://github.com/Sedona-Solutions/sedona-sbo/blob/8548be4170d191cb1a3e263577aaaab49f04d5ce/src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php#L544-L592
Sedona-Solutions/sedona-sbo
src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php
BaseCrudController.manageJson
protected function manageJson($source, $target, $field, $action, $contains = true) { $res = ['result' => true, 'message' => '']; $getter = $this->getGetter($field); if ($source->$getter()->contains($target) == $contains) { $event = $this->dispatchPreActionAssociationActionEvent($source, $action, $target); if ($event->getAction() != AdminAssociationActionEvent::DONT_TOUCH) { $source2 = $event->getItem(); $target2 = $event->getTarget(); $action2 = $event->getAction(); $source2->$action2($target2); $this->get('doctrine.orm.entity_manager')->flush(); } //$res['html'] = $this->get("twig")->render("SedonaSBOTestBundle:Admin/Artist:_renderAlbum.html.twig", ['object'=>$target]); $event = $this->dispatchPostActionAssociationActionEvent($source, $action, $target); } return new JsonResponse($res); }
php
protected function manageJson($source, $target, $field, $action, $contains = true) { $res = ['result' => true, 'message' => '']; $getter = $this->getGetter($field); if ($source->$getter()->contains($target) == $contains) { $event = $this->dispatchPreActionAssociationActionEvent($source, $action, $target); if ($event->getAction() != AdminAssociationActionEvent::DONT_TOUCH) { $source2 = $event->getItem(); $target2 = $event->getTarget(); $action2 = $event->getAction(); $source2->$action2($target2); $this->get('doctrine.orm.entity_manager')->flush(); } //$res['html'] = $this->get("twig")->render("SedonaSBOTestBundle:Admin/Artist:_renderAlbum.html.twig", ['object'=>$target]); $event = $this->dispatchPostActionAssociationActionEvent($source, $action, $target); } return new JsonResponse($res); }
[ "protected", "function", "manageJson", "(", "$", "source", ",", "$", "target", ",", "$", "field", ",", "$", "action", ",", "$", "contains", "=", "true", ")", "{", "$", "res", "=", "[", "'result'", "=>", "true", ",", "'message'", "=>", "''", "]", ";", "$", "getter", "=", "$", "this", "->", "getGetter", "(", "$", "field", ")", ";", "if", "(", "$", "source", "->", "$", "getter", "(", ")", "->", "contains", "(", "$", "target", ")", "==", "$", "contains", ")", "{", "$", "event", "=", "$", "this", "->", "dispatchPreActionAssociationActionEvent", "(", "$", "source", ",", "$", "action", ",", "$", "target", ")", ";", "if", "(", "$", "event", "->", "getAction", "(", ")", "!=", "AdminAssociationActionEvent", "::", "DONT_TOUCH", ")", "{", "$", "source2", "=", "$", "event", "->", "getItem", "(", ")", ";", "$", "target2", "=", "$", "event", "->", "getTarget", "(", ")", ";", "$", "action2", "=", "$", "event", "->", "getAction", "(", ")", ";", "$", "source2", "->", "$", "action2", "(", "$", "target2", ")", ";", "$", "this", "->", "get", "(", "'doctrine.orm.entity_manager'", ")", "->", "flush", "(", ")", ";", "}", "//$res['html'] = $this->get(\"twig\")->render(\"SedonaSBOTestBundle:Admin/Artist:_renderAlbum.html.twig\", ['object'=>$target]);", "$", "event", "=", "$", "this", "->", "dispatchPostActionAssociationActionEvent", "(", "$", "source", ",", "$", "action", ",", "$", "target", ")", ";", "}", "return", "new", "JsonResponse", "(", "$", "res", ")", ";", "}" ]
@param $source @param $target @param $field @param $action @param bool $contains @return JsonResponse
[ "@param", "$source", "@param", "$target", "@param", "$field", "@param", "$action", "@param", "bool", "$contains" ]
train
https://github.com/Sedona-Solutions/sedona-sbo/blob/8548be4170d191cb1a3e263577aaaab49f04d5ce/src/Sedona/SBORuntimeBundle/Controller/BaseCrudController.php#L603-L626
nyeholt/silverstripe-external-content
thirdparty/Zend/Validate/StringLength.php
Zend_Validate_StringLength.setEncoding
public function setEncoding($encoding = null) { if ($encoding !== null) { $orig = iconv_get_encoding('internal_encoding'); $result = iconv_set_encoding('internal_encoding', $encoding); if (!$result) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Given encoding not supported on this OS!'); } iconv_set_encoding('internal_encoding', $orig); } $this->_encoding = $encoding; return $this; }
php
public function setEncoding($encoding = null) { if ($encoding !== null) { $orig = iconv_get_encoding('internal_encoding'); $result = iconv_set_encoding('internal_encoding', $encoding); if (!$result) { require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Given encoding not supported on this OS!'); } iconv_set_encoding('internal_encoding', $orig); } $this->_encoding = $encoding; return $this; }
[ "public", "function", "setEncoding", "(", "$", "encoding", "=", "null", ")", "{", "if", "(", "$", "encoding", "!==", "null", ")", "{", "$", "orig", "=", "iconv_get_encoding", "(", "'internal_encoding'", ")", ";", "$", "result", "=", "iconv_set_encoding", "(", "'internal_encoding'", ",", "$", "encoding", ")", ";", "if", "(", "!", "$", "result", ")", "{", "require_once", "'Zend/Validate/Exception.php'", ";", "throw", "new", "Zend_Validate_Exception", "(", "'Given encoding not supported on this OS!'", ")", ";", "}", "iconv_set_encoding", "(", "'internal_encoding'", ",", "$", "orig", ")", ";", "}", "$", "this", "->", "_encoding", "=", "$", "encoding", ";", "return", "$", "this", ";", "}" ]
Sets a new encoding to use @param string $encoding @return Zend_Validate_StringLength
[ "Sets", "a", "new", "encoding", "to", "use" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/thirdparty/Zend/Validate/StringLength.php#L173-L188
yuncms/framework
src/helpers/StringHelper.php
StringHelper.byteStrBetween
public static function byteStrBetween($string, $start, $end = null) { if (($startPos = static::byteStrPos($string, $start)) !== false) { if ($end) { if (($end_pos = static::byteStrPos($string, $end, $startPos + static::byteLength($start))) !== false) { return static::byteSubstr($string, $startPos + static::byteLength($start), $end_pos - ($startPos + static::byteLength($start))); } } else { return static::byteSubstr($string, $startPos); } } return false; }
php
public static function byteStrBetween($string, $start, $end = null) { if (($startPos = static::byteStrPos($string, $start)) !== false) { if ($end) { if (($end_pos = static::byteStrPos($string, $end, $startPos + static::byteLength($start))) !== false) { return static::byteSubstr($string, $startPos + static::byteLength($start), $end_pos - ($startPos + static::byteLength($start))); } } else { return static::byteSubstr($string, $startPos); } } return false; }
[ "public", "static", "function", "byteStrBetween", "(", "$", "string", ",", "$", "start", ",", "$", "end", "=", "null", ")", "{", "if", "(", "(", "$", "startPos", "=", "static", "::", "byteStrPos", "(", "$", "string", ",", "$", "start", ")", ")", "!==", "false", ")", "{", "if", "(", "$", "end", ")", "{", "if", "(", "(", "$", "end_pos", "=", "static", "::", "byteStrPos", "(", "$", "string", ",", "$", "end", ",", "$", "startPos", "+", "static", "::", "byteLength", "(", "$", "start", ")", ")", ")", "!==", "false", ")", "{", "return", "static", "::", "byteSubstr", "(", "$", "string", ",", "$", "startPos", "+", "static", "::", "byteLength", "(", "$", "start", ")", ",", "$", "end_pos", "-", "(", "$", "startPos", "+", "static", "::", "byteLength", "(", "$", "start", ")", ")", ")", ";", "}", "}", "else", "{", "return", "static", "::", "byteSubstr", "(", "$", "string", ",", "$", "startPos", ")", ";", "}", "}", "return", "false", ";", "}" ]
提取两个字符串之间的值,不包括分隔符 @param string $string 待提取的只付出 @param string $start 开始字符串 @param string|null $end 结束字符串,省略将返回所有的。 @return bool|string substring between $start and $end or false if either string is not found
[ "提取两个字符串之间的值,不包括分隔符" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L48-L60
yuncms/framework
src/helpers/StringHelper.php
StringHelper.contains
public static function contains(string $haystack, string $needle, bool $caseSensitive = true): bool { return BaseStringy::create($haystack)->contains($needle, $caseSensitive); }
php
public static function contains(string $haystack, string $needle, bool $caseSensitive = true): bool { return BaseStringy::create($haystack)->contains($needle, $caseSensitive); }
[ "public", "static", "function", "contains", "(", "string", "$", "haystack", ",", "string", "$", "needle", ",", "bool", "$", "caseSensitive", "=", "true", ")", ":", "bool", "{", "return", "BaseStringy", "::", "create", "(", "$", "haystack", ")", "->", "contains", "(", "$", "needle", ",", "$", "caseSensitive", ")", ";", "}" ]
Returns true if the string contains $needle, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false. @param string $haystack The string being checked. @param string $needle The substring to look for. @param bool $caseSensitive Whether or not to force case-sensitivity. @return bool Whether or not $haystack contains $needle.
[ "Returns", "true", "if", "the", "string", "contains", "$needle", "false", "otherwise", ".", "By", "default", "the", "comparison", "is", "case", "-", "sensitive", "but", "can", "be", "made", "insensitive", "by", "setting", "$caseSensitive", "to", "false", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L129-L132
yuncms/framework
src/helpers/StringHelper.php
StringHelper.containsAny
public static function containsAny(string $haystack, array $needles, bool $caseSensitive = true): bool { return BaseStringy::create($haystack)->containsAny($needles, $caseSensitive); }
php
public static function containsAny(string $haystack, array $needles, bool $caseSensitive = true): bool { return BaseStringy::create($haystack)->containsAny($needles, $caseSensitive); }
[ "public", "static", "function", "containsAny", "(", "string", "$", "haystack", ",", "array", "$", "needles", ",", "bool", "$", "caseSensitive", "=", "true", ")", ":", "bool", "{", "return", "BaseStringy", "::", "create", "(", "$", "haystack", ")", "->", "containsAny", "(", "$", "needles", ",", "$", "caseSensitive", ")", ";", "}" ]
Returns true if the string contains any $needles, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false. @param string $haystack The string being checked. @param array $needles The substrings to look for. @param bool $caseSensitive Whether or not to force case-sensitivity. @return bool Whether or not $haystack contains any $needles.
[ "Returns", "true", "if", "the", "string", "contains", "any", "$needles", "false", "otherwise", ".", "By", "default", "the", "comparison", "is", "case", "-", "sensitive", "but", "can", "be", "made", "insensitive", "by", "setting", "$caseSensitive", "to", "false", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L143-L146
yuncms/framework
src/helpers/StringHelper.php
StringHelper.countSubstrings
public static function countSubstrings(string $str, string $substring, bool $caseSensitive = true): int { return BaseStringy::create($str)->countSubstr($substring, $caseSensitive); }
php
public static function countSubstrings(string $str, string $substring, bool $caseSensitive = true): int { return BaseStringy::create($str)->countSubstr($substring, $caseSensitive); }
[ "public", "static", "function", "countSubstrings", "(", "string", "$", "str", ",", "string", "$", "substring", ",", "bool", "$", "caseSensitive", "=", "true", ")", ":", "int", "{", "return", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "countSubstr", "(", "$", "substring", ",", "$", "caseSensitive", ")", ";", "}" ]
Returns the number of occurrences of $substring in the given string. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false. @param string $str The string to search through. @param string $substring The substring to search for. @param bool $caseSensitive Whether or not to enforce case-sensitivity @return int The number of $substring occurrences.
[ "Returns", "the", "number", "of", "occurrences", "of", "$substring", "in", "the", "given", "string", ".", "By", "default", "the", "comparison", "is", "case", "-", "sensitive", "but", "can", "be", "made", "insensitive", "by", "setting", "$caseSensitive", "to", "false", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L171-L174
yuncms/framework
src/helpers/StringHelper.php
StringHelper.delimit
public static function delimit(string $str, string $delimiter): string { return (string)BaseStringy::create($str)->delimit($delimiter); }
php
public static function delimit(string $str, string $delimiter): string { return (string)BaseStringy::create($str)->delimit($delimiter); }
[ "public", "static", "function", "delimit", "(", "string", "$", "str", ",", "string", "$", "delimiter", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "delimit", "(", "$", "delimiter", ")", ";", "}" ]
Returns a lowercase and trimmed string separated by the given delimiter. Delimiters are inserted before uppercase characters (with the exception of the first character of the string), and in place of spaces, dashes, and underscores. Alpha delimiters are not converted to lowercase. @param string $str The string to delimit. @param string $delimiter Sequence used to separate parts of the string @return string The delimited string.
[ "Returns", "a", "lowercase", "and", "trimmed", "string", "separated", "by", "the", "given", "delimiter", ".", "Delimiters", "are", "inserted", "before", "uppercase", "characters", "(", "with", "the", "exception", "of", "the", "first", "character", "of", "the", "string", ")", "and", "in", "place", "of", "spaces", "dashes", "and", "underscores", ".", "Alpha", "delimiters", "are", "not", "converted", "to", "lowercase", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L185-L188
yuncms/framework
src/helpers/StringHelper.php
StringHelper.endsWith
public static function endsWith($str, $substring, $caseSensitive = true): bool { return BaseStringy::create($str)->endsWith($substring, $caseSensitive); }
php
public static function endsWith($str, $substring, $caseSensitive = true): bool { return BaseStringy::create($str)->endsWith($substring, $caseSensitive); }
[ "public", "static", "function", "endsWith", "(", "$", "str", ",", "$", "substring", ",", "$", "caseSensitive", "=", "true", ")", ":", "bool", "{", "return", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "endsWith", "(", "$", "substring", ",", "$", "caseSensitive", ")", ";", "}" ]
Returns true if the string ends with $substring, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false. @param string $str The string to check the end of. @param string $substring The substring to look for. @param bool $caseSensitive Whether or not to force case-sensitivity. @return bool Whether or not $str ends with $substring.
[ "Returns", "true", "if", "the", "string", "ends", "with", "$substring", "false", "otherwise", ".", "By", "default", "the", "comparison", "is", "case", "-", "sensitive", "but", "can", "be", "made", "insensitive", "by", "setting", "$caseSensitive", "to", "false", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L199-L202
yuncms/framework
src/helpers/StringHelper.php
StringHelper.ensureLeft
public static function ensureLeft(string $str, string $substring): string { return (string)BaseStringy::create($str)->ensureLeft($substring); }
php
public static function ensureLeft(string $str, string $substring): string { return (string)BaseStringy::create($str)->ensureLeft($substring); }
[ "public", "static", "function", "ensureLeft", "(", "string", "$", "str", ",", "string", "$", "substring", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "ensureLeft", "(", "$", "substring", ")", ";", "}" ]
Ensures that the string begins with $substring. If it doesn't, it's prepended. @param string $str The string to modify. @param string $substring The substring to add if not present. @return string The string prefixed by the $substring.
[ "Ensures", "that", "the", "string", "begins", "with", "$substring", ".", "If", "it", "doesn", "t", "it", "s", "prepended", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L211-L214
yuncms/framework
src/helpers/StringHelper.php
StringHelper.ensureRight
public static function ensureRight(string $str, string $substring): string { return (string)BaseStringy::create($str)->ensureRight($substring); }
php
public static function ensureRight(string $str, string $substring): string { return (string)BaseStringy::create($str)->ensureRight($substring); }
[ "public", "static", "function", "ensureRight", "(", "string", "$", "str", ",", "string", "$", "substring", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "ensureRight", "(", "$", "substring", ")", ";", "}" ]
Ensures that the string ends with $substring. If it doesn't, it's appended. @param string $str The string to modify. @param string $substring The substring to add if not present. @return string The string suffixed by the $substring.
[ "Ensures", "that", "the", "string", "ends", "with", "$substring", ".", "If", "it", "doesn", "t", "it", "s", "appended", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L223-L226
yuncms/framework
src/helpers/StringHelper.php
StringHelper.first
public static function first(string $str, int $number): string { return (string)BaseStringy::create($str)->first($number); }
php
public static function first(string $str, int $number): string { return (string)BaseStringy::create($str)->first($number); }
[ "public", "static", "function", "first", "(", "string", "$", "str", ",", "int", "$", "number", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "first", "(", "$", "number", ")", ";", "}" ]
Returns the first $n characters of the string. @param string $str The string from which to get the substring. @param int $number The Number of chars to retrieve from the start. @return string The first $number characters.
[ "Returns", "the", "first", "$n", "characters", "of", "the", "string", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L235-L238
yuncms/framework
src/helpers/StringHelper.php
StringHelper.charAt
public static function charAt(string $str, int $i): string { return (string)BaseStringy::create($str)->at($i); }
php
public static function charAt(string $str, int $i): string { return (string)BaseStringy::create($str)->at($i); }
[ "public", "static", "function", "charAt", "(", "string", "$", "str", ",", "int", "$", "i", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "at", "(", "$", "i", ")", ";", "}" ]
Returns the character at a specific point in a potentially multibyte string. @param string $str The string to check. @param int $i The 0-offset position in the string to check. @return string
[ "Returns", "the", "character", "at", "a", "specific", "point", "in", "a", "potentially", "multibyte", "string", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L247-L250
yuncms/framework
src/helpers/StringHelper.php
StringHelper.indexOf
public static function indexOf($str, $needle, $offset = 0) { return BaseStringy::create($str)->indexOf($needle, $offset); }
php
public static function indexOf($str, $needle, $offset = 0) { return BaseStringy::create($str)->indexOf($needle, $offset); }
[ "public", "static", "function", "indexOf", "(", "$", "str", ",", "$", "needle", ",", "$", "offset", "=", "0", ")", "{", "return", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "indexOf", "(", "$", "needle", ",", "$", "offset", ")", ";", "}" ]
Returns the index of the first occurrence of $needle in the string, and false if not found. Accepts an optional offset from which to begin the search. @param string $str The string to check the index of. @param string $needle The substring to look for. @param int $offset The offset from which to search. @return int|bool The occurrence's index if found, otherwise false.
[ "Returns", "the", "index", "of", "the", "first", "occurrence", "of", "$needle", "in", "the", "string", "and", "false", "if", "not", "found", ".", "Accepts", "an", "optional", "offset", "from", "which", "to", "begin", "the", "search", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L283-L286
yuncms/framework
src/helpers/StringHelper.php
StringHelper.indexOfLast
public static function indexOfLast($str, $needle, $offset = 0) { return BaseStringy::create($str)->indexOfLast($needle, $offset); }
php
public static function indexOfLast($str, $needle, $offset = 0) { return BaseStringy::create($str)->indexOfLast($needle, $offset); }
[ "public", "static", "function", "indexOfLast", "(", "$", "str", ",", "$", "needle", ",", "$", "offset", "=", "0", ")", "{", "return", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "indexOfLast", "(", "$", "needle", ",", "$", "offset", ")", ";", "}" ]
Returns the index of the last occurrence of $needle in the string,and false if not found. Accepts an optional offset from which to begin the search. Offsets may be negative to count from the last character in the string. @param string $str The string to check the last index of. @param string $needle The substring to look for. @param int $offset The offset from which to search. @return int|bool The occurrence's last index if found, otherwise false.
[ "Returns", "the", "index", "of", "the", "last", "occurrence", "of", "$needle", "in", "the", "string", "and", "false", "if", "not", "found", ".", "Accepts", "an", "optional", "offset", "from", "which", "to", "begin", "the", "search", ".", "Offsets", "may", "be", "negative", "to", "count", "from", "the", "last", "character", "in", "the", "string", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L298-L301
yuncms/framework
src/helpers/StringHelper.php
StringHelper.insert
public static function insert(string $str, string $substring, int $index): string { return (string)BaseStringy::create($str)->insert($substring, $index); }
php
public static function insert(string $str, string $substring, int $index): string { return (string)BaseStringy::create($str)->insert($substring, $index); }
[ "public", "static", "function", "insert", "(", "string", "$", "str", ",", "string", "$", "substring", ",", "int", "$", "index", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "insert", "(", "$", "substring", ",", "$", "index", ")", ";", "}" ]
Inserts $substring into the string at the $index provided. @param string $str The string to insert into. @param string $substring The string to be inserted. @param int $index The 0-based index at which to insert the substring. @return string The resulting string after the insertion
[ "Inserts", "$substring", "into", "the", "string", "at", "the", "$index", "provided", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L311-L314
yuncms/framework
src/helpers/StringHelper.php
StringHelper.last
public static function last(string $str, int $number): string { return (string)BaseStringy::create($str)->last($number); }
php
public static function last(string $str, int $number): string { return (string)BaseStringy::create($str)->last($number); }
[ "public", "static", "function", "last", "(", "string", "$", "str", ",", "int", "$", "number", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "last", "(", "$", "number", ")", ";", "}" ]
Returns the last $number characters of the string. @param string $str The string from which to get the substring. @param int $number The Number of chars to retrieve from the end. @return string The last $number characters.
[ "Returns", "the", "last", "$number", "characters", "of", "the", "string", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L400-L403
yuncms/framework
src/helpers/StringHelper.php
StringHelper.lines
public static function lines(string $str): array { $lines = BaseStringy::create($str)->lines(); foreach ($lines as $i => $line) { $lines[$i] = $line; } /** @var string[] $lines */ return $lines; }
php
public static function lines(string $str): array { $lines = BaseStringy::create($str)->lines(); foreach ($lines as $i => $line) { $lines[$i] = $line; } /** @var string[] $lines */ return $lines; }
[ "public", "static", "function", "lines", "(", "string", "$", "str", ")", ":", "array", "{", "$", "lines", "=", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "lines", "(", ")", ";", "foreach", "(", "$", "lines", "as", "$", "i", "=>", "$", "line", ")", "{", "$", "lines", "[", "$", "i", "]", "=", "$", "line", ";", "}", "/** @var string[] $lines */", "return", "$", "lines", ";", "}" ]
Splits on newlines and carriage returns, returning an array of strings corresponding to the lines in the string. @param string $str The string to split. @return string[] An array of strings.
[ "Splits", "on", "newlines", "and", "carriage", "returns", "returning", "an", "array", "of", "strings", "corresponding", "to", "the", "lines", "in", "the", "string", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L422-L432
yuncms/framework
src/helpers/StringHelper.php
StringHelper.toKebabCase
public static function toKebabCase(string $string, string $glue = '-', bool $lower = true, bool $removePunctuation = true): string { $words = self::_prepStringForCasing($string, $lower, $removePunctuation); return implode($glue, $words); }
php
public static function toKebabCase(string $string, string $glue = '-', bool $lower = true, bool $removePunctuation = true): string { $words = self::_prepStringForCasing($string, $lower, $removePunctuation); return implode($glue, $words); }
[ "public", "static", "function", "toKebabCase", "(", "string", "$", "string", ",", "string", "$", "glue", "=", "'-'", ",", "bool", "$", "lower", "=", "true", ",", "bool", "$", "removePunctuation", "=", "true", ")", ":", "string", "{", "$", "words", "=", "self", "::", "_prepStringForCasing", "(", "$", "string", ",", "$", "lower", ",", "$", "removePunctuation", ")", ";", "return", "implode", "(", "$", "glue", ",", "$", "words", ")", ";", "}" ]
kebab-cases a string. @param string $string The string @param string $glue The string used to glue the words together (default is a hyphen) @param bool $lower Whether the string should be lowercased (default is true) @param bool $removePunctuation Whether punctuation marks should be removed (default is true) @return string The kebab-cased string @see toCamelCase() @see toPascalCase() @see toSnakeCase()
[ "kebab", "-", "cases", "a", "string", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L457-L462
yuncms/framework
src/helpers/StringHelper.php
StringHelper.toCamelCase
public static function toCamelCase(string $string): string { $words = self::_prepStringForCasing($string); if (empty($words)) { return ''; } $string = array_shift($words) . implode('', array_map([ static::class, 'upperCaseFirst' ], $words)); return $string; }
php
public static function toCamelCase(string $string): string { $words = self::_prepStringForCasing($string); if (empty($words)) { return ''; } $string = array_shift($words) . implode('', array_map([ static::class, 'upperCaseFirst' ], $words)); return $string; }
[ "public", "static", "function", "toCamelCase", "(", "string", "$", "string", ")", ":", "string", "{", "$", "words", "=", "self", "::", "_prepStringForCasing", "(", "$", "string", ")", ";", "if", "(", "empty", "(", "$", "words", ")", ")", "{", "return", "''", ";", "}", "$", "string", "=", "array_shift", "(", "$", "words", ")", ".", "implode", "(", "''", ",", "array_map", "(", "[", "static", "::", "class", ",", "'upperCaseFirst'", "]", ",", "$", "words", ")", ")", ";", "return", "$", "string", ";", "}" ]
camelCases a string. @param string $string The string @return string @see toKebabCase() @see toPascalCase() @see toSnakeCase()
[ "camelCases", "a", "string", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L473-L487
yuncms/framework
src/helpers/StringHelper.php
StringHelper.toPascalCase
public static function toPascalCase(string $string): string { $words = self::_prepStringForCasing($string); $string = implode('', array_map([ static::class, 'upperCaseFirst' ], $words)); return $string; }
php
public static function toPascalCase(string $string): string { $words = self::_prepStringForCasing($string); $string = implode('', array_map([ static::class, 'upperCaseFirst' ], $words)); return $string; }
[ "public", "static", "function", "toPascalCase", "(", "string", "$", "string", ")", ":", "string", "{", "$", "words", "=", "self", "::", "_prepStringForCasing", "(", "$", "string", ")", ";", "$", "string", "=", "implode", "(", "''", ",", "array_map", "(", "[", "static", "::", "class", ",", "'upperCaseFirst'", "]", ",", "$", "words", ")", ")", ";", "return", "$", "string", ";", "}" ]
PascalCases a string. @param string $string The string @return string @see toKebabCase() @see toCamelCase() @see toSnakeCase()
[ "PascalCases", "a", "string", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L498-L507
yuncms/framework
src/helpers/StringHelper.php
StringHelper.toSnakeCase
public static function toSnakeCase(string $string): string { $words = self::_prepStringForCasing($string); return implode('_', $words); }
php
public static function toSnakeCase(string $string): string { $words = self::_prepStringForCasing($string); return implode('_', $words); }
[ "public", "static", "function", "toSnakeCase", "(", "string", "$", "string", ")", ":", "string", "{", "$", "words", "=", "self", "::", "_prepStringForCasing", "(", "$", "string", ")", ";", "return", "implode", "(", "'_'", ",", "$", "words", ")", ";", "}" ]
snake_cases a string. @param string $string The string @return string @see toKebabCase() @see toCamelCase() @see toPascalCase()
[ "snake_cases", "a", "string", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L518-L523
yuncms/framework
src/helpers/StringHelper.php
StringHelper.split
public static function split(string $string, string $delimiter = ','): array { return preg_split('/\s*' . preg_quote($delimiter, '/') . '\s*/', $string, -1, PREG_SPLIT_NO_EMPTY); }
php
public static function split(string $string, string $delimiter = ','): array { return preg_split('/\s*' . preg_quote($delimiter, '/') . '\s*/', $string, -1, PREG_SPLIT_NO_EMPTY); }
[ "public", "static", "function", "split", "(", "string", "$", "string", ",", "string", "$", "delimiter", "=", "','", ")", ":", "array", "{", "return", "preg_split", "(", "'/\\s*'", ".", "preg_quote", "(", "$", "delimiter", ",", "'/'", ")", ".", "'\\s*/'", ",", "$", "string", ",", "-", "1", ",", "PREG_SPLIT_NO_EMPTY", ")", ";", "}" ]
Splits a string into chunks on a given delimiter. @param string $string The string @param string $delimiter The delimiter to split the string on (defaults to a comma) @return string[] The segments of the string
[ "Splits", "a", "string", "into", "chunks", "on", "a", "given", "delimiter", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L532-L535
yuncms/framework
src/helpers/StringHelper.php
StringHelper.padBoth
public static function padBoth($str, $length, $padStr = ' '): string { return (string)BaseStringy::create($str)->padBoth($length, $padStr); }
php
public static function padBoth($str, $length, $padStr = ' '): string { return (string)BaseStringy::create($str)->padBoth($length, $padStr); }
[ "public", "static", "function", "padBoth", "(", "$", "str", ",", "$", "length", ",", "$", "padStr", "=", "' '", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "padBoth", "(", "$", "length", ",", "$", "padStr", ")", ";", "}" ]
Returns a new string of a given length such that both sides of the string are padded. @param string $str The string to pad. @param int $length The desired string length after padding. @param string $padStr The string used to pad, defaults to space. @return string The padded string.
[ "Returns", "a", "new", "string", "of", "a", "given", "length", "such", "that", "both", "sides", "of", "the", "string", "are", "padded", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L570-L573
yuncms/framework
src/helpers/StringHelper.php
StringHelper.padLeft
public static function padLeft(string $str, int $length, string $padStr = ' '): string { return (string)BaseStringy::create($str)->padLeft($length, $padStr); }
php
public static function padLeft(string $str, int $length, string $padStr = ' '): string { return (string)BaseStringy::create($str)->padLeft($length, $padStr); }
[ "public", "static", "function", "padLeft", "(", "string", "$", "str", ",", "int", "$", "length", ",", "string", "$", "padStr", "=", "' '", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "padLeft", "(", "$", "length", ",", "$", "padStr", ")", ";", "}" ]
Returns a new string of a given length such that the beginning of the string is padded. @param string $str The string to pad. @param int $length The desired string length after padding. @param string $padStr The string used to pad, defaults to space. @return string The padded string.
[ "Returns", "a", "new", "string", "of", "a", "given", "length", "such", "that", "the", "beginning", "of", "the", "string", "is", "padded", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L583-L586
yuncms/framework
src/helpers/StringHelper.php
StringHelper.padRight
public static function padRight(string $str, int $length, string $padStr = ' '): string { return (string)BaseStringy::create($str)->padRight($length, $padStr); }
php
public static function padRight(string $str, int $length, string $padStr = ' '): string { return (string)BaseStringy::create($str)->padRight($length, $padStr); }
[ "public", "static", "function", "padRight", "(", "string", "$", "str", ",", "int", "$", "length", ",", "string", "$", "padStr", "=", "' '", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "padRight", "(", "$", "length", ",", "$", "padStr", ")", ";", "}" ]
Returns a new string of a given length such that the end of the string is padded. @param string $str The string to pad. @param int $length The desired string length after padding. @param string $padStr The string used to pad, defaults to space. @return string The padded string.
[ "Returns", "a", "new", "string", "of", "a", "given", "length", "such", "that", "the", "end", "of", "the", "string", "is", "padded", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L596-L599
yuncms/framework
src/helpers/StringHelper.php
StringHelper.randomString
public static function randomString(int $length = 36, bool $extendedChars = false): string { if ($extendedChars) { $validChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!@#$%^&*()-_=+[]\{}|;:\'",./<>?"'; } else { $validChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; } return static::randomStringWithChars($validChars, $length); }
php
public static function randomString(int $length = 36, bool $extendedChars = false): string { if ($extendedChars) { $validChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!@#$%^&*()-_=+[]\{}|;:\'",./<>?"'; } else { $validChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; } return static::randomStringWithChars($validChars, $length); }
[ "public", "static", "function", "randomString", "(", "int", "$", "length", "=", "36", ",", "bool", "$", "extendedChars", "=", "false", ")", ":", "string", "{", "if", "(", "$", "extendedChars", ")", "{", "$", "validChars", "=", "'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`~!@#$%^&*()-_=+[]\\{}|;:\\'\",./<>?\"'", ";", "}", "else", "{", "$", "validChars", "=", "'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'", ";", "}", "return", "static", "::", "randomStringWithChars", "(", "$", "validChars", ",", "$", "length", ")", ";", "}" ]
Generates a random string of latin alphanumeric characters that defaults to a $length of 36. If $extendedChars is set to true, additional symbols can be included in the string. Note that the generated string is *not* a cryptographically secure string. @param int $length The length of the random string. Defaults to 36. @param bool $extendedChars Whether to include symbols in the random string. @return string The randomly generated string. @throws \Exception
[ "Generates", "a", "random", "string", "of", "latin", "alphanumeric", "characters", "that", "defaults", "to", "a", "$length", "of", "36", ".", "If", "$extendedChars", "is", "set", "to", "true", "additional", "symbols", "can", "be", "included", "in", "the", "string", ".", "Note", "that", "the", "generated", "string", "is", "*", "not", "*", "a", "cryptographically", "secure", "string", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L611-L620
yuncms/framework
src/helpers/StringHelper.php
StringHelper.randomStringWithChars
public static function randomStringWithChars(string $validChars, int $length): string { $randomString = ''; // count the number of chars in the valid chars string so we know how many choices we have $numValidChars = static::length($validChars); // repeat the steps until we've created a string of the right length for ($i = 0; $i < $length; $i++) { // pick a random number from 1 up to the number of valid chars $randomPick = random_int(1, $numValidChars); // take the random character out of the string of valid chars $randomChar = $validChars[$randomPick - 1]; // add the randomly-chosen char onto the end of our string $randomString .= $randomChar; } return $randomString; }
php
public static function randomStringWithChars(string $validChars, int $length): string { $randomString = ''; // count the number of chars in the valid chars string so we know how many choices we have $numValidChars = static::length($validChars); // repeat the steps until we've created a string of the right length for ($i = 0; $i < $length; $i++) { // pick a random number from 1 up to the number of valid chars $randomPick = random_int(1, $numValidChars); // take the random character out of the string of valid chars $randomChar = $validChars[$randomPick - 1]; // add the randomly-chosen char onto the end of our string $randomString .= $randomChar; } return $randomString; }
[ "public", "static", "function", "randomStringWithChars", "(", "string", "$", "validChars", ",", "int", "$", "length", ")", ":", "string", "{", "$", "randomString", "=", "''", ";", "// count the number of chars in the valid chars string so we know how many choices we have", "$", "numValidChars", "=", "static", "::", "length", "(", "$", "validChars", ")", ";", "// repeat the steps until we've created a string of the right length", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "length", ";", "$", "i", "++", ")", "{", "// pick a random number from 1 up to the number of valid chars", "$", "randomPick", "=", "random_int", "(", "1", ",", "$", "numValidChars", ")", ";", "// take the random character out of the string of valid chars", "$", "randomChar", "=", "$", "validChars", "[", "$", "randomPick", "-", "1", "]", ";", "// add the randomly-chosen char onto the end of our string", "$", "randomString", ".=", "$", "randomChar", ";", "}", "return", "$", "randomString", ";", "}" ]
Generates a random string of characters. Note that the generated string is *not* a cryptographically secure string. If you need a cryptographically secure string, use [[\craft\services\Security::generateRandomString()|<code>Craft::$app->security->generateRandomString()</code>]]. @param string $validChars A string containing the valid characters @param int $length The length of the random string @return string The randomly generated string. @throws \Exception
[ "Generates", "a", "random", "string", "of", "characters", ".", "Note", "that", "the", "generated", "string", "is", "*", "not", "*", "a", "cryptographically", "secure", "string", ".", "If", "you", "need", "a", "cryptographically", "secure", "string", "use", "[[", "\\", "craft", "\\", "services", "\\", "Security", "::", "generateRandomString", "()", "|<code", ">", "Craft", "::", "$app", "-", ">", "security", "-", ">", "generateRandomString", "()", "<", "/", "code", ">", "]]", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L632-L652
yuncms/framework
src/helpers/StringHelper.php
StringHelper.regexReplace
public static function regexReplace(string $str, string $pattern, string $replacement, string $options = 'msr'): string { return (string)BaseStringy::create($str)->regexReplace($pattern, $replacement, $options); }
php
public static function regexReplace(string $str, string $pattern, string $replacement, string $options = 'msr'): string { return (string)BaseStringy::create($str)->regexReplace($pattern, $replacement, $options); }
[ "public", "static", "function", "regexReplace", "(", "string", "$", "str", ",", "string", "$", "pattern", ",", "string", "$", "replacement", ",", "string", "$", "options", "=", "'msr'", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "regexReplace", "(", "$", "pattern", ",", "$", "replacement", ",", "$", "options", ")", ";", "}" ]
Replaces all occurrences of $pattern in $str by $replacement. An alias for mb_ereg_replace(). @param string $str The haystack to search through. @param string $pattern The regular expression pattern. @param string $replacement The string to replace with. @param string $options Matching conditions to be used. Defaults to 'msr'. See [here](http://php.net/manual/en/function.mb-ereg-replace.php) for all options. @return string The resulting string after the replacements.
[ "Replaces", "all", "occurrences", "of", "$pattern", "in", "$str", "by", "$replacement", ".", "An", "alias", "for", "mb_ereg_replace", "()", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L664-L667
yuncms/framework
src/helpers/StringHelper.php
StringHelper.removeLeft
public static function removeLeft(string $str, string $substring): string { return (string)BaseStringy::create($str)->removeLeft($substring); }
php
public static function removeLeft(string $str, string $substring): string { return (string)BaseStringy::create($str)->removeLeft($substring); }
[ "public", "static", "function", "removeLeft", "(", "string", "$", "str", ",", "string", "$", "substring", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "removeLeft", "(", "$", "substring", ")", ";", "}" ]
Returns a new string with the prefix $substring removed, if present. @param string $str The string from which to remove the prefix. @param string $substring The prefix to remove. @return string The string without the prefix $substring.
[ "Returns", "a", "new", "string", "with", "the", "prefix", "$substring", "removed", "if", "present", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L676-L679
yuncms/framework
src/helpers/StringHelper.php
StringHelper.removeRight
public static function removeRight(string $str, string $substring): string { return (string)BaseStringy::create($str)->removeRight($substring); }
php
public static function removeRight(string $str, string $substring): string { return (string)BaseStringy::create($str)->removeRight($substring); }
[ "public", "static", "function", "removeRight", "(", "string", "$", "str", ",", "string", "$", "substring", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "removeRight", "(", "$", "substring", ")", ";", "}" ]
Returns a new string with the suffix $substring removed, if present. @param string $str The string from which to remove the suffix. @param string $substring The suffix to remove. @return string The string without the suffix $substring.
[ "Returns", "a", "new", "string", "with", "the", "suffix", "$substring", "removed", "if", "present", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L688-L691
yuncms/framework
src/helpers/StringHelper.php
StringHelper.replace
public static function replace(string $str, string $search, string $replacement): string { return (string)BaseStringy::create($str)->replace($search, $replacement); }
php
public static function replace(string $str, string $search, string $replacement): string { return (string)BaseStringy::create($str)->replace($search, $replacement); }
[ "public", "static", "function", "replace", "(", "string", "$", "str", ",", "string", "$", "search", ",", "string", "$", "replacement", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "replace", "(", "$", "search", ",", "$", "replacement", ")", ";", "}" ]
Replaces all occurrences of $search in $str by $replacement. @param string $str The haystack to search through. @param string $search The needle to search for. @param string $replacement The string to replace with. @return string The resulting string after the replacements.
[ "Replaces", "all", "occurrences", "of", "$search", "in", "$str", "by", "$replacement", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L701-L704
yuncms/framework
src/helpers/StringHelper.php
StringHelper.safeTruncate
public static function safeTruncate(string $str, int $length, string $substring = ''): string { return (string)BaseStringy::create($str)->safeTruncate($length, $substring); }
php
public static function safeTruncate(string $str, int $length, string $substring = ''): string { return (string)BaseStringy::create($str)->safeTruncate($length, $substring); }
[ "public", "static", "function", "safeTruncate", "(", "string", "$", "str", ",", "int", "$", "length", ",", "string", "$", "substring", "=", "''", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "safeTruncate", "(", "$", "length", ",", "$", "substring", ")", ";", "}" ]
Truncates the string to a given length, while ensuring that it does not split words. If $substring is provided, and truncating occurs, the string is further truncated so that the substring may be appended without exceeding t he desired length. @param string $str The string to truncate. @param int $length The desired length of the truncated string. @param string $substring The substring to append if it can fit. @return string The resulting string after truncating.
[ "Truncates", "the", "string", "to", "a", "given", "length", "while", "ensuring", "that", "it", "does", "not", "split", "words", ".", "If", "$substring", "is", "provided", "and", "truncating", "occurs", "the", "string", "is", "further", "truncated", "so", "that", "the", "substring", "may", "be", "appended", "without", "exceeding", "t", "he", "desired", "length", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L727-L730
yuncms/framework
src/helpers/StringHelper.php
StringHelper.startsWith
public static function startsWith($str, $substring, $caseSensitive = true): bool { return BaseStringy::create($str)->startsWith($substring, $caseSensitive); }
php
public static function startsWith($str, $substring, $caseSensitive = true): bool { return BaseStringy::create($str)->startsWith($substring, $caseSensitive); }
[ "public", "static", "function", "startsWith", "(", "$", "str", ",", "$", "substring", ",", "$", "caseSensitive", "=", "true", ")", ":", "bool", "{", "return", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "startsWith", "(", "$", "substring", ",", "$", "caseSensitive", ")", ";", "}" ]
Returns true if the string begins with $substring, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false. @param string $str The string to check the start of. @param string $substring The substring to look for. @param bool $caseSensitive Whether or not to enforce case-sensitivity. @return bool Whether or not $str starts with $substring.
[ "Returns", "true", "if", "the", "string", "begins", "with", "$substring", "false", "otherwise", ".", "By", "default", "the", "comparison", "is", "case", "-", "sensitive", "but", "can", "be", "made", "insensitive", "by", "setting", "$caseSensitive", "to", "false", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L741-L744
yuncms/framework
src/helpers/StringHelper.php
StringHelper.substr
public static function substr(string $str, int $start, int $length = null): string { return (string)BaseStringy::create($str)->substr($start, $length); }
php
public static function substr(string $str, int $start, int $length = null): string { return (string)BaseStringy::create($str)->substr($start, $length); }
[ "public", "static", "function", "substr", "(", "string", "$", "str", ",", "int", "$", "start", ",", "int", "$", "length", "=", "null", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "substr", "(", "$", "start", ",", "$", "length", ")", ";", "}" ]
Returns the substring beginning at $start with the specified|null $length. It differs from the mb_substr() function in that providing a|null $length of null will return the rest of the string, rather than an empty string. @param string $str The string to get the length of. @param int $start Position of the first character to use. @param int|null $length Maximum number of characters used. @return string The substring of $str.
[ "Returns", "the", "substring", "beginning", "at", "$start", "with", "the", "specified|null", "$length", ".", "It", "differs", "from", "the", "mb_substr", "()", "function", "in", "that", "providing", "a|null", "$length", "of", "null", "will", "return", "the", "rest", "of", "the", "string", "rather", "than", "an", "empty", "string", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L755-L758
yuncms/framework
src/helpers/StringHelper.php
StringHelper.titleize
public static function titleize(string $str, array $ignore = null): string { return (string)BaseStringy::create($str)->titleize($ignore); }
php
public static function titleize(string $str, array $ignore = null): string { return (string)BaseStringy::create($str)->titleize($ignore); }
[ "public", "static", "function", "titleize", "(", "string", "$", "str", ",", "array", "$", "ignore", "=", "null", ")", ":", "string", "{", "return", "(", "string", ")", "BaseStringy", "::", "create", "(", "$", "str", ")", "->", "titleize", "(", "$", "ignore", ")", ";", "}" ]
Returns a trimmed string with the first letter of each word capitalized. Ignores the case of other letters, preserving any acronyms. Also accepts an array, $ignore, allowing you to list words not to be capitalized. @param string $str The string to titleize. @param array|null $ignore An array of words not to capitalize. @return string The titleized string.
[ "Returns", "a", "trimmed", "string", "with", "the", "first", "letter", "of", "each", "word", "capitalized", ".", "Ignores", "the", "case", "of", "other", "letters", "preserving", "any", "acronyms", ".", "Also", "accepts", "an", "array", "$ignore", "allowing", "you", "to", "list", "words", "not", "to", "be", "capitalized", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L779-L782
yuncms/framework
src/helpers/StringHelper.php
StringHelper.toString
public static function toString($object, string $glue = ','): string { if (is_scalar($object) || (is_object($object) && method_exists($object, '__toString'))) { return (string)$object; } if (is_array($object) || $object instanceof \IteratorAggregate) { $stringValues = []; foreach ($object as $value) { if (($value = static::toString($value, $glue)) !== '') { $stringValues[] = $value; } } return implode($glue, $stringValues); } return ''; }
php
public static function toString($object, string $glue = ','): string { if (is_scalar($object) || (is_object($object) && method_exists($object, '__toString'))) { return (string)$object; } if (is_array($object) || $object instanceof \IteratorAggregate) { $stringValues = []; foreach ($object as $value) { if (($value = static::toString($value, $glue)) !== '') { $stringValues[] = $value; } } return implode($glue, $stringValues); } return ''; }
[ "public", "static", "function", "toString", "(", "$", "object", ",", "string", "$", "glue", "=", "','", ")", ":", "string", "{", "if", "(", "is_scalar", "(", "$", "object", ")", "||", "(", "is_object", "(", "$", "object", ")", "&&", "method_exists", "(", "$", "object", ",", "'__toString'", ")", ")", ")", "{", "return", "(", "string", ")", "$", "object", ";", "}", "if", "(", "is_array", "(", "$", "object", ")", "||", "$", "object", "instanceof", "\\", "IteratorAggregate", ")", "{", "$", "stringValues", "=", "[", "]", ";", "foreach", "(", "$", "object", "as", "$", "value", ")", "{", "if", "(", "(", "$", "value", "=", "static", "::", "toString", "(", "$", "value", ",", "$", "glue", ")", ")", "!==", "''", ")", "{", "$", "stringValues", "[", "]", "=", "$", "value", ";", "}", "}", "return", "implode", "(", "$", "glue", ",", "$", "stringValues", ")", ";", "}", "return", "''", ";", "}" ]
Converts an object to its string representation. If the object is an array, will glue the array elements togeter with the $glue param. Otherwise will cast the object to a string. @param mixed $object The object to convert to a string. @param string $glue The glue to use if the object is an array. @return string The string representation of the object.
[ "Converts", "an", "object", "to", "its", "string", "representation", ".", "If", "the", "object", "is", "an", "array", "will", "glue", "the", "array", "elements", "togeter", "with", "the", "$glue", "param", ".", "Otherwise", "will", "cast", "the", "object", "to", "a", "string", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L803-L822
yuncms/framework
src/helpers/StringHelper.php
StringHelper.ObjectId
public static function ObjectId() { if (class_exists('MongoDB\BSON\ObjectId')) {//优先使用 return (new ObjectId())->__toString(); } else { try { $bytes = Yii::$app->security->generateRandomKey(32); return substr(bin2hex($bytes), 0, 24); } catch (Exception $e) { try { return sprintf('%04x%04x%04x%04x%04x%04x', // 32 bits for "time_low" random_int(0, 0xffff), random_int(0, 0xffff), // 16 bits for "time_mid" random_int(0, 0xffff), // 16 bits for "time_hi_and_version", four most significant bits holds version number 4 random_int(0, 0x0fff) | 0x4000, // 16 bits, 8 bits for "clk_seq_hi_res", 8 bits for "clk_seq_low", two most significant bits holds zero and // one for variant DCE1.1 random_int(0, 0x3fff) | 0x8000, // 16 bits for "node" random_int(0, 0xffff) ); } catch (\Exception $e) { $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $str = ''; for ($i = 0; $i < 24; $i++) { $str .= $chars[mt_rand(0, strlen($chars) - 1)]; } return $str; } } } }
php
public static function ObjectId() { if (class_exists('MongoDB\BSON\ObjectId')) {//优先使用 return (new ObjectId())->__toString(); } else { try { $bytes = Yii::$app->security->generateRandomKey(32); return substr(bin2hex($bytes), 0, 24); } catch (Exception $e) { try { return sprintf('%04x%04x%04x%04x%04x%04x', // 32 bits for "time_low" random_int(0, 0xffff), random_int(0, 0xffff), // 16 bits for "time_mid" random_int(0, 0xffff), // 16 bits for "time_hi_and_version", four most significant bits holds version number 4 random_int(0, 0x0fff) | 0x4000, // 16 bits, 8 bits for "clk_seq_hi_res", 8 bits for "clk_seq_low", two most significant bits holds zero and // one for variant DCE1.1 random_int(0, 0x3fff) | 0x8000, // 16 bits for "node" random_int(0, 0xffff) ); } catch (\Exception $e) { $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $str = ''; for ($i = 0; $i < 24; $i++) { $str .= $chars[mt_rand(0, strlen($chars) - 1)]; } return $str; } } } }
[ "public", "static", "function", "ObjectId", "(", ")", "{", "if", "(", "class_exists", "(", "'MongoDB\\BSON\\ObjectId'", ")", ")", "{", "//优先使用", "return", "(", "new", "ObjectId", "(", ")", ")", "->", "__toString", "(", ")", ";", "}", "else", "{", "try", "{", "$", "bytes", "=", "Yii", "::", "$", "app", "->", "security", "->", "generateRandomKey", "(", "32", ")", ";", "return", "substr", "(", "bin2hex", "(", "$", "bytes", ")", ",", "0", ",", "24", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "try", "{", "return", "sprintf", "(", "'%04x%04x%04x%04x%04x%04x'", ",", "// 32 bits for \"time_low\"", "random_int", "(", "0", ",", "0xffff", ")", ",", "random_int", "(", "0", ",", "0xffff", ")", ",", "// 16 bits for \"time_mid\"", "random_int", "(", "0", ",", "0xffff", ")", ",", "// 16 bits for \"time_hi_and_version\", four most significant bits holds version number 4", "random_int", "(", "0", ",", "0x0fff", ")", "|", "0x4000", ",", "// 16 bits, 8 bits for \"clk_seq_hi_res\", 8 bits for \"clk_seq_low\", two most significant bits holds zero and", "// one for variant DCE1.1", "random_int", "(", "0", ",", "0x3fff", ")", "|", "0x8000", ",", "// 16 bits for \"node\"", "random_int", "(", "0", ",", "0xffff", ")", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "chars", "=", "'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'", ";", "$", "str", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "24", ";", "$", "i", "++", ")", "{", "$", "str", ".=", "$", "chars", "[", "mt_rand", "(", "0", ",", "strlen", "(", "$", "chars", ")", "-", "1", ")", "]", ";", "}", "return", "$", "str", ";", "}", "}", "}", "}" ]
获取一个对象ID @return string
[ "获取一个对象ID" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/helpers/StringHelper.php#L873-L906