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 |
|---|---|---|---|---|---|---|---|---|---|---|
platformsh/platformsh-cli | src/Command/Self/SelfInstallCommand.php | SelfInstallCommand.findShellConfigFile | protected function findShellConfigFile()
{
// Special handling for the .environment file on Platform.sh environments.
$envPrefix = $this->config()->get('service.env_prefix');
if (getenv($envPrefix . 'PROJECT') !== false
&& getenv($envPrefix . 'APP_DIR') !== false
&& getenv($envPrefix . 'APP_DIR') === Filesystem::getHomeDirectory()) {
return getenv($envPrefix . 'APP_DIR') . '/.environment';
}
$shell = null;
if (getenv('SHELL') !== false) {
$shell = basename(getenv('SHELL'));
$this->debug('Detected shell: ' . $shell);
}
$candidates = [
'.bashrc',
'.bash_profile',
];
// OS X ignores .bashrc if .bash_profile is present.
if (OsUtil::isOsX()) {
$candidates = [
'.bash_profile',
'.bashrc',
];
}
if ($shell === 'zsh' || getenv('ZSH')) {
array_unshift($candidates, '.zshrc');
array_unshift($candidates, '.zprofile');
}
$homeDir = Filesystem::getHomeDirectory();
foreach ($candidates as $candidate) {
if (file_exists($homeDir . DIRECTORY_SEPARATOR . $candidate)) {
$this->debug('Found existing config file: ' . $homeDir . DIRECTORY_SEPARATOR . $candidate);
return $homeDir . DIRECTORY_SEPARATOR . $candidate;
}
}
// If none of the files exist (yet), and we are on Bash, and the home
// directory is writable, then use ~/.bashrc.
if (is_writable($homeDir) && $shell === 'bash') {
$this->debug('Defaulting to ~/.bashrc');
return $homeDir . DIRECTORY_SEPARATOR . '.bashrc';
}
return false;
} | php | protected function findShellConfigFile()
{
// Special handling for the .environment file on Platform.sh environments.
$envPrefix = $this->config()->get('service.env_prefix');
if (getenv($envPrefix . 'PROJECT') !== false
&& getenv($envPrefix . 'APP_DIR') !== false
&& getenv($envPrefix . 'APP_DIR') === Filesystem::getHomeDirectory()) {
return getenv($envPrefix . 'APP_DIR') . '/.environment';
}
$shell = null;
if (getenv('SHELL') !== false) {
$shell = basename(getenv('SHELL'));
$this->debug('Detected shell: ' . $shell);
}
$candidates = [
'.bashrc',
'.bash_profile',
];
// OS X ignores .bashrc if .bash_profile is present.
if (OsUtil::isOsX()) {
$candidates = [
'.bash_profile',
'.bashrc',
];
}
if ($shell === 'zsh' || getenv('ZSH')) {
array_unshift($candidates, '.zshrc');
array_unshift($candidates, '.zprofile');
}
$homeDir = Filesystem::getHomeDirectory();
foreach ($candidates as $candidate) {
if (file_exists($homeDir . DIRECTORY_SEPARATOR . $candidate)) {
$this->debug('Found existing config file: ' . $homeDir . DIRECTORY_SEPARATOR . $candidate);
return $homeDir . DIRECTORY_SEPARATOR . $candidate;
}
}
// If none of the files exist (yet), and we are on Bash, and the home
// directory is writable, then use ~/.bashrc.
if (is_writable($homeDir) && $shell === 'bash') {
$this->debug('Defaulting to ~/.bashrc');
return $homeDir . DIRECTORY_SEPARATOR . '.bashrc';
}
return false;
} | [
"protected",
"function",
"findShellConfigFile",
"(",
")",
"{",
"// Special handling for the .environment file on Platform.sh environments.",
"$",
"envPrefix",
"=",
"$",
"this",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"'service.env_prefix'",
")",
";",
"if",
"(",
"g... | Finds a shell configuration file for the user.
@return string|false
The absolute path to a shell config file, or false on failure. | [
"Finds",
"a",
"shell",
"configuration",
"file",
"for",
"the",
"user",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Self/SelfInstallCommand.php#L293-L345 |
platformsh/platformsh-cli | src/Service/Config.php | Config.has | public function has($name, $notNull = true)
{
$value = NestedArrayUtil::getNestedArrayValue(self::$config, explode('.', $name), $exists);
return $exists && (!$notNull || $value !== null);
} | php | public function has($name, $notNull = true)
{
$value = NestedArrayUtil::getNestedArrayValue(self::$config, explode('.', $name), $exists);
return $exists && (!$notNull || $value !== null);
} | [
"public",
"function",
"has",
"(",
"$",
"name",
",",
"$",
"notNull",
"=",
"true",
")",
"{",
"$",
"value",
"=",
"NestedArrayUtil",
"::",
"getNestedArrayValue",
"(",
"self",
"::",
"$",
"config",
",",
"explode",
"(",
"'.'",
",",
"$",
"name",
")",
",",
"$... | Check if a configuration value is defined.
@param string $name The configuration name (e.g. 'application.name').
@param bool $notNull Set false to treat null configuration values as
defined.
@return bool | [
"Check",
"if",
"a",
"configuration",
"value",
"is",
"defined",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Config.php#L59-L64 |
platformsh/platformsh-cli | src/Service/Config.php | Config.get | public function get($name)
{
$value = NestedArrayUtil::getNestedArrayValue(self::$config, explode('.', $name), $exists);
if (!$exists) {
throw new \RuntimeException('Configuration not defined: ' . $name);
}
return $value;
} | php | public function get($name)
{
$value = NestedArrayUtil::getNestedArrayValue(self::$config, explode('.', $name), $exists);
if (!$exists) {
throw new \RuntimeException('Configuration not defined: ' . $name);
}
return $value;
} | [
"public",
"function",
"get",
"(",
"$",
"name",
")",
"{",
"$",
"value",
"=",
"NestedArrayUtil",
"::",
"getNestedArrayValue",
"(",
"self",
"::",
"$",
"config",
",",
"explode",
"(",
"'.'",
",",
"$",
"name",
")",
",",
"$",
"exists",
")",
";",
"if",
"(",
... | Get a configuration value.
@param string $name The configuration name (e.g. 'application.name').
@throws \RuntimeException if the configuration is not defined.
@return null|string|bool|array | [
"Get",
"a",
"configuration",
"value",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Config.php#L75-L83 |
platformsh/platformsh-cli | src/Service/Config.php | Config.getWithDefault | public function getWithDefault($name, $default)
{
$value = NestedArrayUtil::getNestedArrayValue(self::$config, explode('.', $name), $exists);
if (!$exists) {
return $default;
}
return $value;
} | php | public function getWithDefault($name, $default)
{
$value = NestedArrayUtil::getNestedArrayValue(self::$config, explode('.', $name), $exists);
if (!$exists) {
return $default;
}
return $value;
} | [
"public",
"function",
"getWithDefault",
"(",
"$",
"name",
",",
"$",
"default",
")",
"{",
"$",
"value",
"=",
"NestedArrayUtil",
"::",
"getNestedArrayValue",
"(",
"self",
"::",
"$",
"config",
",",
"explode",
"(",
"'.'",
",",
"$",
"name",
")",
",",
"$",
"... | Get a configuration value, specifying a default if it does not exist.
@param string $name
@param mixed $default
@return mixed | [
"Get",
"a",
"configuration",
"value",
"specifying",
"a",
"default",
"if",
"it",
"does",
"not",
"exist",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Config.php#L93-L101 |
platformsh/platformsh-cli | src/Service/Config.php | Config.getUserConfigDir | public function getUserConfigDir($absolute = true)
{
$path = $this->get('application.user_config_dir');
return $absolute ? $this->fs()->getHomeDirectory() . '/' . $path : $path;
} | php | public function getUserConfigDir($absolute = true)
{
$path = $this->get('application.user_config_dir');
return $absolute ? $this->fs()->getHomeDirectory() . '/' . $path : $path;
} | [
"public",
"function",
"getUserConfigDir",
"(",
"$",
"absolute",
"=",
"true",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"get",
"(",
"'application.user_config_dir'",
")",
";",
"return",
"$",
"absolute",
"?",
"$",
"this",
"->",
"fs",
"(",
")",
"->",
... | Get the directory where the CLI is normally installed and configured.
@param bool $absolute Whether to return an absolute path. If false,
the path will be relative to the home directory.
@return string | [
"Get",
"the",
"directory",
"where",
"the",
"CLI",
"is",
"normally",
"installed",
"and",
"configured",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Config.php#L111-L116 |
platformsh/platformsh-cli | src/Service/Config.php | Config.loadConfigFromFile | protected function loadConfigFromFile($filename)
{
$contents = file_get_contents($filename);
if ($contents === false) {
throw new \RuntimeException('Failed to read config file: ' . $filename);
}
return (array) Yaml::parse($contents);
} | php | protected function loadConfigFromFile($filename)
{
$contents = file_get_contents($filename);
if ($contents === false) {
throw new \RuntimeException('Failed to read config file: ' . $filename);
}
return (array) Yaml::parse($contents);
} | [
"protected",
"function",
"loadConfigFromFile",
"(",
"$",
"filename",
")",
"{",
"$",
"contents",
"=",
"file_get_contents",
"(",
"$",
"filename",
")",
";",
"if",
"(",
"$",
"contents",
"===",
"false",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"... | @param string $filename
@return array | [
"@param",
"string",
"$filename"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Config.php#L165-L173 |
platformsh/platformsh-cli | src/Service/Config.php | Config.getEnv | protected function getEnv($name)
{
$prefix = isset(self::$config['application']['env_prefix']) ? self::$config['application']['env_prefix'] : '';
if (array_key_exists($prefix . $name, $this->env)) {
return $this->env[$prefix . $name];
}
return getenv($prefix . $name);
} | php | protected function getEnv($name)
{
$prefix = isset(self::$config['application']['env_prefix']) ? self::$config['application']['env_prefix'] : '';
if (array_key_exists($prefix . $name, $this->env)) {
return $this->env[$prefix . $name];
}
return getenv($prefix . $name);
} | [
"protected",
"function",
"getEnv",
"(",
"$",
"name",
")",
"{",
"$",
"prefix",
"=",
"isset",
"(",
"self",
"::",
"$",
"config",
"[",
"'application'",
"]",
"[",
"'env_prefix'",
"]",
")",
"?",
"self",
"::",
"$",
"config",
"[",
"'application'",
"]",
"[",
... | Get an environment variable
@param string $name
The variable name. The configured prefix will be prepended.
@return mixed|false
The value of the environment variable, or false if it is not set. | [
"Get",
"an",
"environment",
"variable"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Config.php#L207-L215 |
platformsh/platformsh-cli | src/Service/Config.php | Config.isCommandEnabled | public function isCommandEnabled($name)
{
if (!empty(self::$config['application']['disabled_commands'])
&& in_array($name, self::$config['application']['disabled_commands'])) {
return false;
}
if (!empty(self::$config['application']['experimental_commands'])
&& in_array($name, self::$config['application']['experimental_commands'])) {
return !empty(self::$config['experimental']['all_experiments'])
|| (
!empty(self::$config['experimental']['enable_commands'])
&& in_array($name, self::$config['experimental']['enable_commands'])
);
}
return true;
} | php | public function isCommandEnabled($name)
{
if (!empty(self::$config['application']['disabled_commands'])
&& in_array($name, self::$config['application']['disabled_commands'])) {
return false;
}
if (!empty(self::$config['application']['experimental_commands'])
&& in_array($name, self::$config['application']['experimental_commands'])) {
return !empty(self::$config['experimental']['all_experiments'])
|| (
!empty(self::$config['experimental']['enable_commands'])
&& in_array($name, self::$config['experimental']['enable_commands'])
);
}
return true;
} | [
"public",
"function",
"isCommandEnabled",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"self",
"::",
"$",
"config",
"[",
"'application'",
"]",
"[",
"'disabled_commands'",
"]",
")",
"&&",
"in_array",
"(",
"$",
"name",
",",
"self",
"::",
"$"... | Test if a command should be enabled.
@param string $name
@return bool | [
"Test",
"if",
"a",
"command",
"should",
"be",
"enabled",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Config.php#L285-L301 |
platformsh/platformsh-cli | src/Service/Config.php | Config.getVersion | public function getVersion() {
if (isset($this->version)) {
return $this->version;
}
$version = $this->get('application.version');
if (substr($version, 0, 1) === '@' && substr($version, -1) === '@') {
// Silently try getting the version from Git.
$tag = (new Shell())->execute(['git', 'describe', '--tags'], CLI_ROOT);
if ($tag !== false && substr($tag, 0, 1) === 'v') {
$version = trim($tag);
}
}
$this->version = $version;
return $version;
} | php | public function getVersion() {
if (isset($this->version)) {
return $this->version;
}
$version = $this->get('application.version');
if (substr($version, 0, 1) === '@' && substr($version, -1) === '@') {
// Silently try getting the version from Git.
$tag = (new Shell())->execute(['git', 'describe', '--tags'], CLI_ROOT);
if ($tag !== false && substr($tag, 0, 1) === 'v') {
$version = trim($tag);
}
}
$this->version = $version;
return $version;
} | [
"public",
"function",
"getVersion",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"version",
")",
")",
"{",
"return",
"$",
"this",
"->",
"version",
";",
"}",
"$",
"version",
"=",
"$",
"this",
"->",
"get",
"(",
"'application.version'",
")... | Returns this application version.
@return string | [
"Returns",
"this",
"application",
"version",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Service/Config.php#L308-L323 |
platformsh/platformsh-cli | src/Command/Project/ProjectDeleteCommand.php | ProjectDeleteCommand.validateInput | protected function validateInput(InputInterface $input, $envNotRequired = false, $selectDefaultEnv = false)
{
if ($projectId = $input->getArgument('project')) {
if ($input->getOption('project')) {
throw new ConsoleInvalidArgumentException(
'You cannot use both the <project> argument and the --project option'
);
}
$input->setOption('project', $projectId);
}
parent::validateInput($input, $envNotRequired);
} | php | protected function validateInput(InputInterface $input, $envNotRequired = false, $selectDefaultEnv = false)
{
if ($projectId = $input->getArgument('project')) {
if ($input->getOption('project')) {
throw new ConsoleInvalidArgumentException(
'You cannot use both the <project> argument and the --project option'
);
}
$input->setOption('project', $projectId);
}
parent::validateInput($input, $envNotRequired);
} | [
"protected",
"function",
"validateInput",
"(",
"InputInterface",
"$",
"input",
",",
"$",
"envNotRequired",
"=",
"false",
",",
"$",
"selectDefaultEnv",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"projectId",
"=",
"$",
"input",
"->",
"getArgument",
"(",
"'project... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Project/ProjectDeleteCommand.php#L84-L95 |
platformsh/platformsh-cli | src/Command/SubscriptionInfoCommand.php | SubscriptionInfoCommand.listProperties | protected function listProperties(Subscription $subscription)
{
$headings = [];
$values = [];
foreach ($subscription->getProperties() as $key => $value) {
$headings[] = new AdaptiveTableCell($key, ['wrap' => false]);
$values[] = $this->formatter->format($value, $key);
}
/** @var \Platformsh\Cli\Service\Table $table */
$table = $this->getService('table');
$table->renderSimple($values, $headings);
return 0;
} | php | protected function listProperties(Subscription $subscription)
{
$headings = [];
$values = [];
foreach ($subscription->getProperties() as $key => $value) {
$headings[] = new AdaptiveTableCell($key, ['wrap' => false]);
$values[] = $this->formatter->format($value, $key);
}
/** @var \Platformsh\Cli\Service\Table $table */
$table = $this->getService('table');
$table->renderSimple($values, $headings);
return 0;
} | [
"protected",
"function",
"listProperties",
"(",
"Subscription",
"$",
"subscription",
")",
"{",
"$",
"headings",
"=",
"[",
"]",
";",
"$",
"values",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"subscription",
"->",
"getProperties",
"(",
")",
"as",
"$",
"key",... | @param Subscription $subscription
@return int | [
"@param",
"Subscription",
"$subscription"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/SubscriptionInfoCommand.php#L88-L101 |
platformsh/platformsh-cli | src/Command/SubscriptionInfoCommand.php | SubscriptionInfoCommand.setProperty | protected function setProperty($property, $value, Subscription $subscription)
{
$type = $this->getType($property);
if (!$type) {
$this->stdErr->writeln("Property not writable: <error>$property</error>");
return 1;
}
if ($type === 'boolean' && $value === 'false') {
$value = false;
}
settype($value, $type);
$currentValue = $subscription->getProperty($property);
if ($currentValue === $value) {
$this->stdErr->writeln(
"Property <info>$property</info> already set as: " . $this->formatter->format($value, $property)
);
return 0;
}
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$confirmMessage = sprintf(
"Are you sure you want to change property '%s' from <comment>%s</comment> to <comment>%s</comment>?",
$property,
$this->formatter->format($currentValue, $property),
$this->formatter->format($value, $property)
);
$warning = sprintf(
'<comment>This action may %s the cost of your subscription.</comment>',
is_numeric($value) && $value > $currentValue ? 'increase' : 'change'
);
$confirmMessage = $warning . "\n" . $confirmMessage;
if (!$questionHelper->confirm($confirmMessage)) {
return 1;
}
$subscription->update([$property => $value]);
$this->stdErr->writeln(sprintf(
'Property <info>%s</info> set to: %s',
$property,
$this->formatter->format($value, $property)
));
return 0;
} | php | protected function setProperty($property, $value, Subscription $subscription)
{
$type = $this->getType($property);
if (!$type) {
$this->stdErr->writeln("Property not writable: <error>$property</error>");
return 1;
}
if ($type === 'boolean' && $value === 'false') {
$value = false;
}
settype($value, $type);
$currentValue = $subscription->getProperty($property);
if ($currentValue === $value) {
$this->stdErr->writeln(
"Property <info>$property</info> already set as: " . $this->formatter->format($value, $property)
);
return 0;
}
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$confirmMessage = sprintf(
"Are you sure you want to change property '%s' from <comment>%s</comment> to <comment>%s</comment>?",
$property,
$this->formatter->format($currentValue, $property),
$this->formatter->format($value, $property)
);
$warning = sprintf(
'<comment>This action may %s the cost of your subscription.</comment>',
is_numeric($value) && $value > $currentValue ? 'increase' : 'change'
);
$confirmMessage = $warning . "\n" . $confirmMessage;
if (!$questionHelper->confirm($confirmMessage)) {
return 1;
}
$subscription->update([$property => $value]);
$this->stdErr->writeln(sprintf(
'Property <info>%s</info> set to: %s',
$property,
$this->formatter->format($value, $property)
));
return 0;
} | [
"protected",
"function",
"setProperty",
"(",
"$",
"property",
",",
"$",
"value",
",",
"Subscription",
"$",
"subscription",
")",
"{",
"$",
"type",
"=",
"$",
"this",
"->",
"getType",
"(",
"$",
"property",
")",
";",
"if",
"(",
"!",
"$",
"type",
")",
"{"... | @param string $property
@param string $value
@param Subscription $subscription
@return int | [
"@param",
"string",
"$property",
"@param",
"string",
"$value",
"@param",
"Subscription",
"$subscription"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/SubscriptionInfoCommand.php#L110-L155 |
platformsh/platformsh-cli | src/Command/Environment/EnvironmentActivateCommand.php | EnvironmentActivateCommand.activateMultiple | protected function activateMultiple(array $environments, InputInterface $input, OutputInterface $output)
{
$parentId = $input->getOption('parent');
if ($parentId && !$this->api()->getEnvironment($parentId, $this->getSelectedProject())) {
$this->stdErr->writeln(sprintf('Parent environment not found: <error>%s</error>', $parentId));
return false;
}
$count = count($environments);
$processed = 0;
// Confirm which environments the user wishes to be activated.
$process = [];
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
foreach ($environments as $environment) {
if (!$environment->operationAvailable('activate', true)) {
if ($environment->isActive()) {
$output->writeln("The environment " . $this->api()->getEnvironmentLabel($environment) . " is already active.");
$count--;
continue;
}
$output->writeln(
"Operation not available: The environment " . $this->api()->getEnvironmentLabel($environment, 'error') . " can't be activated."
);
continue;
}
$question = "Are you sure you want to activate the environment " . $this->api()->getEnvironmentLabel($environment) . "?";
if (!$questionHelper->confirm($question)) {
continue;
}
$process[$environment->id] = $environment;
}
$activities = [];
/** @var Environment $environment */
foreach ($process as $environmentId => $environment) {
try {
if ($parentId && $parentId !== $environment->parent && $parentId !== $environmentId) {
$output->writeln(sprintf(
'Setting parent of environment <info>%s</info> to <info>%s</info>',
$environmentId,
$parentId
));
$result = $environment->update(['parent' => $parentId]);
$activities = array_merge($activities, $result->getActivities());
}
$output->writeln(sprintf(
'Activating environment <info>%s</info>',
$environmentId
));
$activities[] = $environment->activate();
$processed++;
} catch (\Exception $e) {
$output->writeln($e->getMessage());
}
}
$success = $processed >= $count;
if ($processed) {
if ($this->shouldWait($input)) {
/** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */
$activityMonitor = $this->getService('activity_monitor');
$result = $activityMonitor->waitMultiple($activities, $this->getSelectedProject());
$success = $success && $result;
}
$this->api()->clearEnvironmentsCache($this->getSelectedProject()->id);
}
return $success;
} | php | protected function activateMultiple(array $environments, InputInterface $input, OutputInterface $output)
{
$parentId = $input->getOption('parent');
if ($parentId && !$this->api()->getEnvironment($parentId, $this->getSelectedProject())) {
$this->stdErr->writeln(sprintf('Parent environment not found: <error>%s</error>', $parentId));
return false;
}
$count = count($environments);
$processed = 0;
// Confirm which environments the user wishes to be activated.
$process = [];
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
foreach ($environments as $environment) {
if (!$environment->operationAvailable('activate', true)) {
if ($environment->isActive()) {
$output->writeln("The environment " . $this->api()->getEnvironmentLabel($environment) . " is already active.");
$count--;
continue;
}
$output->writeln(
"Operation not available: The environment " . $this->api()->getEnvironmentLabel($environment, 'error') . " can't be activated."
);
continue;
}
$question = "Are you sure you want to activate the environment " . $this->api()->getEnvironmentLabel($environment) . "?";
if (!$questionHelper->confirm($question)) {
continue;
}
$process[$environment->id] = $environment;
}
$activities = [];
/** @var Environment $environment */
foreach ($process as $environmentId => $environment) {
try {
if ($parentId && $parentId !== $environment->parent && $parentId !== $environmentId) {
$output->writeln(sprintf(
'Setting parent of environment <info>%s</info> to <info>%s</info>',
$environmentId,
$parentId
));
$result = $environment->update(['parent' => $parentId]);
$activities = array_merge($activities, $result->getActivities());
}
$output->writeln(sprintf(
'Activating environment <info>%s</info>',
$environmentId
));
$activities[] = $environment->activate();
$processed++;
} catch (\Exception $e) {
$output->writeln($e->getMessage());
}
}
$success = $processed >= $count;
if ($processed) {
if ($this->shouldWait($input)) {
/** @var \Platformsh\Cli\Service\ActivityMonitor $activityMonitor */
$activityMonitor = $this->getService('activity_monitor');
$result = $activityMonitor->waitMultiple($activities, $this->getSelectedProject());
$success = $success && $result;
}
$this->api()->clearEnvironmentsCache($this->getSelectedProject()->id);
}
return $success;
} | [
"protected",
"function",
"activateMultiple",
"(",
"array",
"$",
"environments",
",",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"parentId",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'parent'",
")",
";",
"if",
"(",... | @param Environment[] $environments
@param InputInterface $input
@param OutputInterface $output
@return bool | [
"@param",
"Environment",
"[]",
"$environments",
"@param",
"InputInterface",
"$input",
"@param",
"OutputInterface",
"$output"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Environment/EnvironmentActivateCommand.php#L55-L125 |
platformsh/platformsh-cli | src/Local/DependencyManager/Npm.php | Npm.install | public function install($path, array $dependencies, $global = false)
{
if ($global) {
$this->installGlobal($dependencies);
return;
}
$packageJsonFile = $path . '/package.json';
$packageJson = json_encode([
'name' => 'temporary-build-dependencies',
'version' => '1.0.0',
'private' => true,
'dependencies' => $dependencies,
], JSON_PRETTY_PRINT);
$current = file_exists($packageJsonFile) ? file_get_contents($packageJsonFile) : false;
if ($current !== $packageJson) {
file_put_contents($packageJsonFile, $packageJson);
}
$this->runCommand('npm install --global-style', $path);
} | php | public function install($path, array $dependencies, $global = false)
{
if ($global) {
$this->installGlobal($dependencies);
return;
}
$packageJsonFile = $path . '/package.json';
$packageJson = json_encode([
'name' => 'temporary-build-dependencies',
'version' => '1.0.0',
'private' => true,
'dependencies' => $dependencies,
], JSON_PRETTY_PRINT);
$current = file_exists($packageJsonFile) ? file_get_contents($packageJsonFile) : false;
if ($current !== $packageJson) {
file_put_contents($packageJsonFile, $packageJson);
}
$this->runCommand('npm install --global-style', $path);
} | [
"public",
"function",
"install",
"(",
"$",
"path",
",",
"array",
"$",
"dependencies",
",",
"$",
"global",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"global",
")",
"{",
"$",
"this",
"->",
"installGlobal",
"(",
"$",
"dependencies",
")",
";",
"return",
";... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/DependencyManager/Npm.php#L29-L47 |
platformsh/platformsh-cli | src/Local/DependencyManager/Npm.php | Npm.installGlobal | private function installGlobal(array $dependencies)
{
foreach ($dependencies as $package => $version) {
if (!$this->isInstalledGlobally($package)) {
$arg = $version === '*' ? $package : $package . '@' . $version;
$this->runCommand('npm install --global ' . escapeshellarg($arg));
}
}
} | php | private function installGlobal(array $dependencies)
{
foreach ($dependencies as $package => $version) {
if (!$this->isInstalledGlobally($package)) {
$arg = $version === '*' ? $package : $package . '@' . $version;
$this->runCommand('npm install --global ' . escapeshellarg($arg));
}
}
} | [
"private",
"function",
"installGlobal",
"(",
"array",
"$",
"dependencies",
")",
"{",
"foreach",
"(",
"$",
"dependencies",
"as",
"$",
"package",
"=>",
"$",
"version",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isInstalledGlobally",
"(",
"$",
"package",
... | Install dependencies globally.
@param array $dependencies | [
"Install",
"dependencies",
"globally",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/DependencyManager/Npm.php#L54-L62 |
platformsh/platformsh-cli | src/Local/DependencyManager/Npm.php | Npm.isInstalledGlobally | private function isInstalledGlobally($package)
{
if (!isset($this->globalList)) {
$this->globalList = $this->shell->execute(
['npm', 'ls', '--global', '--no-progress', '--depth=0']
);
}
return $this->globalList && strpos($this->globalList, $package . '@') !== false;
} | php | private function isInstalledGlobally($package)
{
if (!isset($this->globalList)) {
$this->globalList = $this->shell->execute(
['npm', 'ls', '--global', '--no-progress', '--depth=0']
);
}
return $this->globalList && strpos($this->globalList, $package . '@') !== false;
} | [
"private",
"function",
"isInstalledGlobally",
"(",
"$",
"package",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"globalList",
")",
")",
"{",
"$",
"this",
"->",
"globalList",
"=",
"$",
"this",
"->",
"shell",
"->",
"execute",
"(",
"[",
"'... | @param string $package
@return bool | [
"@param",
"string",
"$package"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Local/DependencyManager/Npm.php#L69-L78 |
platformsh/platformsh-cli | src/SiteAlias/DrushYaml.php | DrushYaml.getExistingAliases | protected function getExistingAliases($currentGroup, $previousGroup = null)
{
$aliases = parent::getExistingAliases($currentGroup, $previousGroup);
if (empty($aliases)) {
foreach (array_filter([$currentGroup, $previousGroup]) as $groupName) {
$filename = $this->getFilename($groupName);
if (file_exists($filename) && ($content = file_get_contents($filename))) {
$aliases = array_merge($aliases, (array) Yaml::parse($content));
}
}
}
return $aliases;
} | php | protected function getExistingAliases($currentGroup, $previousGroup = null)
{
$aliases = parent::getExistingAliases($currentGroup, $previousGroup);
if (empty($aliases)) {
foreach (array_filter([$currentGroup, $previousGroup]) as $groupName) {
$filename = $this->getFilename($groupName);
if (file_exists($filename) && ($content = file_get_contents($filename))) {
$aliases = array_merge($aliases, (array) Yaml::parse($content));
}
}
}
return $aliases;
} | [
"protected",
"function",
"getExistingAliases",
"(",
"$",
"currentGroup",
",",
"$",
"previousGroup",
"=",
"null",
")",
"{",
"$",
"aliases",
"=",
"parent",
"::",
"getExistingAliases",
"(",
"$",
"currentGroup",
",",
"$",
"previousGroup",
")",
";",
"if",
"(",
"e... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/SiteAlias/DrushYaml.php#L29-L42 |
platformsh/platformsh-cli | src/Application.php | Application.configureIO | protected function configureIO(InputInterface $input, OutputInterface $output)
{
// Set the input to non-interactive if the yes or no options are used.
if ($input->hasParameterOption(['--yes', '-y', '--no', '-n'])) {
$input->setInteractive(false);
}
// Allow the NO_COLOR, CLICOLOR_FORCE, and TERM environment variables to
// override whether colors are used in the output.
// See: https://no-color.org
// See: https://en.wikipedia.org/wiki/Computer_terminal#Dumb_terminals
/* @see StreamOutput::hasColorSupport() */
if (getenv('CLICOLOR_FORCE') === '1') {
$output->setDecorated(true);
} elseif (getenv('NO_COLOR')
|| getenv('CLICOLOR_FORCE') === '0'
|| getenv('TERM') === 'dumb'
|| getenv($this->cliConfig->get('application.env_prefix') . 'NO_COLOR')) {
$output->setDecorated(false);
}
parent::configureIO($input, $output);
} | php | protected function configureIO(InputInterface $input, OutputInterface $output)
{
// Set the input to non-interactive if the yes or no options are used.
if ($input->hasParameterOption(['--yes', '-y', '--no', '-n'])) {
$input->setInteractive(false);
}
// Allow the NO_COLOR, CLICOLOR_FORCE, and TERM environment variables to
// override whether colors are used in the output.
// See: https://no-color.org
// See: https://en.wikipedia.org/wiki/Computer_terminal#Dumb_terminals
/* @see StreamOutput::hasColorSupport() */
if (getenv('CLICOLOR_FORCE') === '1') {
$output->setDecorated(true);
} elseif (getenv('NO_COLOR')
|| getenv('CLICOLOR_FORCE') === '0'
|| getenv('TERM') === 'dumb'
|| getenv($this->cliConfig->get('application.env_prefix') . 'NO_COLOR')) {
$output->setDecorated(false);
}
parent::configureIO($input, $output);
} | [
"protected",
"function",
"configureIO",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"// Set the input to non-interactive if the yes or no options are used.",
"if",
"(",
"$",
"input",
"->",
"hasParameterOption",
"(",
"[",
"'--yes'"... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Application.php#L241-L263 |
platformsh/platformsh-cli | src/Application.php | Application.doRunCommand | protected function doRunCommand(ConsoleCommand $command, InputInterface $input, OutputInterface $output)
{
$this->setCurrentCommand($command);
// Build the command synopsis early, so it doesn't include default
// options and arguments (such as --help and <command>).
// @todo find a better solution for this?
$this->currentCommand->getSynopsis();
return parent::doRunCommand($command, $input, $output);
} | php | protected function doRunCommand(ConsoleCommand $command, InputInterface $input, OutputInterface $output)
{
$this->setCurrentCommand($command);
// Build the command synopsis early, so it doesn't include default
// options and arguments (such as --help and <command>).
// @todo find a better solution for this?
$this->currentCommand->getSynopsis();
return parent::doRunCommand($command, $input, $output);
} | [
"protected",
"function",
"doRunCommand",
"(",
"ConsoleCommand",
"$",
"command",
",",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"setCurrentCommand",
"(",
"$",
"command",
")",
";",
"// Build the command synop... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Application.php#L268-L278 |
platformsh/platformsh-cli | src/Application.php | Application.renderException | public function renderException(\Exception $e, OutputInterface $output)
{
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
$main = $e;
do {
$exceptionName = get_class($e);
if (($pos = strrpos($exceptionName, '\\')) !== false) {
$exceptionName = substr($exceptionName, $pos + 1);
}
$title = sprintf(' [%s] ', $exceptionName);
$len = strlen($title);
$width = (new Terminal())->getWidth() - 1;
$formatter = $output->getFormatter();
$lines = array();
foreach (preg_split('/\r?\n/', $e->getMessage()) as $line) {
foreach (str_split($line, $width - 4) as $chunk) {
// pre-format lines to get the right string length
$lineLength = strlen(preg_replace('/\[[^m]*m/', '', $formatter->format($chunk))) + 4;
$lines[] = array($chunk, $lineLength);
$len = max($lineLength, $len);
}
}
$messages = array();
$messages[] = $emptyLine = $formatter->format(sprintf('<error>%s</error>', str_repeat(' ', $len)));
$messages[] = $formatter->format(sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - strlen($title)))));
foreach ($lines as $line) {
$messages[] = $formatter->format(sprintf('<error> %s %s</error>', $line[0], str_repeat(' ', $len - $line[1])));
}
$messages[] = $emptyLine;
$messages[] = '';
$output->writeln($messages, OutputInterface::OUTPUT_RAW | OutputInterface::VERBOSITY_QUIET);
if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
$output->writeln('<comment>Exception trace:</comment>', OutputInterface::VERBOSITY_QUIET);
// exception related properties
$trace = $e->getTrace();
array_unshift($trace, array(
'function' => '',
'file' => $e->getFile() !== null ? $e->getFile() : 'n/a',
'line' => $e->getLine() !== null ? $e->getLine() : 'n/a',
'args' => array(),
));
for ($i = 0, $count = count($trace); $i < $count; ++$i) {
$class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
$type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
$function = $trace[$i]['function'];
$file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
$line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
$output->writeln(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line), OutputInterface::VERBOSITY_QUIET);
}
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
}
} while ($e = $e->getPrevious());
if (isset($this->currentCommand)
&& $this->currentCommand->getName() !== 'welcome'
&& ($main instanceof ConsoleInvalidArgumentException
|| $main instanceof ConsoleInvalidOptionException
|| $main instanceof ConsoleRuntimeException
)) {
$output->writeln(
sprintf('Usage: <info>%s</info>', $this->currentCommand->getSynopsis()),
OutputInterface::VERBOSITY_QUIET
);
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
$output->writeln(sprintf(
'For more information, type: <info>%s help %s</info>',
$this->cliConfig->get('application.executable'),
$this->currentCommand->getName()
), OutputInterface::VERBOSITY_QUIET);
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
}
} | php | public function renderException(\Exception $e, OutputInterface $output)
{
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
$main = $e;
do {
$exceptionName = get_class($e);
if (($pos = strrpos($exceptionName, '\\')) !== false) {
$exceptionName = substr($exceptionName, $pos + 1);
}
$title = sprintf(' [%s] ', $exceptionName);
$len = strlen($title);
$width = (new Terminal())->getWidth() - 1;
$formatter = $output->getFormatter();
$lines = array();
foreach (preg_split('/\r?\n/', $e->getMessage()) as $line) {
foreach (str_split($line, $width - 4) as $chunk) {
// pre-format lines to get the right string length
$lineLength = strlen(preg_replace('/\[[^m]*m/', '', $formatter->format($chunk))) + 4;
$lines[] = array($chunk, $lineLength);
$len = max($lineLength, $len);
}
}
$messages = array();
$messages[] = $emptyLine = $formatter->format(sprintf('<error>%s</error>', str_repeat(' ', $len)));
$messages[] = $formatter->format(sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - strlen($title)))));
foreach ($lines as $line) {
$messages[] = $formatter->format(sprintf('<error> %s %s</error>', $line[0], str_repeat(' ', $len - $line[1])));
}
$messages[] = $emptyLine;
$messages[] = '';
$output->writeln($messages, OutputInterface::OUTPUT_RAW | OutputInterface::VERBOSITY_QUIET);
if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
$output->writeln('<comment>Exception trace:</comment>', OutputInterface::VERBOSITY_QUIET);
// exception related properties
$trace = $e->getTrace();
array_unshift($trace, array(
'function' => '',
'file' => $e->getFile() !== null ? $e->getFile() : 'n/a',
'line' => $e->getLine() !== null ? $e->getLine() : 'n/a',
'args' => array(),
));
for ($i = 0, $count = count($trace); $i < $count; ++$i) {
$class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
$type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
$function = $trace[$i]['function'];
$file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
$line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
$output->writeln(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line), OutputInterface::VERBOSITY_QUIET);
}
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
}
} while ($e = $e->getPrevious());
if (isset($this->currentCommand)
&& $this->currentCommand->getName() !== 'welcome'
&& ($main instanceof ConsoleInvalidArgumentException
|| $main instanceof ConsoleInvalidOptionException
|| $main instanceof ConsoleRuntimeException
)) {
$output->writeln(
sprintf('Usage: <info>%s</info>', $this->currentCommand->getSynopsis()),
OutputInterface::VERBOSITY_QUIET
);
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
$output->writeln(sprintf(
'For more information, type: <info>%s help %s</info>',
$this->cliConfig->get('application.executable'),
$this->currentCommand->getName()
), OutputInterface::VERBOSITY_QUIET);
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
}
} | [
"public",
"function",
"renderException",
"(",
"\\",
"Exception",
"$",
"e",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"''",
",",
"OutputInterface",
"::",
"VERBOSITY_QUIET",
")",
";",
"$",
"main",
"=",
"$",
"e",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Application.php#L295-L377 |
platformsh/platformsh-cli | src/Command/Db/DbDumpCommand.php | DbDumpCommand.getDefaultFilename | private function getDefaultFilename(
Environment $environment,
$dbServiceName = null,
$schema = null,
array $includedTables = [],
array $excludedTables = [],
$schemaOnly = false,
$gzip = false)
{
$defaultFilename = $environment->project . '--' . $environment->machine_name;
if ($dbServiceName !== null) {
$defaultFilename .= '--' . $dbServiceName;
}
if ($schema !== null) {
$defaultFilename .= '--' . $schema;
}
if ($includedTables) {
$defaultFilename .= '--' . implode(',', $includedTables);
}
if ($excludedTables) {
$defaultFilename .= '--excl-' . implode(',', $excludedTables);
}
if ($schemaOnly) {
$defaultFilename .= '--schema';
}
$defaultFilename .= '--dump.sql';
if ($gzip) {
$defaultFilename .= '.gz';
}
return $defaultFilename;
} | php | private function getDefaultFilename(
Environment $environment,
$dbServiceName = null,
$schema = null,
array $includedTables = [],
array $excludedTables = [],
$schemaOnly = false,
$gzip = false)
{
$defaultFilename = $environment->project . '--' . $environment->machine_name;
if ($dbServiceName !== null) {
$defaultFilename .= '--' . $dbServiceName;
}
if ($schema !== null) {
$defaultFilename .= '--' . $schema;
}
if ($includedTables) {
$defaultFilename .= '--' . implode(',', $includedTables);
}
if ($excludedTables) {
$defaultFilename .= '--excl-' . implode(',', $excludedTables);
}
if ($schemaOnly) {
$defaultFilename .= '--schema';
}
$defaultFilename .= '--dump.sql';
if ($gzip) {
$defaultFilename .= '.gz';
}
return $defaultFilename;
} | [
"private",
"function",
"getDefaultFilename",
"(",
"Environment",
"$",
"environment",
",",
"$",
"dbServiceName",
"=",
"null",
",",
"$",
"schema",
"=",
"null",
",",
"array",
"$",
"includedTables",
"=",
"[",
"]",
",",
"array",
"$",
"excludedTables",
"=",
"[",
... | Get the default dump filename.
@param Environment $environment
@param string|null $dbServiceName
@param string|null $schema
@param array $includedTables
@param array $excludedTables
@param bool $schemaOnly
@param bool $gzip
@return string | [
"Get",
"the",
"default",
"dump",
"filename",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Db/DbDumpCommand.php#L288-L319 |
platformsh/platformsh-cli | src/Command/Variable/VariableCreateCommand.php | VariableCreateCommand.configure | protected function configure()
{
$this
->setName('variable:create')
->setDescription('Create a variable')
->addArgument('name', InputArgument::OPTIONAL, 'The variable name');
$this->form = Form::fromArray($this->getFields());
$this->form->configureInputDefinition($this->getDefinition());
$this->addProjectOption()
->addEnvironmentOption()
->addWaitOptions();
} | php | protected function configure()
{
$this
->setName('variable:create')
->setDescription('Create a variable')
->addArgument('name', InputArgument::OPTIONAL, 'The variable name');
$this->form = Form::fromArray($this->getFields());
$this->form->configureInputDefinition($this->getDefinition());
$this->addProjectOption()
->addEnvironmentOption()
->addWaitOptions();
} | [
"protected",
"function",
"configure",
"(",
")",
"{",
"$",
"this",
"->",
"setName",
"(",
"'variable:create'",
")",
"->",
"setDescription",
"(",
"'Create a variable'",
")",
"->",
"addArgument",
"(",
"'name'",
",",
"InputArgument",
"::",
"OPTIONAL",
",",
"'The vari... | {@inheritdoc} | [
"{"
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Command/Variable/VariableCreateCommand.php#L20-L31 |
platformsh/platformsh-cli | src/Util/YamlParser.php | YamlParser.parseContent | public function parseContent($content, $filename)
{
try {
$parsed = (new Yaml())->parse($content, Yaml::PARSE_CUSTOM_TAGS);
} catch (ParseException $e) {
throw new ParseException($e->getMessage(), $e->getParsedLine(), $e->getSnippet(), $filename, $e->getPrevious());
}
return $this->processTags($parsed, $filename);
} | php | public function parseContent($content, $filename)
{
try {
$parsed = (new Yaml())->parse($content, Yaml::PARSE_CUSTOM_TAGS);
} catch (ParseException $e) {
throw new ParseException($e->getMessage(), $e->getParsedLine(), $e->getSnippet(), $filename, $e->getPrevious());
}
return $this->processTags($parsed, $filename);
} | [
"public",
"function",
"parseContent",
"(",
"$",
"content",
",",
"$",
"filename",
")",
"{",
"try",
"{",
"$",
"parsed",
"=",
"(",
"new",
"Yaml",
"(",
")",
")",
"->",
"parse",
"(",
"$",
"content",
",",
"Yaml",
"::",
"PARSE_CUSTOM_TAGS",
")",
";",
"}",
... | Parses a YAML string.
@param string $content The YAML content.
@param string $filename The filename where the content originated. This
is required for formatting useful error messages.
@throws \Platformsh\Cli\Exception\InvalidConfigException if the config is invalid
@throws ParseException if the config could not be parsed
@return mixed | [
"Parses",
"a",
"YAML",
"string",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/YamlParser.php#L41-L50 |
platformsh/platformsh-cli | src/Util/YamlParser.php | YamlParser.readFile | private function readFile($filename)
{
if (!file_exists($filename)) {
throw new \Exception(sprintf('File not found: %s', $filename));
}
if (!is_readable($filename) || ($content = file_get_contents($filename)) === false) {
throw new \Exception(sprintf('Failed to read file: %s', $filename));
}
return $content;
} | php | private function readFile($filename)
{
if (!file_exists($filename)) {
throw new \Exception(sprintf('File not found: %s', $filename));
}
if (!is_readable($filename) || ($content = file_get_contents($filename)) === false) {
throw new \Exception(sprintf('Failed to read file: %s', $filename));
}
return $content;
} | [
"private",
"function",
"readFile",
"(",
"$",
"filename",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"filename",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"sprintf",
"(",
"'File not found: %s'",
",",
"$",
"filename",
")",
")",
";",
... | Reads a file and throws appropriate exceptions on failure.
@param string $filename
@throws \Exception if the file cannot be found or read.
@return string | [
"Reads",
"a",
"file",
"and",
"throws",
"appropriate",
"exceptions",
"on",
"failure",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/YamlParser.php#L61-L71 |
platformsh/platformsh-cli | src/Util/YamlParser.php | YamlParser.processTags | private function processTags($config, $filename)
{
if (!is_array($config)) {
return $this->processSingleTag($config, $filename);
}
foreach ($config as $key => $item) {
if (is_array($item)) {
$config[$key] = $this->processTags($item, $filename);
} else {
$config[$key] = $this->processSingleTag($item, $filename, $key);
}
}
return $config;
} | php | private function processTags($config, $filename)
{
if (!is_array($config)) {
return $this->processSingleTag($config, $filename);
}
foreach ($config as $key => $item) {
if (is_array($item)) {
$config[$key] = $this->processTags($item, $filename);
} else {
$config[$key] = $this->processSingleTag($item, $filename, $key);
}
}
return $config;
} | [
"private",
"function",
"processTags",
"(",
"$",
"config",
",",
"$",
"filename",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"config",
")",
")",
"{",
"return",
"$",
"this",
"->",
"processSingleTag",
"(",
"$",
"config",
",",
"$",
"filename",
")",
"... | Processes custom tags in the parsed config.
@param array $config
@param string $filename
@throws \Platformsh\Cli\Exception\InvalidConfigException
@return array | [
"Processes",
"custom",
"tags",
"in",
"the",
"parsed",
"config",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/YamlParser.php#L83-L97 |
platformsh/platformsh-cli | src/Util/YamlParser.php | YamlParser.processSingleTag | private function processSingleTag($item, $filename, $configKey = '')
{
if ($item instanceof TaggedValue) {
$tag = $item->getTag();
$value = $item->getValue();
} elseif (is_string($item) && strlen($item) && $item[0] === '!' && preg_match('/\!([a-z]+)[ \t]+(.+)$/i', $item, $matches)) {
$tag = $matches[1];
$value = Yaml::parse($matches[2]);
if (!is_string($value)) {
return $item;
}
} else {
return $item;
}
// Process the '!include' tag. The '!archive' and '!file' tags are
// ignored as they are not relevant to the CLI (yet).
switch ($tag) {
case 'include':
return $this->resolveInclude($value, $filename, $configKey);
}
return $item;
} | php | private function processSingleTag($item, $filename, $configKey = '')
{
if ($item instanceof TaggedValue) {
$tag = $item->getTag();
$value = $item->getValue();
} elseif (is_string($item) && strlen($item) && $item[0] === '!' && preg_match('/\!([a-z]+)[ \t]+(.+)$/i', $item, $matches)) {
$tag = $matches[1];
$value = Yaml::parse($matches[2]);
if (!is_string($value)) {
return $item;
}
} else {
return $item;
}
// Process the '!include' tag. The '!archive' and '!file' tags are
// ignored as they are not relevant to the CLI (yet).
switch ($tag) {
case 'include':
return $this->resolveInclude($value, $filename, $configKey);
}
return $item;
} | [
"private",
"function",
"processSingleTag",
"(",
"$",
"item",
",",
"$",
"filename",
",",
"$",
"configKey",
"=",
"''",
")",
"{",
"if",
"(",
"$",
"item",
"instanceof",
"TaggedValue",
")",
"{",
"$",
"tag",
"=",
"$",
"item",
"->",
"getTag",
"(",
")",
";",... | Processes a single config item, which may be a custom tag.
@param mixed $item
@param string $filename
@param string $configKey
@return mixed | [
"Processes",
"a",
"single",
"config",
"item",
"which",
"may",
"be",
"a",
"custom",
"tag",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/YamlParser.php#L108-L131 |
platformsh/platformsh-cli | src/Util/YamlParser.php | YamlParser.resolveInclude | private function resolveInclude($value, $filename, $configKey = '')
{
if (is_string($value)) {
$includeType = 'yaml';
$includePath = $value;
} elseif (is_array($value)) {
if ($missing = array_diff(['type', 'path'], array_keys($value))) {
throw new InvalidConfigException('The !include tag is missing the key(s): ' . implode(', ', $missing), $filename, $configKey);
}
$includeType = $value['type'];
$includePath = $value['path'];
} else {
throw new InvalidConfigException('The !include tag must be a string (for a YAML include), or an object containing "type" and "path".', $filename, $configKey);
}
$dir = dirname($filename);
if (!$realDir = realpath($dir)) {
throw new \RuntimeException('Failed to resolve directory: ' . $dir);
}
$includeFile = rtrim($realDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($includePath, DIRECTORY_SEPARATOR);
try {
switch ($includeType) {
// Ignore binary and archive values (for now at least).
case 'archive':
case 'binary':
return $value;
case 'yaml':
return $this->parseFile($includeFile);
case 'string':
return $this->readFile($includeFile);
default:
throw new InvalidConfigException(sprintf(
'Unrecognized !include tag type "%s"',
$includeType
), $filename, $configKey);
}
} catch (\Exception $e) {
if ($e instanceof InvalidConfigException) {
throw $e;
}
throw new InvalidConfigException($e->getMessage(), $filename, $configKey);
}
} | php | private function resolveInclude($value, $filename, $configKey = '')
{
if (is_string($value)) {
$includeType = 'yaml';
$includePath = $value;
} elseif (is_array($value)) {
if ($missing = array_diff(['type', 'path'], array_keys($value))) {
throw new InvalidConfigException('The !include tag is missing the key(s): ' . implode(', ', $missing), $filename, $configKey);
}
$includeType = $value['type'];
$includePath = $value['path'];
} else {
throw new InvalidConfigException('The !include tag must be a string (for a YAML include), or an object containing "type" and "path".', $filename, $configKey);
}
$dir = dirname($filename);
if (!$realDir = realpath($dir)) {
throw new \RuntimeException('Failed to resolve directory: ' . $dir);
}
$includeFile = rtrim($realDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($includePath, DIRECTORY_SEPARATOR);
try {
switch ($includeType) {
// Ignore binary and archive values (for now at least).
case 'archive':
case 'binary':
return $value;
case 'yaml':
return $this->parseFile($includeFile);
case 'string':
return $this->readFile($includeFile);
default:
throw new InvalidConfigException(sprintf(
'Unrecognized !include tag type "%s"',
$includeType
), $filename, $configKey);
}
} catch (\Exception $e) {
if ($e instanceof InvalidConfigException) {
throw $e;
}
throw new InvalidConfigException($e->getMessage(), $filename, $configKey);
}
} | [
"private",
"function",
"resolveInclude",
"(",
"$",
"value",
",",
"$",
"filename",
",",
"$",
"configKey",
"=",
"''",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"$",
"includeType",
"=",
"'yaml'",
";",
"$",
"includePath",
"=",
"... | Resolve an !include config tag value.
@param mixed $value
@param string $filename
@param string $configKey
@throws \Platformsh\Cli\Exception\InvalidConfigException
@return string|array | [
"Resolve",
"an",
"!include",
"config",
"tag",
"value",
"."
] | train | https://github.com/platformsh/platformsh-cli/blob/cc72d56f69ee570f66f989e6cb51a09097ed2611/src/Util/YamlParser.php#L144-L189 |
spatie/flysystem-dropbox | src/DropboxAdapter.php | DropboxAdapter.rename | public function rename($path, $newPath): bool
{
$path = $this->applyPathPrefix($path);
$newPath = $this->applyPathPrefix($newPath);
try {
$this->client->move($path, $newPath);
} catch (BadRequest $e) {
return false;
}
return true;
} | php | public function rename($path, $newPath): bool
{
$path = $this->applyPathPrefix($path);
$newPath = $this->applyPathPrefix($newPath);
try {
$this->client->move($path, $newPath);
} catch (BadRequest $e) {
return false;
}
return true;
} | [
"public",
"function",
"rename",
"(",
"$",
"path",
",",
"$",
"newPath",
")",
":",
"bool",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"applyPathPrefix",
"(",
"$",
"path",
")",
";",
"$",
"newPath",
"=",
"$",
"this",
"->",
"applyPathPrefix",
"(",
"$",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/spatie/flysystem-dropbox/blob/1166665b03cbea55e63408c6fb29b629f8553c74/src/DropboxAdapter.php#L61-L73 |
spatie/flysystem-dropbox | src/DropboxAdapter.php | DropboxAdapter.copy | public function copy($path, $newpath): bool
{
$path = $this->applyPathPrefix($path);
$newpath = $this->applyPathPrefix($newpath);
try {
$this->client->copy($path, $newpath);
} catch (BadRequest $e) {
return false;
}
return true;
} | php | public function copy($path, $newpath): bool
{
$path = $this->applyPathPrefix($path);
$newpath = $this->applyPathPrefix($newpath);
try {
$this->client->copy($path, $newpath);
} catch (BadRequest $e) {
return false;
}
return true;
} | [
"public",
"function",
"copy",
"(",
"$",
"path",
",",
"$",
"newpath",
")",
":",
"bool",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"applyPathPrefix",
"(",
"$",
"path",
")",
";",
"$",
"newpath",
"=",
"$",
"this",
"->",
"applyPathPrefix",
"(",
"$",
"ne... | {@inheritdoc} | [
"{"
] | train | https://github.com/spatie/flysystem-dropbox/blob/1166665b03cbea55e63408c6fb29b629f8553c74/src/DropboxAdapter.php#L78-L90 |
spatie/flysystem-dropbox | src/DropboxAdapter.php | DropboxAdapter.delete | public function delete($path): bool
{
$location = $this->applyPathPrefix($path);
try {
$this->client->delete($location);
} catch (BadRequest $e) {
return false;
}
return true;
} | php | public function delete($path): bool
{
$location = $this->applyPathPrefix($path);
try {
$this->client->delete($location);
} catch (BadRequest $e) {
return false;
}
return true;
} | [
"public",
"function",
"delete",
"(",
"$",
"path",
")",
":",
"bool",
"{",
"$",
"location",
"=",
"$",
"this",
"->",
"applyPathPrefix",
"(",
"$",
"path",
")",
";",
"try",
"{",
"$",
"this",
"->",
"client",
"->",
"delete",
"(",
"$",
"location",
")",
";"... | {@inheritdoc} | [
"{"
] | train | https://github.com/spatie/flysystem-dropbox/blob/1166665b03cbea55e63408c6fb29b629f8553c74/src/DropboxAdapter.php#L95-L106 |
spatie/flysystem-dropbox | src/DropboxAdapter.php | DropboxAdapter.createDir | public function createDir($dirname, Config $config)
{
$path = $this->applyPathPrefix($dirname);
try {
$object = $this->client->createFolder($path);
} catch (BadRequest $e) {
return false;
}
return $this->normalizeResponse($object);
} | php | public function createDir($dirname, Config $config)
{
$path = $this->applyPathPrefix($dirname);
try {
$object = $this->client->createFolder($path);
} catch (BadRequest $e) {
return false;
}
return $this->normalizeResponse($object);
} | [
"public",
"function",
"createDir",
"(",
"$",
"dirname",
",",
"Config",
"$",
"config",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"applyPathPrefix",
"(",
"$",
"dirname",
")",
";",
"try",
"{",
"$",
"object",
"=",
"$",
"this",
"->",
"client",
"->",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/spatie/flysystem-dropbox/blob/1166665b03cbea55e63408c6fb29b629f8553c74/src/DropboxAdapter.php#L119-L130 |
spatie/flysystem-dropbox | src/DropboxAdapter.php | DropboxAdapter.readStream | public function readStream($path)
{
$path = $this->applyPathPrefix($path);
try {
$stream = $this->client->download($path);
} catch (BadRequest $e) {
return false;
}
return compact('stream');
} | php | public function readStream($path)
{
$path = $this->applyPathPrefix($path);
try {
$stream = $this->client->download($path);
} catch (BadRequest $e) {
return false;
}
return compact('stream');
} | [
"public",
"function",
"readStream",
"(",
"$",
"path",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"applyPathPrefix",
"(",
"$",
"path",
")",
";",
"try",
"{",
"$",
"stream",
"=",
"$",
"this",
"->",
"client",
"->",
"download",
"(",
"$",
"path",
")"... | {@inheritdoc} | [
"{"
] | train | https://github.com/spatie/flysystem-dropbox/blob/1166665b03cbea55e63408c6fb29b629f8553c74/src/DropboxAdapter.php#L159-L170 |
spatie/flysystem-dropbox | src/DropboxAdapter.php | DropboxAdapter.listContents | public function listContents($directory = '', $recursive = false): array
{
$location = $this->applyPathPrefix($directory);
try {
$result = $this->client->listFolder($location, $recursive);
} catch (BadRequest $e) {
return [];
}
$entries = $result['entries'];
while ($result['has_more']) {
$result = $this->client->listFolderContinue($result['cursor']);
$entries = array_merge($entries, $result['entries']);
}
if (! count($entries)) {
return [];
}
return array_map(function ($entry) {
$path = $this->removePathPrefix($entry['path_display']);
return $this->normalizeResponse($entry, $path);
}, $entries);
} | php | public function listContents($directory = '', $recursive = false): array
{
$location = $this->applyPathPrefix($directory);
try {
$result = $this->client->listFolder($location, $recursive);
} catch (BadRequest $e) {
return [];
}
$entries = $result['entries'];
while ($result['has_more']) {
$result = $this->client->listFolderContinue($result['cursor']);
$entries = array_merge($entries, $result['entries']);
}
if (! count($entries)) {
return [];
}
return array_map(function ($entry) {
$path = $this->removePathPrefix($entry['path_display']);
return $this->normalizeResponse($entry, $path);
}, $entries);
} | [
"public",
"function",
"listContents",
"(",
"$",
"directory",
"=",
"''",
",",
"$",
"recursive",
"=",
"false",
")",
":",
"array",
"{",
"$",
"location",
"=",
"$",
"this",
"->",
"applyPathPrefix",
"(",
"$",
"directory",
")",
";",
"try",
"{",
"$",
"result",... | {@inheritdoc} | [
"{"
] | train | https://github.com/spatie/flysystem-dropbox/blob/1166665b03cbea55e63408c6fb29b629f8553c74/src/DropboxAdapter.php#L175-L201 |
spatie/flysystem-dropbox | src/DropboxAdapter.php | DropboxAdapter.getMetadata | public function getMetadata($path)
{
$path = $this->applyPathPrefix($path);
try {
$object = $this->client->getMetadata($path);
} catch (BadRequest $e) {
return false;
}
return $this->normalizeResponse($object);
} | php | public function getMetadata($path)
{
$path = $this->applyPathPrefix($path);
try {
$object = $this->client->getMetadata($path);
} catch (BadRequest $e) {
return false;
}
return $this->normalizeResponse($object);
} | [
"public",
"function",
"getMetadata",
"(",
"$",
"path",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"applyPathPrefix",
"(",
"$",
"path",
")",
";",
"try",
"{",
"$",
"object",
"=",
"$",
"this",
"->",
"client",
"->",
"getMetadata",
"(",
"$",
"path",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/spatie/flysystem-dropbox/blob/1166665b03cbea55e63408c6fb29b629f8553c74/src/DropboxAdapter.php#L206-L217 |
spatie/flysystem-dropbox | src/DropboxAdapter.php | DropboxAdapter.upload | protected function upload(string $path, $contents, string $mode)
{
$path = $this->applyPathPrefix($path);
try {
$object = $this->client->upload($path, $contents, $mode);
} catch (BadRequest $e) {
return false;
}
return $this->normalizeResponse($object);
} | php | protected function upload(string $path, $contents, string $mode)
{
$path = $this->applyPathPrefix($path);
try {
$object = $this->client->upload($path, $contents, $mode);
} catch (BadRequest $e) {
return false;
}
return $this->normalizeResponse($object);
} | [
"protected",
"function",
"upload",
"(",
"string",
"$",
"path",
",",
"$",
"contents",
",",
"string",
"$",
"mode",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"applyPathPrefix",
"(",
"$",
"path",
")",
";",
"try",
"{",
"$",
"object",
"=",
"$",
"thi... | @param string $path
@param resource|string $contents
@param string $mode
@return array|false file metadata | [
"@param",
"string",
"$path",
"@param",
"resource|string",
"$contents",
"@param",
"string",
"$mode"
] | train | https://github.com/spatie/flysystem-dropbox/blob/1166665b03cbea55e63408c6fb29b629f8553c74/src/DropboxAdapter.php#L280-L291 |
bizley/yii2-migration | src/table/TableColumnSmallInt.php | TableColumnSmallInt.getLength | public function getLength()
{
return in_array($this->schema, $this->lengthSchemas, true) ? $this->size : null;
} | php | public function getLength()
{
return in_array($this->schema, $this->lengthSchemas, true) ? $this->size : null;
} | [
"public",
"function",
"getLength",
"(",
")",
"{",
"return",
"in_array",
"(",
"$",
"this",
"->",
"schema",
",",
"$",
"this",
"->",
"lengthSchemas",
",",
"true",
")",
"?",
"$",
"this",
"->",
"size",
":",
"null",
";",
"}"
] | Returns length of the column.
@return int|string | [
"Returns",
"length",
"of",
"the",
"column",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumnSmallInt.php#L25-L28 |
bizley/yii2-migration | src/table/TableColumnSmallInt.php | TableColumnSmallInt.setLength | public function setLength($value): void
{
if (in_array($this->schema, $this->lengthSchemas, true)) {
$this->size = $value;
$this->precision = $value;
}
} | php | public function setLength($value): void
{
if (in_array($this->schema, $this->lengthSchemas, true)) {
$this->size = $value;
$this->precision = $value;
}
} | [
"public",
"function",
"setLength",
"(",
"$",
"value",
")",
":",
"void",
"{",
"if",
"(",
"in_array",
"(",
"$",
"this",
"->",
"schema",
",",
"$",
"this",
"->",
"lengthSchemas",
",",
"true",
")",
")",
"{",
"$",
"this",
"->",
"size",
"=",
"$",
"value",... | Sets length of the column.
@param string|int $value | [
"Sets",
"length",
"of",
"the",
"column",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumnSmallInt.php#L34-L40 |
bizley/yii2-migration | src/table/TableColumnSmallInt.php | TableColumnSmallInt.buildSpecificDefinition | public function buildSpecificDefinition(TableStructure $table): void
{
$this->definition[] = 'smallInteger(' . ($table->generalSchema ? null : $this->length) . ')';
} | php | public function buildSpecificDefinition(TableStructure $table): void
{
$this->definition[] = 'smallInteger(' . ($table->generalSchema ? null : $this->length) . ')';
} | [
"public",
"function",
"buildSpecificDefinition",
"(",
"TableStructure",
"$",
"table",
")",
":",
"void",
"{",
"$",
"this",
"->",
"definition",
"[",
"]",
"=",
"'smallInteger('",
".",
"(",
"$",
"table",
"->",
"generalSchema",
"?",
"null",
":",
"$",
"this",
"-... | Builds methods chain for column definition.
@param TableStructure $table | [
"Builds",
"methods",
"chain",
"for",
"column",
"definition",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumnSmallInt.php#L46-L49 |
bizley/yii2-migration | src/table/TablePrimaryKey.php | TablePrimaryKey.render | public function render(TableStructure $table, int $indent = 8): string
{
return str_repeat(' ', $indent)
. "\$this->addPrimaryKey('"
. ($this->name ?: self::GENERIC_PRIMARY_KEY)
. "', '"
. $table->renderName()
. "', ['"
. implode("', '", $this->columns)
. "']);";
} | php | public function render(TableStructure $table, int $indent = 8): string
{
return str_repeat(' ', $indent)
. "\$this->addPrimaryKey('"
. ($this->name ?: self::GENERIC_PRIMARY_KEY)
. "', '"
. $table->renderName()
. "', ['"
. implode("', '", $this->columns)
. "']);";
} | [
"public",
"function",
"render",
"(",
"TableStructure",
"$",
"table",
",",
"int",
"$",
"indent",
"=",
"8",
")",
":",
"string",
"{",
"return",
"str_repeat",
"(",
"' '",
",",
"$",
"indent",
")",
".",
"\"\\$this->addPrimaryKey('\"",
".",
"(",
"$",
"this",
"-... | Renders the key.
@param TableStructure $table
@param int $indent
@return string | [
"Renders",
"the",
"key",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TablePrimaryKey.php#L46-L56 |
bizley/yii2-migration | src/table/TablePrimaryKey.php | TablePrimaryKey.addColumn | public function addColumn(string $name): void
{
if (!in_array($name, $this->columns, true)) {
$this->columns[] = $name;
}
} | php | public function addColumn(string $name): void
{
if (!in_array($name, $this->columns, true)) {
$this->columns[] = $name;
}
} | [
"public",
"function",
"addColumn",
"(",
"string",
"$",
"name",
")",
":",
"void",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"columns",
",",
"true",
")",
")",
"{",
"$",
"this",
"->",
"columns",
"[",
"]",
"=",
"$",
... | Adds column to the key.
@param string $name | [
"Adds",
"column",
"to",
"the",
"key",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TablePrimaryKey.php#L62-L67 |
bizley/yii2-migration | src/table/TableChange.php | TableChange.getValue | public function getValue()
{
switch ($this->method) {
case 'createTable':
$columns = [];
foreach ((array)$this->data as $column => $schema) {
$columns[] = TableColumnFactory::build([
'schema' => $this->schema,
'name' => $column,
'type' => $schema['type'],
'length' => $schema['length'] ?? null,
'isNotNull' => $schema['isNotNull'] ?? null,
'isUnique' => $schema['isUnique'] ?? null,
'isPrimaryKey' => $schema['isPrimaryKey'] ?? null,
'check' => $schema['check'] ?? null,
'default' => $schema['default'] ?? null,
'append' => $schema['append'] ?? null,
'isUnsigned' => $schema['isUnsigned'] ?? null,
'comment' => !empty($schema['comment']) ? $schema['comment'] : null,
]);
}
return $columns;
case 'renameColumn':
return [
'old' => $this->data[0],
'new' => $this->data[1],
];
case 'addColumn':
case 'alterColumn':
return TableColumnFactory::build([
'schema' => $this->schema,
'name' => $this->data[0],
'type' => $this->data[1]['type'],
'length' => $this->data[1]['length'] ?? null,
'isNotNull' => $this->data[1]['isNotNull'] ?? null,
'isUnique' => $this->data[1]['isUnique'] ?? null,
'isPrimaryKey' => $this->data[1]['isPrimaryKey'] ?? null,
'check' => $this->data[1]['check'] ?? null,
'default' => $this->data[1]['default'] ?? null,
'append' => $this->data[1]['append'] ?? null,
'isUnsigned' => $this->data[1]['isUnsigned'] ?? null,
'comment' => !empty($this->data[1]['comment']) ? $this->data[1]['comment'] : null,
]);
case 'addPrimaryKey':
return new TablePrimaryKey([
'name' => $this->data[0],
'columns' => $this->data[1],
]);
case 'addForeignKey':
return new TableForeignKey([
'name' => $this->data[0],
'columns' => $this->data[1],
'refTable' => $this->data[2],
'refColumns' => $this->data[3],
]);
case 'createIndex':
return new TableIndex([
'name' => $this->data[0],
'columns' => $this->data[1],
'unique' => $this->data[2],
]);
case 'addCommentOnColumn':
return [
'name' => $this->data[0],
'comment' => $this->data[1],
];
case 'renameTable':
case 'dropTable':
case 'dropColumn':
case 'dropPrimaryKey':
case 'dropForeignKey':
case 'dropIndex':
case 'dropCommentFromColumn':
default:
return $this->data;
}
} | php | public function getValue()
{
switch ($this->method) {
case 'createTable':
$columns = [];
foreach ((array)$this->data as $column => $schema) {
$columns[] = TableColumnFactory::build([
'schema' => $this->schema,
'name' => $column,
'type' => $schema['type'],
'length' => $schema['length'] ?? null,
'isNotNull' => $schema['isNotNull'] ?? null,
'isUnique' => $schema['isUnique'] ?? null,
'isPrimaryKey' => $schema['isPrimaryKey'] ?? null,
'check' => $schema['check'] ?? null,
'default' => $schema['default'] ?? null,
'append' => $schema['append'] ?? null,
'isUnsigned' => $schema['isUnsigned'] ?? null,
'comment' => !empty($schema['comment']) ? $schema['comment'] : null,
]);
}
return $columns;
case 'renameColumn':
return [
'old' => $this->data[0],
'new' => $this->data[1],
];
case 'addColumn':
case 'alterColumn':
return TableColumnFactory::build([
'schema' => $this->schema,
'name' => $this->data[0],
'type' => $this->data[1]['type'],
'length' => $this->data[1]['length'] ?? null,
'isNotNull' => $this->data[1]['isNotNull'] ?? null,
'isUnique' => $this->data[1]['isUnique'] ?? null,
'isPrimaryKey' => $this->data[1]['isPrimaryKey'] ?? null,
'check' => $this->data[1]['check'] ?? null,
'default' => $this->data[1]['default'] ?? null,
'append' => $this->data[1]['append'] ?? null,
'isUnsigned' => $this->data[1]['isUnsigned'] ?? null,
'comment' => !empty($this->data[1]['comment']) ? $this->data[1]['comment'] : null,
]);
case 'addPrimaryKey':
return new TablePrimaryKey([
'name' => $this->data[0],
'columns' => $this->data[1],
]);
case 'addForeignKey':
return new TableForeignKey([
'name' => $this->data[0],
'columns' => $this->data[1],
'refTable' => $this->data[2],
'refColumns' => $this->data[3],
]);
case 'createIndex':
return new TableIndex([
'name' => $this->data[0],
'columns' => $this->data[1],
'unique' => $this->data[2],
]);
case 'addCommentOnColumn':
return [
'name' => $this->data[0],
'comment' => $this->data[1],
];
case 'renameTable':
case 'dropTable':
case 'dropColumn':
case 'dropPrimaryKey':
case 'dropForeignKey':
case 'dropIndex':
case 'dropCommentFromColumn':
default:
return $this->data;
}
} | [
"public",
"function",
"getValue",
"(",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"method",
")",
"{",
"case",
"'createTable'",
":",
"$",
"columns",
"=",
"[",
"]",
";",
"foreach",
"(",
"(",
"array",
")",
"$",
"this",
"->",
"data",
"as",
"$",
"colum... | Returns change value.
@return array|string|TableColumn|TablePrimaryKey|TableForeignKey|TableIndex
@throws InvalidConfigException | [
"Returns",
"change",
"value",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableChange.php#L44-L128 |
bizley/yii2-migration | src/table/TableColumnInt.php | TableColumnInt.buildSpecificDefinition | public function buildSpecificDefinition(TableStructure $table): void
{
if ($table->generalSchema && !$table->primaryKey->isComposite() && $this->isColumnInPK($table->primaryKey)) {
$this->isPkPossible = false;
$this->isNotNullPossible = false;
$this->definition[] = 'primaryKey()';
} else {
$this->definition[] = 'integer(' . ($table->generalSchema ? null : $this->length) . ')';
}
} | php | public function buildSpecificDefinition(TableStructure $table): void
{
if ($table->generalSchema && !$table->primaryKey->isComposite() && $this->isColumnInPK($table->primaryKey)) {
$this->isPkPossible = false;
$this->isNotNullPossible = false;
$this->definition[] = 'primaryKey()';
} else {
$this->definition[] = 'integer(' . ($table->generalSchema ? null : $this->length) . ')';
}
} | [
"public",
"function",
"buildSpecificDefinition",
"(",
"TableStructure",
"$",
"table",
")",
":",
"void",
"{",
"if",
"(",
"$",
"table",
"->",
"generalSchema",
"&&",
"!",
"$",
"table",
"->",
"primaryKey",
"->",
"isComposite",
"(",
")",
"&&",
"$",
"this",
"->"... | Builds methods chain for column definition.
@param TableStructure $table | [
"Builds",
"methods",
"chain",
"for",
"column",
"definition",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumnInt.php#L46-L55 |
bizley/yii2-migration | src/table/TableColumnTime.php | TableColumnTime.getLength | public function getLength()
{
return in_array($this->schema, $this->lengthSchemas, true) ? $this->precision : null;
} | php | public function getLength()
{
return in_array($this->schema, $this->lengthSchemas, true) ? $this->precision : null;
} | [
"public",
"function",
"getLength",
"(",
")",
"{",
"return",
"in_array",
"(",
"$",
"this",
"->",
"schema",
",",
"$",
"this",
"->",
"lengthSchemas",
",",
"true",
")",
"?",
"$",
"this",
"->",
"precision",
":",
"null",
";",
"}"
] | Returns length of the column.
@return int|string | [
"Returns",
"length",
"of",
"the",
"column",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumnTime.php#L25-L28 |
bizley/yii2-migration | src/table/TableColumnUPK.php | TableColumnUPK.buildSpecificDefinition | public function buildSpecificDefinition(TableStructure $table): void
{
parent::buildSpecificDefinition($table);
if ($table->generalSchema) {
$this->definition[] = 'unsigned()';
$this->isUnsignedPossible = false;
}
} | php | public function buildSpecificDefinition(TableStructure $table): void
{
parent::buildSpecificDefinition($table);
if ($table->generalSchema) {
$this->definition[] = 'unsigned()';
$this->isUnsignedPossible = false;
}
} | [
"public",
"function",
"buildSpecificDefinition",
"(",
"TableStructure",
"$",
"table",
")",
":",
"void",
"{",
"parent",
"::",
"buildSpecificDefinition",
"(",
"$",
"table",
")",
";",
"if",
"(",
"$",
"table",
"->",
"generalSchema",
")",
"{",
"$",
"this",
"->",
... | Builds methods chain for column definition.
@param TableStructure $table | [
"Builds",
"methods",
"chain",
"for",
"column",
"definition",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumnUPK.php#L17-L25 |
bizley/yii2-migration | src/table/TablePlan.php | TablePlan.render | public function render(TableStructure $table): string
{
$output = '';
foreach ($this->dropColumn as $name) {
$output .= " \$this->dropColumn('" . $table->renderName() . "', '{$name}');\n";
}
/* @var $column TableColumn */
foreach ($this->addColumn as $name => $column) {
$output .= " \$this->addColumn('" . $table->renderName() . "', '{$name}', " . $column->renderDefinition($table) . ");\n";
}
/* @var $column TableColumn */
foreach ($this->alterColumn as $name => $column) {
$output .= " \$this->alterColumn('" . $table->renderName() . "', '{$name}', " . $column->renderDefinition($table) . ");\n";
}
foreach ($this->dropForeignKey as $name) {
$output .= " \$this->dropForeignKey('{$name}', '" . $table->renderName() . "');\n";
}
/* @var $foreignKey TableForeignKey */
foreach ($this->addForeignKey as $name => $foreignKey) {
$output .= $foreignKey->render($table);
}
foreach ($this->dropIndex as $name) {
$output .= " \$this->dropIndex('{$name}', '" . $table->renderName() . "');\n";
}
/* @var $index TableIndex */
foreach ($this->createIndex as $name => $index) {
$output .= $index->render($table) . "\n";
}
if (!empty($this->dropPrimaryKey)) {
$output .= " \$this->dropPrimaryKey('{$this->dropPrimaryKey}', '" . $table->renderName() . "');\n";
}
if ($this->addPrimaryKey) {
$output .= $this->addPrimaryKey->render($table) . "\n";
}
return $output;
} | php | public function render(TableStructure $table): string
{
$output = '';
foreach ($this->dropColumn as $name) {
$output .= " \$this->dropColumn('" . $table->renderName() . "', '{$name}');\n";
}
/* @var $column TableColumn */
foreach ($this->addColumn as $name => $column) {
$output .= " \$this->addColumn('" . $table->renderName() . "', '{$name}', " . $column->renderDefinition($table) . ");\n";
}
/* @var $column TableColumn */
foreach ($this->alterColumn as $name => $column) {
$output .= " \$this->alterColumn('" . $table->renderName() . "', '{$name}', " . $column->renderDefinition($table) . ");\n";
}
foreach ($this->dropForeignKey as $name) {
$output .= " \$this->dropForeignKey('{$name}', '" . $table->renderName() . "');\n";
}
/* @var $foreignKey TableForeignKey */
foreach ($this->addForeignKey as $name => $foreignKey) {
$output .= $foreignKey->render($table);
}
foreach ($this->dropIndex as $name) {
$output .= " \$this->dropIndex('{$name}', '" . $table->renderName() . "');\n";
}
/* @var $index TableIndex */
foreach ($this->createIndex as $name => $index) {
$output .= $index->render($table) . "\n";
}
if (!empty($this->dropPrimaryKey)) {
$output .= " \$this->dropPrimaryKey('{$this->dropPrimaryKey}', '" . $table->renderName() . "');\n";
}
if ($this->addPrimaryKey) {
$output .= $this->addPrimaryKey->render($table) . "\n";
}
return $output;
} | [
"public",
"function",
"render",
"(",
"TableStructure",
"$",
"table",
")",
":",
"string",
"{",
"$",
"output",
"=",
"''",
";",
"foreach",
"(",
"$",
"this",
"->",
"dropColumn",
"as",
"$",
"name",
")",
"{",
"$",
"output",
".=",
"\" \\$this->dropColumn('... | Renders migration changes.
@param TableStructure $table
@return string | [
"Renders",
"migration",
"changes",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TablePlan.php#L65-L110 |
bizley/yii2-migration | src/table/TableStructure.php | TableStructure.identifySchema | public static function identifySchema(?string $schemaClass): string
{
switch ($schemaClass) {
case 'yii\db\mssql\Schema':
return self::SCHEMA_MSSQL;
case 'yii\db\oci\Schema':
return self::SCHEMA_OCI;
case 'yii\db\pgsql\Schema':
return self::SCHEMA_PGSQL;
case 'yii\db\sqlite\Schema':
return self::SCHEMA_SQLITE;
case 'yii\db\cubrid\Schema':
return self::SCHEMA_CUBRID;
case 'yii\db\mysql\Schema':
return self::SCHEMA_MYSQL;
default:
return self::SCHEMA_UNSUPPORTED;
}
} | php | public static function identifySchema(?string $schemaClass): string
{
switch ($schemaClass) {
case 'yii\db\mssql\Schema':
return self::SCHEMA_MSSQL;
case 'yii\db\oci\Schema':
return self::SCHEMA_OCI;
case 'yii\db\pgsql\Schema':
return self::SCHEMA_PGSQL;
case 'yii\db\sqlite\Schema':
return self::SCHEMA_SQLITE;
case 'yii\db\cubrid\Schema':
return self::SCHEMA_CUBRID;
case 'yii\db\mysql\Schema':
return self::SCHEMA_MYSQL;
default:
return self::SCHEMA_UNSUPPORTED;
}
} | [
"public",
"static",
"function",
"identifySchema",
"(",
"?",
"string",
"$",
"schemaClass",
")",
":",
"string",
"{",
"switch",
"(",
"$",
"schemaClass",
")",
"{",
"case",
"'yii\\db\\mssql\\Schema'",
":",
"return",
"self",
"::",
"SCHEMA_MSSQL",
";",
"case",
"'yii\... | Returns schema code based on its class name.
@param null|string $schemaClass
@return string
@since 3.1 | [
"Returns",
"schema",
"code",
"based",
"on",
"its",
"class",
"name",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableStructure.php#L99-L123 |
bizley/yii2-migration | src/table/TableStructure.php | TableStructure.renderName | public function renderName(): string
{
$tableName = $this->name;
if (!$this->usePrefix) {
return $tableName;
}
if ($this->dbPrefix && strpos($this->name, $this->dbPrefix) === 0) {
$tableName = substr($this->name, mb_strlen($this->dbPrefix, 'UTF-8'));
}
return '{{%' . $tableName . '}}';
} | php | public function renderName(): string
{
$tableName = $this->name;
if (!$this->usePrefix) {
return $tableName;
}
if ($this->dbPrefix && strpos($this->name, $this->dbPrefix) === 0) {
$tableName = substr($this->name, mb_strlen($this->dbPrefix, 'UTF-8'));
}
return '{{%' . $tableName . '}}';
} | [
"public",
"function",
"renderName",
"(",
")",
":",
"string",
"{",
"$",
"tableName",
"=",
"$",
"this",
"->",
"name",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"usePrefix",
")",
"{",
"return",
"$",
"tableName",
";",
"}",
"if",
"(",
"$",
"this",
"->",
... | Renders table name.
@return string | [
"Renders",
"table",
"name",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableStructure.php#L138-L151 |
bizley/yii2-migration | src/table/TableStructure.php | TableStructure.render | public function render(): string
{
return $this->renderTable() . $this->renderPk() . $this->renderIndexes() . $this->renderForeignKeys() . "\n";
} | php | public function render(): string
{
return $this->renderTable() . $this->renderPk() . $this->renderIndexes() . $this->renderForeignKeys() . "\n";
} | [
"public",
"function",
"render",
"(",
")",
":",
"string",
"{",
"return",
"$",
"this",
"->",
"renderTable",
"(",
")",
".",
"$",
"this",
"->",
"renderPk",
"(",
")",
".",
"$",
"this",
"->",
"renderIndexes",
"(",
")",
".",
"$",
"this",
"->",
"renderForeig... | Renders the migration structure.
@return string | [
"Renders",
"the",
"migration",
"structure",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableStructure.php#L157-L160 |
bizley/yii2-migration | src/table/TableStructure.php | TableStructure.renderTable | public function renderTable(): string
{
$output = '';
if ($this->tableOptionsInit !== null) {
$output .= " {$this->tableOptionsInit}\n\n";
}
$output .= " \$this->createTable('" . $this->renderName() . "', [";
foreach ($this->columns as $column) {
$output .= "\n" . $column->render($this);
}
$output .= "\n ]" . ($this->tableOptions !== null ? ", {$this->tableOptions}" : '') . ");\n";
return $output;
} | php | public function renderTable(): string
{
$output = '';
if ($this->tableOptionsInit !== null) {
$output .= " {$this->tableOptionsInit}\n\n";
}
$output .= " \$this->createTable('" . $this->renderName() . "', [";
foreach ($this->columns as $column) {
$output .= "\n" . $column->render($this);
}
$output .= "\n ]" . ($this->tableOptions !== null ? ", {$this->tableOptions}" : '') . ");\n";
return $output;
} | [
"public",
"function",
"renderTable",
"(",
")",
":",
"string",
"{",
"$",
"output",
"=",
"''",
";",
"if",
"(",
"$",
"this",
"->",
"tableOptionsInit",
"!==",
"null",
")",
"{",
"$",
"output",
".=",
"\" {$this->tableOptionsInit}\\n\\n\"",
";",
"}",
"$",
... | Renders the table.
@return string | [
"Renders",
"the",
"table",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableStructure.php#L166-L183 |
bizley/yii2-migration | src/table/TableStructure.php | TableStructure.renderPk | public function renderPk(): string
{
$output = '';
if ($this->primaryKey->isComposite()) {
$output .= "\n" . $this->primaryKey->render($this);
}
return $output;
} | php | public function renderPk(): string
{
$output = '';
if ($this->primaryKey->isComposite()) {
$output .= "\n" . $this->primaryKey->render($this);
}
return $output;
} | [
"public",
"function",
"renderPk",
"(",
")",
":",
"string",
"{",
"$",
"output",
"=",
"''",
";",
"if",
"(",
"$",
"this",
"->",
"primaryKey",
"->",
"isComposite",
"(",
")",
")",
"{",
"$",
"output",
".=",
"\"\\n\"",
".",
"$",
"this",
"->",
"primaryKey",
... | Renders the primary key.
@return string | [
"Renders",
"the",
"primary",
"key",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableStructure.php#L189-L198 |
bizley/yii2-migration | src/table/TableStructure.php | TableStructure.renderIndexes | public function renderIndexes(): string
{
$output = '';
if ($this->indexes) {
foreach ($this->indexes as $index) {
foreach ($this->foreignKeys as $foreignKey) {
if ($foreignKey->name === $index->name) {
continue 2;
}
}
$output .= "\n" . $index->render($this);
}
}
return $output;
} | php | public function renderIndexes(): string
{
$output = '';
if ($this->indexes) {
foreach ($this->indexes as $index) {
foreach ($this->foreignKeys as $foreignKey) {
if ($foreignKey->name === $index->name) {
continue 2;
}
}
$output .= "\n" . $index->render($this);
}
}
return $output;
} | [
"public",
"function",
"renderIndexes",
"(",
")",
":",
"string",
"{",
"$",
"output",
"=",
"''",
";",
"if",
"(",
"$",
"this",
"->",
"indexes",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"indexes",
"as",
"$",
"index",
")",
"{",
"foreach",
"(",
"$",
... | Renders the indexes.
@return string | [
"Renders",
"the",
"indexes",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableStructure.php#L204-L221 |
bizley/yii2-migration | src/table/TableStructure.php | TableStructure.renderForeignKeys | public function renderForeignKeys(): string
{
$output = '';
if ($this->foreignKeys) {
foreach ($this->foreignKeys as $foreignKey) {
$output .= "\n" . $foreignKey->render($this);
}
}
return $output;
} | php | public function renderForeignKeys(): string
{
$output = '';
if ($this->foreignKeys) {
foreach ($this->foreignKeys as $foreignKey) {
$output .= "\n" . $foreignKey->render($this);
}
}
return $output;
} | [
"public",
"function",
"renderForeignKeys",
"(",
")",
":",
"string",
"{",
"$",
"output",
"=",
"''",
";",
"if",
"(",
"$",
"this",
"->",
"foreignKeys",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"foreignKeys",
"as",
"$",
"foreignKey",
")",
"{",
"$",
"... | Renders the foreign keys.
@return string | [
"Renders",
"the",
"foreign",
"keys",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableStructure.php#L227-L238 |
bizley/yii2-migration | src/table/TableStructure.php | TableStructure.applyChanges | public function applyChanges(array $changes): void
{
/* @var $change TableChange */
foreach ($changes as $change) {
if (!$change instanceof TableChange) {
throw new InvalidArgumentException('You must provide array of TableChange objects.');
}
switch ($change->method) {
case 'createTable':
/* @var $column TableColumn */
foreach ($change->value as $column) {
$this->columns[$column->name] = $column;
if ($column->isPrimaryKey || $column->isColumnAppendPK()) {
if ($this->primaryKey === null) {
$this->primaryKey = new TablePrimaryKey(['columns' => [$column->name]]);
} else {
$this->primaryKey->addColumn($column->name);
}
}
}
break;
case 'addColumn':
$this->columns[$change->value->name] = $change->value;
if ($change->value->isPrimaryKey || $change->value->isColumnAppendPK()) {
if ($this->primaryKey === null) {
$this->primaryKey = new TablePrimaryKey(['columns' => [$change->value->name]]);
} else {
$this->primaryKey->addColumn($change->value->name);
}
}
break;
case 'dropColumn':
unset($this->columns[$change->value]);
break;
case 'renameColumn':
if (isset($this->columns[$change->value['old']])) {
$this->columns[$change->value['new']] = $this->columns[$change->value['old']];
$this->columns[$change->value['new']]->name = $change->value['new'];
unset($this->columns[$change->value['old']]);
}
break;
case 'alterColumn':
$this->columns[$change->value->name] = $change->value;
break;
case 'addPrimaryKey':
$this->primaryKey = $change->value;
foreach ($this->primaryKey->columns as $column) {
if (isset($this->columns[$column])) {
if (empty($this->columns[$column]->append)) {
$this->columns[$column]->append = $this->columns[$column]->prepareSchemaAppend(true, false);
} elseif (!$this->columns[$column]->isColumnAppendPK()) {
$this->columns[$column]->append .= ' ' . $this->columns[$column]->prepareSchemaAppend(true, false);
}
}
}
break;
case 'dropPrimaryKey':
if ($this->primaryKey !== null) {
foreach ($this->primaryKey->columns as $column) {
if (isset($this->columns[$column]) && !empty($this->columns[$column]->append)) {
$this->columns[$column]->append = $this->columns[$column]->removePKAppend();
}
}
}
$this->primaryKey = null;
break;
case 'addForeignKey':
$this->foreignKeys[$change->value->name] = $change->value;
break;
case 'dropForeignKey':
unset($this->foreignKeys[$change->value]);
break;
case 'createIndex':
$this->indexes[$change->value->name] = $change->value;
if (
$change->value->unique
&& isset($this->columns[$change->value->columns[0]])
&& count($change->value->columns) === 1
) {
$this->columns[$change->value->columns[0]]->isUnique = true;
}
break;
case 'dropIndex':
if (
$this->indexes[$change->value]->unique
&& count($this->indexes[$change->value]->columns) === 1
&& isset($this->columns[$this->indexes[$change->value]->columns[0]])
&& $this->columns[$this->indexes[$change->value]->columns[0]]->isUnique
) {
$this->columns[$this->indexes[$change->value]->columns[0]]->isUnique = false;
}
unset($this->indexes[$change->value]);
break;
case 'addCommentOnColumn':
if (isset($this->columns[$change->value->name])) {
$this->columns[$change->value->name]->comment = $change->value->comment;
}
break;
case 'dropCommentFromColumn':
if (isset($this->columns[$change->value])) {
$this->columns[$change->value]->comment = null;
}
}
}
} | php | public function applyChanges(array $changes): void
{
/* @var $change TableChange */
foreach ($changes as $change) {
if (!$change instanceof TableChange) {
throw new InvalidArgumentException('You must provide array of TableChange objects.');
}
switch ($change->method) {
case 'createTable':
/* @var $column TableColumn */
foreach ($change->value as $column) {
$this->columns[$column->name] = $column;
if ($column->isPrimaryKey || $column->isColumnAppendPK()) {
if ($this->primaryKey === null) {
$this->primaryKey = new TablePrimaryKey(['columns' => [$column->name]]);
} else {
$this->primaryKey->addColumn($column->name);
}
}
}
break;
case 'addColumn':
$this->columns[$change->value->name] = $change->value;
if ($change->value->isPrimaryKey || $change->value->isColumnAppendPK()) {
if ($this->primaryKey === null) {
$this->primaryKey = new TablePrimaryKey(['columns' => [$change->value->name]]);
} else {
$this->primaryKey->addColumn($change->value->name);
}
}
break;
case 'dropColumn':
unset($this->columns[$change->value]);
break;
case 'renameColumn':
if (isset($this->columns[$change->value['old']])) {
$this->columns[$change->value['new']] = $this->columns[$change->value['old']];
$this->columns[$change->value['new']]->name = $change->value['new'];
unset($this->columns[$change->value['old']]);
}
break;
case 'alterColumn':
$this->columns[$change->value->name] = $change->value;
break;
case 'addPrimaryKey':
$this->primaryKey = $change->value;
foreach ($this->primaryKey->columns as $column) {
if (isset($this->columns[$column])) {
if (empty($this->columns[$column]->append)) {
$this->columns[$column]->append = $this->columns[$column]->prepareSchemaAppend(true, false);
} elseif (!$this->columns[$column]->isColumnAppendPK()) {
$this->columns[$column]->append .= ' ' . $this->columns[$column]->prepareSchemaAppend(true, false);
}
}
}
break;
case 'dropPrimaryKey':
if ($this->primaryKey !== null) {
foreach ($this->primaryKey->columns as $column) {
if (isset($this->columns[$column]) && !empty($this->columns[$column]->append)) {
$this->columns[$column]->append = $this->columns[$column]->removePKAppend();
}
}
}
$this->primaryKey = null;
break;
case 'addForeignKey':
$this->foreignKeys[$change->value->name] = $change->value;
break;
case 'dropForeignKey':
unset($this->foreignKeys[$change->value]);
break;
case 'createIndex':
$this->indexes[$change->value->name] = $change->value;
if (
$change->value->unique
&& isset($this->columns[$change->value->columns[0]])
&& count($change->value->columns) === 1
) {
$this->columns[$change->value->columns[0]]->isUnique = true;
}
break;
case 'dropIndex':
if (
$this->indexes[$change->value]->unique
&& count($this->indexes[$change->value]->columns) === 1
&& isset($this->columns[$this->indexes[$change->value]->columns[0]])
&& $this->columns[$this->indexes[$change->value]->columns[0]]->isUnique
) {
$this->columns[$this->indexes[$change->value]->columns[0]]->isUnique = false;
}
unset($this->indexes[$change->value]);
break;
case 'addCommentOnColumn':
if (isset($this->columns[$change->value->name])) {
$this->columns[$change->value->name]->comment = $change->value->comment;
}
break;
case 'dropCommentFromColumn':
if (isset($this->columns[$change->value])) {
$this->columns[$change->value]->comment = null;
}
}
}
} | [
"public",
"function",
"applyChanges",
"(",
"array",
"$",
"changes",
")",
":",
"void",
"{",
"/* @var $change TableChange */",
"foreach",
"(",
"$",
"changes",
"as",
"$",
"change",
")",
"{",
"if",
"(",
"!",
"$",
"change",
"instanceof",
"TableChange",
")",
"{",
... | Builds table structure based on the list of changes from the Updater.
@param TableChange[] $changes
@throws InvalidArgumentException | [
"Builds",
"table",
"structure",
"based",
"on",
"the",
"list",
"of",
"changes",
"from",
"the",
"Updater",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableStructure.php#L245-L367 |
bizley/yii2-migration | src/table/TableColumn.php | TableColumn.buildGeneralDefinition | protected function buildGeneralDefinition(TableStructure $table): void
{
array_unshift($this->definition, '$this');
if ($this->isUnsignedPossible && $this->isUnsigned) {
$this->definition[] = 'unsigned()';
}
if ($this->isNotNullPossible && $this->isNotNull) {
$this->definition[] = 'notNull()';
}
if ($this->default !== null) {
if ($this->default instanceof Expression) {
$this->definition[] = "defaultExpression('" . $this->escapeQuotes($this->default->expression) . "')";
} elseif (is_array($this->default)) {
$this->definition[] = "defaultValue('" . $this->escapeQuotes(Json::encode($this->default)) . "')";
} else {
$this->definition[] = "defaultValue('" . $this->escapeQuotes((string)$this->default) . "')";
}
}
if ($this->isPkPossible && !$table->primaryKey->isComposite() && $this->isColumnInPK($table->primaryKey)) {
$append = $this->prepareSchemaAppend(true, $this->autoIncrement);
if (!empty($this->append)) {
$append .= ' ' . $this->append;
}
$this->definition[] = "append('" . $this->escapeQuotes((string)$append) . "')";
} elseif (!empty($this->append)) {
$this->definition[] = "append('" . $this->escapeQuotes((string)$this->append) . "')";
}
if ($this->comment) {
$this->definition[] = "comment('" . $this->escapeQuotes((string)$this->comment) . "')";
}
} | php | protected function buildGeneralDefinition(TableStructure $table): void
{
array_unshift($this->definition, '$this');
if ($this->isUnsignedPossible && $this->isUnsigned) {
$this->definition[] = 'unsigned()';
}
if ($this->isNotNullPossible && $this->isNotNull) {
$this->definition[] = 'notNull()';
}
if ($this->default !== null) {
if ($this->default instanceof Expression) {
$this->definition[] = "defaultExpression('" . $this->escapeQuotes($this->default->expression) . "')";
} elseif (is_array($this->default)) {
$this->definition[] = "defaultValue('" . $this->escapeQuotes(Json::encode($this->default)) . "')";
} else {
$this->definition[] = "defaultValue('" . $this->escapeQuotes((string)$this->default) . "')";
}
}
if ($this->isPkPossible && !$table->primaryKey->isComposite() && $this->isColumnInPK($table->primaryKey)) {
$append = $this->prepareSchemaAppend(true, $this->autoIncrement);
if (!empty($this->append)) {
$append .= ' ' . $this->append;
}
$this->definition[] = "append('" . $this->escapeQuotes((string)$append) . "')";
} elseif (!empty($this->append)) {
$this->definition[] = "append('" . $this->escapeQuotes((string)$this->append) . "')";
}
if ($this->comment) {
$this->definition[] = "comment('" . $this->escapeQuotes((string)$this->comment) . "')";
}
} | [
"protected",
"function",
"buildGeneralDefinition",
"(",
"TableStructure",
"$",
"table",
")",
":",
"void",
"{",
"array_unshift",
"(",
"$",
"this",
"->",
"definition",
",",
"'$this'",
")",
";",
"if",
"(",
"$",
"this",
"->",
"isUnsignedPossible",
"&&",
"$",
"th... | Builds general methods chain for column definition.
@param TableStructure $table | [
"Builds",
"general",
"methods",
"chain",
"for",
"column",
"definition",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumn.php#L135-L170 |
bizley/yii2-migration | src/table/TableColumn.php | TableColumn.renderDefinition | public function renderDefinition(TableStructure $table): string
{
$this->buildSpecificDefinition($table);
$this->buildGeneralDefinition($table);
return implode('->', $this->definition);
} | php | public function renderDefinition(TableStructure $table): string
{
$this->buildSpecificDefinition($table);
$this->buildGeneralDefinition($table);
return implode('->', $this->definition);
} | [
"public",
"function",
"renderDefinition",
"(",
"TableStructure",
"$",
"table",
")",
":",
"string",
"{",
"$",
"this",
"->",
"buildSpecificDefinition",
"(",
"$",
"table",
")",
";",
"$",
"this",
"->",
"buildGeneralDefinition",
"(",
"$",
"table",
")",
";",
"retu... | Renders column definition.
@param TableStructure $table
@return string | [
"Renders",
"column",
"definition",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumn.php#L177-L183 |
bizley/yii2-migration | src/table/TableColumn.php | TableColumn.render | public function render(TableStructure $table, int $indent = 12): string
{
return str_repeat(' ', $indent) . "'{$this->name}' => " . $this->renderDefinition($table) . ',';
} | php | public function render(TableStructure $table, int $indent = 12): string
{
return str_repeat(' ', $indent) . "'{$this->name}' => " . $this->renderDefinition($table) . ',';
} | [
"public",
"function",
"render",
"(",
"TableStructure",
"$",
"table",
",",
"int",
"$",
"indent",
"=",
"12",
")",
":",
"string",
"{",
"return",
"str_repeat",
"(",
"' '",
",",
"$",
"indent",
")",
".",
"\"'{$this->name}' => \"",
".",
"$",
"this",
"->",
"rend... | Renders the column.
@param TableStructure $table
@param int $indent
@return string | [
"Renders",
"the",
"column",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumn.php#L191-L194 |
bizley/yii2-migration | src/table/TableColumn.php | TableColumn.isColumnInPK | public function isColumnInPK(TablePrimaryKey $pk): bool
{
return in_array($this->name, $pk->columns, true);
} | php | public function isColumnInPK(TablePrimaryKey $pk): bool
{
return in_array($this->name, $pk->columns, true);
} | [
"public",
"function",
"isColumnInPK",
"(",
"TablePrimaryKey",
"$",
"pk",
")",
":",
"bool",
"{",
"return",
"in_array",
"(",
"$",
"this",
"->",
"name",
",",
"$",
"pk",
"->",
"columns",
",",
"true",
")",
";",
"}"
] | Checks if column is a part of primary key.
@param TablePrimaryKey $pk
@return bool | [
"Checks",
"if",
"column",
"is",
"a",
"part",
"of",
"primary",
"key",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumn.php#L201-L204 |
bizley/yii2-migration | src/table/TableColumn.php | TableColumn.isColumnAppendPK | public function isColumnAppendPK(): bool
{
if (empty($this->append)) {
return false;
}
if ($this->schema === TableStructure::SCHEMA_MSSQL) {
if (stripos($this->append, 'IDENTITY') !== false && stripos($this->append, 'PRIMARY KEY') !== false) {
return true;
}
} elseif (stripos($this->append, 'PRIMARY KEY') !== false) {
return true;
}
return false;
} | php | public function isColumnAppendPK(): bool
{
if (empty($this->append)) {
return false;
}
if ($this->schema === TableStructure::SCHEMA_MSSQL) {
if (stripos($this->append, 'IDENTITY') !== false && stripos($this->append, 'PRIMARY KEY') !== false) {
return true;
}
} elseif (stripos($this->append, 'PRIMARY KEY') !== false) {
return true;
}
return false;
} | [
"public",
"function",
"isColumnAppendPK",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"append",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"schema",
"===",
"TableStructure",
"::",
"SCHEMA_MSSQL... | Checks if information of primary key is set in append property.
@return bool | [
"Checks",
"if",
"information",
"of",
"primary",
"key",
"is",
"set",
"in",
"append",
"property",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumn.php#L210-L225 |
bizley/yii2-migration | src/table/TableColumn.php | TableColumn.prepareSchemaAppend | public function prepareSchemaAppend(bool $primaryKey, bool $autoIncrement): ?string
{
switch ($this->schema) {
case TableStructure::SCHEMA_MSSQL:
$append = $primaryKey ? 'IDENTITY PRIMARY KEY' : '';
break;
case TableStructure::SCHEMA_OCI:
case TableStructure::SCHEMA_PGSQL:
$append = $primaryKey ? 'PRIMARY KEY' : '';
break;
case TableStructure::SCHEMA_SQLITE:
$append = trim(($primaryKey ? 'PRIMARY KEY ' : '') . ($autoIncrement ? 'AUTOINCREMENT' : ''));
break;
case TableStructure::SCHEMA_CUBRID:
case TableStructure::SCHEMA_MYSQL:
default:
$append = trim(($autoIncrement ? 'AUTO_INCREMENT ' : '') . ($primaryKey ? 'PRIMARY KEY' : ''));
}
return empty($append) ? null : $append;
} | php | public function prepareSchemaAppend(bool $primaryKey, bool $autoIncrement): ?string
{
switch ($this->schema) {
case TableStructure::SCHEMA_MSSQL:
$append = $primaryKey ? 'IDENTITY PRIMARY KEY' : '';
break;
case TableStructure::SCHEMA_OCI:
case TableStructure::SCHEMA_PGSQL:
$append = $primaryKey ? 'PRIMARY KEY' : '';
break;
case TableStructure::SCHEMA_SQLITE:
$append = trim(($primaryKey ? 'PRIMARY KEY ' : '') . ($autoIncrement ? 'AUTOINCREMENT' : ''));
break;
case TableStructure::SCHEMA_CUBRID:
case TableStructure::SCHEMA_MYSQL:
default:
$append = trim(($autoIncrement ? 'AUTO_INCREMENT ' : '') . ($primaryKey ? 'PRIMARY KEY' : ''));
}
return empty($append) ? null : $append;
} | [
"public",
"function",
"prepareSchemaAppend",
"(",
"bool",
"$",
"primaryKey",
",",
"bool",
"$",
"autoIncrement",
")",
":",
"?",
"string",
"{",
"switch",
"(",
"$",
"this",
"->",
"schema",
")",
"{",
"case",
"TableStructure",
"::",
"SCHEMA_MSSQL",
":",
"$",
"a... | Prepares append SQL based on schema.
@param bool $primaryKey
@param bool $autoIncrement
@return string|null | [
"Prepares",
"append",
"SQL",
"based",
"on",
"schema",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumn.php#L233-L256 |
bizley/yii2-migration | src/table/TableColumn.php | TableColumn.removePKAppend | public function removePKAppend(): ?string
{
if (!$this->isColumnAppendPK()) {
return null;
}
$uppercaseAppend = preg_replace('/\s+/', ' ', mb_strtoupper($this->append, 'UTF-8'));
switch ($this->schema) {
case TableStructure::SCHEMA_MSSQL:
$formattedAppend = str_replace(['PRIMARY KEY', 'IDENTITY'], '', $uppercaseAppend);
break;
case TableStructure::SCHEMA_OCI:
case TableStructure::SCHEMA_PGSQL:
$formattedAppend = str_replace('PRIMARY KEY', '', $uppercaseAppend);
break;
case TableStructure::SCHEMA_SQLITE:
$formattedAppend = str_replace(['PRIMARY KEY', 'AUTOINCREMENT'], '', $uppercaseAppend);
break;
case TableStructure::SCHEMA_CUBRID:
case TableStructure::SCHEMA_MYSQL:
default:
$formattedAppend = str_replace(['PRIMARY KEY', 'AUTO_INCREMENT'], '', $uppercaseAppend);
}
$formattedAppend = trim($formattedAppend);
return !empty($formattedAppend) ? $formattedAppend : null;
} | php | public function removePKAppend(): ?string
{
if (!$this->isColumnAppendPK()) {
return null;
}
$uppercaseAppend = preg_replace('/\s+/', ' ', mb_strtoupper($this->append, 'UTF-8'));
switch ($this->schema) {
case TableStructure::SCHEMA_MSSQL:
$formattedAppend = str_replace(['PRIMARY KEY', 'IDENTITY'], '', $uppercaseAppend);
break;
case TableStructure::SCHEMA_OCI:
case TableStructure::SCHEMA_PGSQL:
$formattedAppend = str_replace('PRIMARY KEY', '', $uppercaseAppend);
break;
case TableStructure::SCHEMA_SQLITE:
$formattedAppend = str_replace(['PRIMARY KEY', 'AUTOINCREMENT'], '', $uppercaseAppend);
break;
case TableStructure::SCHEMA_CUBRID:
case TableStructure::SCHEMA_MYSQL:
default:
$formattedAppend = str_replace(['PRIMARY KEY', 'AUTO_INCREMENT'], '', $uppercaseAppend);
}
$formattedAppend = trim($formattedAppend);
return !empty($formattedAppend) ? $formattedAppend : null;
} | [
"public",
"function",
"removePKAppend",
"(",
")",
":",
"?",
"string",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isColumnAppendPK",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"uppercaseAppend",
"=",
"preg_replace",
"(",
"'/\\s+/'",
",",
"' '",
... | Removes information of primary key in append property.
@return null|string | [
"Removes",
"information",
"of",
"primary",
"key",
"in",
"append",
"property",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumn.php#L272-L303 |
bizley/yii2-migration | src/table/TableColumnBigPK.php | TableColumnBigPK.buildSpecificDefinition | public function buildSpecificDefinition(TableStructure $table): void
{
$this->definition[] = 'bigPrimaryKey(' . ($table->generalSchema ? null : $this->length) . ')';
if ($table->generalSchema) {
$this->isPkPossible = false;
$this->isNotNullPossible = false;
}
} | php | public function buildSpecificDefinition(TableStructure $table): void
{
$this->definition[] = 'bigPrimaryKey(' . ($table->generalSchema ? null : $this->length) . ')';
if ($table->generalSchema) {
$this->isPkPossible = false;
$this->isNotNullPossible = false;
}
} | [
"public",
"function",
"buildSpecificDefinition",
"(",
"TableStructure",
"$",
"table",
")",
":",
"void",
"{",
"$",
"this",
"->",
"definition",
"[",
"]",
"=",
"'bigPrimaryKey('",
".",
"(",
"$",
"table",
"->",
"generalSchema",
"?",
"null",
":",
"$",
"this",
"... | Builds methods chain for column definition.
@param TableStructure $table | [
"Builds",
"methods",
"chain",
"for",
"column",
"definition",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumnBigPK.php#L46-L53 |
bizley/yii2-migration | src/table/TableColumnMoney.php | TableColumnMoney.setLength | public function setLength($value): void
{
$length = is_array($value) ? $value : preg_split('\s*,\s*', $value);
if (isset($length[0]) && !empty($length[0])) {
$this->precision = $length[0];
}
if (isset($length[1]) && !empty($length[1])) {
$this->scale = $length[1];
}
} | php | public function setLength($value): void
{
$length = is_array($value) ? $value : preg_split('\s*,\s*', $value);
if (isset($length[0]) && !empty($length[0])) {
$this->precision = $length[0];
}
if (isset($length[1]) && !empty($length[1])) {
$this->scale = $length[1];
}
} | [
"public",
"function",
"setLength",
"(",
"$",
"value",
")",
":",
"void",
"{",
"$",
"length",
"=",
"is_array",
"(",
"$",
"value",
")",
"?",
"$",
"value",
":",
"preg_split",
"(",
"'\\s*,\\s*'",
",",
"$",
"value",
")",
";",
"if",
"(",
"isset",
"(",
"$"... | Sets length of the column.
@param array|string|int $value | [
"Sets",
"length",
"of",
"the",
"column",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumnMoney.php#L29-L40 |
bizley/yii2-migration | src/Updater.php | Updater.init | public function init(): void
{
parent::init();
$this->_currentTable = $this->tableName;
foreach ($this->skipMigrations as $index => $migration) {
$this->skipMigrations[$index] = trim($migration, '\\');
}
} | php | public function init(): void
{
parent::init();
$this->_currentTable = $this->tableName;
foreach ($this->skipMigrations as $index => $migration) {
$this->skipMigrations[$index] = trim($migration, '\\');
}
} | [
"public",
"function",
"init",
"(",
")",
":",
"void",
"{",
"parent",
"::",
"init",
"(",
")",
";",
"$",
"this",
"->",
"_currentTable",
"=",
"$",
"this",
"->",
"tableName",
";",
"foreach",
"(",
"$",
"this",
"->",
"skipMigrations",
"as",
"$",
"index",
"=... | Sets current table name and clears skipped migrations names.
@throws InvalidConfigException | [
"Sets",
"current",
"table",
"name",
"and",
"clears",
"skipped",
"migrations",
"names",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Updater.php#L75-L84 |
bizley/yii2-migration | src/Updater.php | Updater.fetchHistory | public function fetchHistory(): array
{
if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
return [];
}
$rows = (new Query())
->select(['version', 'apply_time'])
->from($this->migrationTable)
->orderBy(['apply_time' => SORT_DESC, 'version' => SORT_DESC])
->all($this->db);
$history = [];
foreach ($rows as $key => $row) {
if ($row['version'] === MigrateController::BASE_MIGRATION) {
continue;
}
if (preg_match('/m?(\d{6}_?\d{6})(\D.*)?$/is', $row['version'], $matches)) {
$row['canonicalVersion'] = str_replace('_', '', $matches[1]);
} else {
$row['canonicalVersion'] = $row['version'];
}
$row['apply_time'] = (int)$row['apply_time'];
$history[] = $row;
}
usort($history, static function ($a, $b) {
if ($a['apply_time'] === $b['apply_time']) {
if (($compareResult = strcasecmp($b['canonicalVersion'], $a['canonicalVersion'])) !== 0) {
return $compareResult;
}
return strcasecmp($b['version'], $a['version']);
}
return ($a['apply_time'] > $b['apply_time']) ? -1 : 1;
});
return ArrayHelper::map($history, 'version', 'apply_time');
} | php | public function fetchHistory(): array
{
if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
return [];
}
$rows = (new Query())
->select(['version', 'apply_time'])
->from($this->migrationTable)
->orderBy(['apply_time' => SORT_DESC, 'version' => SORT_DESC])
->all($this->db);
$history = [];
foreach ($rows as $key => $row) {
if ($row['version'] === MigrateController::BASE_MIGRATION) {
continue;
}
if (preg_match('/m?(\d{6}_?\d{6})(\D.*)?$/is', $row['version'], $matches)) {
$row['canonicalVersion'] = str_replace('_', '', $matches[1]);
} else {
$row['canonicalVersion'] = $row['version'];
}
$row['apply_time'] = (int)$row['apply_time'];
$history[] = $row;
}
usort($history, static function ($a, $b) {
if ($a['apply_time'] === $b['apply_time']) {
if (($compareResult = strcasecmp($b['canonicalVersion'], $a['canonicalVersion'])) !== 0) {
return $compareResult;
}
return strcasecmp($b['version'], $a['version']);
}
return ($a['apply_time'] > $b['apply_time']) ? -1 : 1;
});
return ArrayHelper::map($history, 'version', 'apply_time');
} | [
"public",
"function",
"fetchHistory",
"(",
")",
":",
"array",
"{",
"if",
"(",
"$",
"this",
"->",
"db",
"->",
"schema",
"->",
"getTableSchema",
"(",
"$",
"this",
"->",
"migrationTable",
",",
"true",
")",
"===",
"null",
")",
"{",
"return",
"[",
"]",
";... | Returns the migration history.
This is slightly modified MigrateController::getMigrationHistory() method.
Migrations are fetched from newest to oldest.
@return array the migration history | [
"Returns",
"the",
"migration",
"history",
".",
"This",
"is",
"slightly",
"modified",
"MigrateController",
"::",
"getMigrationHistory",
"()",
"method",
".",
"Migrations",
"are",
"fetched",
"from",
"newest",
"to",
"oldest",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Updater.php#L101-L144 |
bizley/yii2-migration | src/Updater.php | Updater.gatherChanges | protected function gatherChanges(array $changes): bool
{
if (!isset($changes[$this->_currentTable])) {
return true;
}
$data = array_reverse($changes[$this->_currentTable]);
/* @var $tableChange TableChange */
foreach ($data as $tableChange) {
if ($tableChange->method === 'dropTable') {
return false;
}
if ($tableChange->method === 'renameTable') {
$this->_currentTable = $tableChange->value;
return $this->gatherChanges($changes);
}
$this->_appliedChanges[] = $tableChange;
if ($tableChange->method === 'createTable') {
return false;
}
}
return true;
} | php | protected function gatherChanges(array $changes): bool
{
if (!isset($changes[$this->_currentTable])) {
return true;
}
$data = array_reverse($changes[$this->_currentTable]);
/* @var $tableChange TableChange */
foreach ($data as $tableChange) {
if ($tableChange->method === 'dropTable') {
return false;
}
if ($tableChange->method === 'renameTable') {
$this->_currentTable = $tableChange->value;
return $this->gatherChanges($changes);
}
$this->_appliedChanges[] = $tableChange;
if ($tableChange->method === 'createTable') {
return false;
}
}
return true;
} | [
"protected",
"function",
"gatherChanges",
"(",
"array",
"$",
"changes",
")",
":",
"bool",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"changes",
"[",
"$",
"this",
"->",
"_currentTable",
"]",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"data",
"=",
... | Gathers applied changes.
@param array $changes
@return bool true if more data can be analysed or false if this must be last one
@since 2.3.0 | [
"Gathers",
"applied",
"changes",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Updater.php#L154-L181 |
bizley/yii2-migration | src/Updater.php | Updater.extract | protected function extract(string $migration): array
{
if (strpos($migration, '\\') === false) {
$file = Yii::getAlias($this->migrationPath . DIRECTORY_SEPARATOR . $migration . '.php');
if (!file_exists($file)) {
throw new ErrorException("File '{$file}' can not be found! Check migration history table.");
}
require_once $file;
}
$subject = new $migration;
$subject->db = $this->db;
$subject->up();
return $subject->changes;
} | php | protected function extract(string $migration): array
{
if (strpos($migration, '\\') === false) {
$file = Yii::getAlias($this->migrationPath . DIRECTORY_SEPARATOR . $migration . '.php');
if (!file_exists($file)) {
throw new ErrorException("File '{$file}' can not be found! Check migration history table.");
}
require_once $file;
}
$subject = new $migration;
$subject->db = $this->db;
$subject->up();
return $subject->changes;
} | [
"protected",
"function",
"extract",
"(",
"string",
"$",
"migration",
")",
":",
"array",
"{",
"if",
"(",
"strpos",
"(",
"$",
"migration",
",",
"'\\\\'",
")",
"===",
"false",
")",
"{",
"$",
"file",
"=",
"Yii",
"::",
"getAlias",
"(",
"$",
"this",
"->",
... | Extracts migration data structures.
@param string $migration
@return array
@throws InvalidArgumentException
@throws ErrorException | [
"Extracts",
"migration",
"data",
"structures",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Updater.php#L190-L207 |
bizley/yii2-migration | src/Updater.php | Updater.getOldTable | public function getOldTable(): TableStructure
{
if ($this->_oldTable === null) {
$this->_oldTable = new TableStructure([
'schema' => get_class($this->db->schema),
'generalSchema' => $this->generalSchema,
'usePrefix' => $this->useTablePrefix,
'dbPrefix' => $this->db->tablePrefix,
]);
$this->_oldTable->applyChanges(array_reverse($this->_appliedChanges));
}
return $this->_oldTable;
} | php | public function getOldTable(): TableStructure
{
if ($this->_oldTable === null) {
$this->_oldTable = new TableStructure([
'schema' => get_class($this->db->schema),
'generalSchema' => $this->generalSchema,
'usePrefix' => $this->useTablePrefix,
'dbPrefix' => $this->db->tablePrefix,
]);
$this->_oldTable->applyChanges(array_reverse($this->_appliedChanges));
}
return $this->_oldTable;
} | [
"public",
"function",
"getOldTable",
"(",
")",
":",
"TableStructure",
"{",
"if",
"(",
"$",
"this",
"->",
"_oldTable",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"_oldTable",
"=",
"new",
"TableStructure",
"(",
"[",
"'schema'",
"=>",
"get_class",
"(",
"$"... | Returns the table structure as applied in gathered migrations.
@return TableStructure
@since 2.3.0
@throws InvalidArgumentException | [
"Returns",
"the",
"table",
"structure",
"as",
"applied",
"in",
"gathered",
"migrations",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Updater.php#L217-L231 |
bizley/yii2-migration | src/Updater.php | Updater.displayValue | public function displayValue($value): string
{
if ($value === null) {
return 'NULL';
}
if ($value === true) {
return 'TRUE';
}
if ($value === false) {
return 'FALSE';
}
if (is_array($value)) {
return Json::encode($value);
}
return '"' . str_replace('"', '\"', $value) . '"';
} | php | public function displayValue($value): string
{
if ($value === null) {
return 'NULL';
}
if ($value === true) {
return 'TRUE';
}
if ($value === false) {
return 'FALSE';
}
if (is_array($value)) {
return Json::encode($value);
}
return '"' . str_replace('"', '\"', $value) . '"';
} | [
"public",
"function",
"displayValue",
"(",
"$",
"value",
")",
":",
"string",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"return",
"'NULL'",
";",
"}",
"if",
"(",
"$",
"value",
"===",
"true",
")",
"{",
"return",
"'TRUE'",
";",
"}",
"if",
... | Returns values as a string.
@param mixed $value
@return string | [
"Returns",
"values",
"as",
"a",
"string",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Updater.php#L238-L257 |
bizley/yii2-migration | src/Updater.php | Updater.confirmCompositePrimaryKey | protected function confirmCompositePrimaryKey(array $newKeys): bool
{
if (count($this->table->primaryKey->columns) === 1 && count($newKeys) === 1) {
/* @var $column TableColumn */
foreach ($this->plan->addColumn as $name => $column) {
if ($name === $newKeys[0] && $column->isColumnAppendPK()) {
return false;
}
}
foreach ($this->plan->alterColumn as $name => $column) {
if ($name === $newKeys[0] && $column->isColumnAppendPK()) {
return false;
}
}
return true;
}
if (count($this->table->primaryKey->columns) > 1) {
foreach ($newKeys as $key) {
/* @var $column TableColumn */
foreach ($this->plan->addColumn as $name => $column) {
if ($name === $key) {
$column->append = $column->removePKAppend();
}
}
foreach ($this->plan->alterColumn as $name => $column) {
if ($name === $key) {
$column->append = $column->removePKAppend();
}
}
}
}
return true;
} | php | protected function confirmCompositePrimaryKey(array $newKeys): bool
{
if (count($this->table->primaryKey->columns) === 1 && count($newKeys) === 1) {
/* @var $column TableColumn */
foreach ($this->plan->addColumn as $name => $column) {
if ($name === $newKeys[0] && $column->isColumnAppendPK()) {
return false;
}
}
foreach ($this->plan->alterColumn as $name => $column) {
if ($name === $newKeys[0] && $column->isColumnAppendPK()) {
return false;
}
}
return true;
}
if (count($this->table->primaryKey->columns) > 1) {
foreach ($newKeys as $key) {
/* @var $column TableColumn */
foreach ($this->plan->addColumn as $name => $column) {
if ($name === $key) {
$column->append = $column->removePKAppend();
}
}
foreach ($this->plan->alterColumn as $name => $column) {
if ($name === $key) {
$column->append = $column->removePKAppend();
}
}
}
}
return true;
} | [
"protected",
"function",
"confirmCompositePrimaryKey",
"(",
"array",
"$",
"newKeys",
")",
":",
"bool",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"table",
"->",
"primaryKey",
"->",
"columns",
")",
"===",
"1",
"&&",
"count",
"(",
"$",
"newKeys",
")"... | Confirms adding composite primary key and removes excessive PK statements.
@param array $newKeys
@return bool
@since 2.1.2 | [
"Confirms",
"adding",
"composite",
"primary",
"key",
"and",
"removes",
"excessive",
"PK",
"statements",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Updater.php#L265-L302 |
bizley/yii2-migration | src/Updater.php | Updater.compareStructures | protected function compareStructures(): bool
{
if (empty($this->_appliedChanges)) {
return true;
}
$different = false;
if ($this->showOnly) {
echo "SHOWING DIFFERENCES:\n";
}
foreach ($this->table->columns as $name => $column) {
if (!isset($this->oldTable->columns[$name])) {
if ($this->showOnly) {
echo " - missing column '$name'\n";
} else {
$this->plan->addColumn[$name] = $column;
}
$different = true;
continue;
}
foreach (['type', 'isNotNull', 'length', 'isUnique', 'isUnsigned', 'default', 'append', 'comment'] as $property) {
if ($this->generalSchema && $property === 'length') {
continue;
}
if (
!$this->generalSchema
&& $property === 'append'
&& $column->append === null
&& !$this->table->primaryKey->isComposite()
&& $column->isColumnInPK($this->table->primaryKey)
) {
$column->append = $column->prepareSchemaAppend(true, $column->autoIncrement);
}
if ($this->oldTable->columns[$name]->$property !== $column->$property) {
if ($this->showOnly) {
echo " - different '$name' column property: $property (";
echo 'DB: ' . $this->displayValue($column->$property) . ' <> ';
echo 'MIG: ' . $this->displayValue($this->oldTable->columns[$name]->$property) . ")\n";
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
echo " (!) ALTER COLUMN is not supported by SQLite: Migration must be created manually\n";
}
} elseif (!isset($this->plan->alterColumn[$name])) {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('ALTER COLUMN is not supported by SQLite.');
}
$this->plan->alterColumn[$name] = $column;
}
$different = true;
}
}
}
foreach ($this->oldTable->columns as $name => $column) {
if (!isset($this->table->columns[$name])) {
if ($this->showOnly) {
echo " - excessive column '$name'\n";
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
echo " (!) DROP COLUMN is not supported by SQLite: Migration must be created manually\n";
}
} else {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('DROP COLUMN is not supported by SQLite.');
}
$this->plan->dropColumn[] = $name;
}
$different = true;
}
}
foreach ($this->table->foreignKeys as $name => $foreignKey) {
if (!isset($this->oldTable->foreignKeys[$name])) {
if ($this->showOnly) {
echo " - missing foreign key '$name'\n";
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
echo " (!) ADD FOREIGN KEY is not supported by SQLite: Migration must be created manually\n";
}
} else {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('ADD FOREIGN KEY is not supported by SQLite.');
}
$this->plan->addForeignKey[$name] = $foreignKey;
}
$different = true;
continue;
}
$tableFKColumns = !empty($this->table->foreignKeys[$name]->columns) ? $this->table->foreignKeys[$name]->columns : [];
$oldTableFKColumns = !empty($this->oldTable->foreignKeys[$name]->columns) ? $this->oldTable->foreignKeys[$name]->columns : [];
if (
count(
array_merge(
array_diff($tableFKColumns, array_intersect($tableFKColumns, $oldTableFKColumns)),
array_diff($oldTableFKColumns, array_intersect($tableFKColumns, $oldTableFKColumns))
)
)
) {
if ($this->showOnly) {
echo " - different foreign key '$name' columns (";
echo 'DB: (' . implode(', ', $tableFKColumns) . ') <> ';
echo 'MIG: (' . implode(', ', $oldTableFKColumns) . "))\n";
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
echo " (!) DROP/ADD FOREIGN KEY is not supported by SQLite: Migration must be created manually\n";
}
} else {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('DROP/ADD FOREIGN KEY is not supported by SQLite.');
}
$this->plan->dropForeignKey[] = $name;
$this->plan->addForeignKey[$name] = $foreignKey;
}
$different = true;
continue;
}
$tableFKRefColumns = !empty($this->table->foreignKeys[$name]->refColumns) ? $this->table->foreignKeys[$name]->refColumns : [];
$oldTableFKRefColumns = !empty($this->oldTable->foreignKeys[$name]->refColumns) ? $this->oldTable->foreignKeys[$name]->refColumns : [];
if (
count(
array_merge(
array_diff($tableFKRefColumns, array_intersect($tableFKRefColumns, $oldTableFKRefColumns)),
array_diff($oldTableFKRefColumns, array_intersect($tableFKRefColumns, $oldTableFKRefColumns))
)
)
) {
if ($this->showOnly) {
echo " - different foreign key '$name' referral columns (";
echo 'DB: (' . implode(', ', $tableFKRefColumns) . ') <> ';
echo 'MIG: (' . implode(', ', $oldTableFKRefColumns) . "))\n";
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
echo " (!) DROP/ADD FOREIGN KEY is not supported by SQLite: Migration must be created manually\n";
}
} else {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('DROP/ADD FOREIGN KEY is not supported by SQLite.');
}
$this->plan->dropForeignKey[] = $name;
$this->plan->addForeignKey[$name] = $foreignKey;
}
$different = true;
}
}
foreach ($this->oldTable->foreignKeys as $name => $foreignKey) {
if (!isset($this->table->foreignKeys[$name])) {
if ($this->showOnly) {
echo " - excessive foreign key '$name'\n";
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
echo " (!) DROP FOREIGN KEY is not supported by SQLite: Migration must be created manually\n";
}
} else {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('DROP FOREIGN KEY is not supported by SQLite.');
}
$this->plan->dropForeignKey[] = $name;
}
$different = true;
}
}
$tablePKColumns = !empty($this->table->primaryKey->columns) ? $this->table->primaryKey->columns : [];
$oldTablePKColumns = !empty($this->oldTable->primaryKey->columns) ? $this->oldTable->primaryKey->columns : [];
$newKeys = array_merge(
array_diff($tablePKColumns, array_intersect($tablePKColumns, $oldTablePKColumns)),
array_diff($oldTablePKColumns, array_intersect($tablePKColumns, $oldTablePKColumns))
);
if (count($newKeys)) {
if ($this->showOnly) {
echo " - different primary key definition\n";
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
echo " (!) DROP/ADD PRIMARY KEY is not supported by SQLite: Migration must be created manually\n";
}
} else {
if (!empty($this->oldTable->primaryKey->columns)) {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('DROP PRIMARY KEY is not supported by SQLite.');
}
$this->plan->dropPrimaryKey = $this->oldTable->primaryKey->name ?: TablePrimaryKey::GENERIC_PRIMARY_KEY;
}
if (!empty($this->table->primaryKey->columns) && $this->confirmCompositePrimaryKey($newKeys)) {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('ADD PRIMARY KEY is not supported by SQLite.');
}
$this->plan->addPrimaryKey = $this->table->primaryKey;
}
}
$different = true;
}
foreach ($this->table->indexes as $name => $index) {
if (!isset($this->oldTable->indexes[$name])) {
if ($this->showOnly) {
echo " - missing index '$name'\n";
} else {
$this->plan->createIndex[$name] = $index;
}
$different = true;
continue;
}
if ($this->oldTable->indexes[$name]->unique !== $this->table->indexes[$name]->unique) {
if ($this->showOnly) {
echo " - different index '$name' definition (";
echo 'DB: unique ' . $this->displayValue($this->table->indexes[$name]->unique) . ' <> ';
echo 'MIG: unique ' . $this->displayValue($this->oldTable->indexes[$name]->unique) . ")\n";
} else {
$this->plan->dropIndex[] = $name;
$this->plan->createIndex[$name] = $index;
}
$different = true;
continue;
}
$tableIndexColumns = !empty($this->table->indexes[$name]->columns) ? $this->table->indexes[$name]->columns : [];
$oldTableIndexColumns = !empty($this->oldTable->indexes[$name]->columns) ? $this->oldTable->indexes[$name]->columns : [];
if (
count(
array_merge(
array_diff($tableIndexColumns, array_intersect($tableIndexColumns, $oldTableIndexColumns)),
array_diff($oldTableIndexColumns, array_intersect($tableIndexColumns, $oldTableIndexColumns))
)
)
) {
if ($this->showOnly) {
echo " - different index '$name' columns (";
echo 'DB: (' . implode(', ', $tableIndexColumns) . ') <> ';
echo 'MIG: (' . implode(', ', $oldTableIndexColumns) . "))\n";
} else {
$this->plan->dropIndex[] = $name;
$this->plan->createIndex[$name] = $index;
}
$different = true;
}
}
foreach ($this->oldTable->indexes as $name => $index) {
if (!isset($this->table->indexes[$name])) {
if ($this->showOnly) {
echo " - excessive index '$name'\n";
} else {
$this->plan->dropIndex[] = $name;
}
$different = true;
}
}
return $different;
} | php | protected function compareStructures(): bool
{
if (empty($this->_appliedChanges)) {
return true;
}
$different = false;
if ($this->showOnly) {
echo "SHOWING DIFFERENCES:\n";
}
foreach ($this->table->columns as $name => $column) {
if (!isset($this->oldTable->columns[$name])) {
if ($this->showOnly) {
echo " - missing column '$name'\n";
} else {
$this->plan->addColumn[$name] = $column;
}
$different = true;
continue;
}
foreach (['type', 'isNotNull', 'length', 'isUnique', 'isUnsigned', 'default', 'append', 'comment'] as $property) {
if ($this->generalSchema && $property === 'length') {
continue;
}
if (
!$this->generalSchema
&& $property === 'append'
&& $column->append === null
&& !$this->table->primaryKey->isComposite()
&& $column->isColumnInPK($this->table->primaryKey)
) {
$column->append = $column->prepareSchemaAppend(true, $column->autoIncrement);
}
if ($this->oldTable->columns[$name]->$property !== $column->$property) {
if ($this->showOnly) {
echo " - different '$name' column property: $property (";
echo 'DB: ' . $this->displayValue($column->$property) . ' <> ';
echo 'MIG: ' . $this->displayValue($this->oldTable->columns[$name]->$property) . ")\n";
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
echo " (!) ALTER COLUMN is not supported by SQLite: Migration must be created manually\n";
}
} elseif (!isset($this->plan->alterColumn[$name])) {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('ALTER COLUMN is not supported by SQLite.');
}
$this->plan->alterColumn[$name] = $column;
}
$different = true;
}
}
}
foreach ($this->oldTable->columns as $name => $column) {
if (!isset($this->table->columns[$name])) {
if ($this->showOnly) {
echo " - excessive column '$name'\n";
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
echo " (!) DROP COLUMN is not supported by SQLite: Migration must be created manually\n";
}
} else {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('DROP COLUMN is not supported by SQLite.');
}
$this->plan->dropColumn[] = $name;
}
$different = true;
}
}
foreach ($this->table->foreignKeys as $name => $foreignKey) {
if (!isset($this->oldTable->foreignKeys[$name])) {
if ($this->showOnly) {
echo " - missing foreign key '$name'\n";
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
echo " (!) ADD FOREIGN KEY is not supported by SQLite: Migration must be created manually\n";
}
} else {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('ADD FOREIGN KEY is not supported by SQLite.');
}
$this->plan->addForeignKey[$name] = $foreignKey;
}
$different = true;
continue;
}
$tableFKColumns = !empty($this->table->foreignKeys[$name]->columns) ? $this->table->foreignKeys[$name]->columns : [];
$oldTableFKColumns = !empty($this->oldTable->foreignKeys[$name]->columns) ? $this->oldTable->foreignKeys[$name]->columns : [];
if (
count(
array_merge(
array_diff($tableFKColumns, array_intersect($tableFKColumns, $oldTableFKColumns)),
array_diff($oldTableFKColumns, array_intersect($tableFKColumns, $oldTableFKColumns))
)
)
) {
if ($this->showOnly) {
echo " - different foreign key '$name' columns (";
echo 'DB: (' . implode(', ', $tableFKColumns) . ') <> ';
echo 'MIG: (' . implode(', ', $oldTableFKColumns) . "))\n";
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
echo " (!) DROP/ADD FOREIGN KEY is not supported by SQLite: Migration must be created manually\n";
}
} else {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('DROP/ADD FOREIGN KEY is not supported by SQLite.');
}
$this->plan->dropForeignKey[] = $name;
$this->plan->addForeignKey[$name] = $foreignKey;
}
$different = true;
continue;
}
$tableFKRefColumns = !empty($this->table->foreignKeys[$name]->refColumns) ? $this->table->foreignKeys[$name]->refColumns : [];
$oldTableFKRefColumns = !empty($this->oldTable->foreignKeys[$name]->refColumns) ? $this->oldTable->foreignKeys[$name]->refColumns : [];
if (
count(
array_merge(
array_diff($tableFKRefColumns, array_intersect($tableFKRefColumns, $oldTableFKRefColumns)),
array_diff($oldTableFKRefColumns, array_intersect($tableFKRefColumns, $oldTableFKRefColumns))
)
)
) {
if ($this->showOnly) {
echo " - different foreign key '$name' referral columns (";
echo 'DB: (' . implode(', ', $tableFKRefColumns) . ') <> ';
echo 'MIG: (' . implode(', ', $oldTableFKRefColumns) . "))\n";
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
echo " (!) DROP/ADD FOREIGN KEY is not supported by SQLite: Migration must be created manually\n";
}
} else {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('DROP/ADD FOREIGN KEY is not supported by SQLite.');
}
$this->plan->dropForeignKey[] = $name;
$this->plan->addForeignKey[$name] = $foreignKey;
}
$different = true;
}
}
foreach ($this->oldTable->foreignKeys as $name => $foreignKey) {
if (!isset($this->table->foreignKeys[$name])) {
if ($this->showOnly) {
echo " - excessive foreign key '$name'\n";
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
echo " (!) DROP FOREIGN KEY is not supported by SQLite: Migration must be created manually\n";
}
} else {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('DROP FOREIGN KEY is not supported by SQLite.');
}
$this->plan->dropForeignKey[] = $name;
}
$different = true;
}
}
$tablePKColumns = !empty($this->table->primaryKey->columns) ? $this->table->primaryKey->columns : [];
$oldTablePKColumns = !empty($this->oldTable->primaryKey->columns) ? $this->oldTable->primaryKey->columns : [];
$newKeys = array_merge(
array_diff($tablePKColumns, array_intersect($tablePKColumns, $oldTablePKColumns)),
array_diff($oldTablePKColumns, array_intersect($tablePKColumns, $oldTablePKColumns))
);
if (count($newKeys)) {
if ($this->showOnly) {
echo " - different primary key definition\n";
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
echo " (!) DROP/ADD PRIMARY KEY is not supported by SQLite: Migration must be created manually\n";
}
} else {
if (!empty($this->oldTable->primaryKey->columns)) {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('DROP PRIMARY KEY is not supported by SQLite.');
}
$this->plan->dropPrimaryKey = $this->oldTable->primaryKey->name ?: TablePrimaryKey::GENERIC_PRIMARY_KEY;
}
if (!empty($this->table->primaryKey->columns) && $this->confirmCompositePrimaryKey($newKeys)) {
if ($this->table->getSchema() === TableStructure::SCHEMA_SQLITE) {
throw new NotSupportedException('ADD PRIMARY KEY is not supported by SQLite.');
}
$this->plan->addPrimaryKey = $this->table->primaryKey;
}
}
$different = true;
}
foreach ($this->table->indexes as $name => $index) {
if (!isset($this->oldTable->indexes[$name])) {
if ($this->showOnly) {
echo " - missing index '$name'\n";
} else {
$this->plan->createIndex[$name] = $index;
}
$different = true;
continue;
}
if ($this->oldTable->indexes[$name]->unique !== $this->table->indexes[$name]->unique) {
if ($this->showOnly) {
echo " - different index '$name' definition (";
echo 'DB: unique ' . $this->displayValue($this->table->indexes[$name]->unique) . ' <> ';
echo 'MIG: unique ' . $this->displayValue($this->oldTable->indexes[$name]->unique) . ")\n";
} else {
$this->plan->dropIndex[] = $name;
$this->plan->createIndex[$name] = $index;
}
$different = true;
continue;
}
$tableIndexColumns = !empty($this->table->indexes[$name]->columns) ? $this->table->indexes[$name]->columns : [];
$oldTableIndexColumns = !empty($this->oldTable->indexes[$name]->columns) ? $this->oldTable->indexes[$name]->columns : [];
if (
count(
array_merge(
array_diff($tableIndexColumns, array_intersect($tableIndexColumns, $oldTableIndexColumns)),
array_diff($oldTableIndexColumns, array_intersect($tableIndexColumns, $oldTableIndexColumns))
)
)
) {
if ($this->showOnly) {
echo " - different index '$name' columns (";
echo 'DB: (' . implode(', ', $tableIndexColumns) . ') <> ';
echo 'MIG: (' . implode(', ', $oldTableIndexColumns) . "))\n";
} else {
$this->plan->dropIndex[] = $name;
$this->plan->createIndex[$name] = $index;
}
$different = true;
}
}
foreach ($this->oldTable->indexes as $name => $index) {
if (!isset($this->table->indexes[$name])) {
if ($this->showOnly) {
echo " - excessive index '$name'\n";
} else {
$this->plan->dropIndex[] = $name;
}
$different = true;
}
}
return $different;
} | [
"protected",
"function",
"compareStructures",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"_appliedChanges",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"different",
"=",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"sh... | Compares migration structure and database structure and gather required modifications.
@return bool whether modification is required or not
@throws NotSupportedException | [
"Compares",
"migration",
"structure",
"and",
"database",
"structure",
"and",
"gather",
"required",
"modifications",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Updater.php#L323-L612 |
bizley/yii2-migration | src/Updater.php | Updater.isUpdateRequired | public function isUpdateRequired(): bool
{
$history = $this->fetchHistory();
if (!empty($history)) {
$this->setDummyMigrationClass();
foreach ($history as $migration => $time) {
$migration = trim($migration, '\\');
if (in_array($migration, $this->skipMigrations, true)) {
continue;
}
if (!$this->gatherChanges($this->extract($migration))) {
break;
}
}
return $this->compareStructures();
}
return true;
} | php | public function isUpdateRequired(): bool
{
$history = $this->fetchHistory();
if (!empty($history)) {
$this->setDummyMigrationClass();
foreach ($history as $migration => $time) {
$migration = trim($migration, '\\');
if (in_array($migration, $this->skipMigrations, true)) {
continue;
}
if (!$this->gatherChanges($this->extract($migration))) {
break;
}
}
return $this->compareStructures();
}
return true;
} | [
"public",
"function",
"isUpdateRequired",
"(",
")",
":",
"bool",
"{",
"$",
"history",
"=",
"$",
"this",
"->",
"fetchHistory",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"history",
")",
")",
"{",
"$",
"this",
"->",
"setDummyMigrationClass",
"(",
... | Checks if new updating migration is required.
@return bool
@throws ErrorException
@throws NotSupportedException | [
"Checks",
"if",
"new",
"updating",
"migration",
"is",
"required",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Updater.php#L620-L642 |
bizley/yii2-migration | src/Updater.php | Updater.generateMigration | public function generateMigration(): string
{
if (empty($this->_modifications)) {
return parent::generateMigration();
}
return $this->view->renderFile(Yii::getAlias($this->templateFileUpdate), [
'className' => $this->className,
'table' => $this->table,
'plan' => $this->plan,
'namespace' => $this->normalizedNamespace
]);
} | php | public function generateMigration(): string
{
if (empty($this->_modifications)) {
return parent::generateMigration();
}
return $this->view->renderFile(Yii::getAlias($this->templateFileUpdate), [
'className' => $this->className,
'table' => $this->table,
'plan' => $this->plan,
'namespace' => $this->normalizedNamespace
]);
} | [
"public",
"function",
"generateMigration",
"(",
")",
":",
"string",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"_modifications",
")",
")",
"{",
"return",
"parent",
"::",
"generateMigration",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"view",
... | Generates migration content or echoes exception message.
@return string | [
"Generates",
"migration",
"content",
"or",
"echoes",
"exception",
"message",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Updater.php#L648-L660 |
bizley/yii2-migration | src/table/TableColumnFactory.php | TableColumnFactory.build | public static function build(array $configuration = []): ?TableColumn
{
if (!array_key_exists('type', $configuration)) {
throw new InvalidConfigException('Configuration for TableColumnFactory is missing "type" key.');
}
switch ($configuration['type']) {
case Schema::TYPE_PK:
return new TableColumnPK($configuration);
case Schema::TYPE_UPK:
return new TableColumnUPK($configuration);
case Schema::TYPE_BIGPK:
return new TableColumnBigPK($configuration);
case Schema::TYPE_UBIGPK:
return new TableColumnBigUPK($configuration);
case Schema::TYPE_CHAR:
return new TableColumnChar($configuration);
case Schema::TYPE_STRING:
return new TableColumnString($configuration);
case Schema::TYPE_TEXT:
return new TableColumnText($configuration);
case Schema::TYPE_TINYINT:
return new TableColumnTinyInt($configuration);
case Schema::TYPE_SMALLINT:
return new TableColumnSmallInt($configuration);
case Schema::TYPE_INTEGER:
return new TableColumnInt($configuration);
case Schema::TYPE_BIGINT:
return new TableColumnBigInt($configuration);
case Schema::TYPE_BINARY:
return new TableColumnBinary($configuration);
case Schema::TYPE_FLOAT:
return new TableColumnFloat($configuration);
case Schema::TYPE_DOUBLE:
return new TableColumnDouble($configuration);
case Schema::TYPE_DATETIME:
return new TableColumnDateTime($configuration);
case Schema::TYPE_TIMESTAMP:
return new TableColumnTimestamp($configuration);
case Schema::TYPE_TIME:
return new TableColumnTime($configuration);
case Schema::TYPE_DATE:
return new TableColumnDate($configuration);
case Schema::TYPE_DECIMAL:
return new TableColumnDecimal($configuration);
case Schema::TYPE_BOOLEAN:
return new TableColumnBoolean($configuration);
case Schema::TYPE_MONEY:
return new TableColumnMoney($configuration);
case Schema::TYPE_JSON:
return new TableColumnJson($configuration);
default:
throw new InvalidConfigException("Unsupported schema type '{$configuration['type']}' for TableColumnFactory.");
}
} | php | public static function build(array $configuration = []): ?TableColumn
{
if (!array_key_exists('type', $configuration)) {
throw new InvalidConfigException('Configuration for TableColumnFactory is missing "type" key.');
}
switch ($configuration['type']) {
case Schema::TYPE_PK:
return new TableColumnPK($configuration);
case Schema::TYPE_UPK:
return new TableColumnUPK($configuration);
case Schema::TYPE_BIGPK:
return new TableColumnBigPK($configuration);
case Schema::TYPE_UBIGPK:
return new TableColumnBigUPK($configuration);
case Schema::TYPE_CHAR:
return new TableColumnChar($configuration);
case Schema::TYPE_STRING:
return new TableColumnString($configuration);
case Schema::TYPE_TEXT:
return new TableColumnText($configuration);
case Schema::TYPE_TINYINT:
return new TableColumnTinyInt($configuration);
case Schema::TYPE_SMALLINT:
return new TableColumnSmallInt($configuration);
case Schema::TYPE_INTEGER:
return new TableColumnInt($configuration);
case Schema::TYPE_BIGINT:
return new TableColumnBigInt($configuration);
case Schema::TYPE_BINARY:
return new TableColumnBinary($configuration);
case Schema::TYPE_FLOAT:
return new TableColumnFloat($configuration);
case Schema::TYPE_DOUBLE:
return new TableColumnDouble($configuration);
case Schema::TYPE_DATETIME:
return new TableColumnDateTime($configuration);
case Schema::TYPE_TIMESTAMP:
return new TableColumnTimestamp($configuration);
case Schema::TYPE_TIME:
return new TableColumnTime($configuration);
case Schema::TYPE_DATE:
return new TableColumnDate($configuration);
case Schema::TYPE_DECIMAL:
return new TableColumnDecimal($configuration);
case Schema::TYPE_BOOLEAN:
return new TableColumnBoolean($configuration);
case Schema::TYPE_MONEY:
return new TableColumnMoney($configuration);
case Schema::TYPE_JSON:
return new TableColumnJson($configuration);
default:
throw new InvalidConfigException("Unsupported schema type '{$configuration['type']}' for TableColumnFactory.");
}
} | [
"public",
"static",
"function",
"build",
"(",
"array",
"$",
"configuration",
"=",
"[",
"]",
")",
":",
"?",
"TableColumn",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"'type'",
",",
"$",
"configuration",
")",
")",
"{",
"throw",
"new",
"InvalidConfigExcept... | Builds table column object based on the type.
@param array $configuration
@return TableColumn
@throws InvalidConfigException | [
"Builds",
"table",
"column",
"object",
"based",
"on",
"the",
"type",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/table/TableColumnFactory.php#L23-L99 |
bizley/yii2-migration | src/dummy/Migration.php | Migration.extractColumns | protected function extractColumns($columns)
{
$schema = [];
foreach ($columns as $name => $data) {
$schema[$name] = $this->extractColumn($data);
}
return $schema;
} | php | protected function extractColumns($columns)
{
$schema = [];
foreach ($columns as $name => $data) {
$schema[$name] = $this->extractColumn($data);
}
return $schema;
} | [
"protected",
"function",
"extractColumns",
"(",
"$",
"columns",
")",
"{",
"$",
"schema",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"name",
"=>",
"$",
"data",
")",
"{",
"$",
"schema",
"[",
"$",
"name",
"]",
"=",
"$",
"this",
"... | Returns extracted columns data.
@param array $columns
@return array | [
"Returns",
"extracted",
"columns",
"data",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/dummy/Migration.php#L92-L101 |
bizley/yii2-migration | src/dummy/Migration.php | Migration.fillTypeMapProperties | public function fillTypeMapProperties($type, $keyToDb, $dbToKey)
{
$schema = [];
if (!array_key_exists($type, $keyToDb)) {
$schema['type'] = $type;
return $schema;
}
$builder = $keyToDb[$type];
if (strpos($builder, 'NOT NULL') !== false) {
$schema['isNotNull'] = true;
$builder = trim(str_replace('NOT NULL', '', $builder));
}
if (strpos($builder, 'AUTO_INCREMENT') !== false) {
$schema['autoIncrement'] = true;
$builder = trim(str_replace('AUTO_INCREMENT', '', $builder));
}
if (strpos($builder, 'AUTOINCREMENT') !== false) {
$schema['autoIncrement'] = true;
$builder = trim(str_replace('AUTOINCREMENT', '', $builder));
}
if (strpos($builder, 'IDENTITY PRIMARY KEY') !== false) {
$schema['isPrimaryKey'] = true;
$builder = trim(str_replace('IDENTITY PRIMARY KEY', '', $builder));
}
if (strpos($builder, 'PRIMARY KEY') !== false) {
$schema['isPrimaryKey'] = true;
$builder = trim(str_replace('PRIMARY KEY', '', $builder));
}
if (strpos($builder, 'UNSIGNED') !== false) {
$schema['isUnsigned'] = true;
$builder = trim(str_replace('UNSIGNED', '', $builder));
}
preg_match('/^([a-zA-Z ]+)(\(([0-9,]+)\))?$/', $builder, $matches);
if (array_key_exists($matches[1], $dbToKey)) {
if (!empty($matches[3])) {
$schema['length'] = $matches[3];
}
$schema['type'] = $dbToKey[$matches[1]];
}
return $schema;
} | php | public function fillTypeMapProperties($type, $keyToDb, $dbToKey)
{
$schema = [];
if (!array_key_exists($type, $keyToDb)) {
$schema['type'] = $type;
return $schema;
}
$builder = $keyToDb[$type];
if (strpos($builder, 'NOT NULL') !== false) {
$schema['isNotNull'] = true;
$builder = trim(str_replace('NOT NULL', '', $builder));
}
if (strpos($builder, 'AUTO_INCREMENT') !== false) {
$schema['autoIncrement'] = true;
$builder = trim(str_replace('AUTO_INCREMENT', '', $builder));
}
if (strpos($builder, 'AUTOINCREMENT') !== false) {
$schema['autoIncrement'] = true;
$builder = trim(str_replace('AUTOINCREMENT', '', $builder));
}
if (strpos($builder, 'IDENTITY PRIMARY KEY') !== false) {
$schema['isPrimaryKey'] = true;
$builder = trim(str_replace('IDENTITY PRIMARY KEY', '', $builder));
}
if (strpos($builder, 'PRIMARY KEY') !== false) {
$schema['isPrimaryKey'] = true;
$builder = trim(str_replace('PRIMARY KEY', '', $builder));
}
if (strpos($builder, 'UNSIGNED') !== false) {
$schema['isUnsigned'] = true;
$builder = trim(str_replace('UNSIGNED', '', $builder));
}
preg_match('/^([a-zA-Z ]+)(\(([0-9,]+)\))?$/', $builder, $matches);
if (array_key_exists($matches[1], $dbToKey)) {
if (!empty($matches[3])) {
$schema['length'] = $matches[3];
}
$schema['type'] = $dbToKey[$matches[1]];
}
return $schema;
} | [
"public",
"function",
"fillTypeMapProperties",
"(",
"$",
"type",
",",
"$",
"keyToDb",
",",
"$",
"dbToKey",
")",
"{",
"$",
"schema",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"type",
",",
"$",
"keyToDb",
")",
")",
"{",
"$",
"... | Updates column properties based on schema type map.
@param string $type
@param array $keyToDb
@param array $dbToKey
@return array | [
"Updates",
"column",
"properties",
"based",
"on",
"schema",
"type",
"map",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/dummy/Migration.php#L110-L162 |
bizley/yii2-migration | src/dummy/Migration.php | Migration.extractColumn | protected function extractColumn($columnData)
{
if (!$columnData instanceof ColumnSchemaBuilder) {
throw new InvalidArgumentException('Column data must be provided as an instance of yii\db\ColumnSchemaBuilder.');
}
$reflectionClass = new ReflectionClass($columnData);
$reflectionProperty = $reflectionClass->getProperty('type');
$reflectionProperty->setAccessible(true);
$schema = $this->fillTypeMapProperties(
$reflectionProperty->getValue($columnData),
$this->db->schema->createQueryBuilder()->typeMap,
$this->db->schema->typeMap
);
foreach (['length', 'isNotNull', 'isUnique', 'check', 'default', 'append', 'isUnsigned'] as $property) {
$reflectionProperty = $reflectionClass->getProperty($property);
$reflectionProperty->setAccessible(true);
$value = $reflectionProperty->getValue($columnData);
if ($value !== null || !isset($schema[$property])) {
$schema[$property] = $value;
}
}
$schema['comment'] = empty($columnData->comment) ? '' : $columnData->comment;
return $schema;
} | php | protected function extractColumn($columnData)
{
if (!$columnData instanceof ColumnSchemaBuilder) {
throw new InvalidArgumentException('Column data must be provided as an instance of yii\db\ColumnSchemaBuilder.');
}
$reflectionClass = new ReflectionClass($columnData);
$reflectionProperty = $reflectionClass->getProperty('type');
$reflectionProperty->setAccessible(true);
$schema = $this->fillTypeMapProperties(
$reflectionProperty->getValue($columnData),
$this->db->schema->createQueryBuilder()->typeMap,
$this->db->schema->typeMap
);
foreach (['length', 'isNotNull', 'isUnique', 'check', 'default', 'append', 'isUnsigned'] as $property) {
$reflectionProperty = $reflectionClass->getProperty($property);
$reflectionProperty->setAccessible(true);
$value = $reflectionProperty->getValue($columnData);
if ($value !== null || !isset($schema[$property])) {
$schema[$property] = $value;
}
}
$schema['comment'] = empty($columnData->comment) ? '' : $columnData->comment;
return $schema;
} | [
"protected",
"function",
"extractColumn",
"(",
"$",
"columnData",
")",
"{",
"if",
"(",
"!",
"$",
"columnData",
"instanceof",
"ColumnSchemaBuilder",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Column data must be provided as an instance of yii\\db\\ColumnSch... | Returns extracted column data.
Since 3.3.0 InvalidArgumentException is thrown for non-ColumnSchemaBuilder $columnData.
@param ColumnSchemaBuilder $columnData
@return array
@throws ReflectionException
@throws InvalidArgumentException in case column data is not an instance of ColumnSchemaBuilder | [
"Returns",
"extracted",
"column",
"data",
".",
"Since",
"3",
".",
"3",
".",
"0",
"InvalidArgumentException",
"is",
"thrown",
"for",
"non",
"-",
"ColumnSchemaBuilder",
"$columnData",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/dummy/Migration.php#L172-L201 |
bizley/yii2-migration | src/dummy/Migration.php | Migration.addChange | public function addChange($table, $method, $data)
{
$table = $this->getRawTableName($table);
if (!isset($this->changes[$table])) {
$this->changes[$table] = [];
}
$this->changes[$table][] = new TableChange([
'schema' => TableStructure::identifySchema(get_class($this->db->schema)),
'table' => $table,
'method' => $method,
'data' => $data,
]);
} | php | public function addChange($table, $method, $data)
{
$table = $this->getRawTableName($table);
if (!isset($this->changes[$table])) {
$this->changes[$table] = [];
}
$this->changes[$table][] = new TableChange([
'schema' => TableStructure::identifySchema(get_class($this->db->schema)),
'table' => $table,
'method' => $method,
'data' => $data,
]);
} | [
"public",
"function",
"addChange",
"(",
"$",
"table",
",",
"$",
"method",
",",
"$",
"data",
")",
"{",
"$",
"table",
"=",
"$",
"this",
"->",
"getRawTableName",
"(",
"$",
"table",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"changes",
... | Adds method of structure change and its data
@param string $table
@param string $method
@param mixed $data | [
"Adds",
"method",
"of",
"structure",
"change",
"and",
"its",
"data"
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/dummy/Migration.php#L219-L233 |
bizley/yii2-migration | src/dummy/Migration.php | Migration.createTable | public function createTable($table, $columns, $options = null)
{
$this->addChange($table, 'createTable', $this->extractColumns($columns));
} | php | public function createTable($table, $columns, $options = null)
{
$this->addChange($table, 'createTable', $this->extractColumns($columns));
} | [
"public",
"function",
"createTable",
"(",
"$",
"table",
",",
"$",
"columns",
",",
"$",
"options",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"addChange",
"(",
"$",
"table",
",",
"'createTable'",
",",
"$",
"this",
"->",
"extractColumns",
"(",
"$",
"colum... | {@inheritdoc} | [
"{"
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/dummy/Migration.php#L278-L281 |
bizley/yii2-migration | src/dummy/Migration.php | Migration.addColumn | public function addColumn($table, $column, $type)
{
$this->addChange($table, 'addColumn', [$column, $this->extractColumn($type)]);
} | php | public function addColumn($table, $column, $type)
{
$this->addChange($table, 'addColumn', [$column, $this->extractColumn($type)]);
} | [
"public",
"function",
"addColumn",
"(",
"$",
"table",
",",
"$",
"column",
",",
"$",
"type",
")",
"{",
"$",
"this",
"->",
"addChange",
"(",
"$",
"table",
",",
"'addColumn'",
",",
"[",
"$",
"column",
",",
"$",
"this",
"->",
"extractColumn",
"(",
"$",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/dummy/Migration.php#L310-L313 |
bizley/yii2-migration | src/dummy/Migration.php | Migration.alterColumn | public function alterColumn($table, $column, $type)
{
$this->addChange($table, 'alterColumn', [$column, $this->extractColumn($type)]);
} | php | public function alterColumn($table, $column, $type)
{
$this->addChange($table, 'alterColumn', [$column, $this->extractColumn($type)]);
} | [
"public",
"function",
"alterColumn",
"(",
"$",
"table",
",",
"$",
"column",
",",
"$",
"type",
")",
"{",
"$",
"this",
"->",
"addChange",
"(",
"$",
"table",
",",
"'alterColumn'",
",",
"[",
"$",
"column",
",",
"$",
"this",
"->",
"extractColumn",
"(",
"$... | {@inheritdoc} | [
"{"
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/dummy/Migration.php#L334-L337 |
bizley/yii2-migration | src/dummy/Migration.php | Migration.addPrimaryKey | public function addPrimaryKey($name, $table, $columns)
{
$this->addChange(
$table,
'addPrimaryKey',
[
$name,
is_array($columns) ? $columns : preg_split('/\s*,\s*/', $columns)
]
);
} | php | public function addPrimaryKey($name, $table, $columns)
{
$this->addChange(
$table,
'addPrimaryKey',
[
$name,
is_array($columns) ? $columns : preg_split('/\s*,\s*/', $columns)
]
);
} | [
"public",
"function",
"addPrimaryKey",
"(",
"$",
"name",
",",
"$",
"table",
",",
"$",
"columns",
")",
"{",
"$",
"this",
"->",
"addChange",
"(",
"$",
"table",
",",
"'addPrimaryKey'",
",",
"[",
"$",
"name",
",",
"is_array",
"(",
"$",
"columns",
")",
"?... | {@inheritdoc} | [
"{"
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/dummy/Migration.php#L342-L352 |
bizley/yii2-migration | src/dummy/Migration.php | Migration.addForeignKey | public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
{
$this->addChange($table, 'addForeignKey', [
$name,
is_array($columns) ? $columns : preg_split('/\s*,\s*/', $columns),
$refTable,
is_array($refColumns) ? $refColumns : preg_split('/\s*,\s*/', $refColumns),
$delete,
$update
]);
} | php | public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
{
$this->addChange($table, 'addForeignKey', [
$name,
is_array($columns) ? $columns : preg_split('/\s*,\s*/', $columns),
$refTable,
is_array($refColumns) ? $refColumns : preg_split('/\s*,\s*/', $refColumns),
$delete,
$update
]);
} | [
"public",
"function",
"addForeignKey",
"(",
"$",
"name",
",",
"$",
"table",
",",
"$",
"columns",
",",
"$",
"refTable",
",",
"$",
"refColumns",
",",
"$",
"delete",
"=",
"null",
",",
"$",
"update",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"addChange",... | {@inheritdoc} | [
"{"
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/dummy/Migration.php#L365-L375 |
bizley/yii2-migration | src/dummy/Migration.php | Migration.createIndex | public function createIndex($name, $table, $columns, $unique = false)
{
$this->addChange(
$table,
'createIndex',
[
$name,
is_array($columns) ? $columns : preg_split('/\s*,\s*/', $columns),
$unique
]
);
} | php | public function createIndex($name, $table, $columns, $unique = false)
{
$this->addChange(
$table,
'createIndex',
[
$name,
is_array($columns) ? $columns : preg_split('/\s*,\s*/', $columns),
$unique
]
);
} | [
"public",
"function",
"createIndex",
"(",
"$",
"name",
",",
"$",
"table",
",",
"$",
"columns",
",",
"$",
"unique",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"addChange",
"(",
"$",
"table",
",",
"'createIndex'",
",",
"[",
"$",
"name",
",",
"is_array"... | {@inheritdoc} | [
"{"
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/dummy/Migration.php#L388-L399 |
bizley/yii2-migration | src/Generator.php | Generator.getTableSchema | public function getTableSchema(): ?TableSchema
{
if ($this->_tableSchema === null) {
$this->_tableSchema = $this->db->getTableSchema($this->tableName);
}
return $this->_tableSchema;
} | php | public function getTableSchema(): ?TableSchema
{
if ($this->_tableSchema === null) {
$this->_tableSchema = $this->db->getTableSchema($this->tableName);
}
return $this->_tableSchema;
} | [
"public",
"function",
"getTableSchema",
"(",
")",
":",
"?",
"TableSchema",
"{",
"if",
"(",
"$",
"this",
"->",
"_tableSchema",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"_tableSchema",
"=",
"$",
"this",
"->",
"db",
"->",
"getTableSchema",
"(",
"$",
"t... | Returns table schema.
@return TableSchema|null | [
"Returns",
"table",
"schema",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Generator.php#L114-L121 |
bizley/yii2-migration | src/Generator.php | Generator.getTablePrimaryKey | protected function getTablePrimaryKey(): TablePrimaryKey
{
$data = [];
/* @var $constraint Constraint */
$constraint = $this->db->schema->getTablePrimaryKey($this->tableName, true);
if ($constraint) {
$data = [
'columns' => $constraint->columnNames,
'name' => $constraint->name,
];
} elseif ($this->db->schema instanceof Schema) {
// SQLite bug-case fixed in Yii 2.0.16 https://github.com/yiisoft/yii2/issues/16897
if ($this->tableSchema !== null && $this->tableSchema->primaryKey) {
$data = [
'columns' => $this->tableSchema->primaryKey,
];
}
}
return new TablePrimaryKey($data);
} | php | protected function getTablePrimaryKey(): TablePrimaryKey
{
$data = [];
/* @var $constraint Constraint */
$constraint = $this->db->schema->getTablePrimaryKey($this->tableName, true);
if ($constraint) {
$data = [
'columns' => $constraint->columnNames,
'name' => $constraint->name,
];
} elseif ($this->db->schema instanceof Schema) {
// SQLite bug-case fixed in Yii 2.0.16 https://github.com/yiisoft/yii2/issues/16897
if ($this->tableSchema !== null && $this->tableSchema->primaryKey) {
$data = [
'columns' => $this->tableSchema->primaryKey,
];
}
}
return new TablePrimaryKey($data);
} | [
"protected",
"function",
"getTablePrimaryKey",
"(",
")",
":",
"TablePrimaryKey",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"/* @var $constraint Constraint */",
"$",
"constraint",
"=",
"$",
"this",
"->",
"db",
"->",
"schema",
"->",
"getTablePrimaryKey",
"(",
"$",
"... | Returns table primary key.
@return TablePrimaryKey | [
"Returns",
"table",
"primary",
"key",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Generator.php#L127-L149 |
bizley/yii2-migration | src/Generator.php | Generator.getTableColumns | protected function getTableColumns(array $indexes = [], ?string $schema = null): array
{
$columns = [];
if ($this->tableSchema instanceof TableSchema) {
$indexData = !empty($indexes) ? $indexes : $this->getTableIndexes();
foreach ($this->tableSchema->columns as $column) {
$isUnique = false;
foreach ($indexData as $index) {
if ($index->unique && $index->columns[0] === $column->name && count($index->columns) === 1) {
$isUnique = true;
break;
}
}
$columns[$column->name] = TableColumnFactory::build([
'schema' => $schema,
'name' => $column->name,
'type' => $column->type,
'size' => $column->size,
'precision' => $column->precision,
'scale' => $column->scale,
'isNotNull' => $column->allowNull ? null : true,
'isUnique' => $isUnique,
'check' => null,
'default' => $column->defaultValue,
'isPrimaryKey' => $column->isPrimaryKey,
'autoIncrement' => $column->autoIncrement,
'isUnsigned' => $column->unsigned,
'comment' => $column->comment ?: null,
]);
}
}
return $columns;
} | php | protected function getTableColumns(array $indexes = [], ?string $schema = null): array
{
$columns = [];
if ($this->tableSchema instanceof TableSchema) {
$indexData = !empty($indexes) ? $indexes : $this->getTableIndexes();
foreach ($this->tableSchema->columns as $column) {
$isUnique = false;
foreach ($indexData as $index) {
if ($index->unique && $index->columns[0] === $column->name && count($index->columns) === 1) {
$isUnique = true;
break;
}
}
$columns[$column->name] = TableColumnFactory::build([
'schema' => $schema,
'name' => $column->name,
'type' => $column->type,
'size' => $column->size,
'precision' => $column->precision,
'scale' => $column->scale,
'isNotNull' => $column->allowNull ? null : true,
'isUnique' => $isUnique,
'check' => null,
'default' => $column->defaultValue,
'isPrimaryKey' => $column->isPrimaryKey,
'autoIncrement' => $column->autoIncrement,
'isUnsigned' => $column->unsigned,
'comment' => $column->comment ?: null,
]);
}
}
return $columns;
} | [
"protected",
"function",
"getTableColumns",
"(",
"array",
"$",
"indexes",
"=",
"[",
"]",
",",
"?",
"string",
"$",
"schema",
"=",
"null",
")",
":",
"array",
"{",
"$",
"columns",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"tableSchema",
"instanc... | Returns columns structure.
@param TableIndex[] $indexes
@param string $schema
@return TableColumn[]
@throws InvalidConfigException | [
"Returns",
"columns",
"structure",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Generator.php#L158-L196 |
bizley/yii2-migration | src/Generator.php | Generator.getTableForeignKeys | protected function getTableForeignKeys(): array
{
$data = [];
$fks = $this->db->schema->getTableForeignKeys($this->tableName, true);
/* @var $fk ForeignKeyConstraint */
foreach ($fks as $fk) {
$data[$fk->name] = new TableForeignKey([
'name' => $fk->name,
'columns' => $fk->columnNames,
'refTable' => $fk->foreignTableName,
'refColumns' => $fk->foreignColumnNames,
'onDelete' => $fk->onDelete,
'onUpdate' => $fk->onUpdate,
]);
}
return $data;
} | php | protected function getTableForeignKeys(): array
{
$data = [];
$fks = $this->db->schema->getTableForeignKeys($this->tableName, true);
/* @var $fk ForeignKeyConstraint */
foreach ($fks as $fk) {
$data[$fk->name] = new TableForeignKey([
'name' => $fk->name,
'columns' => $fk->columnNames,
'refTable' => $fk->foreignTableName,
'refColumns' => $fk->foreignColumnNames,
'onDelete' => $fk->onDelete,
'onUpdate' => $fk->onUpdate,
]);
}
return $data;
} | [
"protected",
"function",
"getTableForeignKeys",
"(",
")",
":",
"array",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"$",
"fks",
"=",
"$",
"this",
"->",
"db",
"->",
"schema",
"->",
"getTableForeignKeys",
"(",
"$",
"this",
"->",
"tableName",
",",
"true",
")",
... | Returns foreign keys structure.
@return TableForeignKey[] | [
"Returns",
"foreign",
"keys",
"structure",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Generator.php#L202-L221 |
bizley/yii2-migration | src/Generator.php | Generator.getTableIndexes | protected function getTableIndexes(): array
{
$data = [];
$idxs = $this->db->schema->getTableIndexes($this->tableName, true);
/* @var $idx IndexConstraint */
foreach ($idxs as $idx) {
if (!$idx->isPrimary) {
$data[$idx->name] = new TableIndex([
'name' => $idx->name,
'unique' => $idx->isUnique,
'columns' => $idx->columnNames
]);
}
}
return $data;
} | php | protected function getTableIndexes(): array
{
$data = [];
$idxs = $this->db->schema->getTableIndexes($this->tableName, true);
/* @var $idx IndexConstraint */
foreach ($idxs as $idx) {
if (!$idx->isPrimary) {
$data[$idx->name] = new TableIndex([
'name' => $idx->name,
'unique' => $idx->isUnique,
'columns' => $idx->columnNames
]);
}
}
return $data;
} | [
"protected",
"function",
"getTableIndexes",
"(",
")",
":",
"array",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"$",
"idxs",
"=",
"$",
"this",
"->",
"db",
"->",
"schema",
"->",
"getTableIndexes",
"(",
"$",
"this",
"->",
"tableName",
",",
"true",
")",
";",
... | Returns table indexes.
@return TableIndex[]
@since 2.2.2 | [
"Returns",
"table",
"indexes",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Generator.php#L228-L246 |
bizley/yii2-migration | src/Generator.php | Generator.getTable | public function getTable(): TableStructure
{
if ($this->_table === null) {
$indexes = $this->getTableIndexes();
$this->_table = new TableStructure([
'name' => $this->tableName,
'schema' => get_class($this->db->schema),
'generalSchema' => $this->generalSchema,
'usePrefix' => $this->useTablePrefix,
'dbPrefix' => $this->db->tablePrefix,
'primaryKey' => $this->getTablePrimaryKey(),
'foreignKeys' => $this->getTableForeignKeys(),
'indexes' => $indexes,
'tableOptionsInit' => $this->tableOptionsInit,
'tableOptions' => $this->tableOptions,
]);
$this->_table->columns = $this->getTableColumns($indexes, $this->_table->schema);
}
return $this->_table;
} | php | public function getTable(): TableStructure
{
if ($this->_table === null) {
$indexes = $this->getTableIndexes();
$this->_table = new TableStructure([
'name' => $this->tableName,
'schema' => get_class($this->db->schema),
'generalSchema' => $this->generalSchema,
'usePrefix' => $this->useTablePrefix,
'dbPrefix' => $this->db->tablePrefix,
'primaryKey' => $this->getTablePrimaryKey(),
'foreignKeys' => $this->getTableForeignKeys(),
'indexes' => $indexes,
'tableOptionsInit' => $this->tableOptionsInit,
'tableOptions' => $this->tableOptions,
]);
$this->_table->columns = $this->getTableColumns($indexes, $this->_table->schema);
}
return $this->_table;
} | [
"public",
"function",
"getTable",
"(",
")",
":",
"TableStructure",
"{",
"if",
"(",
"$",
"this",
"->",
"_table",
"===",
"null",
")",
"{",
"$",
"indexes",
"=",
"$",
"this",
"->",
"getTableIndexes",
"(",
")",
";",
"$",
"this",
"->",
"_table",
"=",
"new"... | Returns table data
@return TableStructure
@throws InvalidConfigException | [
"Returns",
"table",
"data"
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Generator.php#L255-L277 |
bizley/yii2-migration | src/Generator.php | Generator.generateMigration | public function generateMigration(): string
{
return $this->view->renderFile(Yii::getAlias($this->templateFile), [
'table' => $this->table,
'className' => $this->className,
'namespace' => $this->normalizedNamespace
]);
} | php | public function generateMigration(): string
{
return $this->view->renderFile(Yii::getAlias($this->templateFile), [
'table' => $this->table,
'className' => $this->className,
'namespace' => $this->normalizedNamespace
]);
} | [
"public",
"function",
"generateMigration",
"(",
")",
":",
"string",
"{",
"return",
"$",
"this",
"->",
"view",
"->",
"renderFile",
"(",
"Yii",
"::",
"getAlias",
"(",
"$",
"this",
"->",
"templateFile",
")",
",",
"[",
"'table'",
"=>",
"$",
"this",
"->",
"... | Generates migration content or echoes exception message.
@return string | [
"Generates",
"migration",
"content",
"or",
"echoes",
"exception",
"message",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/Generator.php#L292-L299 |
bizley/yii2-migration | src/controllers/MigrationController.php | MigrationController.options | public function options($actionID) // BC declaration
{
$defaultOptions = array_merge(parent::options($actionID), ['db']);
$createOptions = [
'migrationPath',
'migrationNamespace',
'generalSchema',
'templateFile',
'useTablePrefix',
'fixHistory',
'migrationTable',
'tableOptionsInit',
'tableOptions',
];
$updateOptions = [
'showOnly',
'templateFileUpdate',
'skipMigrations'
];
switch ($actionID) {
case 'create':
$options = array_merge($defaultOptions, $createOptions);
break;
case 'create-all':
$options = array_merge(
$defaultOptions,
$createOptions,
['excludeTables']
);
break;
case 'update':
$options = array_merge(
$defaultOptions,
$createOptions,
$updateOptions
);
break;
case 'update-all':
$options = array_merge(
$defaultOptions,
$createOptions,
$updateOptions,
['excludeTables']
);
break;
default:
$options = $defaultOptions;
}
return $options;
} | php | public function options($actionID) // BC declaration
{
$defaultOptions = array_merge(parent::options($actionID), ['db']);
$createOptions = [
'migrationPath',
'migrationNamespace',
'generalSchema',
'templateFile',
'useTablePrefix',
'fixHistory',
'migrationTable',
'tableOptionsInit',
'tableOptions',
];
$updateOptions = [
'showOnly',
'templateFileUpdate',
'skipMigrations'
];
switch ($actionID) {
case 'create':
$options = array_merge($defaultOptions, $createOptions);
break;
case 'create-all':
$options = array_merge(
$defaultOptions,
$createOptions,
['excludeTables']
);
break;
case 'update':
$options = array_merge(
$defaultOptions,
$createOptions,
$updateOptions
);
break;
case 'update-all':
$options = array_merge(
$defaultOptions,
$createOptions,
$updateOptions,
['excludeTables']
);
break;
default:
$options = $defaultOptions;
}
return $options;
} | [
"public",
"function",
"options",
"(",
"$",
"actionID",
")",
"// BC declaration",
"{",
"$",
"defaultOptions",
"=",
"array_merge",
"(",
"parent",
"::",
"options",
"(",
"$",
"actionID",
")",
",",
"[",
"'db'",
"]",
")",
";",
"$",
"createOptions",
"=",
"[",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/controllers/MigrationController.php#L167-L223 |
bizley/yii2-migration | src/controllers/MigrationController.php | MigrationController.init | public function init(): void
{
parent::init();
foreach (['useTablePrefix', 'showOnly', 'generalSchema', 'fixHistory'] as $property) {
if ($this->$property !== true) {
if ($this->$property === 'true' || $this->$property === 1) {
$this->$property = true;
}
$this->$property = (bool)$this->$property;
}
}
} | php | public function init(): void
{
parent::init();
foreach (['useTablePrefix', 'showOnly', 'generalSchema', 'fixHistory'] as $property) {
if ($this->$property !== true) {
if ($this->$property === 'true' || $this->$property === 1) {
$this->$property = true;
}
$this->$property = (bool)$this->$property;
}
}
} | [
"public",
"function",
"init",
"(",
")",
":",
"void",
"{",
"parent",
"::",
"init",
"(",
")",
";",
"foreach",
"(",
"[",
"'useTablePrefix'",
",",
"'showOnly'",
",",
"'generalSchema'",
",",
"'fixHistory'",
"]",
"as",
"$",
"property",
")",
"{",
"if",
"(",
"... | Makes sure boolean properties are boolean. | [
"Makes",
"sure",
"boolean",
"properties",
"are",
"boolean",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/controllers/MigrationController.php#L249-L262 |
bizley/yii2-migration | src/controllers/MigrationController.php | MigrationController.beforeAction | public function beforeAction($action): bool // BC declaration
{
if (!parent::beforeAction($action)) {
return false;
}
if (!$this->showOnly && in_array($action->id, ['create', 'create-all', 'update', 'update-all'], true)) {
if ($this->migrationPath !== null) {
$this->migrationPath = $this->preparePathDirectory($this->migrationPath);
}
if ($this->migrationNamespace !== null) {
$this->migrationNamespace = FileHelper::normalizePath($this->migrationNamespace, '\\');
$this->workingPath = $this->preparePathDirectory(FileHelper::normalizePath('@' . $this->migrationNamespace, '/'));
} else {
$this->workingPath = $this->migrationPath;
}
}
$this->db = Instance::ensure($this->db, Connection::class);
$this->stdout("Yii 2 Migration Generator Tool v{$this->version}\n\n", Console::FG_CYAN);
return true;
} | php | public function beforeAction($action): bool // BC declaration
{
if (!parent::beforeAction($action)) {
return false;
}
if (!$this->showOnly && in_array($action->id, ['create', 'create-all', 'update', 'update-all'], true)) {
if ($this->migrationPath !== null) {
$this->migrationPath = $this->preparePathDirectory($this->migrationPath);
}
if ($this->migrationNamespace !== null) {
$this->migrationNamespace = FileHelper::normalizePath($this->migrationNamespace, '\\');
$this->workingPath = $this->preparePathDirectory(FileHelper::normalizePath('@' . $this->migrationNamespace, '/'));
} else {
$this->workingPath = $this->migrationPath;
}
}
$this->db = Instance::ensure($this->db, Connection::class);
$this->stdout("Yii 2 Migration Generator Tool v{$this->version}\n\n", Console::FG_CYAN);
return true;
} | [
"public",
"function",
"beforeAction",
"(",
"$",
"action",
")",
":",
"bool",
"// BC declaration",
"{",
"if",
"(",
"!",
"parent",
"::",
"beforeAction",
"(",
"$",
"action",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"... | This method is invoked right before an action is to be executed (after all possible filters).
It checks the existence of the migrationPath and makes sure DB connection is prepared.
@param Action $action the action to be executed.
@return bool whether the action should continue to be executed.
@throws InvalidConfigException
@throws Exception | [
"This",
"method",
"is",
"invoked",
"right",
"before",
"an",
"action",
"is",
"to",
"be",
"executed",
"(",
"after",
"all",
"possible",
"filters",
")",
".",
"It",
"checks",
"the",
"existence",
"of",
"the",
"migrationPath",
"and",
"makes",
"sure",
"DB",
"conne... | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/controllers/MigrationController.php#L274-L297 |
bizley/yii2-migration | src/controllers/MigrationController.php | MigrationController.preparePathDirectory | public function preparePathDirectory(string $path): string
{
$translatedPath = Yii::getAlias($path);
if (!is_dir($translatedPath)) {
FileHelper::createDirectory($translatedPath);
}
return $translatedPath;
} | php | public function preparePathDirectory(string $path): string
{
$translatedPath = Yii::getAlias($path);
if (!is_dir($translatedPath)) {
FileHelper::createDirectory($translatedPath);
}
return $translatedPath;
} | [
"public",
"function",
"preparePathDirectory",
"(",
"string",
"$",
"path",
")",
":",
"string",
"{",
"$",
"translatedPath",
"=",
"Yii",
"::",
"getAlias",
"(",
"$",
"path",
")",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"translatedPath",
")",
")",
"{",
"Fi... | Prepares path directory.
@param string $path
@return string
@throws Exception
@since 1.1 | [
"Prepares",
"path",
"directory",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/controllers/MigrationController.php#L306-L315 |
bizley/yii2-migration | src/controllers/MigrationController.php | MigrationController.addMigrationHistory | protected function addMigrationHistory(string $version, ?string $namespace = null): void
{
$this->stdout(' > Adding migration history entry ...', Console::FG_YELLOW);
$this->db->createCommand()->insert(
$this->migrationTable,
[
'version' => ($namespace ? $namespace . '\\' : '') . $version,
'apply_time' => time(),
]
)->execute();
$this->stdout("DONE.\n", Console::FG_GREEN);
} | php | protected function addMigrationHistory(string $version, ?string $namespace = null): void
{
$this->stdout(' > Adding migration history entry ...', Console::FG_YELLOW);
$this->db->createCommand()->insert(
$this->migrationTable,
[
'version' => ($namespace ? $namespace . '\\' : '') . $version,
'apply_time' => time(),
]
)->execute();
$this->stdout("DONE.\n", Console::FG_GREEN);
} | [
"protected",
"function",
"addMigrationHistory",
"(",
"string",
"$",
"version",
",",
"?",
"string",
"$",
"namespace",
"=",
"null",
")",
":",
"void",
"{",
"$",
"this",
"->",
"stdout",
"(",
"' > Adding migration history entry ...'",
",",
"Console",
"::",
"FG_YELLOW... | Adds migration history entry.
@param string $version
@param string|null $namespace
@throws DbException
@since 2.0 | [
"Adds",
"migration",
"history",
"entry",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/controllers/MigrationController.php#L352-L365 |
bizley/yii2-migration | src/controllers/MigrationController.php | MigrationController.actionList | public function actionList(): int
{
$tables = $this->db->schema->getTableNames();
if (!$tables) {
$this->stdout(" > Your database does not contain any tables yet.\n");
} else {
$this->stdout(' > Your database contains ' . count($tables) . " tables:\n");
foreach ($tables as $table) {
$this->stdout(" - $table\n");
}
}
$this->stdout("\n > Run\n", Console::FG_GREEN);
$tab = $this->ansiFormat('<table>', Console::FG_YELLOW);
$cmd = $this->ansiFormat('migration/create', Console::FG_CYAN);
$this->stdout(" $cmd $tab\n");
$this->stdout(" to generate creating migration for the specific table.\n", Console::FG_GREEN);
$cmd = $this->ansiFormat('migration/create-all', Console::FG_CYAN);
$this->stdout(" $cmd\n");
$this->stdout(" to generate creating migrations for all the tables.\n", Console::FG_GREEN);
$cmd = $this->ansiFormat('migration/update', Console::FG_CYAN);
$this->stdout(" $cmd $tab\n");
$this->stdout(" to generate updating migration for the specific table.\n", Console::FG_GREEN);
$cmd = $this->ansiFormat('migration/update-all', Console::FG_CYAN);
$this->stdout(" $cmd\n");
$this->stdout(" to generate updating migrations for all the tables.\n", Console::FG_GREEN);
return ExitCode::OK;
} | php | public function actionList(): int
{
$tables = $this->db->schema->getTableNames();
if (!$tables) {
$this->stdout(" > Your database does not contain any tables yet.\n");
} else {
$this->stdout(' > Your database contains ' . count($tables) . " tables:\n");
foreach ($tables as $table) {
$this->stdout(" - $table\n");
}
}
$this->stdout("\n > Run\n", Console::FG_GREEN);
$tab = $this->ansiFormat('<table>', Console::FG_YELLOW);
$cmd = $this->ansiFormat('migration/create', Console::FG_CYAN);
$this->stdout(" $cmd $tab\n");
$this->stdout(" to generate creating migration for the specific table.\n", Console::FG_GREEN);
$cmd = $this->ansiFormat('migration/create-all', Console::FG_CYAN);
$this->stdout(" $cmd\n");
$this->stdout(" to generate creating migrations for all the tables.\n", Console::FG_GREEN);
$cmd = $this->ansiFormat('migration/update', Console::FG_CYAN);
$this->stdout(" $cmd $tab\n");
$this->stdout(" to generate updating migration for the specific table.\n", Console::FG_GREEN);
$cmd = $this->ansiFormat('migration/update-all', Console::FG_CYAN);
$this->stdout(" $cmd\n");
$this->stdout(" to generate updating migrations for all the tables.\n", Console::FG_GREEN);
return ExitCode::OK;
} | [
"public",
"function",
"actionList",
"(",
")",
":",
"int",
"{",
"$",
"tables",
"=",
"$",
"this",
"->",
"db",
"->",
"schema",
"->",
"getTableNames",
"(",
")",
";",
"if",
"(",
"!",
"$",
"tables",
")",
"{",
"$",
"this",
"->",
"stdout",
"(",
"\" > Your ... | Lists all tables in the database.
@return int
@since 2.1 | [
"Lists",
"all",
"tables",
"in",
"the",
"database",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/controllers/MigrationController.php#L372-L410 |
bizley/yii2-migration | src/controllers/MigrationController.php | MigrationController.actionCreate | public function actionCreate(string $table): int
{
$tables = [$table];
if (strpos($table, ',') !== false) {
$tables = explode(',', $table);
}
$migrationsGenerated = 0;
foreach ($tables as $name) {
$this->stdout(" > Generating create migration for table '{$name}' ...", Console::FG_YELLOW);
$className = 'm' . gmdate('ymd_His') . '_create_table_' . $name;
$file = Yii::getAlias($this->workingPath . DIRECTORY_SEPARATOR . $className . '.php');
$generator = new Generator([
'db' => $this->db,
'view' => $this->view,
'useTablePrefix' => $this->useTablePrefix,
'templateFile' => $this->templateFile,
'tableName' => $name,
'className' => $className,
'namespace' => $this->migrationNamespace,
'generalSchema' => $this->generalSchema,
'tableOptionsInit' => $this->tableOptionsInit,
'tableOptions' => $this->tableOptions,
]);
if ($generator->tableSchema === null) {
$this->stdout("ERROR!\n > Table '{$name}' does not exist!\n\n", Console::FG_RED);
return ExitCode::DATAERR;
}
if ($this->generateFile($file, $generator->generateMigration()) === false) {
$this->stdout("ERROR!\n > Migration file for table '{$name}' can not be generated!\n\n", Console::FG_RED);
return ExitCode::SOFTWARE;
}
$migrationsGenerated++;
$this->stdout("DONE!\n", Console::FG_GREEN);
$this->stdout(" > Saved as '{$file}'\n");
if ($this->fixHistory) {
if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
$this->createMigrationHistoryTable();
}
$this->addMigrationHistory($className, $this->migrationNamespace);
}
$this->stdout("\n");
}
if ($migrationsGenerated) {
$this->stdout(" Generated $migrationsGenerated file(s).\n", Console::FG_YELLOW);
$this->stdout(" (!) Remember to verify files before applying migration.\n\n", Console::FG_YELLOW);
} else {
$this->stdout(" No files generated.\n\n", Console::FG_YELLOW);
}
return ExitCode::OK;
} | php | public function actionCreate(string $table): int
{
$tables = [$table];
if (strpos($table, ',') !== false) {
$tables = explode(',', $table);
}
$migrationsGenerated = 0;
foreach ($tables as $name) {
$this->stdout(" > Generating create migration for table '{$name}' ...", Console::FG_YELLOW);
$className = 'm' . gmdate('ymd_His') . '_create_table_' . $name;
$file = Yii::getAlias($this->workingPath . DIRECTORY_SEPARATOR . $className . '.php');
$generator = new Generator([
'db' => $this->db,
'view' => $this->view,
'useTablePrefix' => $this->useTablePrefix,
'templateFile' => $this->templateFile,
'tableName' => $name,
'className' => $className,
'namespace' => $this->migrationNamespace,
'generalSchema' => $this->generalSchema,
'tableOptionsInit' => $this->tableOptionsInit,
'tableOptions' => $this->tableOptions,
]);
if ($generator->tableSchema === null) {
$this->stdout("ERROR!\n > Table '{$name}' does not exist!\n\n", Console::FG_RED);
return ExitCode::DATAERR;
}
if ($this->generateFile($file, $generator->generateMigration()) === false) {
$this->stdout("ERROR!\n > Migration file for table '{$name}' can not be generated!\n\n", Console::FG_RED);
return ExitCode::SOFTWARE;
}
$migrationsGenerated++;
$this->stdout("DONE!\n", Console::FG_GREEN);
$this->stdout(" > Saved as '{$file}'\n");
if ($this->fixHistory) {
if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
$this->createMigrationHistoryTable();
}
$this->addMigrationHistory($className, $this->migrationNamespace);
}
$this->stdout("\n");
}
if ($migrationsGenerated) {
$this->stdout(" Generated $migrationsGenerated file(s).\n", Console::FG_YELLOW);
$this->stdout(" (!) Remember to verify files before applying migration.\n\n", Console::FG_YELLOW);
} else {
$this->stdout(" No files generated.\n\n", Console::FG_YELLOW);
}
return ExitCode::OK;
} | [
"public",
"function",
"actionCreate",
"(",
"string",
"$",
"table",
")",
":",
"int",
"{",
"$",
"tables",
"=",
"[",
"$",
"table",
"]",
";",
"if",
"(",
"strpos",
"(",
"$",
"table",
",",
"','",
")",
"!==",
"false",
")",
"{",
"$",
"tables",
"=",
"expl... | Creates new migration for the given tables.
@param string $table Table names separated by commas.
@return int
@throws DbException | [
"Creates",
"new",
"migration",
"for",
"the",
"given",
"tables",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/controllers/MigrationController.php#L429-L492 |
bizley/yii2-migration | src/controllers/MigrationController.php | MigrationController.actionCreateAll | public function actionCreateAll(): int
{
$tables = $this->removeExcludedTables($this->db->schema->getTableNames());
if (!$tables) {
$this->stdout(' > Your database does not contain any tables yet.', Console::FG_YELLOW);
return ExitCode::OK;
}
if ($this->confirm(' > Are you sure you want to generate ' . count($tables) . ' migrations?')) {
return $this->actionCreate(implode(',', $tables));
}
$this->stdout(" Operation cancelled by user.\n\n", Console::FG_YELLOW);
return ExitCode::OK;
} | php | public function actionCreateAll(): int
{
$tables = $this->removeExcludedTables($this->db->schema->getTableNames());
if (!$tables) {
$this->stdout(' > Your database does not contain any tables yet.', Console::FG_YELLOW);
return ExitCode::OK;
}
if ($this->confirm(' > Are you sure you want to generate ' . count($tables) . ' migrations?')) {
return $this->actionCreate(implode(',', $tables));
}
$this->stdout(" Operation cancelled by user.\n\n", Console::FG_YELLOW);
return ExitCode::OK;
} | [
"public",
"function",
"actionCreateAll",
"(",
")",
":",
"int",
"{",
"$",
"tables",
"=",
"$",
"this",
"->",
"removeExcludedTables",
"(",
"$",
"this",
"->",
"db",
"->",
"schema",
"->",
"getTableNames",
"(",
")",
")",
";",
"if",
"(",
"!",
"$",
"tables",
... | Creates new migrations for every table in database.
Since 3.0.0 migration history table is skipped.
@return int
@throws DbException
@since 2.1 | [
"Creates",
"new",
"migrations",
"for",
"every",
"table",
"in",
"database",
".",
"Since",
"3",
".",
"0",
".",
"0",
"migration",
"history",
"table",
"is",
"skipped",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/controllers/MigrationController.php#L501-L518 |
bizley/yii2-migration | src/controllers/MigrationController.php | MigrationController.actionUpdate | public function actionUpdate(string $table): int
{
$tables = [$table];
if (strpos($table, ',') !== false) {
$tables = explode(',', $table);
}
$migrationsGenerated = 0;
foreach ($tables as $name) {
$this->stdout(" > Generating update migration for table '{$name}' ...", Console::FG_YELLOW);
$className = 'm' . gmdate('ymd_His') . '_update_table_' . $name;
$file = Yii::getAlias($this->workingPath . DIRECTORY_SEPARATOR . $className . '.php');
$updater = new Updater([
'db' => $this->db,
'view' => $this->view,
'useTablePrefix' => $this->useTablePrefix,
'templateFile' => $this->templateFile,
'templateFileUpdate' => $this->templateFileUpdate,
'tableName' => $name,
'className' => $className,
'namespace' => $this->migrationNamespace,
'migrationPath' => $this->migrationPath,
'migrationTable' => $this->migrationTable,
'showOnly' => $this->showOnly,
'generalSchema' => $this->generalSchema,
'skipMigrations' => $this->skipMigrations,
]);
if ($updater->tableSchema === null) {
$this->stdout("ERROR!\n > Table '{$name}' does not exist!\n\n", Console::FG_RED);
return ExitCode::DATAERR;
}
try {
if (!$updater->isUpdateRequired()) {
$this->stdout("UPDATE NOT REQUIRED.\n\n", Console::FG_YELLOW);
continue;
}
} catch (NotSupportedException $exception) {
$this->stdout("WARNING!\n > Updating table '{$name}' requires manual migration!\n", Console::FG_RED);
$this->stdout(' > ' . $exception->getMessage() . "\n\n", Console::FG_RED);
continue;
}
if (!$this->showOnly) {
if ($this->generateFile($file, $updater->generateMigration()) === false) {
$this->stdout("ERROR!\n > Migration file for table '{$name}' can not be generated!\n\n", Console::FG_RED);
return ExitCode::SOFTWARE;
}
$migrationsGenerated++;
$this->stdout("DONE!\n", Console::FG_GREEN);
$this->stdout(" > Saved as '{$file}'\n");
if ($this->fixHistory) {
if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
$this->createMigrationHistoryTable();
}
$this->addMigrationHistory($className, $this->migrationNamespace);
}
}
$this->stdout("\n");
}
if ($migrationsGenerated) {
$this->stdout(" Generated $migrationsGenerated file(s).\n", Console::FG_YELLOW);
$this->stdout(" (!) Remember to verify files before applying migration.\n\n", Console::FG_YELLOW);
} else {
$this->stdout(" No files generated.\n\n", Console::FG_YELLOW);
}
return ExitCode::OK;
} | php | public function actionUpdate(string $table): int
{
$tables = [$table];
if (strpos($table, ',') !== false) {
$tables = explode(',', $table);
}
$migrationsGenerated = 0;
foreach ($tables as $name) {
$this->stdout(" > Generating update migration for table '{$name}' ...", Console::FG_YELLOW);
$className = 'm' . gmdate('ymd_His') . '_update_table_' . $name;
$file = Yii::getAlias($this->workingPath . DIRECTORY_SEPARATOR . $className . '.php');
$updater = new Updater([
'db' => $this->db,
'view' => $this->view,
'useTablePrefix' => $this->useTablePrefix,
'templateFile' => $this->templateFile,
'templateFileUpdate' => $this->templateFileUpdate,
'tableName' => $name,
'className' => $className,
'namespace' => $this->migrationNamespace,
'migrationPath' => $this->migrationPath,
'migrationTable' => $this->migrationTable,
'showOnly' => $this->showOnly,
'generalSchema' => $this->generalSchema,
'skipMigrations' => $this->skipMigrations,
]);
if ($updater->tableSchema === null) {
$this->stdout("ERROR!\n > Table '{$name}' does not exist!\n\n", Console::FG_RED);
return ExitCode::DATAERR;
}
try {
if (!$updater->isUpdateRequired()) {
$this->stdout("UPDATE NOT REQUIRED.\n\n", Console::FG_YELLOW);
continue;
}
} catch (NotSupportedException $exception) {
$this->stdout("WARNING!\n > Updating table '{$name}' requires manual migration!\n", Console::FG_RED);
$this->stdout(' > ' . $exception->getMessage() . "\n\n", Console::FG_RED);
continue;
}
if (!$this->showOnly) {
if ($this->generateFile($file, $updater->generateMigration()) === false) {
$this->stdout("ERROR!\n > Migration file for table '{$name}' can not be generated!\n\n", Console::FG_RED);
return ExitCode::SOFTWARE;
}
$migrationsGenerated++;
$this->stdout("DONE!\n", Console::FG_GREEN);
$this->stdout(" > Saved as '{$file}'\n");
if ($this->fixHistory) {
if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
$this->createMigrationHistoryTable();
}
$this->addMigrationHistory($className, $this->migrationNamespace);
}
}
$this->stdout("\n");
}
if ($migrationsGenerated) {
$this->stdout(" Generated $migrationsGenerated file(s).\n", Console::FG_YELLOW);
$this->stdout(" (!) Remember to verify files before applying migration.\n\n", Console::FG_YELLOW);
} else {
$this->stdout(" No files generated.\n\n", Console::FG_YELLOW);
}
return ExitCode::OK;
} | [
"public",
"function",
"actionUpdate",
"(",
"string",
"$",
"table",
")",
":",
"int",
"{",
"$",
"tables",
"=",
"[",
"$",
"table",
"]",
";",
"if",
"(",
"strpos",
"(",
"$",
"table",
",",
"','",
")",
"!==",
"false",
")",
"{",
"$",
"tables",
"=",
"expl... | Creates new update migration for the given tables.
@param string $table Table names separated by commas.
@return int
@throws ErrorException
@throws DbException
@since 2.0 | [
"Creates",
"new",
"update",
"migration",
"for",
"the",
"given",
"tables",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/controllers/MigrationController.php#L528-L609 |
bizley/yii2-migration | src/controllers/MigrationController.php | MigrationController.actionUpdateAll | public function actionUpdateAll(): int
{
$tables = $this->removeExcludedTables($this->db->schema->getTableNames());
if (!$tables) {
$this->stdout(' > Your database does not contain any tables yet.', Console::FG_YELLOW);
return ExitCode::OK;
}
if ($this->confirm(' > Are you sure you want to potentially generate ' . count($tables) . ' migrations?')) {
return $this->actionUpdate(implode(',', $tables));
}
$this->stdout(" Operation cancelled by user.\n\n", Console::FG_YELLOW);
return ExitCode::OK;
} | php | public function actionUpdateAll(): int
{
$tables = $this->removeExcludedTables($this->db->schema->getTableNames());
if (!$tables) {
$this->stdout(' > Your database does not contain any tables yet.', Console::FG_YELLOW);
return ExitCode::OK;
}
if ($this->confirm(' > Are you sure you want to potentially generate ' . count($tables) . ' migrations?')) {
return $this->actionUpdate(implode(',', $tables));
}
$this->stdout(" Operation cancelled by user.\n\n", Console::FG_YELLOW);
return ExitCode::OK;
} | [
"public",
"function",
"actionUpdateAll",
"(",
")",
":",
"int",
"{",
"$",
"tables",
"=",
"$",
"this",
"->",
"removeExcludedTables",
"(",
"$",
"this",
"->",
"db",
"->",
"schema",
"->",
"getTableNames",
"(",
")",
")",
";",
"if",
"(",
"!",
"$",
"tables",
... | Creates new update migrations for every table in database.
Since 3.0.0 migration history table is skipped.
@return int
@throws ErrorException
@throws DbException
@since 2.1 | [
"Creates",
"new",
"update",
"migrations",
"for",
"every",
"table",
"in",
"database",
".",
"Since",
"3",
".",
"0",
".",
"0",
"migration",
"history",
"table",
"is",
"skipped",
"."
] | train | https://github.com/bizley/yii2-migration/blob/881d9a790a137a0e1aa7b0bb40c71ebc9bdab83f/src/controllers/MigrationController.php#L619-L636 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.