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
yiisoft/yii-console
src/Controllers/MigrateController.php
MigrateController.beforeAction
public function beforeAction(Action $action): bool { if (parent::beforeAction($action)) { $this->db = Yii::ensureObject($this->db, Connection::class); return true; } return false; }
php
public function beforeAction(Action $action): bool { if (parent::beforeAction($action)) { $this->db = Yii::ensureObject($this->db, Connection::class); return true; } return false; }
[ "public", "function", "beforeAction", "(", "Action", "$", "action", ")", ":", "bool", "{", "if", "(", "parent", "::", "beforeAction", "(", "$", "action", ")", ")", "{", "$", "this", "->", "db", "=", "Yii", "::", "ensureObject", "(", "$", "this", "->", "db", ",", "Connection", "::", "class", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
This method is invoked right before an action is to be executed (after all possible filters.) It checks the existence of the [[migrationPath]]. @param \yii\base\Action $action the action to be executed. @return bool whether the action should continue to be executed.
[ "This", "method", "is", "invoked", "right", "before", "an", "action", "is", "to", "be", "executed", "(", "after", "all", "possible", "filters", ".", ")", "It", "checks", "the", "existence", "of", "the", "[[", "migrationPath", "]]", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/MigrateController.php#L179-L187
yiisoft/yii-console
src/Controllers/MigrateController.php
MigrateController.createMigration
protected function createMigration($class) { $this->includeMigrationFile($class); return $this->app->createObject([ '__class' => $class, 'db' => $this->db, 'compact' => $this->compact, ]); }
php
protected function createMigration($class) { $this->includeMigrationFile($class); return $this->app->createObject([ '__class' => $class, 'db' => $this->db, 'compact' => $this->compact, ]); }
[ "protected", "function", "createMigration", "(", "$", "class", ")", "{", "$", "this", "->", "includeMigrationFile", "(", "$", "class", ")", ";", "return", "$", "this", "->", "app", "->", "createObject", "(", "[", "'__class'", "=>", "$", "class", ",", "'db'", "=>", "$", "this", "->", "db", ",", "'compact'", "=>", "$", "this", "->", "compact", ",", "]", ")", ";", "}" ]
Creates a new migration instance. @param string $class the migration class name @return \Yiisoft\Db\Migration the migration instance
[ "Creates", "a", "new", "migration", "instance", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/MigrateController.php#L194-L203
yiisoft/yii-console
src/Controllers/MigrateController.php
MigrateController.truncateDatabase
protected function truncateDatabase() { $db = $this->db; $schemas = $db->schema->getTableSchemas(); // First drop all foreign keys, foreach ($schemas as $schema) { if ($schema->foreignKeys) { foreach ($schema->foreignKeys as $name => $foreignKey) { $db->createCommand()->dropForeignKey($name, $schema->name)->execute(); $this->stdout("Foreign key $name dropped.\n"); } } } // Then drop the tables: foreach ($schemas as $schema) { $db->createCommand()->dropTable($schema->name)->execute(); $this->stdout("Table {$schema->name} dropped.\n"); } }
php
protected function truncateDatabase() { $db = $this->db; $schemas = $db->schema->getTableSchemas(); // First drop all foreign keys, foreach ($schemas as $schema) { if ($schema->foreignKeys) { foreach ($schema->foreignKeys as $name => $foreignKey) { $db->createCommand()->dropForeignKey($name, $schema->name)->execute(); $this->stdout("Foreign key $name dropped.\n"); } } } // Then drop the tables: foreach ($schemas as $schema) { $db->createCommand()->dropTable($schema->name)->execute(); $this->stdout("Table {$schema->name} dropped.\n"); } }
[ "protected", "function", "truncateDatabase", "(", ")", "{", "$", "db", "=", "$", "this", "->", "db", ";", "$", "schemas", "=", "$", "db", "->", "schema", "->", "getTableSchemas", "(", ")", ";", "// First drop all foreign keys,", "foreach", "(", "$", "schemas", "as", "$", "schema", ")", "{", "if", "(", "$", "schema", "->", "foreignKeys", ")", "{", "foreach", "(", "$", "schema", "->", "foreignKeys", "as", "$", "name", "=>", "$", "foreignKey", ")", "{", "$", "db", "->", "createCommand", "(", ")", "->", "dropForeignKey", "(", "$", "name", ",", "$", "schema", "->", "name", ")", "->", "execute", "(", ")", ";", "$", "this", "->", "stdout", "(", "\"Foreign key $name dropped.\\n\"", ")", ";", "}", "}", "}", "// Then drop the tables:", "foreach", "(", "$", "schemas", "as", "$", "schema", ")", "{", "$", "db", "->", "createCommand", "(", ")", "->", "dropTable", "(", "$", "schema", "->", "name", ")", "->", "execute", "(", ")", ";", "$", "this", "->", "stdout", "(", "\"Table {$schema->name} dropped.\\n\"", ")", ";", "}", "}" ]
{@inheritdoc} @since 2.0.13
[ "{" ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/MigrateController.php#L296-L316
yiisoft/yii-jquery
src/Validators/Client/UrlValidator.php
UrlValidator.getClientOptions
public function getClientOptions($validator, $model, $attribute) { if (strpos($validator->pattern, '{schemes}') !== false) { $pattern = str_replace('{schemes}', '(' . implode('|', $validator->validSchemes) . ')', $validator->pattern); } else { $pattern = $validator->pattern; } $options = [ 'pattern' => new JsExpression($pattern), 'message' => $validator->formatMessage($validator->message, [ 'attribute' => $model->getAttributeLabel($attribute), ]), 'enableIDN' => (bool) $validator->enableIDN, ]; if ($validator->skipOnEmpty) { $options['skipOnEmpty'] = 1; } if ($validator->defaultScheme !== null) { $options['defaultScheme'] = $validator->defaultScheme; } return $options; }
php
public function getClientOptions($validator, $model, $attribute) { if (strpos($validator->pattern, '{schemes}') !== false) { $pattern = str_replace('{schemes}', '(' . implode('|', $validator->validSchemes) . ')', $validator->pattern); } else { $pattern = $validator->pattern; } $options = [ 'pattern' => new JsExpression($pattern), 'message' => $validator->formatMessage($validator->message, [ 'attribute' => $model->getAttributeLabel($attribute), ]), 'enableIDN' => (bool) $validator->enableIDN, ]; if ($validator->skipOnEmpty) { $options['skipOnEmpty'] = 1; } if ($validator->defaultScheme !== null) { $options['defaultScheme'] = $validator->defaultScheme; } return $options; }
[ "public", "function", "getClientOptions", "(", "$", "validator", ",", "$", "model", ",", "$", "attribute", ")", "{", "if", "(", "strpos", "(", "$", "validator", "->", "pattern", ",", "'{schemes}'", ")", "!==", "false", ")", "{", "$", "pattern", "=", "str_replace", "(", "'{schemes}'", ",", "'('", ".", "implode", "(", "'|'", ",", "$", "validator", "->", "validSchemes", ")", ".", "')'", ",", "$", "validator", "->", "pattern", ")", ";", "}", "else", "{", "$", "pattern", "=", "$", "validator", "->", "pattern", ";", "}", "$", "options", "=", "[", "'pattern'", "=>", "new", "JsExpression", "(", "$", "pattern", ")", ",", "'message'", "=>", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "message", ",", "[", "'attribute'", "=>", "$", "model", "->", "getAttributeLabel", "(", "$", "attribute", ")", ",", "]", ")", ",", "'enableIDN'", "=>", "(", "bool", ")", "$", "validator", "->", "enableIDN", ",", "]", ";", "if", "(", "$", "validator", "->", "skipOnEmpty", ")", "{", "$", "options", "[", "'skipOnEmpty'", "]", "=", "1", ";", "}", "if", "(", "$", "validator", "->", "defaultScheme", "!==", "null", ")", "{", "$", "options", "[", "'defaultScheme'", "]", "=", "$", "validator", "->", "defaultScheme", ";", "}", "return", "$", "options", ";", "}" ]
Returns the client-side validation options. @param \yii\validators\UrlValidator $validator the server-side validator. @param \yii\base\Model $model the model being validated @param string $attribute the attribute name being validated @return array the client-side validation options
[ "Returns", "the", "client", "-", "side", "validation", "options", "." ]
train
https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/UrlValidator.php#L48-L71
yiisoft/yii-jquery
src/Validators/Client/FileValidator.php
FileValidator.getClientOptions
public function getClientOptions($validator, $model, $attribute) { $label = $model->getAttributeLabel($attribute); $options = []; if ($validator->message !== null) { $options['message'] = $validator->formatMessage($validator->message, [ 'attribute' => $label, ]); } $options['skipOnEmpty'] = $validator->skipOnEmpty; if (!$validator->skipOnEmpty) { $options['uploadRequired'] = $validator->formatMessage($validator->uploadRequired, [ 'attribute' => $label, ]); } if ($validator->mimeTypes !== null) { $mimeTypes = []; foreach ($validator->mimeTypes as $mimeType) { $mimeTypes[] = new JsExpression(Html::escapeJsRegularExpression($validator->buildMimeTypeRegexp($mimeType))); } $options['mimeTypes'] = $mimeTypes; $options['wrongMimeType'] = $validator->formatMessage($validator->wrongMimeType, [ 'attribute' => $label, 'mimeTypes' => implode(', ', $validator->mimeTypes), ]); } if ($validator->extensions !== null) { $options['extensions'] = $validator->extensions; $options['wrongExtension'] = $validator->formatMessage($validator->wrongExtension, [ 'attribute' => $label, 'extensions' => implode(', ', $validator->extensions), ]); } if ($validator->minSize !== null) { $options['minSize'] = $validator->minSize; $options['tooSmall'] = $validator->formatMessage($validator->tooSmall, [ 'attribute' => $label, 'limit' => $validator->minSize, 'formattedLimit' => Yii::$app->formatter->asShortSize($validator->minSize), ]); } if ($validator->maxSize !== null) { $options['maxSize'] = $validator->maxSize; $options['tooBig'] = $validator->formatMessage($validator->tooBig, [ 'attribute' => $label, 'limit' => $validator->getSizeLimit(), 'formattedLimit' => Yii::$app->formatter->asShortSize($validator->getSizeLimit()), ]); } if ($validator->maxFiles !== null) { $options['maxFiles'] = $validator->maxFiles; $options['tooMany'] = $validator->formatMessage($validator->tooMany, [ 'attribute' => $label, 'limit' => $validator->maxFiles, ]); } return $options; }
php
public function getClientOptions($validator, $model, $attribute) { $label = $model->getAttributeLabel($attribute); $options = []; if ($validator->message !== null) { $options['message'] = $validator->formatMessage($validator->message, [ 'attribute' => $label, ]); } $options['skipOnEmpty'] = $validator->skipOnEmpty; if (!$validator->skipOnEmpty) { $options['uploadRequired'] = $validator->formatMessage($validator->uploadRequired, [ 'attribute' => $label, ]); } if ($validator->mimeTypes !== null) { $mimeTypes = []; foreach ($validator->mimeTypes as $mimeType) { $mimeTypes[] = new JsExpression(Html::escapeJsRegularExpression($validator->buildMimeTypeRegexp($mimeType))); } $options['mimeTypes'] = $mimeTypes; $options['wrongMimeType'] = $validator->formatMessage($validator->wrongMimeType, [ 'attribute' => $label, 'mimeTypes' => implode(', ', $validator->mimeTypes), ]); } if ($validator->extensions !== null) { $options['extensions'] = $validator->extensions; $options['wrongExtension'] = $validator->formatMessage($validator->wrongExtension, [ 'attribute' => $label, 'extensions' => implode(', ', $validator->extensions), ]); } if ($validator->minSize !== null) { $options['minSize'] = $validator->minSize; $options['tooSmall'] = $validator->formatMessage($validator->tooSmall, [ 'attribute' => $label, 'limit' => $validator->minSize, 'formattedLimit' => Yii::$app->formatter->asShortSize($validator->minSize), ]); } if ($validator->maxSize !== null) { $options['maxSize'] = $validator->maxSize; $options['tooBig'] = $validator->formatMessage($validator->tooBig, [ 'attribute' => $label, 'limit' => $validator->getSizeLimit(), 'formattedLimit' => Yii::$app->formatter->asShortSize($validator->getSizeLimit()), ]); } if ($validator->maxFiles !== null) { $options['maxFiles'] = $validator->maxFiles; $options['tooMany'] = $validator->formatMessage($validator->tooMany, [ 'attribute' => $label, 'limit' => $validator->maxFiles, ]); } return $options; }
[ "public", "function", "getClientOptions", "(", "$", "validator", ",", "$", "model", ",", "$", "attribute", ")", "{", "$", "label", "=", "$", "model", "->", "getAttributeLabel", "(", "$", "attribute", ")", ";", "$", "options", "=", "[", "]", ";", "if", "(", "$", "validator", "->", "message", "!==", "null", ")", "{", "$", "options", "[", "'message'", "]", "=", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "message", ",", "[", "'attribute'", "=>", "$", "label", ",", "]", ")", ";", "}", "$", "options", "[", "'skipOnEmpty'", "]", "=", "$", "validator", "->", "skipOnEmpty", ";", "if", "(", "!", "$", "validator", "->", "skipOnEmpty", ")", "{", "$", "options", "[", "'uploadRequired'", "]", "=", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "uploadRequired", ",", "[", "'attribute'", "=>", "$", "label", ",", "]", ")", ";", "}", "if", "(", "$", "validator", "->", "mimeTypes", "!==", "null", ")", "{", "$", "mimeTypes", "=", "[", "]", ";", "foreach", "(", "$", "validator", "->", "mimeTypes", "as", "$", "mimeType", ")", "{", "$", "mimeTypes", "[", "]", "=", "new", "JsExpression", "(", "Html", "::", "escapeJsRegularExpression", "(", "$", "validator", "->", "buildMimeTypeRegexp", "(", "$", "mimeType", ")", ")", ")", ";", "}", "$", "options", "[", "'mimeTypes'", "]", "=", "$", "mimeTypes", ";", "$", "options", "[", "'wrongMimeType'", "]", "=", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "wrongMimeType", ",", "[", "'attribute'", "=>", "$", "label", ",", "'mimeTypes'", "=>", "implode", "(", "', '", ",", "$", "validator", "->", "mimeTypes", ")", ",", "]", ")", ";", "}", "if", "(", "$", "validator", "->", "extensions", "!==", "null", ")", "{", "$", "options", "[", "'extensions'", "]", "=", "$", "validator", "->", "extensions", ";", "$", "options", "[", "'wrongExtension'", "]", "=", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "wrongExtension", ",", "[", "'attribute'", "=>", "$", "label", ",", "'extensions'", "=>", "implode", "(", "', '", ",", "$", "validator", "->", "extensions", ")", ",", "]", ")", ";", "}", "if", "(", "$", "validator", "->", "minSize", "!==", "null", ")", "{", "$", "options", "[", "'minSize'", "]", "=", "$", "validator", "->", "minSize", ";", "$", "options", "[", "'tooSmall'", "]", "=", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "tooSmall", ",", "[", "'attribute'", "=>", "$", "label", ",", "'limit'", "=>", "$", "validator", "->", "minSize", ",", "'formattedLimit'", "=>", "Yii", "::", "$", "app", "->", "formatter", "->", "asShortSize", "(", "$", "validator", "->", "minSize", ")", ",", "]", ")", ";", "}", "if", "(", "$", "validator", "->", "maxSize", "!==", "null", ")", "{", "$", "options", "[", "'maxSize'", "]", "=", "$", "validator", "->", "maxSize", ";", "$", "options", "[", "'tooBig'", "]", "=", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "tooBig", ",", "[", "'attribute'", "=>", "$", "label", ",", "'limit'", "=>", "$", "validator", "->", "getSizeLimit", "(", ")", ",", "'formattedLimit'", "=>", "Yii", "::", "$", "app", "->", "formatter", "->", "asShortSize", "(", "$", "validator", "->", "getSizeLimit", "(", ")", ")", ",", "]", ")", ";", "}", "if", "(", "$", "validator", "->", "maxFiles", "!==", "null", ")", "{", "$", "options", "[", "'maxFiles'", "]", "=", "$", "validator", "->", "maxFiles", ";", "$", "options", "[", "'tooMany'", "]", "=", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "tooMany", ",", "[", "'attribute'", "=>", "$", "label", ",", "'limit'", "=>", "$", "validator", "->", "maxFiles", ",", "]", ")", ";", "}", "return", "$", "options", ";", "}" ]
Returns the client-side validation options. @param \yii\validators\FileValidator $validator the server-side validator. @param \yii\base\Model $model the model being validated @param string $attribute the attribute name being validated @return array the client-side validation options
[ "Returns", "the", "client", "-", "side", "validation", "options", "." ]
train
https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/FileValidator.php#L45-L111
yiisoft/yii-jquery
src/Validators/Client/RangeValidator.php
RangeValidator.build
public function build($validator, $model, $attribute, $view) { /* @var $validator \yii\validators\RangeValidator */ if ($validator->range instanceof \Closure) { $validator->range = call_user_func($validator->range, $model, $attribute); } ValidationAsset::register($view); $options = $this->getClientOptions($validator, $model, $attribute); return 'yii.validation.range(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');'; }
php
public function build($validator, $model, $attribute, $view) { /* @var $validator \yii\validators\RangeValidator */ if ($validator->range instanceof \Closure) { $validator->range = call_user_func($validator->range, $model, $attribute); } ValidationAsset::register($view); $options = $this->getClientOptions($validator, $model, $attribute); return 'yii.validation.range(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');'; }
[ "public", "function", "build", "(", "$", "validator", ",", "$", "model", ",", "$", "attribute", ",", "$", "view", ")", "{", "/* @var $validator \\yii\\validators\\RangeValidator */", "if", "(", "$", "validator", "->", "range", "instanceof", "\\", "Closure", ")", "{", "$", "validator", "->", "range", "=", "call_user_func", "(", "$", "validator", "->", "range", ",", "$", "model", ",", "$", "attribute", ")", ";", "}", "ValidationAsset", "::", "register", "(", "$", "view", ")", ";", "$", "options", "=", "$", "this", "->", "getClientOptions", "(", "$", "validator", ",", "$", "model", ",", "$", "attribute", ")", ";", "return", "'yii.validation.range(value, messages, '", ".", "json_encode", "(", "$", "options", ",", "JSON_UNESCAPED_SLASHES", "|", "JSON_UNESCAPED_UNICODE", ")", ".", "');'", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/RangeValidator.php#L27-L36
yiisoft/yii-jquery
src/Validators/Client/RangeValidator.php
RangeValidator.getClientOptions
public function getClientOptions($validator, $model, $attribute) { $range = []; foreach ($validator->range as $value) { $range[] = (string) $value; } $options = [ 'range' => $range, 'not' => $validator->not, 'message' => $validator->formatMessage($validator->message, [ 'attribute' => $model->getAttributeLabel($attribute), ]), ]; if ($validator->skipOnEmpty) { $options['skipOnEmpty'] = 1; } if ($validator->allowArray) { $options['allowArray'] = 1; } return $options; }
php
public function getClientOptions($validator, $model, $attribute) { $range = []; foreach ($validator->range as $value) { $range[] = (string) $value; } $options = [ 'range' => $range, 'not' => $validator->not, 'message' => $validator->formatMessage($validator->message, [ 'attribute' => $model->getAttributeLabel($attribute), ]), ]; if ($validator->skipOnEmpty) { $options['skipOnEmpty'] = 1; } if ($validator->allowArray) { $options['allowArray'] = 1; } return $options; }
[ "public", "function", "getClientOptions", "(", "$", "validator", ",", "$", "model", ",", "$", "attribute", ")", "{", "$", "range", "=", "[", "]", ";", "foreach", "(", "$", "validator", "->", "range", "as", "$", "value", ")", "{", "$", "range", "[", "]", "=", "(", "string", ")", "$", "value", ";", "}", "$", "options", "=", "[", "'range'", "=>", "$", "range", ",", "'not'", "=>", "$", "validator", "->", "not", ",", "'message'", "=>", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "message", ",", "[", "'attribute'", "=>", "$", "model", "->", "getAttributeLabel", "(", "$", "attribute", ")", ",", "]", ")", ",", "]", ";", "if", "(", "$", "validator", "->", "skipOnEmpty", ")", "{", "$", "options", "[", "'skipOnEmpty'", "]", "=", "1", ";", "}", "if", "(", "$", "validator", "->", "allowArray", ")", "{", "$", "options", "[", "'allowArray'", "]", "=", "1", ";", "}", "return", "$", "options", ";", "}" ]
Returns the client-side validation options. @param \yii\validators\RangeValidator $validator the server-side validator. @param \yii\base\Model $model the model being validated @param string $attribute the attribute name being validated @return array the client-side validation options
[ "Returns", "the", "client", "-", "side", "validation", "options", "." ]
train
https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/RangeValidator.php#L45-L66
yiisoft/yii-jquery
src/Validators/Client/EmailValidator.php
EmailValidator.getClientOptions
public function getClientOptions($validator, $model, $attribute) { $options = [ 'pattern' => new JsExpression($validator->pattern), 'fullPattern' => new JsExpression($validator->fullPattern), 'allowName' => $validator->allowName, 'message' => $validator->formatMessage($validator->message, [ 'attribute' => $model->getAttributeLabel($attribute), ]), 'enableIDN' => (bool)$validator->enableIDN, ]; if ($validator->skipOnEmpty) { $options['skipOnEmpty'] = 1; } return $options; }
php
public function getClientOptions($validator, $model, $attribute) { $options = [ 'pattern' => new JsExpression($validator->pattern), 'fullPattern' => new JsExpression($validator->fullPattern), 'allowName' => $validator->allowName, 'message' => $validator->formatMessage($validator->message, [ 'attribute' => $model->getAttributeLabel($attribute), ]), 'enableIDN' => (bool)$validator->enableIDN, ]; if ($validator->skipOnEmpty) { $options['skipOnEmpty'] = 1; } return $options; }
[ "public", "function", "getClientOptions", "(", "$", "validator", ",", "$", "model", ",", "$", "attribute", ")", "{", "$", "options", "=", "[", "'pattern'", "=>", "new", "JsExpression", "(", "$", "validator", "->", "pattern", ")", ",", "'fullPattern'", "=>", "new", "JsExpression", "(", "$", "validator", "->", "fullPattern", ")", ",", "'allowName'", "=>", "$", "validator", "->", "allowName", ",", "'message'", "=>", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "message", ",", "[", "'attribute'", "=>", "$", "model", "->", "getAttributeLabel", "(", "$", "attribute", ")", ",", "]", ")", ",", "'enableIDN'", "=>", "(", "bool", ")", "$", "validator", "->", "enableIDN", ",", "]", ";", "if", "(", "$", "validator", "->", "skipOnEmpty", ")", "{", "$", "options", "[", "'skipOnEmpty'", "]", "=", "1", ";", "}", "return", "$", "options", ";", "}" ]
Returns the client-side validation options. @param \yii\validators\EmailValidator $validator the server-side validator. @param \yii\base\Model $model the model being validated @param string $attribute the attribute name being validated @return array the client-side validation options
[ "Returns", "the", "client", "-", "side", "validation", "options", "." ]
train
https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/EmailValidator.php#L48-L64
yiisoft/yii-jquery
src/Validators/Client/ImageValidator.php
ImageValidator.build
public function build($validator, $model, $attribute, $view) { ValidationAsset::register($view); $options = $this->getClientOptions($validator, $model, $attribute); return 'yii.validation.image(attribute, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ', deferred);'; }
php
public function build($validator, $model, $attribute, $view) { ValidationAsset::register($view); $options = $this->getClientOptions($validator, $model, $attribute); return 'yii.validation.image(attribute, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ', deferred);'; }
[ "public", "function", "build", "(", "$", "validator", ",", "$", "model", ",", "$", "attribute", ",", "$", "view", ")", "{", "ValidationAsset", "::", "register", "(", "$", "view", ")", ";", "$", "options", "=", "$", "this", "->", "getClientOptions", "(", "$", "validator", ",", "$", "model", ",", "$", "attribute", ")", ";", "return", "'yii.validation.image(attribute, messages, '", ".", "json_encode", "(", "$", "options", ",", "JSON_UNESCAPED_SLASHES", "|", "JSON_UNESCAPED_UNICODE", ")", ".", "', deferred);'", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/ImageValidator.php#L26-L31
yiisoft/yii-jquery
src/Validators/Client/ImageValidator.php
ImageValidator.getClientOptions
public function getClientOptions($validator, $model, $attribute) { $options = parent::getClientOptions($validator, $model, $attribute); $label = $model->getAttributeLabel($attribute); if ($validator->notImage !== null) { $options['notImage'] = $validator->formatMessage($validator->notImage, [ 'attribute' => $label, ]); } if ($validator->minWidth !== null) { $options['minWidth'] = $validator->minWidth; $options['underWidth'] = $validator->formatMessage($validator->underWidth, [ 'attribute' => $label, 'limit' => $validator->minWidth, ]); } if ($validator->maxWidth !== null) { $options['maxWidth'] = $validator->maxWidth; $options['overWidth'] = $validator->formatMessage($validator->overWidth, [ 'attribute' => $label, 'limit' => $validator->maxWidth, ]); } if ($validator->minHeight !== null) { $options['minHeight'] = $validator->minHeight; $options['underHeight'] = $validator->formatMessage($validator->underHeight, [ 'attribute' => $label, 'limit' => $validator->minHeight, ]); } if ($validator->maxHeight !== null) { $options['maxHeight'] = $validator->maxHeight; $options['overHeight'] = $validator->formatMessage($validator->overHeight, [ 'attribute' => $label, 'limit' => $validator->maxHeight, ]); } return $options; }
php
public function getClientOptions($validator, $model, $attribute) { $options = parent::getClientOptions($validator, $model, $attribute); $label = $model->getAttributeLabel($attribute); if ($validator->notImage !== null) { $options['notImage'] = $validator->formatMessage($validator->notImage, [ 'attribute' => $label, ]); } if ($validator->minWidth !== null) { $options['minWidth'] = $validator->minWidth; $options['underWidth'] = $validator->formatMessage($validator->underWidth, [ 'attribute' => $label, 'limit' => $validator->minWidth, ]); } if ($validator->maxWidth !== null) { $options['maxWidth'] = $validator->maxWidth; $options['overWidth'] = $validator->formatMessage($validator->overWidth, [ 'attribute' => $label, 'limit' => $validator->maxWidth, ]); } if ($validator->minHeight !== null) { $options['minHeight'] = $validator->minHeight; $options['underHeight'] = $validator->formatMessage($validator->underHeight, [ 'attribute' => $label, 'limit' => $validator->minHeight, ]); } if ($validator->maxHeight !== null) { $options['maxHeight'] = $validator->maxHeight; $options['overHeight'] = $validator->formatMessage($validator->overHeight, [ 'attribute' => $label, 'limit' => $validator->maxHeight, ]); } return $options; }
[ "public", "function", "getClientOptions", "(", "$", "validator", ",", "$", "model", ",", "$", "attribute", ")", "{", "$", "options", "=", "parent", "::", "getClientOptions", "(", "$", "validator", ",", "$", "model", ",", "$", "attribute", ")", ";", "$", "label", "=", "$", "model", "->", "getAttributeLabel", "(", "$", "attribute", ")", ";", "if", "(", "$", "validator", "->", "notImage", "!==", "null", ")", "{", "$", "options", "[", "'notImage'", "]", "=", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "notImage", ",", "[", "'attribute'", "=>", "$", "label", ",", "]", ")", ";", "}", "if", "(", "$", "validator", "->", "minWidth", "!==", "null", ")", "{", "$", "options", "[", "'minWidth'", "]", "=", "$", "validator", "->", "minWidth", ";", "$", "options", "[", "'underWidth'", "]", "=", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "underWidth", ",", "[", "'attribute'", "=>", "$", "label", ",", "'limit'", "=>", "$", "validator", "->", "minWidth", ",", "]", ")", ";", "}", "if", "(", "$", "validator", "->", "maxWidth", "!==", "null", ")", "{", "$", "options", "[", "'maxWidth'", "]", "=", "$", "validator", "->", "maxWidth", ";", "$", "options", "[", "'overWidth'", "]", "=", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "overWidth", ",", "[", "'attribute'", "=>", "$", "label", ",", "'limit'", "=>", "$", "validator", "->", "maxWidth", ",", "]", ")", ";", "}", "if", "(", "$", "validator", "->", "minHeight", "!==", "null", ")", "{", "$", "options", "[", "'minHeight'", "]", "=", "$", "validator", "->", "minHeight", ";", "$", "options", "[", "'underHeight'", "]", "=", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "underHeight", ",", "[", "'attribute'", "=>", "$", "label", ",", "'limit'", "=>", "$", "validator", "->", "minHeight", ",", "]", ")", ";", "}", "if", "(", "$", "validator", "->", "maxHeight", "!==", "null", ")", "{", "$", "options", "[", "'maxHeight'", "]", "=", "$", "validator", "->", "maxHeight", ";", "$", "options", "[", "'overHeight'", "]", "=", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "overHeight", ",", "[", "'attribute'", "=>", "$", "label", ",", "'limit'", "=>", "$", "validator", "->", "maxHeight", ",", "]", ")", ";", "}", "return", "$", "options", ";", "}" ]
Returns the client-side validation options. @param \yii\validators\ImageValidator $validator the server-side validator. @param \yii\base\Model $model the model being validated @param string $attribute the attribute name being validated @return array the client-side validation options
[ "Returns", "the", "client", "-", "side", "validation", "options", "." ]
train
https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/ImageValidator.php#L40-L85
yiisoft/yii-jquery
src/Validators/Client/StringValidator.php
StringValidator.getClientOptions
public function getClientOptions($validator, $model, $attribute) { $label = $model->getAttributeLabel($attribute); $options = [ 'message' => $validator->formatMessage($validator->message, [ 'attribute' => $label, ]), ]; if ($validator->min !== null) { $options['min'] = $validator->min; $options['tooShort'] = $validator->formatMessage($validator->tooShort, [ 'attribute' => $label, 'min' => $validator->min, ]); } if ($validator->max !== null) { $options['max'] = $validator->max; $options['tooLong'] = $validator->formatMessage($validator->tooLong, [ 'attribute' => $label, 'max' => $validator->max, ]); } if ($validator->length !== null) { $options['is'] = $validator->length; $options['notEqual'] = $validator->formatMessage($validator->notEqual, [ 'attribute' => $label, 'length' => $validator->length, ]); } if ($validator->skipOnEmpty) { $options['skipOnEmpty'] = 1; } return $options; }
php
public function getClientOptions($validator, $model, $attribute) { $label = $model->getAttributeLabel($attribute); $options = [ 'message' => $validator->formatMessage($validator->message, [ 'attribute' => $label, ]), ]; if ($validator->min !== null) { $options['min'] = $validator->min; $options['tooShort'] = $validator->formatMessage($validator->tooShort, [ 'attribute' => $label, 'min' => $validator->min, ]); } if ($validator->max !== null) { $options['max'] = $validator->max; $options['tooLong'] = $validator->formatMessage($validator->tooLong, [ 'attribute' => $label, 'max' => $validator->max, ]); } if ($validator->length !== null) { $options['is'] = $validator->length; $options['notEqual'] = $validator->formatMessage($validator->notEqual, [ 'attribute' => $label, 'length' => $validator->length, ]); } if ($validator->skipOnEmpty) { $options['skipOnEmpty'] = 1; } return $options; }
[ "public", "function", "getClientOptions", "(", "$", "validator", ",", "$", "model", ",", "$", "attribute", ")", "{", "$", "label", "=", "$", "model", "->", "getAttributeLabel", "(", "$", "attribute", ")", ";", "$", "options", "=", "[", "'message'", "=>", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "message", ",", "[", "'attribute'", "=>", "$", "label", ",", "]", ")", ",", "]", ";", "if", "(", "$", "validator", "->", "min", "!==", "null", ")", "{", "$", "options", "[", "'min'", "]", "=", "$", "validator", "->", "min", ";", "$", "options", "[", "'tooShort'", "]", "=", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "tooShort", ",", "[", "'attribute'", "=>", "$", "label", ",", "'min'", "=>", "$", "validator", "->", "min", ",", "]", ")", ";", "}", "if", "(", "$", "validator", "->", "max", "!==", "null", ")", "{", "$", "options", "[", "'max'", "]", "=", "$", "validator", "->", "max", ";", "$", "options", "[", "'tooLong'", "]", "=", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "tooLong", ",", "[", "'attribute'", "=>", "$", "label", ",", "'max'", "=>", "$", "validator", "->", "max", ",", "]", ")", ";", "}", "if", "(", "$", "validator", "->", "length", "!==", "null", ")", "{", "$", "options", "[", "'is'", "]", "=", "$", "validator", "->", "length", ";", "$", "options", "[", "'notEqual'", "]", "=", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "notEqual", ",", "[", "'attribute'", "=>", "$", "label", ",", "'length'", "=>", "$", "validator", "->", "length", ",", "]", ")", ";", "}", "if", "(", "$", "validator", "->", "skipOnEmpty", ")", "{", "$", "options", "[", "'skipOnEmpty'", "]", "=", "1", ";", "}", "return", "$", "options", ";", "}" ]
Returns the client-side validation options. @param \yii\validators\StringValidator $validator the server-side validator. @param \yii\base\Model $model the model being validated @param string $attribute the attribute name being validated @return array the client-side validation options
[ "Returns", "the", "client", "-", "side", "validation", "options", "." ]
train
https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/StringValidator.php#L41-L77
yiisoft/yii-console
src/Controllers/HelpController.php
HelpController.getCommands
public function getCommands() { $commands = $this->getModuleCommands($this->app); sort($commands); return array_unique($commands); }
php
public function getCommands() { $commands = $this->getModuleCommands($this->app); sort($commands); return array_unique($commands); }
[ "public", "function", "getCommands", "(", ")", "{", "$", "commands", "=", "$", "this", "->", "getModuleCommands", "(", "$", "this", "->", "app", ")", ";", "sort", "(", "$", "commands", ")", ";", "return", "array_unique", "(", "$", "commands", ")", ";", "}" ]
Returns all available command names. @return array all available command names
[ "Returns", "all", "available", "command", "names", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/HelpController.php#L173-L178
yiisoft/yii-console
src/Controllers/HelpController.php
HelpController.getCommandDescriptions
protected function getCommandDescriptions() { $descriptions = []; foreach ($this->getCommands() as $command) { $description = ''; $result = $this->app->createController($command); if ($result !== false && $result[0] instanceof Controller) { [$controller, $actionID] = $result; /** @var Controller $controller */ $description = $controller->getHelpSummary(); } $descriptions[$command] = $description; } return $descriptions; }
php
protected function getCommandDescriptions() { $descriptions = []; foreach ($this->getCommands() as $command) { $description = ''; $result = $this->app->createController($command); if ($result !== false && $result[0] instanceof Controller) { [$controller, $actionID] = $result; /** @var Controller $controller */ $description = $controller->getHelpSummary(); } $descriptions[$command] = $description; } return $descriptions; }
[ "protected", "function", "getCommandDescriptions", "(", ")", "{", "$", "descriptions", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getCommands", "(", ")", "as", "$", "command", ")", "{", "$", "description", "=", "''", ";", "$", "result", "=", "$", "this", "->", "app", "->", "createController", "(", "$", "command", ")", ";", "if", "(", "$", "result", "!==", "false", "&&", "$", "result", "[", "0", "]", "instanceof", "Controller", ")", "{", "[", "$", "controller", ",", "$", "actionID", "]", "=", "$", "result", ";", "/** @var Controller $controller */", "$", "description", "=", "$", "controller", "->", "getHelpSummary", "(", ")", ";", "}", "$", "descriptions", "[", "$", "command", "]", "=", "$", "description", ";", "}", "return", "$", "descriptions", ";", "}" ]
Returns an array of commands an their descriptions. @return array all available commands as keys and their description as values.
[ "Returns", "an", "array", "of", "commands", "an", "their", "descriptions", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/HelpController.php#L184-L201
yiisoft/yii-console
src/Controllers/HelpController.php
HelpController.getModuleCommands
protected function getModuleCommands($module) { $prefix = $module instanceof Application ? '' : $module->getUniqueId() . '/'; $commands = []; foreach (array_keys($module->controllerMap) as $id) { $commands[] = $prefix . $id; } foreach ($module->getModules() as $id => $child) { if (($child = $module->getModule($id)) === null) { continue; } foreach ($this->getModuleCommands($child) as $command) { $commands[] = $command; } } $controllerPath = $module->getControllerPath(); if (is_dir($controllerPath)) { $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($controllerPath, \RecursiveDirectoryIterator::KEY_AS_PATHNAME)); $iterator = new \RegexIterator($iterator, '/.*Controller\.php$/', \RecursiveRegexIterator::GET_MATCH); foreach ($iterator as $matches) { $file = $matches[0]; $relativePath = str_replace($controllerPath, '', $file); $class = strtr($relativePath, [ '/' => '\\', '.php' => '', ]); $controllerClass = $module->controllerNamespace . $class; if ($this->validateControllerClass($controllerClass)) { $dir = ltrim(pathinfo($relativePath, PATHINFO_DIRNAME), '\\/'); $command = InflectorHelper::camel2id(substr(basename($file), 0, -14), '-', true); if (!empty($dir)) { $command = $dir . '/' . $command; } $commands[] = $prefix . $command; } } } return $commands; }
php
protected function getModuleCommands($module) { $prefix = $module instanceof Application ? '' : $module->getUniqueId() . '/'; $commands = []; foreach (array_keys($module->controllerMap) as $id) { $commands[] = $prefix . $id; } foreach ($module->getModules() as $id => $child) { if (($child = $module->getModule($id)) === null) { continue; } foreach ($this->getModuleCommands($child) as $command) { $commands[] = $command; } } $controllerPath = $module->getControllerPath(); if (is_dir($controllerPath)) { $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($controllerPath, \RecursiveDirectoryIterator::KEY_AS_PATHNAME)); $iterator = new \RegexIterator($iterator, '/.*Controller\.php$/', \RecursiveRegexIterator::GET_MATCH); foreach ($iterator as $matches) { $file = $matches[0]; $relativePath = str_replace($controllerPath, '', $file); $class = strtr($relativePath, [ '/' => '\\', '.php' => '', ]); $controllerClass = $module->controllerNamespace . $class; if ($this->validateControllerClass($controllerClass)) { $dir = ltrim(pathinfo($relativePath, PATHINFO_DIRNAME), '\\/'); $command = InflectorHelper::camel2id(substr(basename($file), 0, -14), '-', true); if (!empty($dir)) { $command = $dir . '/' . $command; } $commands[] = $prefix . $command; } } } return $commands; }
[ "protected", "function", "getModuleCommands", "(", "$", "module", ")", "{", "$", "prefix", "=", "$", "module", "instanceof", "Application", "?", "''", ":", "$", "module", "->", "getUniqueId", "(", ")", ".", "'/'", ";", "$", "commands", "=", "[", "]", ";", "foreach", "(", "array_keys", "(", "$", "module", "->", "controllerMap", ")", "as", "$", "id", ")", "{", "$", "commands", "[", "]", "=", "$", "prefix", ".", "$", "id", ";", "}", "foreach", "(", "$", "module", "->", "getModules", "(", ")", "as", "$", "id", "=>", "$", "child", ")", "{", "if", "(", "(", "$", "child", "=", "$", "module", "->", "getModule", "(", "$", "id", ")", ")", "===", "null", ")", "{", "continue", ";", "}", "foreach", "(", "$", "this", "->", "getModuleCommands", "(", "$", "child", ")", "as", "$", "command", ")", "{", "$", "commands", "[", "]", "=", "$", "command", ";", "}", "}", "$", "controllerPath", "=", "$", "module", "->", "getControllerPath", "(", ")", ";", "if", "(", "is_dir", "(", "$", "controllerPath", ")", ")", "{", "$", "iterator", "=", "new", "\\", "RecursiveIteratorIterator", "(", "new", "\\", "RecursiveDirectoryIterator", "(", "$", "controllerPath", ",", "\\", "RecursiveDirectoryIterator", "::", "KEY_AS_PATHNAME", ")", ")", ";", "$", "iterator", "=", "new", "\\", "RegexIterator", "(", "$", "iterator", ",", "'/.*Controller\\.php$/'", ",", "\\", "RecursiveRegexIterator", "::", "GET_MATCH", ")", ";", "foreach", "(", "$", "iterator", "as", "$", "matches", ")", "{", "$", "file", "=", "$", "matches", "[", "0", "]", ";", "$", "relativePath", "=", "str_replace", "(", "$", "controllerPath", ",", "''", ",", "$", "file", ")", ";", "$", "class", "=", "strtr", "(", "$", "relativePath", ",", "[", "'/'", "=>", "'\\\\'", ",", "'.php'", "=>", "''", ",", "]", ")", ";", "$", "controllerClass", "=", "$", "module", "->", "controllerNamespace", ".", "$", "class", ";", "if", "(", "$", "this", "->", "validateControllerClass", "(", "$", "controllerClass", ")", ")", "{", "$", "dir", "=", "ltrim", "(", "pathinfo", "(", "$", "relativePath", ",", "PATHINFO_DIRNAME", ")", ",", "'\\\\/'", ")", ";", "$", "command", "=", "InflectorHelper", "::", "camel2id", "(", "substr", "(", "basename", "(", "$", "file", ")", ",", "0", ",", "-", "14", ")", ",", "'-'", ",", "true", ")", ";", "if", "(", "!", "empty", "(", "$", "dir", ")", ")", "{", "$", "command", "=", "$", "dir", ".", "'/'", ".", "$", "command", ";", "}", "$", "commands", "[", "]", "=", "$", "prefix", ".", "$", "command", ";", "}", "}", "}", "return", "$", "commands", ";", "}" ]
Returns available commands of a specified module. @param \yii\base\Module $module the module instance @return array the available command names
[ "Returns", "available", "commands", "of", "a", "specified", "module", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/HelpController.php#L228-L271
yiisoft/yii-console
src/Controllers/HelpController.php
HelpController.validateControllerClass
protected function validateControllerClass($controllerClass) { if (class_exists($controllerClass)) { $class = new \ReflectionClass($controllerClass); return !$class->isAbstract() && $class->isSubclassOf(Controller::class); } return false; }
php
protected function validateControllerClass($controllerClass) { if (class_exists($controllerClass)) { $class = new \ReflectionClass($controllerClass); return !$class->isAbstract() && $class->isSubclassOf(Controller::class); } return false; }
[ "protected", "function", "validateControllerClass", "(", "$", "controllerClass", ")", "{", "if", "(", "class_exists", "(", "$", "controllerClass", ")", ")", "{", "$", "class", "=", "new", "\\", "ReflectionClass", "(", "$", "controllerClass", ")", ";", "return", "!", "$", "class", "->", "isAbstract", "(", ")", "&&", "$", "class", "->", "isSubclassOf", "(", "Controller", "::", "class", ")", ";", "}", "return", "false", ";", "}" ]
Validates if the given class is a valid console controller class. @param string $controllerClass @return bool
[ "Validates", "if", "the", "given", "class", "is", "a", "valid", "console", "controller", "class", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/HelpController.php#L278-L286
yiisoft/yii-console
src/Widgets/Table.php
Table.renderRow
protected function renderRow(array $row, $spanLeft, $spanMiddle, $spanRight) { $size = $this->_columnWidths; $buffer = ''; $arrayPointer = []; $finalChunk = []; for ($i = 0, ($max = $this->calculateRowHeight($row)) ?: $max = 1; $i < $max; $i++) { $buffer .= $spanLeft . ' '; foreach ($size as $index => $cellSize) { $cell = $row[$index] ?? null; $prefix = ''; if ($index !== 0) { $buffer .= $spanMiddle . ' '; } if (is_array($cell)) { if (empty($finalChunk[$index])) { $finalChunk[$index] = ''; $start = 0; $prefix = $this->_listPrefix; if (!isset($arrayPointer[$index])) { $arrayPointer[$index] = 0; } } else { $start = mb_strwidth($finalChunk[$index], $this->app->encoding); } $chunk = mb_substr($cell[$arrayPointer[$index]], $start, $cellSize - 4, $this->app->encoding); $finalChunk[$index] .= $chunk; if (isset($cell[$arrayPointer[$index] + 1]) && $finalChunk[$index] === $cell[$arrayPointer[$index]]) { $arrayPointer[$index]++; $finalChunk[$index] = ''; } } else { $chunk = mb_substr($cell, ($cellSize * $i) - ($i * 2), $cellSize - 2, $this->app->encoding); } $chunk = $prefix . $chunk; $repeat = $cellSize - mb_strwidth($chunk, $this->app->encoding) - 1; $buffer .= $chunk; if ($repeat >= 0) { $buffer .= str_repeat(' ', $repeat); } } $buffer .= "$spanRight\n"; } return $buffer; }
php
protected function renderRow(array $row, $spanLeft, $spanMiddle, $spanRight) { $size = $this->_columnWidths; $buffer = ''; $arrayPointer = []; $finalChunk = []; for ($i = 0, ($max = $this->calculateRowHeight($row)) ?: $max = 1; $i < $max; $i++) { $buffer .= $spanLeft . ' '; foreach ($size as $index => $cellSize) { $cell = $row[$index] ?? null; $prefix = ''; if ($index !== 0) { $buffer .= $spanMiddle . ' '; } if (is_array($cell)) { if (empty($finalChunk[$index])) { $finalChunk[$index] = ''; $start = 0; $prefix = $this->_listPrefix; if (!isset($arrayPointer[$index])) { $arrayPointer[$index] = 0; } } else { $start = mb_strwidth($finalChunk[$index], $this->app->encoding); } $chunk = mb_substr($cell[$arrayPointer[$index]], $start, $cellSize - 4, $this->app->encoding); $finalChunk[$index] .= $chunk; if (isset($cell[$arrayPointer[$index] + 1]) && $finalChunk[$index] === $cell[$arrayPointer[$index]]) { $arrayPointer[$index]++; $finalChunk[$index] = ''; } } else { $chunk = mb_substr($cell, ($cellSize * $i) - ($i * 2), $cellSize - 2, $this->app->encoding); } $chunk = $prefix . $chunk; $repeat = $cellSize - mb_strwidth($chunk, $this->app->encoding) - 1; $buffer .= $chunk; if ($repeat >= 0) { $buffer .= str_repeat(' ', $repeat); } } $buffer .= "$spanRight\n"; } return $buffer; }
[ "protected", "function", "renderRow", "(", "array", "$", "row", ",", "$", "spanLeft", ",", "$", "spanMiddle", ",", "$", "spanRight", ")", "{", "$", "size", "=", "$", "this", "->", "_columnWidths", ";", "$", "buffer", "=", "''", ";", "$", "arrayPointer", "=", "[", "]", ";", "$", "finalChunk", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ",", "(", "$", "max", "=", "$", "this", "->", "calculateRowHeight", "(", "$", "row", ")", ")", "?", ":", "$", "max", "=", "1", ";", "$", "i", "<", "$", "max", ";", "$", "i", "++", ")", "{", "$", "buffer", ".=", "$", "spanLeft", ".", "' '", ";", "foreach", "(", "$", "size", "as", "$", "index", "=>", "$", "cellSize", ")", "{", "$", "cell", "=", "$", "row", "[", "$", "index", "]", "??", "null", ";", "$", "prefix", "=", "''", ";", "if", "(", "$", "index", "!==", "0", ")", "{", "$", "buffer", ".=", "$", "spanMiddle", ".", "' '", ";", "}", "if", "(", "is_array", "(", "$", "cell", ")", ")", "{", "if", "(", "empty", "(", "$", "finalChunk", "[", "$", "index", "]", ")", ")", "{", "$", "finalChunk", "[", "$", "index", "]", "=", "''", ";", "$", "start", "=", "0", ";", "$", "prefix", "=", "$", "this", "->", "_listPrefix", ";", "if", "(", "!", "isset", "(", "$", "arrayPointer", "[", "$", "index", "]", ")", ")", "{", "$", "arrayPointer", "[", "$", "index", "]", "=", "0", ";", "}", "}", "else", "{", "$", "start", "=", "mb_strwidth", "(", "$", "finalChunk", "[", "$", "index", "]", ",", "$", "this", "->", "app", "->", "encoding", ")", ";", "}", "$", "chunk", "=", "mb_substr", "(", "$", "cell", "[", "$", "arrayPointer", "[", "$", "index", "]", "]", ",", "$", "start", ",", "$", "cellSize", "-", "4", ",", "$", "this", "->", "app", "->", "encoding", ")", ";", "$", "finalChunk", "[", "$", "index", "]", ".=", "$", "chunk", ";", "if", "(", "isset", "(", "$", "cell", "[", "$", "arrayPointer", "[", "$", "index", "]", "+", "1", "]", ")", "&&", "$", "finalChunk", "[", "$", "index", "]", "===", "$", "cell", "[", "$", "arrayPointer", "[", "$", "index", "]", "]", ")", "{", "$", "arrayPointer", "[", "$", "index", "]", "++", ";", "$", "finalChunk", "[", "$", "index", "]", "=", "''", ";", "}", "}", "else", "{", "$", "chunk", "=", "mb_substr", "(", "$", "cell", ",", "(", "$", "cellSize", "*", "$", "i", ")", "-", "(", "$", "i", "*", "2", ")", ",", "$", "cellSize", "-", "2", ",", "$", "this", "->", "app", "->", "encoding", ")", ";", "}", "$", "chunk", "=", "$", "prefix", ".", "$", "chunk", ";", "$", "repeat", "=", "$", "cellSize", "-", "mb_strwidth", "(", "$", "chunk", ",", "$", "this", "->", "app", "->", "encoding", ")", "-", "1", ";", "$", "buffer", ".=", "$", "chunk", ";", "if", "(", "$", "repeat", ">=", "0", ")", "{", "$", "buffer", ".=", "str_repeat", "(", "' '", ",", "$", "repeat", ")", ";", "}", "}", "$", "buffer", ".=", "\"$spanRight\\n\"", ";", "}", "return", "$", "buffer", ";", "}" ]
Renders a row of data into a string. @param array $row row of data @param string $spanLeft character for left border @param string $spanMiddle character for middle border @param string $spanRight character for right border @return string @see \Yiisoft\Yii\Console\Widgets\Table::render()
[ "Renders", "a", "row", "of", "data", "into", "a", "string", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Widgets/Table.php#L223-L269
yiisoft/yii-console
src/Widgets/Table.php
Table.calculateRowsSize
protected function calculateRowsSize() { $this->_columnWidths = $columns = []; $totalWidth = 0; $screenWidth = $this->getScreenWidth() - self::CONSOLE_SCROLLBAR_OFFSET; for ($i = 0, $count = count($this->_headers); $i < $count; $i++) { $columns[] = ArrayHelper::getColumn($this->_rows, $i); $columns[$i][] = $this->_headers[$i]; } foreach ($columns as $column) { $columnWidth = max(array_map(function ($val) { if (is_array($val)) { $encodings = array_fill(0, count($val), $this->app->encoding); return max(array_map('mb_strwidth', $val, $encodings)) + mb_strwidth($this->_listPrefix, $this->app->encoding); } return mb_strwidth($val, $this->app->encoding); }, $column)) + 2; $this->_columnWidths[] = $columnWidth; $totalWidth += $columnWidth; } $relativeWidth = $screenWidth / $totalWidth; if ($totalWidth > $screenWidth) { foreach ($this->_columnWidths as $j => $width) { $this->_columnWidths[$j] = (int) ($width * $relativeWidth); if ($j === count($this->_columnWidths)) { $this->_columnWidths = $totalWidth; } $totalWidth -= $this->_columnWidths[$j]; } } }
php
protected function calculateRowsSize() { $this->_columnWidths = $columns = []; $totalWidth = 0; $screenWidth = $this->getScreenWidth() - self::CONSOLE_SCROLLBAR_OFFSET; for ($i = 0, $count = count($this->_headers); $i < $count; $i++) { $columns[] = ArrayHelper::getColumn($this->_rows, $i); $columns[$i][] = $this->_headers[$i]; } foreach ($columns as $column) { $columnWidth = max(array_map(function ($val) { if (is_array($val)) { $encodings = array_fill(0, count($val), $this->app->encoding); return max(array_map('mb_strwidth', $val, $encodings)) + mb_strwidth($this->_listPrefix, $this->app->encoding); } return mb_strwidth($val, $this->app->encoding); }, $column)) + 2; $this->_columnWidths[] = $columnWidth; $totalWidth += $columnWidth; } $relativeWidth = $screenWidth / $totalWidth; if ($totalWidth > $screenWidth) { foreach ($this->_columnWidths as $j => $width) { $this->_columnWidths[$j] = (int) ($width * $relativeWidth); if ($j === count($this->_columnWidths)) { $this->_columnWidths = $totalWidth; } $totalWidth -= $this->_columnWidths[$j]; } } }
[ "protected", "function", "calculateRowsSize", "(", ")", "{", "$", "this", "->", "_columnWidths", "=", "$", "columns", "=", "[", "]", ";", "$", "totalWidth", "=", "0", ";", "$", "screenWidth", "=", "$", "this", "->", "getScreenWidth", "(", ")", "-", "self", "::", "CONSOLE_SCROLLBAR_OFFSET", ";", "for", "(", "$", "i", "=", "0", ",", "$", "count", "=", "count", "(", "$", "this", "->", "_headers", ")", ";", "$", "i", "<", "$", "count", ";", "$", "i", "++", ")", "{", "$", "columns", "[", "]", "=", "ArrayHelper", "::", "getColumn", "(", "$", "this", "->", "_rows", ",", "$", "i", ")", ";", "$", "columns", "[", "$", "i", "]", "[", "]", "=", "$", "this", "->", "_headers", "[", "$", "i", "]", ";", "}", "foreach", "(", "$", "columns", "as", "$", "column", ")", "{", "$", "columnWidth", "=", "max", "(", "array_map", "(", "function", "(", "$", "val", ")", "{", "if", "(", "is_array", "(", "$", "val", ")", ")", "{", "$", "encodings", "=", "array_fill", "(", "0", ",", "count", "(", "$", "val", ")", ",", "$", "this", "->", "app", "->", "encoding", ")", ";", "return", "max", "(", "array_map", "(", "'mb_strwidth'", ",", "$", "val", ",", "$", "encodings", ")", ")", "+", "mb_strwidth", "(", "$", "this", "->", "_listPrefix", ",", "$", "this", "->", "app", "->", "encoding", ")", ";", "}", "return", "mb_strwidth", "(", "$", "val", ",", "$", "this", "->", "app", "->", "encoding", ")", ";", "}", ",", "$", "column", ")", ")", "+", "2", ";", "$", "this", "->", "_columnWidths", "[", "]", "=", "$", "columnWidth", ";", "$", "totalWidth", "+=", "$", "columnWidth", ";", "}", "$", "relativeWidth", "=", "$", "screenWidth", "/", "$", "totalWidth", ";", "if", "(", "$", "totalWidth", ">", "$", "screenWidth", ")", "{", "foreach", "(", "$", "this", "->", "_columnWidths", "as", "$", "j", "=>", "$", "width", ")", "{", "$", "this", "->", "_columnWidths", "[", "$", "j", "]", "=", "(", "int", ")", "(", "$", "width", "*", "$", "relativeWidth", ")", ";", "if", "(", "$", "j", "===", "count", "(", "$", "this", "->", "_columnWidths", ")", ")", "{", "$", "this", "->", "_columnWidths", "=", "$", "totalWidth", ";", "}", "$", "totalWidth", "-=", "$", "this", "->", "_columnWidths", "[", "$", "j", "]", ";", "}", "}", "}" ]
Calculate the size of rows to draw anchor of columns in console. @see \Yiisoft\Yii\Console\Widgets\Table::render()
[ "Calculate", "the", "size", "of", "rows", "to", "draw", "anchor", "of", "columns", "in", "console", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Widgets/Table.php#L299-L334
yiisoft/yii-console
src/Widgets/Table.php
Table.calculateRowHeight
protected function calculateRowHeight($row) { $rowsPerCell = array_map(function ($size, $columnWidth) { if (is_array($columnWidth)) { $rows = 0; foreach ($columnWidth as $width) { $rows += ceil($width / ($size - 2)); } return $rows; } return ceil($columnWidth / ($size - 2)); }, $this->_columnWidths, array_map(function ($val) { if (is_array($val)) { $encodings = array_fill(0, count($val), $this->app->encoding); return array_map('mb_strwidth', $val, $encodings); } return mb_strwidth($val, $this->app->encoding); }, $row) ); return max($rowsPerCell); }
php
protected function calculateRowHeight($row) { $rowsPerCell = array_map(function ($size, $columnWidth) { if (is_array($columnWidth)) { $rows = 0; foreach ($columnWidth as $width) { $rows += ceil($width / ($size - 2)); } return $rows; } return ceil($columnWidth / ($size - 2)); }, $this->_columnWidths, array_map(function ($val) { if (is_array($val)) { $encodings = array_fill(0, count($val), $this->app->encoding); return array_map('mb_strwidth', $val, $encodings); } return mb_strwidth($val, $this->app->encoding); }, $row) ); return max($rowsPerCell); }
[ "protected", "function", "calculateRowHeight", "(", "$", "row", ")", "{", "$", "rowsPerCell", "=", "array_map", "(", "function", "(", "$", "size", ",", "$", "columnWidth", ")", "{", "if", "(", "is_array", "(", "$", "columnWidth", ")", ")", "{", "$", "rows", "=", "0", ";", "foreach", "(", "$", "columnWidth", "as", "$", "width", ")", "{", "$", "rows", "+=", "ceil", "(", "$", "width", "/", "(", "$", "size", "-", "2", ")", ")", ";", "}", "return", "$", "rows", ";", "}", "return", "ceil", "(", "$", "columnWidth", "/", "(", "$", "size", "-", "2", ")", ")", ";", "}", ",", "$", "this", "->", "_columnWidths", ",", "array_map", "(", "function", "(", "$", "val", ")", "{", "if", "(", "is_array", "(", "$", "val", ")", ")", "{", "$", "encodings", "=", "array_fill", "(", "0", ",", "count", "(", "$", "val", ")", ",", "$", "this", "->", "app", "->", "encoding", ")", ";", "return", "array_map", "(", "'mb_strwidth'", ",", "$", "val", ",", "$", "encodings", ")", ";", "}", "return", "mb_strwidth", "(", "$", "val", ",", "$", "this", "->", "app", "->", "encoding", ")", ";", "}", ",", "$", "row", ")", ")", ";", "return", "max", "(", "$", "rowsPerCell", ")", ";", "}" ]
Calculate the height of a row. @param array $row @return int maximum row per cell @see \Yiisoft\Yii\Console\Widgets\Table::render()
[ "Calculate", "the", "height", "of", "a", "row", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Widgets/Table.php#L343-L367
yiisoft/yii-console
src/Widgets/Table.php
Table.getScreenWidth
protected function getScreenWidth() { if (!$this->_screenWidth) { $size = Console::getScreenSize(); $this->_screenWidth = $size[0] ?? self::DEFAULT_CONSOLE_SCREEN_WIDTH + self::CONSOLE_SCROLLBAR_OFFSET; } return $this->_screenWidth; }
php
protected function getScreenWidth() { if (!$this->_screenWidth) { $size = Console::getScreenSize(); $this->_screenWidth = $size[0] ?? self::DEFAULT_CONSOLE_SCREEN_WIDTH + self::CONSOLE_SCROLLBAR_OFFSET; } return $this->_screenWidth; }
[ "protected", "function", "getScreenWidth", "(", ")", "{", "if", "(", "!", "$", "this", "->", "_screenWidth", ")", "{", "$", "size", "=", "Console", "::", "getScreenSize", "(", ")", ";", "$", "this", "->", "_screenWidth", "=", "$", "size", "[", "0", "]", "??", "self", "::", "DEFAULT_CONSOLE_SCREEN_WIDTH", "+", "self", "::", "CONSOLE_SCROLLBAR_OFFSET", ";", "}", "return", "$", "this", "->", "_screenWidth", ";", "}" ]
Getting screen width. If it is not able to determine screen width, default value `123` will be set. @return int screen width
[ "Getting", "screen", "width", ".", "If", "it", "is", "not", "able", "to", "determine", "screen", "width", "default", "value", "123", "will", "be", "set", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Widgets/Table.php#L375-L383
yiisoft/yii-jquery
src/Validators/Client/BooleanValidator.php
BooleanValidator.getClientOptions
public function getClientOptions($validator, $model, $attribute) { $options = [ 'trueValue' => $validator->trueValue, 'falseValue' => $validator->falseValue, 'message' => $validator->formatMessage($validator->message, [ 'attribute' => $model->getAttributeLabel($attribute), 'true' => $validator->trueValue === true ? 'true' : $validator->trueValue, 'false' => $validator->falseValue === false ? 'false' : $validator->falseValue, ]), ]; if ($validator->skipOnEmpty) { $options['skipOnEmpty'] = 1; } if ($validator->strict) { $options['strict'] = 1; } return $options; }
php
public function getClientOptions($validator, $model, $attribute) { $options = [ 'trueValue' => $validator->trueValue, 'falseValue' => $validator->falseValue, 'message' => $validator->formatMessage($validator->message, [ 'attribute' => $model->getAttributeLabel($attribute), 'true' => $validator->trueValue === true ? 'true' : $validator->trueValue, 'false' => $validator->falseValue === false ? 'false' : $validator->falseValue, ]), ]; if ($validator->skipOnEmpty) { $options['skipOnEmpty'] = 1; } if ($validator->strict) { $options['strict'] = 1; } return $options; }
[ "public", "function", "getClientOptions", "(", "$", "validator", ",", "$", "model", ",", "$", "attribute", ")", "{", "$", "options", "=", "[", "'trueValue'", "=>", "$", "validator", "->", "trueValue", ",", "'falseValue'", "=>", "$", "validator", "->", "falseValue", ",", "'message'", "=>", "$", "validator", "->", "formatMessage", "(", "$", "validator", "->", "message", ",", "[", "'attribute'", "=>", "$", "model", "->", "getAttributeLabel", "(", "$", "attribute", ")", ",", "'true'", "=>", "$", "validator", "->", "trueValue", "===", "true", "?", "'true'", ":", "$", "validator", "->", "trueValue", ",", "'false'", "=>", "$", "validator", "->", "falseValue", "===", "false", "?", "'false'", ":", "$", "validator", "->", "falseValue", ",", "]", ")", ",", "]", ";", "if", "(", "$", "validator", "->", "skipOnEmpty", ")", "{", "$", "options", "[", "'skipOnEmpty'", "]", "=", "1", ";", "}", "if", "(", "$", "validator", "->", "strict", ")", "{", "$", "options", "[", "'strict'", "]", "=", "1", ";", "}", "return", "$", "options", ";", "}" ]
Returns the client-side validation options. @param \yii\validators\BooleanValidator $validator the server-side validator. @param \yii\base\Model $model the model being validated @param string $attribute the attribute name being validated @return array the client-side validation options
[ "Returns", "the", "client", "-", "side", "validation", "options", "." ]
train
https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/Validators/Client/BooleanValidator.php#L41-L60
yiisoft/yii-console
src/Exceptions/UnknownCommandException.php
UnknownCommandException.getSuggestedAlternatives
public function getSuggestedAlternatives() { $help = $this->application->createController('help'); if ($help === false || $this->command === '') { return []; } /** @var $helpController HelpController */ [$helpController, $actionID] = $help; $availableActions = []; foreach ($helpController->getCommands() as $command) { $result = $this->application->createController($command); if ($result === false) { continue; } // add the command itself (default action) $availableActions[] = $command; // add all actions of this controller /** @var $controller Controller */ [$controller, $actionID] = $result; $actions = $helpController->getActions($controller); if (!empty($actions)) { $prefix = $controller->getUniqueId(); foreach ($actions as $action) { $availableActions[] = $prefix . '/' . $action; } } } return $this->filterBySimilarity($availableActions, $this->command); }
php
public function getSuggestedAlternatives() { $help = $this->application->createController('help'); if ($help === false || $this->command === '') { return []; } /** @var $helpController HelpController */ [$helpController, $actionID] = $help; $availableActions = []; foreach ($helpController->getCommands() as $command) { $result = $this->application->createController($command); if ($result === false) { continue; } // add the command itself (default action) $availableActions[] = $command; // add all actions of this controller /** @var $controller Controller */ [$controller, $actionID] = $result; $actions = $helpController->getActions($controller); if (!empty($actions)) { $prefix = $controller->getUniqueId(); foreach ($actions as $action) { $availableActions[] = $prefix . '/' . $action; } } } return $this->filterBySimilarity($availableActions, $this->command); }
[ "public", "function", "getSuggestedAlternatives", "(", ")", "{", "$", "help", "=", "$", "this", "->", "application", "->", "createController", "(", "'help'", ")", ";", "if", "(", "$", "help", "===", "false", "||", "$", "this", "->", "command", "===", "''", ")", "{", "return", "[", "]", ";", "}", "/** @var $helpController HelpController */", "[", "$", "helpController", ",", "$", "actionID", "]", "=", "$", "help", ";", "$", "availableActions", "=", "[", "]", ";", "foreach", "(", "$", "helpController", "->", "getCommands", "(", ")", "as", "$", "command", ")", "{", "$", "result", "=", "$", "this", "->", "application", "->", "createController", "(", "$", "command", ")", ";", "if", "(", "$", "result", "===", "false", ")", "{", "continue", ";", "}", "// add the command itself (default action)", "$", "availableActions", "[", "]", "=", "$", "command", ";", "// add all actions of this controller", "/** @var $controller Controller */", "[", "$", "controller", ",", "$", "actionID", "]", "=", "$", "result", ";", "$", "actions", "=", "$", "helpController", "->", "getActions", "(", "$", "controller", ")", ";", "if", "(", "!", "empty", "(", "$", "actions", ")", ")", "{", "$", "prefix", "=", "$", "controller", "->", "getUniqueId", "(", ")", ";", "foreach", "(", "$", "actions", "as", "$", "action", ")", "{", "$", "availableActions", "[", "]", "=", "$", "prefix", ".", "'/'", ".", "$", "action", ";", "}", "}", "}", "return", "$", "this", "->", "filterBySimilarity", "(", "$", "availableActions", ",", "$", "this", "->", "command", ")", ";", "}" ]
Suggest alternative commands for [[$command]] based on string similarity. Alternatives are searched using the following steps: - suggest alternatives that begin with `$command` - find typos by calculating the Levenshtein distance between the unknown command and all available commands. The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete to transform str1 into str2. @see http://php.net/manual/en/function.levenshtein.php @return array a list of suggested alternatives sorted by similarity.
[ "Suggest", "alternative", "commands", "for", "[[", "$command", "]]", "based", "on", "string", "similarity", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Exceptions/UnknownCommandException.php#L68-L99
yiisoft/yii-console
src/Exceptions/UnknownCommandException.php
UnknownCommandException.filterBySimilarity
private function filterBySimilarity($actions, $command) { $alternatives = []; // suggest alternatives that begin with $command first foreach ($actions as $action) { if (strpos($action, $command) === 0) { $alternatives[] = $action; } } // calculate the Levenshtein distance between the unknown command and all available commands. $distances = array_map(function ($action) use ($command) { $action = strlen($action) > 255 ? substr($action, 0, 255) : $action; $command = strlen($command) > 255 ? substr($command, 0, 255) : $command; return levenshtein($action, $command); }, array_combine($actions, $actions)); // we assume a typo if the levensthein distance is no more than 3, i.e. 3 replacements needed $relevantTypos = array_filter($distances, function ($distance) { return $distance <= 3; }); asort($relevantTypos); $alternatives = array_merge($alternatives, array_flip($relevantTypos)); return array_unique($alternatives); }
php
private function filterBySimilarity($actions, $command) { $alternatives = []; // suggest alternatives that begin with $command first foreach ($actions as $action) { if (strpos($action, $command) === 0) { $alternatives[] = $action; } } // calculate the Levenshtein distance between the unknown command and all available commands. $distances = array_map(function ($action) use ($command) { $action = strlen($action) > 255 ? substr($action, 0, 255) : $action; $command = strlen($command) > 255 ? substr($command, 0, 255) : $command; return levenshtein($action, $command); }, array_combine($actions, $actions)); // we assume a typo if the levensthein distance is no more than 3, i.e. 3 replacements needed $relevantTypos = array_filter($distances, function ($distance) { return $distance <= 3; }); asort($relevantTypos); $alternatives = array_merge($alternatives, array_flip($relevantTypos)); return array_unique($alternatives); }
[ "private", "function", "filterBySimilarity", "(", "$", "actions", ",", "$", "command", ")", "{", "$", "alternatives", "=", "[", "]", ";", "// suggest alternatives that begin with $command first", "foreach", "(", "$", "actions", "as", "$", "action", ")", "{", "if", "(", "strpos", "(", "$", "action", ",", "$", "command", ")", "===", "0", ")", "{", "$", "alternatives", "[", "]", "=", "$", "action", ";", "}", "}", "// calculate the Levenshtein distance between the unknown command and all available commands.", "$", "distances", "=", "array_map", "(", "function", "(", "$", "action", ")", "use", "(", "$", "command", ")", "{", "$", "action", "=", "strlen", "(", "$", "action", ")", ">", "255", "?", "substr", "(", "$", "action", ",", "0", ",", "255", ")", ":", "$", "action", ";", "$", "command", "=", "strlen", "(", "$", "command", ")", ">", "255", "?", "substr", "(", "$", "command", ",", "0", ",", "255", ")", ":", "$", "command", ";", "return", "levenshtein", "(", "$", "action", ",", "$", "command", ")", ";", "}", ",", "array_combine", "(", "$", "actions", ",", "$", "actions", ")", ")", ";", "// we assume a typo if the levensthein distance is no more than 3, i.e. 3 replacements needed", "$", "relevantTypos", "=", "array_filter", "(", "$", "distances", ",", "function", "(", "$", "distance", ")", "{", "return", "$", "distance", "<=", "3", ";", "}", ")", ";", "asort", "(", "$", "relevantTypos", ")", ";", "$", "alternatives", "=", "array_merge", "(", "$", "alternatives", ",", "array_flip", "(", "$", "relevantTypos", ")", ")", ";", "return", "array_unique", "(", "$", "alternatives", ")", ";", "}" ]
Find suggest alternative commands based on string similarity. Alternatives are searched using the following steps: - suggest alternatives that begin with `$command` - find typos by calculating the Levenshtein distance between the unknown command and all available commands. The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete to transform str1 into str2. @see http://php.net/manual/en/function.levenshtein.php @param array $actions available command names. @param string $command the command to compare to. @return array a list of suggested alternatives sorted by similarity.
[ "Find", "suggest", "alternative", "commands", "based", "on", "string", "similarity", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Exceptions/UnknownCommandException.php#L116-L142
yiisoft/yii-console
src/Controllers/MessageController.php
MessageController.actionConfig
public function actionConfig($filePath) { $filePath = $this->app->getAlias($filePath); if (file_exists($filePath)) { if (!$this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?")) { return ExitCode::OK; } } $array = VarDumper::export($this->getOptionValues($this->action->id)); $content = <<<EOD <?php /** * Configuration file for 'yii {$this->id}/{$this->defaultAction}' command. * * This file is automatically generated by 'yii {$this->id}/{$this->action->id}' command. * It contains parameters for source code messages extraction. * You may modify this file to suit your needs. * * You can use 'yii {$this->id}/{$this->action->id}-template' command to create * template configuration file with detailed description for each parameter. */ return $array; EOD; if (file_put_contents($filePath, $content, LOCK_EX) === false) { $this->stdout("Configuration file was NOT created: '{$filePath}'.\n\n", Console::FG_RED); return ExitCode::UNSPECIFIED_ERROR; } $this->stdout("Configuration file created: '{$filePath}'.\n\n", Console::FG_GREEN); return ExitCode::OK; }
php
public function actionConfig($filePath) { $filePath = $this->app->getAlias($filePath); if (file_exists($filePath)) { if (!$this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?")) { return ExitCode::OK; } } $array = VarDumper::export($this->getOptionValues($this->action->id)); $content = <<<EOD <?php /** * Configuration file for 'yii {$this->id}/{$this->defaultAction}' command. * * This file is automatically generated by 'yii {$this->id}/{$this->action->id}' command. * It contains parameters for source code messages extraction. * You may modify this file to suit your needs. * * You can use 'yii {$this->id}/{$this->action->id}-template' command to create * template configuration file with detailed description for each parameter. */ return $array; EOD; if (file_put_contents($filePath, $content, LOCK_EX) === false) { $this->stdout("Configuration file was NOT created: '{$filePath}'.\n\n", Console::FG_RED); return ExitCode::UNSPECIFIED_ERROR; } $this->stdout("Configuration file created: '{$filePath}'.\n\n", Console::FG_GREEN); return ExitCode::OK; }
[ "public", "function", "actionConfig", "(", "$", "filePath", ")", "{", "$", "filePath", "=", "$", "this", "->", "app", "->", "getAlias", "(", "$", "filePath", ")", ";", "if", "(", "file_exists", "(", "$", "filePath", ")", ")", "{", "if", "(", "!", "$", "this", "->", "confirm", "(", "\"File '{$filePath}' already exists. Do you wish to overwrite it?\"", ")", ")", "{", "return", "ExitCode", "::", "OK", ";", "}", "}", "$", "array", "=", "VarDumper", "::", "export", "(", "$", "this", "->", "getOptionValues", "(", "$", "this", "->", "action", "->", "id", ")", ")", ";", "$", "content", "=", " <<<EOD\n<?php\n/**\n * Configuration file for 'yii {$this->id}/{$this->defaultAction}' command.\n *\n * This file is automatically generated by 'yii {$this->id}/{$this->action->id}' command.\n * It contains parameters for source code messages extraction.\n * You may modify this file to suit your needs.\n *\n * You can use 'yii {$this->id}/{$this->action->id}-template' command to create\n * template configuration file with detailed description for each parameter.\n */\nreturn $array;\n\nEOD", ";", "if", "(", "file_put_contents", "(", "$", "filePath", ",", "$", "content", ",", "LOCK_EX", ")", "===", "false", ")", "{", "$", "this", "->", "stdout", "(", "\"Configuration file was NOT created: '{$filePath}'.\\n\\n\"", ",", "Console", "::", "FG_RED", ")", ";", "return", "ExitCode", "::", "UNSPECIFIED_ERROR", ";", "}", "$", "this", "->", "stdout", "(", "\"Configuration file created: '{$filePath}'.\\n\\n\"", ",", "Console", "::", "FG_GREEN", ")", ";", "return", "ExitCode", "::", "OK", ";", "}" ]
Creates a configuration file for the "extract" command using command line options specified. The generated configuration file contains parameters required for source code messages extraction. You may use this configuration file with the "extract" command. @param string $filePath output file name or alias. @return int CLI exit code @throws Exception on failure.
[ "Creates", "a", "configuration", "file", "for", "the", "extract", "command", "using", "command", "line", "options", "specified", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/MessageController.php#L217-L250
yiisoft/yii-console
src/Controllers/MessageController.php
MessageController.saveMessagesToPHP
protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort, $markUnused) { foreach ($messages as $category => $msgs) { $file = str_replace('\\', '/', "$dirName/$category.php"); $path = dirname($file); FileHelper::createDirectory($path); $msgs = array_values(array_unique($msgs)); $coloredFileName = Console::ansiFormat($file, [Console::FG_CYAN]); $this->stdout("Saving messages to $coloredFileName...\n"); $this->saveMessagesCategoryToPHP($msgs, $file, $overwrite, $removeUnused, $sort, $category, $markUnused); } }
php
protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort, $markUnused) { foreach ($messages as $category => $msgs) { $file = str_replace('\\', '/', "$dirName/$category.php"); $path = dirname($file); FileHelper::createDirectory($path); $msgs = array_values(array_unique($msgs)); $coloredFileName = Console::ansiFormat($file, [Console::FG_CYAN]); $this->stdout("Saving messages to $coloredFileName...\n"); $this->saveMessagesCategoryToPHP($msgs, $file, $overwrite, $removeUnused, $sort, $category, $markUnused); } }
[ "protected", "function", "saveMessagesToPHP", "(", "$", "messages", ",", "$", "dirName", ",", "$", "overwrite", ",", "$", "removeUnused", ",", "$", "sort", ",", "$", "markUnused", ")", "{", "foreach", "(", "$", "messages", "as", "$", "category", "=>", "$", "msgs", ")", "{", "$", "file", "=", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "\"$dirName/$category.php\"", ")", ";", "$", "path", "=", "dirname", "(", "$", "file", ")", ";", "FileHelper", "::", "createDirectory", "(", "$", "path", ")", ";", "$", "msgs", "=", "array_values", "(", "array_unique", "(", "$", "msgs", ")", ")", ";", "$", "coloredFileName", "=", "Console", "::", "ansiFormat", "(", "$", "file", ",", "[", "Console", "::", "FG_CYAN", "]", ")", ";", "$", "this", "->", "stdout", "(", "\"Saving messages to $coloredFileName...\\n\"", ")", ";", "$", "this", "->", "saveMessagesCategoryToPHP", "(", "$", "msgs", ",", "$", "file", ",", "$", "overwrite", ",", "$", "removeUnused", ",", "$", "sort", ",", "$", "category", ",", "$", "markUnused", ")", ";", "}", "}" ]
Writes messages into PHP files. @param array $messages @param string $dirName name of the directory to write to @param bool $overwrite if existing file should be overwritten without backup @param bool $removeUnused if obsolete translations should be removed @param bool $sort if translations should be sorted @param bool $markUnused if obsolete translations should be marked
[ "Writes", "messages", "into", "PHP", "files", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/MessageController.php#L649-L660
yiisoft/yii-console
src/Controllers/MessageController.php
MessageController.saveMessagesCategoryToPHP
protected function saveMessagesCategoryToPHP($messages, $fileName, $overwrite, $removeUnused, $sort, $category, $markUnused) { if (is_file($fileName)) { $rawExistingMessages = require $fileName; $existingMessages = $rawExistingMessages; sort($messages); ksort($existingMessages); if (array_keys($existingMessages) === $messages && (!$sort || array_keys($rawExistingMessages) === $messages)) { $this->stdout("Nothing new in \"$category\" category... Nothing to save.\n\n", Console::FG_GREEN); return ExitCode::OK; } unset($rawExistingMessages); $merged = []; $untranslated = []; foreach ($messages as $message) { if (array_key_exists($message, $existingMessages) && $existingMessages[$message] !== '') { $merged[$message] = $existingMessages[$message]; } else { $untranslated[] = $message; } } ksort($merged); sort($untranslated); $todo = []; foreach ($untranslated as $message) { $todo[$message] = ''; } ksort($existingMessages); foreach ($existingMessages as $message => $translation) { if (!$removeUnused && !isset($merged[$message]) && !isset($todo[$message])) { if (!$markUnused || (!empty($translation) && (strncmp($translation, '@@', 2) === 0 && substr_compare($translation, '@@', -2, 2) === 0))) { $todo[$message] = $translation; } else { $todo[$message] = '@@' . $translation . '@@'; } } } $merged = array_merge($todo, $merged); if ($sort) { ksort($merged); } if (false === $overwrite) { $fileName .= '.merged'; } $this->stdout("Translation merged.\n"); } else { $merged = []; foreach ($messages as $message) { $merged[$message] = ''; } ksort($merged); } $array = VarDumper::export($merged); $content = <<<EOD <?php {$this->config['phpFileHeader']}{$this->config['phpDocBlock']} return $array; EOD; if (file_put_contents($fileName, $content, LOCK_EX) === false) { $this->stdout("Translation was NOT saved.\n\n", Console::FG_RED); return ExitCode::UNSPECIFIED_ERROR; } $this->stdout("Translation saved.\n\n", Console::FG_GREEN); return ExitCode::OK; }
php
protected function saveMessagesCategoryToPHP($messages, $fileName, $overwrite, $removeUnused, $sort, $category, $markUnused) { if (is_file($fileName)) { $rawExistingMessages = require $fileName; $existingMessages = $rawExistingMessages; sort($messages); ksort($existingMessages); if (array_keys($existingMessages) === $messages && (!$sort || array_keys($rawExistingMessages) === $messages)) { $this->stdout("Nothing new in \"$category\" category... Nothing to save.\n\n", Console::FG_GREEN); return ExitCode::OK; } unset($rawExistingMessages); $merged = []; $untranslated = []; foreach ($messages as $message) { if (array_key_exists($message, $existingMessages) && $existingMessages[$message] !== '') { $merged[$message] = $existingMessages[$message]; } else { $untranslated[] = $message; } } ksort($merged); sort($untranslated); $todo = []; foreach ($untranslated as $message) { $todo[$message] = ''; } ksort($existingMessages); foreach ($existingMessages as $message => $translation) { if (!$removeUnused && !isset($merged[$message]) && !isset($todo[$message])) { if (!$markUnused || (!empty($translation) && (strncmp($translation, '@@', 2) === 0 && substr_compare($translation, '@@', -2, 2) === 0))) { $todo[$message] = $translation; } else { $todo[$message] = '@@' . $translation . '@@'; } } } $merged = array_merge($todo, $merged); if ($sort) { ksort($merged); } if (false === $overwrite) { $fileName .= '.merged'; } $this->stdout("Translation merged.\n"); } else { $merged = []; foreach ($messages as $message) { $merged[$message] = ''; } ksort($merged); } $array = VarDumper::export($merged); $content = <<<EOD <?php {$this->config['phpFileHeader']}{$this->config['phpDocBlock']} return $array; EOD; if (file_put_contents($fileName, $content, LOCK_EX) === false) { $this->stdout("Translation was NOT saved.\n\n", Console::FG_RED); return ExitCode::UNSPECIFIED_ERROR; } $this->stdout("Translation saved.\n\n", Console::FG_GREEN); return ExitCode::OK; }
[ "protected", "function", "saveMessagesCategoryToPHP", "(", "$", "messages", ",", "$", "fileName", ",", "$", "overwrite", ",", "$", "removeUnused", ",", "$", "sort", ",", "$", "category", ",", "$", "markUnused", ")", "{", "if", "(", "is_file", "(", "$", "fileName", ")", ")", "{", "$", "rawExistingMessages", "=", "require", "$", "fileName", ";", "$", "existingMessages", "=", "$", "rawExistingMessages", ";", "sort", "(", "$", "messages", ")", ";", "ksort", "(", "$", "existingMessages", ")", ";", "if", "(", "array_keys", "(", "$", "existingMessages", ")", "===", "$", "messages", "&&", "(", "!", "$", "sort", "||", "array_keys", "(", "$", "rawExistingMessages", ")", "===", "$", "messages", ")", ")", "{", "$", "this", "->", "stdout", "(", "\"Nothing new in \\\"$category\\\" category... Nothing to save.\\n\\n\"", ",", "Console", "::", "FG_GREEN", ")", ";", "return", "ExitCode", "::", "OK", ";", "}", "unset", "(", "$", "rawExistingMessages", ")", ";", "$", "merged", "=", "[", "]", ";", "$", "untranslated", "=", "[", "]", ";", "foreach", "(", "$", "messages", "as", "$", "message", ")", "{", "if", "(", "array_key_exists", "(", "$", "message", ",", "$", "existingMessages", ")", "&&", "$", "existingMessages", "[", "$", "message", "]", "!==", "''", ")", "{", "$", "merged", "[", "$", "message", "]", "=", "$", "existingMessages", "[", "$", "message", "]", ";", "}", "else", "{", "$", "untranslated", "[", "]", "=", "$", "message", ";", "}", "}", "ksort", "(", "$", "merged", ")", ";", "sort", "(", "$", "untranslated", ")", ";", "$", "todo", "=", "[", "]", ";", "foreach", "(", "$", "untranslated", "as", "$", "message", ")", "{", "$", "todo", "[", "$", "message", "]", "=", "''", ";", "}", "ksort", "(", "$", "existingMessages", ")", ";", "foreach", "(", "$", "existingMessages", "as", "$", "message", "=>", "$", "translation", ")", "{", "if", "(", "!", "$", "removeUnused", "&&", "!", "isset", "(", "$", "merged", "[", "$", "message", "]", ")", "&&", "!", "isset", "(", "$", "todo", "[", "$", "message", "]", ")", ")", "{", "if", "(", "!", "$", "markUnused", "||", "(", "!", "empty", "(", "$", "translation", ")", "&&", "(", "strncmp", "(", "$", "translation", ",", "'@@'", ",", "2", ")", "===", "0", "&&", "substr_compare", "(", "$", "translation", ",", "'@@'", ",", "-", "2", ",", "2", ")", "===", "0", ")", ")", ")", "{", "$", "todo", "[", "$", "message", "]", "=", "$", "translation", ";", "}", "else", "{", "$", "todo", "[", "$", "message", "]", "=", "'@@'", ".", "$", "translation", ".", "'@@'", ";", "}", "}", "}", "$", "merged", "=", "array_merge", "(", "$", "todo", ",", "$", "merged", ")", ";", "if", "(", "$", "sort", ")", "{", "ksort", "(", "$", "merged", ")", ";", "}", "if", "(", "false", "===", "$", "overwrite", ")", "{", "$", "fileName", ".=", "'.merged'", ";", "}", "$", "this", "->", "stdout", "(", "\"Translation merged.\\n\"", ")", ";", "}", "else", "{", "$", "merged", "=", "[", "]", ";", "foreach", "(", "$", "messages", "as", "$", "message", ")", "{", "$", "merged", "[", "$", "message", "]", "=", "''", ";", "}", "ksort", "(", "$", "merged", ")", ";", "}", "$", "array", "=", "VarDumper", "::", "export", "(", "$", "merged", ")", ";", "$", "content", "=", " <<<EOD\n<?php\n{$this->config['phpFileHeader']}{$this->config['phpDocBlock']}\nreturn $array;\n\nEOD", ";", "if", "(", "file_put_contents", "(", "$", "fileName", ",", "$", "content", ",", "LOCK_EX", ")", "===", "false", ")", "{", "$", "this", "->", "stdout", "(", "\"Translation was NOT saved.\\n\\n\"", ",", "Console", "::", "FG_RED", ")", ";", "return", "ExitCode", "::", "UNSPECIFIED_ERROR", ";", "}", "$", "this", "->", "stdout", "(", "\"Translation saved.\\n\\n\"", ",", "Console", "::", "FG_GREEN", ")", ";", "return", "ExitCode", "::", "OK", ";", "}" ]
Writes category messages into PHP file. @param array $messages @param string $fileName name of the file to write to @param bool $overwrite if existing file should be overwritten without backup @param bool $removeUnused if obsolete translations should be removed @param bool $sort if translations should be sorted @param string $category message category @param bool $markUnused if obsolete translations should be marked @return int exit code
[ "Writes", "category", "messages", "into", "PHP", "file", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/MessageController.php#L674-L742
yiisoft/yii-console
src/Controllers/BaseMigrateController.php
BaseMigrateController.getNewMigrations
protected function getNewMigrations() { $applied = []; foreach ($this->getMigrationHistory(null) as $class => $time) { $applied[trim($class, '\\')] = true; } $migrationPaths = []; if (is_array($this->migrationPath)) { foreach ($this->migrationPath as $path) { $migrationPaths[] = [$path, '']; } } elseif (!empty($this->migrationPath)) { $migrationPaths[] = [$this->migrationPath, '']; } foreach ($this->migrationNamespaces as $namespace) { $migrationPaths[] = [$this->getNamespacePath($namespace), $namespace]; } $migrations = []; foreach ($migrationPaths as $item) { [$migrationPath, $namespace] = $item; if (!file_exists($migrationPath)) { continue; } $handle = opendir($migrationPath); while (($file = readdir($handle)) !== false) { if ($file === '.' || $file === '..') { continue; } $path = $migrationPath . DIRECTORY_SEPARATOR . $file; if (preg_match('/^(m(\d{6}_?\d{6})\D.*?)\.php$/is', $file, $matches) && is_file($path)) { $class = $matches[1]; if (!empty($namespace)) { $class = $namespace . '\\' . $class; } $time = str_replace('_', '', $matches[2]); if (!isset($applied[$class])) { $migrations[$time . '\\' . $class] = $class; } } } closedir($handle); } ksort($migrations); return array_values($migrations); }
php
protected function getNewMigrations() { $applied = []; foreach ($this->getMigrationHistory(null) as $class => $time) { $applied[trim($class, '\\')] = true; } $migrationPaths = []; if (is_array($this->migrationPath)) { foreach ($this->migrationPath as $path) { $migrationPaths[] = [$path, '']; } } elseif (!empty($this->migrationPath)) { $migrationPaths[] = [$this->migrationPath, '']; } foreach ($this->migrationNamespaces as $namespace) { $migrationPaths[] = [$this->getNamespacePath($namespace), $namespace]; } $migrations = []; foreach ($migrationPaths as $item) { [$migrationPath, $namespace] = $item; if (!file_exists($migrationPath)) { continue; } $handle = opendir($migrationPath); while (($file = readdir($handle)) !== false) { if ($file === '.' || $file === '..') { continue; } $path = $migrationPath . DIRECTORY_SEPARATOR . $file; if (preg_match('/^(m(\d{6}_?\d{6})\D.*?)\.php$/is', $file, $matches) && is_file($path)) { $class = $matches[1]; if (!empty($namespace)) { $class = $namespace . '\\' . $class; } $time = str_replace('_', '', $matches[2]); if (!isset($applied[$class])) { $migrations[$time . '\\' . $class] = $class; } } } closedir($handle); } ksort($migrations); return array_values($migrations); }
[ "protected", "function", "getNewMigrations", "(", ")", "{", "$", "applied", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getMigrationHistory", "(", "null", ")", "as", "$", "class", "=>", "$", "time", ")", "{", "$", "applied", "[", "trim", "(", "$", "class", ",", "'\\\\'", ")", "]", "=", "true", ";", "}", "$", "migrationPaths", "=", "[", "]", ";", "if", "(", "is_array", "(", "$", "this", "->", "migrationPath", ")", ")", "{", "foreach", "(", "$", "this", "->", "migrationPath", "as", "$", "path", ")", "{", "$", "migrationPaths", "[", "]", "=", "[", "$", "path", ",", "''", "]", ";", "}", "}", "elseif", "(", "!", "empty", "(", "$", "this", "->", "migrationPath", ")", ")", "{", "$", "migrationPaths", "[", "]", "=", "[", "$", "this", "->", "migrationPath", ",", "''", "]", ";", "}", "foreach", "(", "$", "this", "->", "migrationNamespaces", "as", "$", "namespace", ")", "{", "$", "migrationPaths", "[", "]", "=", "[", "$", "this", "->", "getNamespacePath", "(", "$", "namespace", ")", ",", "$", "namespace", "]", ";", "}", "$", "migrations", "=", "[", "]", ";", "foreach", "(", "$", "migrationPaths", "as", "$", "item", ")", "{", "[", "$", "migrationPath", ",", "$", "namespace", "]", "=", "$", "item", ";", "if", "(", "!", "file_exists", "(", "$", "migrationPath", ")", ")", "{", "continue", ";", "}", "$", "handle", "=", "opendir", "(", "$", "migrationPath", ")", ";", "while", "(", "(", "$", "file", "=", "readdir", "(", "$", "handle", ")", ")", "!==", "false", ")", "{", "if", "(", "$", "file", "===", "'.'", "||", "$", "file", "===", "'..'", ")", "{", "continue", ";", "}", "$", "path", "=", "$", "migrationPath", ".", "DIRECTORY_SEPARATOR", ".", "$", "file", ";", "if", "(", "preg_match", "(", "'/^(m(\\d{6}_?\\d{6})\\D.*?)\\.php$/is'", ",", "$", "file", ",", "$", "matches", ")", "&&", "is_file", "(", "$", "path", ")", ")", "{", "$", "class", "=", "$", "matches", "[", "1", "]", ";", "if", "(", "!", "empty", "(", "$", "namespace", ")", ")", "{", "$", "class", "=", "$", "namespace", ".", "'\\\\'", ".", "$", "class", ";", "}", "$", "time", "=", "str_replace", "(", "'_'", ",", "''", ",", "$", "matches", "[", "2", "]", ")", ";", "if", "(", "!", "isset", "(", "$", "applied", "[", "$", "class", "]", ")", ")", "{", "$", "migrations", "[", "$", "time", ".", "'\\\\'", ".", "$", "class", "]", "=", "$", "class", ";", "}", "}", "}", "closedir", "(", "$", "handle", ")", ";", "}", "ksort", "(", "$", "migrations", ")", ";", "return", "array_values", "(", "$", "migrations", ")", ";", "}" ]
Returns the migrations that are not applied. @return array list of new migrations
[ "Returns", "the", "migrations", "that", "are", "not", "applied", "." ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/BaseMigrateController.php#L873-L920
yiisoft/yii-console
src/Controllers/BaseMigrateController.php
BaseMigrateController.generateMigrationSourceCode
protected function generateMigrationSourceCode($params) { return $this->renderFile($this->app->getAlias($this->templateFile), $params); }
php
protected function generateMigrationSourceCode($params) { return $this->renderFile($this->app->getAlias($this->templateFile), $params); }
[ "protected", "function", "generateMigrationSourceCode", "(", "$", "params", ")", "{", "return", "$", "this", "->", "renderFile", "(", "$", "this", "->", "app", "->", "getAlias", "(", "$", "this", "->", "templateFile", ")", ",", "$", "params", ")", ";", "}" ]
Generates new migration source PHP code. Child class may override this method, adding extra logic or variation to the process. @param array $params generation parameters, usually following parameters are present: - name: string migration base name - className: string migration class name @return string generated PHP code. @since 2.0.8
[ "Generates", "new", "migration", "source", "PHP", "code", ".", "Child", "class", "may", "override", "this", "method", "adding", "extra", "logic", "or", "variation", "to", "the", "process", ".", "@param", "array", "$params", "generation", "parameters", "usually", "following", "parameters", "are", "present", ":" ]
train
https://github.com/yiisoft/yii-console/blob/b9fb24f8897b4389935738f63b28d82b7e25cc41/src/Controllers/BaseMigrateController.php#L933-L936
yiisoft/yii-jquery
src/GridViewClientScript.php
GridViewClientScript.beforeRun
public function beforeRun($event) { $id = $this->owner->options['id']; $options = Json::htmlEncode($this->getClientOptions()); $view = $this->owner->getView(); GridViewAsset::register($view); $view->registerJs("jQuery('#$id').yiiGridView($options);"); }
php
public function beforeRun($event) { $id = $this->owner->options['id']; $options = Json::htmlEncode($this->getClientOptions()); $view = $this->owner->getView(); GridViewAsset::register($view); $view->registerJs("jQuery('#$id').yiiGridView($options);"); }
[ "public", "function", "beforeRun", "(", "$", "event", ")", "{", "$", "id", "=", "$", "this", "->", "owner", "->", "options", "[", "'id'", "]", ";", "$", "options", "=", "Json", "::", "htmlEncode", "(", "$", "this", "->", "getClientOptions", "(", ")", ")", ";", "$", "view", "=", "$", "this", "->", "owner", "->", "getView", "(", ")", ";", "GridViewAsset", "::", "register", "(", "$", "view", ")", ";", "$", "view", "->", "registerJs", "(", "\"jQuery('#$id').yiiGridView($options);\"", ")", ";", "}" ]
Handles [[Widget::EVENT_BEFORE_RUN]] event, registering related client script. @param \yii\base\Event $event event instance.
[ "Handles", "[[", "Widget", "::", "EVENT_BEFORE_RUN", "]]", "event", "registering", "related", "client", "script", "." ]
train
https://github.com/yiisoft/yii-jquery/blob/1c257928cba2b46d267e90771652abe2b0e2cfcb/src/GridViewClientScript.php#L68-L75
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.applyOnOutput
public function applyOnOutput(HttpAdapter $http = null, $mode = true) { if ($mode == true) { if ($this->applyOnOutput === null) { ob_start([$this, 'returnBuffer']); } $this->applyOnOutput = $http; } elseif ($this->applyOnOutput !== null) { ob_end_clean(); $this->applyOnOutput = null; } }
php
public function applyOnOutput(HttpAdapter $http = null, $mode = true) { if ($mode == true) { if ($this->applyOnOutput === null) { ob_start([$this, 'returnBuffer']); } $this->applyOnOutput = $http; } elseif ($this->applyOnOutput !== null) { ob_end_clean(); $this->applyOnOutput = null; } }
[ "public", "function", "applyOnOutput", "(", "HttpAdapter", "$", "http", "=", "null", ",", "$", "mode", "=", "true", ")", "{", "if", "(", "$", "mode", "==", "true", ")", "{", "if", "(", "$", "this", "->", "applyOnOutput", "===", "null", ")", "{", "ob_start", "(", "[", "$", "this", ",", "'returnBuffer'", "]", ")", ";", "}", "$", "this", "->", "applyOnOutput", "=", "$", "http", ";", "}", "elseif", "(", "$", "this", "->", "applyOnOutput", "!==", "null", ")", "{", "ob_end_clean", "(", ")", ";", "$", "this", "->", "applyOnOutput", "=", "null", ";", "}", "}" ]
Used to enable or disable output buffering with ob_start. When enabled, the ob_start callback will be set to automatically call {@see apply} upon the first byte of output. If unconfigured, the default setting for {@see applyOnOutput} is off. @api @param HttpAdapter $http @param mixed $mode mode is the on/off setting. Any value of type that is loosely castable to a boolean is valid. Passing a boolean of value true will turn output buffering on, passing a boolean of value false will turn it off. The integers 1 and 0 will do the same respectively. @return void
[ "Used", "to", "enable", "or", "disable", "output", "buffering", "with", "ob_start", ".", "When", "enabled", "the", "ob_start", "callback", "will", "be", "set", "to", "automatically", "call", "{", "@see", "apply", "}", "upon", "the", "first", "byte", "of", "output", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L243-L260
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.safeModeException
public function safeModeException($name) { Types::assert(['string' => [$name]]); $this->safeModeExceptions[strtolower($name)] = true; }
php
public function safeModeException($name) { Types::assert(['string' => [$name]]); $this->safeModeExceptions[strtolower($name)] = true; }
[ "public", "function", "safeModeException", "(", "$", "name", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "name", "]", "]", ")", ";", "$", "this", "->", "safeModeExceptions", "[", "strtolower", "(", "$", "name", ")", "]", "=", "true", ";", "}" ]
Used to add an exception to {@see safeMode}. @api @param string $name Specify the name of the header that you wish to be exempt from {@see safeMode} warnings and auto-modification. (Note that if you want to turn safe mode off for all headers, use [`->safeMode(false)`](safeMode) – safe mode is **not** on by default). @return void
[ "Used", "to", "add", "an", "exception", "to", "{", "@see", "safeMode", "}", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L308-L313
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.auto
public function auto($mode = self::AUTO_ALL) { Types::assert(['int' => [$mode]]); $this->automaticHeaders = $mode; }
php
public function auto($mode = self::AUTO_ALL) { Types::assert(['int' => [$mode]]); $this->automaticHeaders = $mode; }
[ "public", "function", "auto", "(", "$", "mode", "=", "self", "::", "AUTO_ALL", ")", "{", "Types", "::", "assert", "(", "[", "'int'", "=>", "[", "$", "mode", "]", "]", ")", ";", "$", "this", "->", "automaticHeaders", "=", "$", "mode", ";", "}" ]
Enable or disable certain automatically applied header functions If unconfigured, the default setting is {@see AUTO_ALL}. @api @param int $mode `auto` accepts one or more of the following constants. Multiple constants may be specified by combination using [bitwise operators](https://secure.php.net/manual/language.operators.bitwise.php). You are **strongly** advised to make use of the constants by name, and **not** by value. Constant values may be updated at any time without a major version bump. @return void
[ "Enable", "or", "disable", "certain", "automatically", "applied", "header", "functions" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L432-L437
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.sameSiteCookies
public function sameSiteCookies($mode = null) { Types::assert(['?string' => [$mode]]); if (isset($mode)) { $mode = strtolower($mode); } if ($mode === 'lax' or $mode === 'strict') { $this->sameSiteCookies = ucfirst($mode); } elseif ( ! isset($mode)) { $this->sameSiteCookies = null; } }
php
public function sameSiteCookies($mode = null) { Types::assert(['?string' => [$mode]]); if (isset($mode)) { $mode = strtolower($mode); } if ($mode === 'lax' or $mode === 'strict') { $this->sameSiteCookies = ucfirst($mode); } elseif ( ! isset($mode)) { $this->sameSiteCookies = null; } }
[ "public", "function", "sameSiteCookies", "(", "$", "mode", "=", "null", ")", "{", "Types", "::", "assert", "(", "[", "'?string'", "=>", "[", "$", "mode", "]", "]", ")", ";", "if", "(", "isset", "(", "$", "mode", ")", ")", "{", "$", "mode", "=", "strtolower", "(", "$", "mode", ")", ";", "}", "if", "(", "$", "mode", "===", "'lax'", "or", "$", "mode", "===", "'strict'", ")", "{", "$", "this", "->", "sameSiteCookies", "=", "ucfirst", "(", "$", "mode", ")", ";", "}", "elseif", "(", "!", "isset", "(", "$", "mode", ")", ")", "{", "$", "this", "->", "sameSiteCookies", "=", "null", ";", "}", "}" ]
Add and configure the default setting for [protected cookies](protectedCookie) that are automatically marked as `SameSite`. If this setting is unspecified the default will be `SameSite=Lax`, if this setting is given an invalid `string` setting the last setting will be honoured. If {@see strictMode} is enabled then the default will be `SameSite=Strict` under the same criteria for set value. If you wish to disable making cookies as same site, see [`->auto`](auto#AUTO_COOKIE_SAMESITE). @api @param ?string $mode Valid values for `$mode` are either (case-insensitively) the strings `'Lax'` and `'Strict'`. If `null` is passed the setting will revert to the default as defined above. If another `string` is passed then the call will be ignored and the previous setting will be retained (if no setting was specified previously then the default will remain). @return void
[ "Add", "and", "configure", "the", "default", "setting", "for", "[", "protected", "cookies", "]", "(", "protectedCookie", ")", "that", "are", "automatically", "marked", "as", "SameSite", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L491-L508
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.removeHeader
public function removeHeader($name) { Types::assert(['string' => [$name]]); $name = strtolower($name); $this->removedHeaders[$name] = true; }
php
public function removeHeader($name) { Types::assert(['string' => [$name]]); $name = strtolower($name); $this->removedHeaders[$name] = true; }
[ "public", "function", "removeHeader", "(", "$", "name", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "name", "]", "]", ")", ";", "$", "name", "=", "strtolower", "(", "$", "name", ")", ";", "$", "this", "->", "removedHeaders", "[", "$", "name", "]", "=", "true", ";", "}" ]
Queue a header for removal. Upon calling {@see apply} the header will be removed. This function can be used to manually prevent [automatic headers](auto) from being sent. @api @param string $name Case insensitive name of the header to remove. @return void
[ "Queue", "a", "header", "for", "removal", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L526-L532
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.protectedCookie
public function protectedCookie( $name, $mode = self::COOKIE_DEFAULT ) { Types::assert( [ 'string|array' => [$name], 'int' => [$mode] ] ); if (is_string($name)) { $name = strtolower($name); } elseif (is_array($name)) { foreach ($name as $cookie) { $this->protectedCookie($cookie, $mode); } return; } $stringTypes = []; if (($mode & self::COOKIE_NAME) === self::COOKIE_NAME) { $stringTypes[] = 'names'; } if (($mode & self::COOKIE_SUBSTR) === self::COOKIE_SUBSTR) { $stringTypes[] = 'substrings'; } foreach ($stringTypes as $type) { if ( ($mode & self::COOKIE_REMOVE) !== self::COOKIE_REMOVE and ! in_array($name, $this->protectedCookies[$type]) ) { $this->protectedCookies[$type][] = $name; } elseif ( ($mode & self::COOKIE_REMOVE) === self::COOKIE_REMOVE and ( $key = array_search( $name, $this->protectedCookies[$type] ) ) !== false ) { unset($this->protectedCookies[$type][$key]); } } }
php
public function protectedCookie( $name, $mode = self::COOKIE_DEFAULT ) { Types::assert( [ 'string|array' => [$name], 'int' => [$mode] ] ); if (is_string($name)) { $name = strtolower($name); } elseif (is_array($name)) { foreach ($name as $cookie) { $this->protectedCookie($cookie, $mode); } return; } $stringTypes = []; if (($mode & self::COOKIE_NAME) === self::COOKIE_NAME) { $stringTypes[] = 'names'; } if (($mode & self::COOKIE_SUBSTR) === self::COOKIE_SUBSTR) { $stringTypes[] = 'substrings'; } foreach ($stringTypes as $type) { if ( ($mode & self::COOKIE_REMOVE) !== self::COOKIE_REMOVE and ! in_array($name, $this->protectedCookies[$type]) ) { $this->protectedCookies[$type][] = $name; } elseif ( ($mode & self::COOKIE_REMOVE) === self::COOKIE_REMOVE and ( $key = array_search( $name, $this->protectedCookies[$type] ) ) !== false ) { unset($this->protectedCookies[$type][$key]); } } }
[ "public", "function", "protectedCookie", "(", "$", "name", ",", "$", "mode", "=", "self", "::", "COOKIE_DEFAULT", ")", "{", "Types", "::", "assert", "(", "[", "'string|array'", "=>", "[", "$", "name", "]", ",", "'int'", "=>", "[", "$", "mode", "]", "]", ")", ";", "if", "(", "is_string", "(", "$", "name", ")", ")", "{", "$", "name", "=", "strtolower", "(", "$", "name", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "name", ")", ")", "{", "foreach", "(", "$", "name", "as", "$", "cookie", ")", "{", "$", "this", "->", "protectedCookie", "(", "$", "cookie", ",", "$", "mode", ")", ";", "}", "return", ";", "}", "$", "stringTypes", "=", "[", "]", ";", "if", "(", "(", "$", "mode", "&", "self", "::", "COOKIE_NAME", ")", "===", "self", "::", "COOKIE_NAME", ")", "{", "$", "stringTypes", "[", "]", "=", "'names'", ";", "}", "if", "(", "(", "$", "mode", "&", "self", "::", "COOKIE_SUBSTR", ")", "===", "self", "::", "COOKIE_SUBSTR", ")", "{", "$", "stringTypes", "[", "]", "=", "'substrings'", ";", "}", "foreach", "(", "$", "stringTypes", "as", "$", "type", ")", "{", "if", "(", "(", "$", "mode", "&", "self", "::", "COOKIE_REMOVE", ")", "!==", "self", "::", "COOKIE_REMOVE", "and", "!", "in_array", "(", "$", "name", ",", "$", "this", "->", "protectedCookies", "[", "$", "type", "]", ")", ")", "{", "$", "this", "->", "protectedCookies", "[", "$", "type", "]", "[", "]", "=", "$", "name", ";", "}", "elseif", "(", "(", "$", "mode", "&", "self", "::", "COOKIE_REMOVE", ")", "===", "self", "::", "COOKIE_REMOVE", "and", "(", "$", "key", "=", "array_search", "(", "$", "name", ",", "$", "this", "->", "protectedCookies", "[", "$", "type", "]", ")", ")", "!==", "false", ")", "{", "unset", "(", "$", "this", "->", "protectedCookies", "[", "$", "type", "]", "[", "$", "key", "]", ")", ";", "}", "}", "}" ]
Configure which cookies SecureHeaders will regard as protected. SecureHeaders will consider substrings and names of cookies separately. By default, cookies that case insensitively match the following substrings or names will be regarded as protected. #### Substrings ``` sess auth login csrf xsrf token antiforgery ``` #### Names ``` sid s persistent ``` If a cookie is protected, then cookie flags will be appended as configured by {@see auto}. The default behaviour is to add `Secure`, `HttpOnly`, and `SameSite=Lax` to ensure cookies are both sent securely, out of the reach of JavaScript, and fairly resistant to csrf attacks. @api @param string|array $name The name (or substring of the name, depending on mode configuration), of the cookie to add/remove from the protection list (depending on mode configuration). Or a list of cookie names (or substrings of the name to match) as an array of strings. @param int $mode `mode` accepts one or more of the following constants. Multiple constants may be specified by combination using [bitwise operators](https://secure.php.net/manual/language.operators.bitwise.php) @return void
[ "Configure", "which", "cookies", "SecureHeaders", "will", "regard", "as", "protected", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L581-L637
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.csp
public function csp() { $args = func_get_args(); Types::assert(['string|array|int|bool|NULL' => $args]); $num = count($args); # look for a bool or intgers (commonly used in place of bools) # if one is found the first of which is loosly interpreted as # the setting for report only, remaining are ignored foreach ($args as $arg) { if (is_bool($arg) or is_int($arg)) { $reportOnly = ($arg == true); break; } } # if no such items can be found, default to enforced csp if ( ! isset($reportOnly)) { $reportOnly = false; } # look at all the arguments for ($i = 0; $i < $num; $i++) { $arg = $args[$i]; # if the arg is an array, then treat is as an entire policy if (is_array($arg)) { $this->cspArray($arg, $reportOnly); } # if the arg is a string elseif (is_string($arg)) { # then the arg is the directive name $friendlyDirective = $arg; # if we've specified a source value (string: source, # or null: directive is flag) if ( ($i + 1 < $num) and (is_string($args[$i+1]) or is_null($args[$i+1])) ) { # then use the value we specified, and skip over the next # item in the loop (since we just used it as a source value) $friendlySource = $args[$i+1]; $i++; } # if no source is specified (either no more args, or one of # unsupported type) else { # assume that the directive is a flag $friendlySource = null; } $this->cspAllow( $friendlyDirective, $friendlySource, $reportOnly ); } } }
php
public function csp() { $args = func_get_args(); Types::assert(['string|array|int|bool|NULL' => $args]); $num = count($args); # look for a bool or intgers (commonly used in place of bools) # if one is found the first of which is loosly interpreted as # the setting for report only, remaining are ignored foreach ($args as $arg) { if (is_bool($arg) or is_int($arg)) { $reportOnly = ($arg == true); break; } } # if no such items can be found, default to enforced csp if ( ! isset($reportOnly)) { $reportOnly = false; } # look at all the arguments for ($i = 0; $i < $num; $i++) { $arg = $args[$i]; # if the arg is an array, then treat is as an entire policy if (is_array($arg)) { $this->cspArray($arg, $reportOnly); } # if the arg is a string elseif (is_string($arg)) { # then the arg is the directive name $friendlyDirective = $arg; # if we've specified a source value (string: source, # or null: directive is flag) if ( ($i + 1 < $num) and (is_string($args[$i+1]) or is_null($args[$i+1])) ) { # then use the value we specified, and skip over the next # item in the loop (since we just used it as a source value) $friendlySource = $args[$i+1]; $i++; } # if no source is specified (either no more args, or one of # unsupported type) else { # assume that the directive is a flag $friendlySource = null; } $this->cspAllow( $friendlyDirective, $friendlySource, $reportOnly ); } } }
[ "public", "function", "csp", "(", ")", "{", "$", "args", "=", "func_get_args", "(", ")", ";", "Types", "::", "assert", "(", "[", "'string|array|int|bool|NULL'", "=>", "$", "args", "]", ")", ";", "$", "num", "=", "count", "(", "$", "args", ")", ";", "# look for a bool or intgers (commonly used in place of bools)", "# if one is found the first of which is loosly interpreted as", "# the setting for report only, remaining are ignored", "foreach", "(", "$", "args", "as", "$", "arg", ")", "{", "if", "(", "is_bool", "(", "$", "arg", ")", "or", "is_int", "(", "$", "arg", ")", ")", "{", "$", "reportOnly", "=", "(", "$", "arg", "==", "true", ")", ";", "break", ";", "}", "}", "# if no such items can be found, default to enforced csp", "if", "(", "!", "isset", "(", "$", "reportOnly", ")", ")", "{", "$", "reportOnly", "=", "false", ";", "}", "# look at all the arguments", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "num", ";", "$", "i", "++", ")", "{", "$", "arg", "=", "$", "args", "[", "$", "i", "]", ";", "# if the arg is an array, then treat is as an entire policy", "if", "(", "is_array", "(", "$", "arg", ")", ")", "{", "$", "this", "->", "cspArray", "(", "$", "arg", ",", "$", "reportOnly", ")", ";", "}", "# if the arg is a string", "elseif", "(", "is_string", "(", "$", "arg", ")", ")", "{", "# then the arg is the directive name", "$", "friendlyDirective", "=", "$", "arg", ";", "# if we've specified a source value (string: source,", "# or null: directive is flag)", "if", "(", "(", "$", "i", "+", "1", "<", "$", "num", ")", "and", "(", "is_string", "(", "$", "args", "[", "$", "i", "+", "1", "]", ")", "or", "is_null", "(", "$", "args", "[", "$", "i", "+", "1", "]", ")", ")", ")", "{", "# then use the value we specified, and skip over the next", "# item in the loop (since we just used it as a source value)", "$", "friendlySource", "=", "$", "args", "[", "$", "i", "+", "1", "]", ";", "$", "i", "++", ";", "}", "# if no source is specified (either no more args, or one of", "# unsupported type)", "else", "{", "# assume that the directive is a flag", "$", "friendlySource", "=", "null", ";", "}", "$", "this", "->", "cspAllow", "(", "$", "friendlyDirective", ",", "$", "friendlySource", ",", "$", "reportOnly", ")", ";", "}", "}", "}" ]
@api @ignore Polymorphic variadic function
[ "@api" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L669-L736
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.cspro
public function cspro() { $args = func_get_args(); Types::assert(['string|array|int|bool|NULL' => $args]); foreach ($args as $i => $arg) { if (is_bool($arg) or is_int($arg)) { unset($args[$i]); } } $args = array_values($args); array_unshift($args, true); call_user_func_array([$this, 'csp'], $args); }
php
public function cspro() { $args = func_get_args(); Types::assert(['string|array|int|bool|NULL' => $args]); foreach ($args as $i => $arg) { if (is_bool($arg) or is_int($arg)) { unset($args[$i]); } } $args = array_values($args); array_unshift($args, true); call_user_func_array([$this, 'csp'], $args); }
[ "public", "function", "cspro", "(", ")", "{", "$", "args", "=", "func_get_args", "(", ")", ";", "Types", "::", "assert", "(", "[", "'string|array|int|bool|NULL'", "=>", "$", "args", "]", ")", ";", "foreach", "(", "$", "args", "as", "$", "i", "=>", "$", "arg", ")", "{", "if", "(", "is_bool", "(", "$", "arg", ")", "or", "is_int", "(", "$", "arg", ")", ")", "{", "unset", "(", "$", "args", "[", "$", "i", "]", ")", ";", "}", "}", "$", "args", "=", "array_values", "(", "$", "args", ")", ";", "array_unshift", "(", "$", "args", ",", "true", ")", ";", "call_user_func_array", "(", "[", "$", "this", ",", "'csp'", "]", ",", "$", "args", ")", ";", "}" ]
@api @ignore Polymorphic variadic function
[ "@api" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L743-L762
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.removeCSPSource
public function removeCSPSource($directive, $source, $reportOnly = null) { Types::assert(['string' => [$directive, $source]]); $csp = &$this->getCSPObject($reportOnly); $source = strtolower($source); $directive = strtolower($directive); if ( ! isset($csp[$directive][$source])) { return false; } unset($csp[$directive][$source]); return true; }
php
public function removeCSPSource($directive, $source, $reportOnly = null) { Types::assert(['string' => [$directive, $source]]); $csp = &$this->getCSPObject($reportOnly); $source = strtolower($source); $directive = strtolower($directive); if ( ! isset($csp[$directive][$source])) { return false; } unset($csp[$directive][$source]); return true; }
[ "public", "function", "removeCSPSource", "(", "$", "directive", ",", "$", "source", ",", "$", "reportOnly", "=", "null", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "directive", ",", "$", "source", "]", "]", ")", ";", "$", "csp", "=", "&", "$", "this", "->", "getCSPObject", "(", "$", "reportOnly", ")", ";", "$", "source", "=", "strtolower", "(", "$", "source", ")", ";", "$", "directive", "=", "strtolower", "(", "$", "directive", ")", ";", "if", "(", "!", "isset", "(", "$", "csp", "[", "$", "directive", "]", "[", "$", "source", "]", ")", ")", "{", "return", "false", ";", "}", "unset", "(", "$", "csp", "[", "$", "directive", "]", "[", "$", "source", "]", ")", ";", "return", "true", ";", "}" ]
Remove a previously added source from a CSP directive. @api @param string $directive The directive (case insensitive) in which the source to be removed resides. @param string $source The source (case insensitive) to remove. @param mixed $reportOnly Loosely casted as a boolean, `true` ensures the function acts on the report only policy, `false` (the default, as `null` casts to false) ensures the function acts on the enforced policy. @return void
[ "Remove", "a", "previously", "added", "source", "from", "a", "CSP", "directive", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L810-L827
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.removeCSPDirective
public function removeCSPDirective($directive, $reportOnly = null) { Types::assert(['string' => [$directive]]); $csp = &$this->getCSPObject($reportOnly); $directive = strtolower($directive); if ( ! isset($csp[$directive])) { return false; } unset($csp[$directive]); return true; }
php
public function removeCSPDirective($directive, $reportOnly = null) { Types::assert(['string' => [$directive]]); $csp = &$this->getCSPObject($reportOnly); $directive = strtolower($directive); if ( ! isset($csp[$directive])) { return false; } unset($csp[$directive]); return true; }
[ "public", "function", "removeCSPDirective", "(", "$", "directive", ",", "$", "reportOnly", "=", "null", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "directive", "]", "]", ")", ";", "$", "csp", "=", "&", "$", "this", "->", "getCSPObject", "(", "$", "reportOnly", ")", ";", "$", "directive", "=", "strtolower", "(", "$", "directive", ")", ";", "if", "(", "!", "isset", "(", "$", "csp", "[", "$", "directive", "]", ")", ")", "{", "return", "false", ";", "}", "unset", "(", "$", "csp", "[", "$", "directive", "]", ")", ";", "return", "true", ";", "}" ]
Remove a previously added directive from CSP. @api @param string $directive The directive (case insensitive) to remove. @param mixed $reportOnly Loosely casted as a boolean, `true` ensures the function acts on the report only policy, `false` (the default, as `null` casts to false) ensures the function acts on the enforced policy. @return void
[ "Remove", "a", "previously", "added", "directive", "from", "CSP", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L843-L859
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.cspHash
public function cspHash( $friendlyDirective, $string, $algo = null, $isFile = null, $reportOnly = null ) { Types::assert( ['string' => [$friendlyDirective, $string], '?string' => [$algo]] ); if ( ! isset($algo) or ! in_array( strtolower($algo), $this->allowedCSPHashAlgs ) ) { $algo = 'sha256'; } $hash = $this->cspDoHash($string, $algo, $isFile); $hashString = "'$algo-$hash'"; $this->cspAllow($friendlyDirective, $hashString, $reportOnly); return $hash; }
php
public function cspHash( $friendlyDirective, $string, $algo = null, $isFile = null, $reportOnly = null ) { Types::assert( ['string' => [$friendlyDirective, $string], '?string' => [$algo]] ); if ( ! isset($algo) or ! in_array( strtolower($algo), $this->allowedCSPHashAlgs ) ) { $algo = 'sha256'; } $hash = $this->cspDoHash($string, $algo, $isFile); $hashString = "'$algo-$hash'"; $this->cspAllow($friendlyDirective, $hashString, $reportOnly); return $hash; }
[ "public", "function", "cspHash", "(", "$", "friendlyDirective", ",", "$", "string", ",", "$", "algo", "=", "null", ",", "$", "isFile", "=", "null", ",", "$", "reportOnly", "=", "null", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "friendlyDirective", ",", "$", "string", "]", ",", "'?string'", "=>", "[", "$", "algo", "]", "]", ")", ";", "if", "(", "!", "isset", "(", "$", "algo", ")", "or", "!", "in_array", "(", "strtolower", "(", "$", "algo", ")", ",", "$", "this", "->", "allowedCSPHashAlgs", ")", ")", "{", "$", "algo", "=", "'sha256'", ";", "}", "$", "hash", "=", "$", "this", "->", "cspDoHash", "(", "$", "string", ",", "$", "algo", ",", "$", "isFile", ")", ";", "$", "hashString", "=", "\"'$algo-$hash'\"", ";", "$", "this", "->", "cspAllow", "(", "$", "friendlyDirective", ",", "$", "hashString", ",", "$", "reportOnly", ")", ";", "return", "$", "hash", ";", "}" ]
Generate a hash of the provided [`$string`](#string) value, and have it added to the [`$friendlyDirective`](#friendlyDirective) directive in CSP. @api @param string $friendlyDirective The (case insensitive) [friendly name](friendly_directives_and_sources#directives) that the hash should be to be added to. @param string $string The string that should be hashed and added to the [`$friendlyDirective`](friendly_directives_and_sources#directives) directive. @param ?string $algo = 'sha256' The hashing algorithm to use. CSP currently supports `sha256`, `sha384`, `sha512`. @param mixed $isFile Loosely casted as a boolean. Indicates that [`$string`](string) instead specifies a file path. @param mixed $reportOnly Loosely casted as a boolean. Indicates that the hash should be added to the report only policy `true`, or the enforced policy `false`. @return string Returns the hash value.
[ "Generate", "a", "hash", "of", "the", "provided", "[", "$string", "]", "(", "#string", ")", "value", "and", "have", "it", "added", "to", "the", "[", "$friendlyDirective", "]", "(", "#friendlyDirective", ")", "directive", "in", "CSP", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L908-L936
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.csproHash
public function csproHash( $friendlyDirective, $string, $algo = null, $isFile = null ) { Types::assert( ['string' => [$friendlyDirective, $string], '?string' => [$algo]] ); return $this->cspHash( $friendlyDirective, $string, $algo, $isFile, true ); }
php
public function csproHash( $friendlyDirective, $string, $algo = null, $isFile = null ) { Types::assert( ['string' => [$friendlyDirective, $string], '?string' => [$algo]] ); return $this->cspHash( $friendlyDirective, $string, $algo, $isFile, true ); }
[ "public", "function", "csproHash", "(", "$", "friendlyDirective", ",", "$", "string", ",", "$", "algo", "=", "null", ",", "$", "isFile", "=", "null", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "friendlyDirective", ",", "$", "string", "]", ",", "'?string'", "=>", "[", "$", "algo", "]", "]", ")", ";", "return", "$", "this", "->", "cspHash", "(", "$", "friendlyDirective", ",", "$", "string", ",", "$", "algo", ",", "$", "isFile", ",", "true", ")", ";", "}" ]
An alias for {@see cspHash} with [reportOnly](cspHash#reportOnly) set to true. @api @param string $friendlyDirective @param string $string @param ?string $algo = 'sha256' @param mixed $isFile @return string
[ "An", "alias", "for", "{", "@see", "cspHash", "}", "with", "[", "reportOnly", "]", "(", "cspHash#reportOnly", ")", "set", "to", "true", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L951-L968
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.cspHashFile
public function cspHashFile( $friendlyDirective, $string, $algo = null, $reportOnly = null ) { Types::assert( ['string' => [$friendlyDirective, $string], '?string' => [$algo]] ); return $this->cspHash( $friendlyDirective, $string, $algo, true, $reportOnly ); }
php
public function cspHashFile( $friendlyDirective, $string, $algo = null, $reportOnly = null ) { Types::assert( ['string' => [$friendlyDirective, $string], '?string' => [$algo]] ); return $this->cspHash( $friendlyDirective, $string, $algo, true, $reportOnly ); }
[ "public", "function", "cspHashFile", "(", "$", "friendlyDirective", ",", "$", "string", ",", "$", "algo", "=", "null", ",", "$", "reportOnly", "=", "null", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "friendlyDirective", ",", "$", "string", "]", ",", "'?string'", "=>", "[", "$", "algo", "]", "]", ")", ";", "return", "$", "this", "->", "cspHash", "(", "$", "friendlyDirective", ",", "$", "string", ",", "$", "algo", ",", "true", ",", "$", "reportOnly", ")", ";", "}" ]
An alias for {@see cspHash} with [isFile](cspHash#isFile) set to `true`. @api @param string $friendlyDirective @param string $string @param ?string $algo = 'sha256' @param mixed $reportOnly @return string
[ "An", "alias", "for", "{", "@see", "cspHash", "}", "with", "[", "isFile", "]", "(", "cspHash#isFile", ")", "set", "to", "true", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L982-L999
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.csproHashFile
public function csproHashFile($friendlyDirective, $string, $algo = null) { Types::assert( ['string' => [$friendlyDirective, $string], '?string' => [$algo]] ); return $this->cspHash($friendlyDirective, $string, $algo, true, true); }
php
public function csproHashFile($friendlyDirective, $string, $algo = null) { Types::assert( ['string' => [$friendlyDirective, $string], '?string' => [$algo]] ); return $this->cspHash($friendlyDirective, $string, $algo, true, true); }
[ "public", "function", "csproHashFile", "(", "$", "friendlyDirective", ",", "$", "string", ",", "$", "algo", "=", "null", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "friendlyDirective", ",", "$", "string", "]", ",", "'?string'", "=>", "[", "$", "algo", "]", "]", ")", ";", "return", "$", "this", "->", "cspHash", "(", "$", "friendlyDirective", ",", "$", "string", ",", "$", "algo", ",", "true", ",", "true", ")", ";", "}" ]
An alias for {@see cspHash} with [reportOnly](cspHash#reportOnly) set to true, and [isFile](cspHash#isFile) set to true. @api @param string $friendlyDirective @param string $string @param ?string $algo = 'sha256' @return string
[ "An", "alias", "for", "{", "@see", "cspHash", "}", "with", "[", "reportOnly", "]", "(", "cspHash#reportOnly", ")", "set", "to", "true", "and", "[", "isFile", "]", "(", "cspHash#isFile", ")", "set", "to", "true", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1013-L1020
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.cspNonce
public function cspNonce($friendlyDirective, $reportOnly = null) { Types::assert(['string' => [$friendlyDirective]]); $reportOnly = ($reportOnly == true); $nonceStore = &$this->cspNonces[ ($reportOnly ? 'reportOnly' : 'enforced') ]; $directive = $this->longDirective($friendlyDirective); if ($this->returnExistingNonce and isset($nonceStore[$directive])) { return $nonceStore[$directive]; } $nonce = $this->cspGenerateNonce(); $nonceString = "'nonce-$nonce'"; $this->addCSPSource($directive, $nonceString, $reportOnly); $nonceStore[$directive] = $nonce; return $nonce; }
php
public function cspNonce($friendlyDirective, $reportOnly = null) { Types::assert(['string' => [$friendlyDirective]]); $reportOnly = ($reportOnly == true); $nonceStore = &$this->cspNonces[ ($reportOnly ? 'reportOnly' : 'enforced') ]; $directive = $this->longDirective($friendlyDirective); if ($this->returnExistingNonce and isset($nonceStore[$directive])) { return $nonceStore[$directive]; } $nonce = $this->cspGenerateNonce(); $nonceString = "'nonce-$nonce'"; $this->addCSPSource($directive, $nonceString, $reportOnly); $nonceStore[$directive] = $nonce; return $nonce; }
[ "public", "function", "cspNonce", "(", "$", "friendlyDirective", ",", "$", "reportOnly", "=", "null", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "friendlyDirective", "]", "]", ")", ";", "$", "reportOnly", "=", "(", "$", "reportOnly", "==", "true", ")", ";", "$", "nonceStore", "=", "&", "$", "this", "->", "cspNonces", "[", "(", "$", "reportOnly", "?", "'reportOnly'", ":", "'enforced'", ")", "]", ";", "$", "directive", "=", "$", "this", "->", "longDirective", "(", "$", "friendlyDirective", ")", ";", "if", "(", "$", "this", "->", "returnExistingNonce", "and", "isset", "(", "$", "nonceStore", "[", "$", "directive", "]", ")", ")", "{", "return", "$", "nonceStore", "[", "$", "directive", "]", ";", "}", "$", "nonce", "=", "$", "this", "->", "cspGenerateNonce", "(", ")", ";", "$", "nonceString", "=", "\"'nonce-$nonce'\"", ";", "$", "this", "->", "addCSPSource", "(", "$", "directive", ",", "$", "nonceString", ",", "$", "reportOnly", ")", ";", "$", "nonceStore", "[", "$", "directive", "]", "=", "$", "nonce", ";", "return", "$", "nonce", ";", "}" ]
Used to securely generate a nonce value, and have it be added to the [`$friendlyDirective`](#friendlyDirective) in CSP. Note that if a nonce already exists for the specified directive, the existing value will be returned instead of generating a new one (multiple nonces in the same directive don't offer any security benefits at present – since they're all treated equally). This should facilitate distributing the nonce to any code that needs it (provided the code can access the SecureHeaders instance). If you want to disable returning an existing nonce, use {@see returnExistingNonce} to turn the behaviour on or off. **Make sure not to use nonces where the content given the nonce is partially of user origin! This would allow an attacker to bypass the protections of CSP!** @api @param string $friendlyDirective The (case insensitive) [friendly name](friendly_directives_and_sources#directives) that the nonce should be to be added to. @param mixed $reportOnly Loosely casted as a boolean. Indicates that the hash should be added to the report only policy `true`, or the enforced policy `false`. @return string Returns the nonce value.
[ "Used", "to", "securely", "generate", "a", "nonce", "value", "and", "have", "it", "be", "added", "to", "the", "[", "$friendlyDirective", "]", "(", "#friendlyDirective", ")", "in", "CSP", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1055-L1081
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.expectCT
public function expectCT( $maxAge = 31536000, $enforce = true, $reportUri = null ) { Types::assert( [ '?int|?string' => [$maxAge], '?string' => [$reportUri] ], [1, 3] ); if (isset($maxAge) or ! isset($this->expectCT['max-age'])) { $this->expectCT['max-age'] = $maxAge; } if (isset($enforce) or ! isset($this->expectCT['enforce'])) { $this->expectCT['enforce'] = (isset($enforce) ? ($enforce == true) : null); } if (isset($reportUri) or ! isset($this->expectCT['report-uri'])) { $this->expectCT['report-uri'] = $reportUri; } }
php
public function expectCT( $maxAge = 31536000, $enforce = true, $reportUri = null ) { Types::assert( [ '?int|?string' => [$maxAge], '?string' => [$reportUri] ], [1, 3] ); if (isset($maxAge) or ! isset($this->expectCT['max-age'])) { $this->expectCT['max-age'] = $maxAge; } if (isset($enforce) or ! isset($this->expectCT['enforce'])) { $this->expectCT['enforce'] = (isset($enforce) ? ($enforce == true) : null); } if (isset($reportUri) or ! isset($this->expectCT['report-uri'])) { $this->expectCT['report-uri'] = $reportUri; } }
[ "public", "function", "expectCT", "(", "$", "maxAge", "=", "31536000", ",", "$", "enforce", "=", "true", ",", "$", "reportUri", "=", "null", ")", "{", "Types", "::", "assert", "(", "[", "'?int|?string'", "=>", "[", "$", "maxAge", "]", ",", "'?string'", "=>", "[", "$", "reportUri", "]", "]", ",", "[", "1", ",", "3", "]", ")", ";", "if", "(", "isset", "(", "$", "maxAge", ")", "or", "!", "isset", "(", "$", "this", "->", "expectCT", "[", "'max-age'", "]", ")", ")", "{", "$", "this", "->", "expectCT", "[", "'max-age'", "]", "=", "$", "maxAge", ";", "}", "if", "(", "isset", "(", "$", "enforce", ")", "or", "!", "isset", "(", "$", "this", "->", "expectCT", "[", "'enforce'", "]", ")", ")", "{", "$", "this", "->", "expectCT", "[", "'enforce'", "]", "=", "(", "isset", "(", "$", "enforce", ")", "?", "(", "$", "enforce", "==", "true", ")", ":", "null", ")", ";", "}", "if", "(", "isset", "(", "$", "reportUri", ")", "or", "!", "isset", "(", "$", "this", "->", "expectCT", "[", "'report-uri'", "]", ")", ")", "{", "$", "this", "->", "expectCT", "[", "'report-uri'", "]", "=", "$", "reportUri", ";", "}", "}" ]
Used to add and configure the Expect-CT header. Expect-CT makes sure that a user's browser will fill the role of ensuring that future requests, within $maxAge seconds will have certificate transparancy. If set to enforcement mode, the browser will fail the TLS connection if the certificate transparency requirement is not met @api @param ?int|string $maxAge The length, in seconds either as a string, or an integer – specify the length that a user's browser should remember that the application should be delivered with a certificate transparency expectation. @param ?mixed $enforce Loosely casted as a boolean, whether to enforce (by failing the TLS connection) that certificate transparency is enabled for the next $maxAge seconds, or whether to only report to the console, and to $reportUri if an address is defined. @param ?string $reportUri A reporting address to send violation reports to. Passing `null` indicates that a reporting address should not be modified on this call (e.g. can be used to prevent overwriting a previous setting). @return void
[ "Used", "to", "add", "and", "configure", "the", "Expect", "-", "CT", "header", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1139-L1167
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.hsts
public function hsts( $maxAge = 31536000, $subdomains = false, $preload = false ) { Types::assert(['int|string' => [$maxAge]]); $this->hsts['max-age'] = $maxAge; $this->hsts['subdomains'] = ($subdomains == true); $this->hsts['preload'] = ($preload == true); }
php
public function hsts( $maxAge = 31536000, $subdomains = false, $preload = false ) { Types::assert(['int|string' => [$maxAge]]); $this->hsts['max-age'] = $maxAge; $this->hsts['subdomains'] = ($subdomains == true); $this->hsts['preload'] = ($preload == true); }
[ "public", "function", "hsts", "(", "$", "maxAge", "=", "31536000", ",", "$", "subdomains", "=", "false", ",", "$", "preload", "=", "false", ")", "{", "Types", "::", "assert", "(", "[", "'int|string'", "=>", "[", "$", "maxAge", "]", "]", ")", ";", "$", "this", "->", "hsts", "[", "'max-age'", "]", "=", "$", "maxAge", ";", "$", "this", "->", "hsts", "[", "'subdomains'", "]", "=", "(", "$", "subdomains", "==", "true", ")", ";", "$", "this", "->", "hsts", "[", "'preload'", "]", "=", "(", "$", "preload", "==", "true", ")", ";", "}" ]
Used to add and configure the Strict-Transport-Security header. HSTS makes sure that a user's browser will fill the role of redirecting them from HTTP to HTTPS so that they need not trust an insecure response from the network. @api @param int|string $maxAge The length, in seconds either as a string, or an integer – specify the length that a user's browser should remember that the application is HTTPS only. @param mixed $subdomains Loosely casted as a boolean, whether to include the `includeSubDomains` flag – to deploy the HSTS policy across the entire domain. @param mixed $preload Loosely casted as a boolean, whether to include the `preload` flag – to consent to have the domain loaded into [various preload lists](https://hstspreload.appspot.com/) (so that a user need not initially visit your site securely to know about the HSTS policy). You must also [manually preload](https://hstspreload.appspot.com/) your domain for this to take effect – the flag just indicates consent. @return void
[ "Used", "to", "add", "and", "configure", "the", "Strict", "-", "Transport", "-", "Security", "header", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1202-L1212
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.hpkp
public function hpkp( $pins, $maxAge = null, $subdomains = null, $reportUri = null, $reportOnly = null ) { Types::assert( [ 'string|array' => [$pins], '?int|?string' => [$maxAge], '?string' => [$reportUri] ], [1, 2, 4] ); $hpkp = &$this->getHPKPObject($reportOnly); # set single values if (isset($maxAge) or ! isset($this->hpkp['max-age'])) { $hpkp['max-age'] = $maxAge; } if (isset($subdomains) or ! isset($this->hpkp['includesubdomains'])) { $hpkp['includesubdomains'] = (isset($subdomains) ? ($subdomains == true) : null); } if (isset($reportUri) or ! isset($this->hpkp['report-uri'])) { $hpkp['report-uri'] = $reportUri; } if ( ! is_array($pins)) { $pins = [$pins]; } # set pins foreach ($pins as $key => $pin) { if (is_array($pin) and count($pin) === 2) { $res = array_intersect($pin, $this->allowedHPKPAlgs); if ( ! empty($res)) { $key = key($res); $hpkp['pins'][] = [ $pin[($key + 1) % 2], $pin[$key] ]; } else { continue; } } elseif ( is_string($pin) or (is_array($pin) and count($pin) === 1 and ($pin = $pin[0]) !== false) ) { $hpkp['pins'][] = [$pin, 'sha256']; } } }
php
public function hpkp( $pins, $maxAge = null, $subdomains = null, $reportUri = null, $reportOnly = null ) { Types::assert( [ 'string|array' => [$pins], '?int|?string' => [$maxAge], '?string' => [$reportUri] ], [1, 2, 4] ); $hpkp = &$this->getHPKPObject($reportOnly); # set single values if (isset($maxAge) or ! isset($this->hpkp['max-age'])) { $hpkp['max-age'] = $maxAge; } if (isset($subdomains) or ! isset($this->hpkp['includesubdomains'])) { $hpkp['includesubdomains'] = (isset($subdomains) ? ($subdomains == true) : null); } if (isset($reportUri) or ! isset($this->hpkp['report-uri'])) { $hpkp['report-uri'] = $reportUri; } if ( ! is_array($pins)) { $pins = [$pins]; } # set pins foreach ($pins as $key => $pin) { if (is_array($pin) and count($pin) === 2) { $res = array_intersect($pin, $this->allowedHPKPAlgs); if ( ! empty($res)) { $key = key($res); $hpkp['pins'][] = [ $pin[($key + 1) % 2], $pin[$key] ]; } else { continue; } } elseif ( is_string($pin) or (is_array($pin) and count($pin) === 1 and ($pin = $pin[0]) !== false) ) { $hpkp['pins'][] = [$pin, 'sha256']; } } }
[ "public", "function", "hpkp", "(", "$", "pins", ",", "$", "maxAge", "=", "null", ",", "$", "subdomains", "=", "null", ",", "$", "reportUri", "=", "null", ",", "$", "reportOnly", "=", "null", ")", "{", "Types", "::", "assert", "(", "[", "'string|array'", "=>", "[", "$", "pins", "]", ",", "'?int|?string'", "=>", "[", "$", "maxAge", "]", ",", "'?string'", "=>", "[", "$", "reportUri", "]", "]", ",", "[", "1", ",", "2", ",", "4", "]", ")", ";", "$", "hpkp", "=", "&", "$", "this", "->", "getHPKPObject", "(", "$", "reportOnly", ")", ";", "# set single values", "if", "(", "isset", "(", "$", "maxAge", ")", "or", "!", "isset", "(", "$", "this", "->", "hpkp", "[", "'max-age'", "]", ")", ")", "{", "$", "hpkp", "[", "'max-age'", "]", "=", "$", "maxAge", ";", "}", "if", "(", "isset", "(", "$", "subdomains", ")", "or", "!", "isset", "(", "$", "this", "->", "hpkp", "[", "'includesubdomains'", "]", ")", ")", "{", "$", "hpkp", "[", "'includesubdomains'", "]", "=", "(", "isset", "(", "$", "subdomains", ")", "?", "(", "$", "subdomains", "==", "true", ")", ":", "null", ")", ";", "}", "if", "(", "isset", "(", "$", "reportUri", ")", "or", "!", "isset", "(", "$", "this", "->", "hpkp", "[", "'report-uri'", "]", ")", ")", "{", "$", "hpkp", "[", "'report-uri'", "]", "=", "$", "reportUri", ";", "}", "if", "(", "!", "is_array", "(", "$", "pins", ")", ")", "{", "$", "pins", "=", "[", "$", "pins", "]", ";", "}", "# set pins", "foreach", "(", "$", "pins", "as", "$", "key", "=>", "$", "pin", ")", "{", "if", "(", "is_array", "(", "$", "pin", ")", "and", "count", "(", "$", "pin", ")", "===", "2", ")", "{", "$", "res", "=", "array_intersect", "(", "$", "pin", ",", "$", "this", "->", "allowedHPKPAlgs", ")", ";", "if", "(", "!", "empty", "(", "$", "res", ")", ")", "{", "$", "key", "=", "key", "(", "$", "res", ")", ";", "$", "hpkp", "[", "'pins'", "]", "[", "]", "=", "[", "$", "pin", "[", "(", "$", "key", "+", "1", ")", "%", "2", "]", ",", "$", "pin", "[", "$", "key", "]", "]", ";", "}", "else", "{", "continue", ";", "}", "}", "elseif", "(", "is_string", "(", "$", "pin", ")", "or", "(", "is_array", "(", "$", "pin", ")", "and", "count", "(", "$", "pin", ")", "===", "1", "and", "(", "$", "pin", "=", "$", "pin", "[", "0", "]", ")", "!==", "false", ")", ")", "{", "$", "hpkp", "[", "'pins'", "]", "[", "]", "=", "[", "$", "pin", ",", "'sha256'", "]", ";", "}", "}", "}" ]
Add and configure the HTTP Public Key Pins header. @param string|array $pins Either give a valid pin as a string here, or give multiple as an array. **Note that browsers will not enforce this header unless a backup pin AND a pin that is currently deployed is specified)**. This means that at least two pins must be specified. (to do this by passing strings, simply call {@see hpkp} again with the second pin as the first argument). Valid array syntax is as follows ```php $pins = array( array('sha256', 'pin1'), array('pin2'), array('pin3', 'sha256') ); $headers->hpkp($pins); ``` The above will add `pin1`, `pin2`, and `pin3` with the associated hash label `sha256`. This is the only valid * HPKP hashing algorithm at time of writing. @api @param ?integer|string $maxAge The length, in seconds that a browser should enforce the policy after last receiving it. If this is left unset across all calls to {@see hpkp}, the value will default to 10 seconds (which isn't much use – so it is best to set the value). Passing `null` indicates that a maxAge should not be modified on this call (e.g. can be used to prevent overwriting a previous setting). @param ?mixed $subdomains Loosely casted to a boolean, whether to include the `includeSubDomains` flag to deploy the policy across the entire domain. `true` enables this flag. Passing `null` indicates that a subdomains should not be modified on this call (e.g. can be used to prevent overwriting a previous setting). @param ?string $reportUri A reporting address to send violation reports to. Passing `null` indicates that a reporting address should not be modified on this call (e.g. can be used to prevent overwriting a previous setting). @param mixed $reportOnly Loosely cased to a boolean. If `true`, settings will apply to the report-only version of this header. @return void
[ "Add", "and", "configure", "the", "HTTP", "Public", "Key", "Pins", "header", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1310-L1380
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.hpkpro
public function hpkpro( $pins, $maxAge = null, $subdomains = null, $reportUri = null ) { Types::assert( [ 'string|array' => [$pins], '?int|?string' => [$maxAge], '?string' => [$reportUri] ], [1, 2, 4] ); return $this->hpkp($pins, $maxAge, $subdomains, $reportUri, true); }
php
public function hpkpro( $pins, $maxAge = null, $subdomains = null, $reportUri = null ) { Types::assert( [ 'string|array' => [$pins], '?int|?string' => [$maxAge], '?string' => [$reportUri] ], [1, 2, 4] ); return $this->hpkp($pins, $maxAge, $subdomains, $reportUri, true); }
[ "public", "function", "hpkpro", "(", "$", "pins", ",", "$", "maxAge", "=", "null", ",", "$", "subdomains", "=", "null", ",", "$", "reportUri", "=", "null", ")", "{", "Types", "::", "assert", "(", "[", "'string|array'", "=>", "[", "$", "pins", "]", ",", "'?int|?string'", "=>", "[", "$", "maxAge", "]", ",", "'?string'", "=>", "[", "$", "reportUri", "]", "]", ",", "[", "1", ",", "2", ",", "4", "]", ")", ";", "return", "$", "this", "->", "hpkp", "(", "$", "pins", ",", "$", "maxAge", ",", "$", "subdomains", ",", "$", "reportUri", ",", "true", ")", ";", "}" ]
Add and configure the HTTP Public Key Pins header in report-only mode. This is an alias for {@see hpkp} with `$reportOnly` set to `true`. @api @param string|array $pins @param ?integer|string $maxAge @param ?mixed $subdomains @param ?string $reportUri @return void
[ "Add", "and", "configure", "the", "HTTP", "Public", "Key", "Pins", "header", "in", "report", "-", "only", "mode", ".", "This", "is", "an", "alias", "for", "{", "@see", "hpkp", "}", "with", "$reportOnly", "set", "to", "true", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1395-L1411
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.hpkpSubdomains
public function hpkpSubdomains($mode = true, $reportOnly = null) { $hpkp = &$this->getHPKPObject($reportOnly); $hpkp['includesubdomains'] = ($mode == true); }
php
public function hpkpSubdomains($mode = true, $reportOnly = null) { $hpkp = &$this->getHPKPObject($reportOnly); $hpkp['includesubdomains'] = ($mode == true); }
[ "public", "function", "hpkpSubdomains", "(", "$", "mode", "=", "true", ",", "$", "reportOnly", "=", "null", ")", "{", "$", "hpkp", "=", "&", "$", "this", "->", "getHPKPObject", "(", "$", "reportOnly", ")", ";", "$", "hpkp", "[", "'includesubdomains'", "]", "=", "(", "$", "mode", "==", "true", ")", ";", "}" ]
Add or remove the `includeSubDomains` flag from the [HPKP](hpkp) policy (note this can be done with the {@see hpkp} function too). @api @param mixed $mode Loosely casted to a boolean, `true` adds the `includeSubDomains` flag, `false` removes it. @param mixed $reportOnly Apply this setting to the report-only version of the HPKP policy header @return void
[ "Add", "or", "remove", "the", "includeSubDomains", "flag", "from", "the", "[", "HPKP", "]", "(", "hpkp", ")", "policy", "(", "note", "this", "can", "be", "done", "with", "the", "{", "@see", "hpkp", "}", "function", "too", ")", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1427-L1432
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.apply
public function apply(HttpAdapter $http = null) { # For ease of use, we allow calling this method without an adapter, # which will cause the headers to be sent with PHP's global methods. if (is_null($http)) { $http = new GlobalHttpAdapter(); } $headers = $http->getHeaders(); foreach ($this->pipeline() as $operation) { $operation->modify($headers); if ($operation instanceof ExposesErrors) { $this->errors = array_merge( $this->errors, $operation->collectErrors() ); } } $http->sendHeaders($headers); $this->reportMissingHeaders($headers); $this->validateHeaders($headers); $this->reportErrors(); return $headers; }
php
public function apply(HttpAdapter $http = null) { # For ease of use, we allow calling this method without an adapter, # which will cause the headers to be sent with PHP's global methods. if (is_null($http)) { $http = new GlobalHttpAdapter(); } $headers = $http->getHeaders(); foreach ($this->pipeline() as $operation) { $operation->modify($headers); if ($operation instanceof ExposesErrors) { $this->errors = array_merge( $this->errors, $operation->collectErrors() ); } } $http->sendHeaders($headers); $this->reportMissingHeaders($headers); $this->validateHeaders($headers); $this->reportErrors(); return $headers; }
[ "public", "function", "apply", "(", "HttpAdapter", "$", "http", "=", "null", ")", "{", "# For ease of use, we allow calling this method without an adapter,", "# which will cause the headers to be sent with PHP's global methods.", "if", "(", "is_null", "(", "$", "http", ")", ")", "{", "$", "http", "=", "new", "GlobalHttpAdapter", "(", ")", ";", "}", "$", "headers", "=", "$", "http", "->", "getHeaders", "(", ")", ";", "foreach", "(", "$", "this", "->", "pipeline", "(", ")", "as", "$", "operation", ")", "{", "$", "operation", "->", "modify", "(", "$", "headers", ")", ";", "if", "(", "$", "operation", "instanceof", "ExposesErrors", ")", "{", "$", "this", "->", "errors", "=", "array_merge", "(", "$", "this", "->", "errors", ",", "$", "operation", "->", "collectErrors", "(", ")", ")", ";", "}", "}", "$", "http", "->", "sendHeaders", "(", "$", "headers", ")", ";", "$", "this", "->", "reportMissingHeaders", "(", "$", "headers", ")", ";", "$", "this", "->", "validateHeaders", "(", "$", "headers", ")", ";", "$", "this", "->", "reportErrors", "(", ")", ";", "return", "$", "headers", ";", "}" ]
Calling this function will initiate the following 1. Existing headers from the HttpAdapter's source will be imported into SecureHeaders' internal list, parsed 2. [Automatic header functions](auto) will be applied 3. [Expect CT](expectCT), [CSP](csp), [HSTS](hsts), and [HPKP](hpkp) policies will be compiled and added to SecureHeaders' internal header list. 4. Headers queued for [removal](removeHeader) will be deleted from SecureHeaders' internal header list 5. [Safe Mode](safeMode) will examine the list of headers, and make any required changes according to its settings 6. The HttpAdapter will be instructed to remove all headers from its header source, Headers will then be copied from SecureHeaders' internal header list, into the HttpAdapter's (now empty) list of headers 7. If [error reporting](errorReporting) is enabled (both within SecureHeaders and according to the PHP configuration values for error reporting, and whether to display errors) * Missing security headers will be reported as `E_USER_WARNING` * Misconfigured headers will be reported as `E_USER_WARNING` or `E_USER_NOTICE` depending on severity, the former being most severe an issue. **Note:** Calling this function is **required** before the first byte of output in order for SecureHeaders to (be able to) do anything. If you're not sure when the first byte of output might occur, or simply don't want to have to call this every time – take a look at {@see applyOnOutput} to have SecureHeaders take care of this for you. @api @param ?HttpAdapter $http = new GlobalHttpAdapter An implementation of the {@see HttpAdapter} interface, to which settings configured via SecureHeaders will be applied. @return HeaderBag Returns the headers
[ "Calling", "this", "function", "will", "initiate", "the", "following" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1491-L1522
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.pipeline
private function pipeline() { $operations = []; if ($this->strictMode) { $operations[] = new AddHeader( 'Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload' ); $operations[] = new AddHeader( 'Expect-CT', 'max-age=31536000; enforce' ); } # Apply security headers for all (HTTP and HTTPS) connections if ($this->automatic(self::AUTO_ADD)) { foreach ($this->headerProposals as $header => $value) { $operations[] = new AddHeader($header, $value); } } if ($this->automatic(self::AUTO_REMOVE)) { $operations[] = new RemoveHeaders( ['Server', 'X-Powered-By'] ); } # Add a secure flag to cookies that look like they hold session data if ($this->automatic(self::AUTO_COOKIE_SECURE)) { $operations[] = ModifyCookies::matchingPartially( $this->protectedCookies['substrings'], 'Secure' ); $operations[] = ModifyCookies::matchingFully( $this->protectedCookies['names'], 'Secure' ); } # Add a httpOnly flag to cookies that look like they hold session data if ($this->automatic(self::AUTO_COOKIE_HTTPONLY)) { $operations[] = ModifyCookies::matchingPartially( $this->protectedCookies['substrings'], 'HttpOnly' ); $operations[] = ModifyCookies::matchingFully( $this->protectedCookies['names'], 'HttpOnly' ); } if ( ($this->automaticHeaders & self::AUTO_COOKIE_SAMESITE) === self::AUTO_COOKIE_SAMESITE ) { # add SameSite to cookies that look like they hold # session data $sameSite = $this->injectableSameSiteValue(); $operations[] = ModifyCookies::matchingPartially( $this->protectedCookies['substrings'], 'SameSite', $sameSite ); $operations[] = ModifyCookies::matchingFully( $this->protectedCookies['names'], 'SameSite', $sameSite ); } $operations[] = new CompileCSP( $this->csp, $this->cspro, $this->csproBlacklist, $this->cspLegacy ); if ( ! empty($this->hsts)) { $operations[] = new CompileHSTS($this->hsts); } if ( ! empty($this->expectCT)) { $operations[] = new CompileExpectCT($this->expectCT); } $operations[] = new CompileHPKP($this->hpkp, $this->hpkpro); $operations[] = new RemoveCookies(array_keys($this->removedCookies)); # Remove all headers that were configured to be removed $operations[] = new RemoveHeaders(array_keys($this->removedHeaders)); if ($this->strictMode) { $operations[] = new InjectStrictDynamic( $this->allowedCSPHashAlgs, ($this->automaticHeaders & self::AUTO_STRICTDYNAMIC_ENFORCE ? InjectStrictDynamic::ENFORCE : 0) | ($this->automaticHeaders & self::AUTO_STRICTDYNAMIC_REPORT ? InjectStrictDynamic::REPORT : 0) ); } if ($this->safeMode) { $operations[] = new ApplySafeMode($this->safeModeExceptions); } return $operations; }
php
private function pipeline() { $operations = []; if ($this->strictMode) { $operations[] = new AddHeader( 'Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload' ); $operations[] = new AddHeader( 'Expect-CT', 'max-age=31536000; enforce' ); } # Apply security headers for all (HTTP and HTTPS) connections if ($this->automatic(self::AUTO_ADD)) { foreach ($this->headerProposals as $header => $value) { $operations[] = new AddHeader($header, $value); } } if ($this->automatic(self::AUTO_REMOVE)) { $operations[] = new RemoveHeaders( ['Server', 'X-Powered-By'] ); } # Add a secure flag to cookies that look like they hold session data if ($this->automatic(self::AUTO_COOKIE_SECURE)) { $operations[] = ModifyCookies::matchingPartially( $this->protectedCookies['substrings'], 'Secure' ); $operations[] = ModifyCookies::matchingFully( $this->protectedCookies['names'], 'Secure' ); } # Add a httpOnly flag to cookies that look like they hold session data if ($this->automatic(self::AUTO_COOKIE_HTTPONLY)) { $operations[] = ModifyCookies::matchingPartially( $this->protectedCookies['substrings'], 'HttpOnly' ); $operations[] = ModifyCookies::matchingFully( $this->protectedCookies['names'], 'HttpOnly' ); } if ( ($this->automaticHeaders & self::AUTO_COOKIE_SAMESITE) === self::AUTO_COOKIE_SAMESITE ) { # add SameSite to cookies that look like they hold # session data $sameSite = $this->injectableSameSiteValue(); $operations[] = ModifyCookies::matchingPartially( $this->protectedCookies['substrings'], 'SameSite', $sameSite ); $operations[] = ModifyCookies::matchingFully( $this->protectedCookies['names'], 'SameSite', $sameSite ); } $operations[] = new CompileCSP( $this->csp, $this->cspro, $this->csproBlacklist, $this->cspLegacy ); if ( ! empty($this->hsts)) { $operations[] = new CompileHSTS($this->hsts); } if ( ! empty($this->expectCT)) { $operations[] = new CompileExpectCT($this->expectCT); } $operations[] = new CompileHPKP($this->hpkp, $this->hpkpro); $operations[] = new RemoveCookies(array_keys($this->removedCookies)); # Remove all headers that were configured to be removed $operations[] = new RemoveHeaders(array_keys($this->removedHeaders)); if ($this->strictMode) { $operations[] = new InjectStrictDynamic( $this->allowedCSPHashAlgs, ($this->automaticHeaders & self::AUTO_STRICTDYNAMIC_ENFORCE ? InjectStrictDynamic::ENFORCE : 0) | ($this->automaticHeaders & self::AUTO_STRICTDYNAMIC_REPORT ? InjectStrictDynamic::REPORT : 0) ); } if ($this->safeMode) { $operations[] = new ApplySafeMode($this->safeModeExceptions); } return $operations; }
[ "private", "function", "pipeline", "(", ")", "{", "$", "operations", "=", "[", "]", ";", "if", "(", "$", "this", "->", "strictMode", ")", "{", "$", "operations", "[", "]", "=", "new", "AddHeader", "(", "'Strict-Transport-Security'", ",", "'max-age=31536000; includeSubDomains; preload'", ")", ";", "$", "operations", "[", "]", "=", "new", "AddHeader", "(", "'Expect-CT'", ",", "'max-age=31536000; enforce'", ")", ";", "}", "# Apply security headers for all (HTTP and HTTPS) connections", "if", "(", "$", "this", "->", "automatic", "(", "self", "::", "AUTO_ADD", ")", ")", "{", "foreach", "(", "$", "this", "->", "headerProposals", "as", "$", "header", "=>", "$", "value", ")", "{", "$", "operations", "[", "]", "=", "new", "AddHeader", "(", "$", "header", ",", "$", "value", ")", ";", "}", "}", "if", "(", "$", "this", "->", "automatic", "(", "self", "::", "AUTO_REMOVE", ")", ")", "{", "$", "operations", "[", "]", "=", "new", "RemoveHeaders", "(", "[", "'Server'", ",", "'X-Powered-By'", "]", ")", ";", "}", "# Add a secure flag to cookies that look like they hold session data", "if", "(", "$", "this", "->", "automatic", "(", "self", "::", "AUTO_COOKIE_SECURE", ")", ")", "{", "$", "operations", "[", "]", "=", "ModifyCookies", "::", "matchingPartially", "(", "$", "this", "->", "protectedCookies", "[", "'substrings'", "]", ",", "'Secure'", ")", ";", "$", "operations", "[", "]", "=", "ModifyCookies", "::", "matchingFully", "(", "$", "this", "->", "protectedCookies", "[", "'names'", "]", ",", "'Secure'", ")", ";", "}", "# Add a httpOnly flag to cookies that look like they hold session data", "if", "(", "$", "this", "->", "automatic", "(", "self", "::", "AUTO_COOKIE_HTTPONLY", ")", ")", "{", "$", "operations", "[", "]", "=", "ModifyCookies", "::", "matchingPartially", "(", "$", "this", "->", "protectedCookies", "[", "'substrings'", "]", ",", "'HttpOnly'", ")", ";", "$", "operations", "[", "]", "=", "ModifyCookies", "::", "matchingFully", "(", "$", "this", "->", "protectedCookies", "[", "'names'", "]", ",", "'HttpOnly'", ")", ";", "}", "if", "(", "(", "$", "this", "->", "automaticHeaders", "&", "self", "::", "AUTO_COOKIE_SAMESITE", ")", "===", "self", "::", "AUTO_COOKIE_SAMESITE", ")", "{", "# add SameSite to cookies that look like they hold", "# session data", "$", "sameSite", "=", "$", "this", "->", "injectableSameSiteValue", "(", ")", ";", "$", "operations", "[", "]", "=", "ModifyCookies", "::", "matchingPartially", "(", "$", "this", "->", "protectedCookies", "[", "'substrings'", "]", ",", "'SameSite'", ",", "$", "sameSite", ")", ";", "$", "operations", "[", "]", "=", "ModifyCookies", "::", "matchingFully", "(", "$", "this", "->", "protectedCookies", "[", "'names'", "]", ",", "'SameSite'", ",", "$", "sameSite", ")", ";", "}", "$", "operations", "[", "]", "=", "new", "CompileCSP", "(", "$", "this", "->", "csp", ",", "$", "this", "->", "cspro", ",", "$", "this", "->", "csproBlacklist", ",", "$", "this", "->", "cspLegacy", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "hsts", ")", ")", "{", "$", "operations", "[", "]", "=", "new", "CompileHSTS", "(", "$", "this", "->", "hsts", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "expectCT", ")", ")", "{", "$", "operations", "[", "]", "=", "new", "CompileExpectCT", "(", "$", "this", "->", "expectCT", ")", ";", "}", "$", "operations", "[", "]", "=", "new", "CompileHPKP", "(", "$", "this", "->", "hpkp", ",", "$", "this", "->", "hpkpro", ")", ";", "$", "operations", "[", "]", "=", "new", "RemoveCookies", "(", "array_keys", "(", "$", "this", "->", "removedCookies", ")", ")", ";", "# Remove all headers that were configured to be removed", "$", "operations", "[", "]", "=", "new", "RemoveHeaders", "(", "array_keys", "(", "$", "this", "->", "removedHeaders", ")", ")", ";", "if", "(", "$", "this", "->", "strictMode", ")", "{", "$", "operations", "[", "]", "=", "new", "InjectStrictDynamic", "(", "$", "this", "->", "allowedCSPHashAlgs", ",", "(", "$", "this", "->", "automaticHeaders", "&", "self", "::", "AUTO_STRICTDYNAMIC_ENFORCE", "?", "InjectStrictDynamic", "::", "ENFORCE", ":", "0", ")", "|", "(", "$", "this", "->", "automaticHeaders", "&", "self", "::", "AUTO_STRICTDYNAMIC_REPORT", "?", "InjectStrictDynamic", "::", "REPORT", ":", "0", ")", ")", ";", "}", "if", "(", "$", "this", "->", "safeMode", ")", "{", "$", "operations", "[", "]", "=", "new", "ApplySafeMode", "(", "$", "this", "->", "safeModeExceptions", ")", ";", "}", "return", "$", "operations", ";", "}" ]
Return an array of header operations, depending on current configuration. These can then be applied to e.g. the current set of headers. @api @return Operation[]
[ "Return", "an", "array", "of", "header", "operations", "depending", "on", "current", "configuration", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1533-L1652
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.returnBuffer
public function returnBuffer($buffer = null) { if ($this->isBufferReturned) { return $buffer; } $this->apply($this->applyOnOutput); if (ob_get_level() and ! empty($this->errorString)) { # prepend any errors to the buffer string (any errors that were # echoed will have been lost during an ob_start callback) $buffer = $this->errorString . $buffer; } # if we were called as part of ob_start, make note of this # (avoid doing redundent work if called again) $this->isBufferReturned = true; return $buffer; }
php
public function returnBuffer($buffer = null) { if ($this->isBufferReturned) { return $buffer; } $this->apply($this->applyOnOutput); if (ob_get_level() and ! empty($this->errorString)) { # prepend any errors to the buffer string (any errors that were # echoed will have been lost during an ob_start callback) $buffer = $this->errorString . $buffer; } # if we were called as part of ob_start, make note of this # (avoid doing redundent work if called again) $this->isBufferReturned = true; return $buffer; }
[ "public", "function", "returnBuffer", "(", "$", "buffer", "=", "null", ")", "{", "if", "(", "$", "this", "->", "isBufferReturned", ")", "{", "return", "$", "buffer", ";", "}", "$", "this", "->", "apply", "(", "$", "this", "->", "applyOnOutput", ")", ";", "if", "(", "ob_get_level", "(", ")", "and", "!", "empty", "(", "$", "this", "->", "errorString", ")", ")", "{", "# prepend any errors to the buffer string (any errors that were", "# echoed will have been lost during an ob_start callback)", "$", "buffer", "=", "$", "this", "->", "errorString", ".", "$", "buffer", ";", "}", "# if we were called as part of ob_start, make note of this", "# (avoid doing redundent work if called again)", "$", "this", "->", "isBufferReturned", "=", "true", ";", "return", "$", "buffer", ";", "}" ]
@ignore Method given to `ob_start` when using {@see applyOnOutput) @param string $buffer @return string
[ "@ignore" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1670-L1691
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.validateHeaders
private function validateHeaders(HeaderBag $headers) { $this->errors = array_merge( $this->errors, Validator::validate($headers) ); }
php
private function validateHeaders(HeaderBag $headers) { $this->errors = array_merge( $this->errors, Validator::validate($headers) ); }
[ "private", "function", "validateHeaders", "(", "HeaderBag", "$", "headers", ")", "{", "$", "this", "->", "errors", "=", "array_merge", "(", "$", "this", "->", "errors", ",", "Validator", "::", "validate", "(", "$", "headers", ")", ")", ";", "}" ]
Validate headers in the HeaderBag and store any errors internally. @param HeaderBag $headers @return void
[ "Validate", "headers", "in", "the", "HeaderBag", "and", "store", "any", "errors", "internally", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1705-L1711
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.cspAllow
private function cspAllow( $friendlyDirective, $friendlySource = null, $reportOnly = null ) { Types::assert( ['string' => [$friendlyDirective, $friendlySource]] ); $directive = $this->longDirective($friendlyDirective); $source = $this->longSource($friendlySource); $this->addCSPSource($directive, $source, $reportOnly); }
php
private function cspAllow( $friendlyDirective, $friendlySource = null, $reportOnly = null ) { Types::assert( ['string' => [$friendlyDirective, $friendlySource]] ); $directive = $this->longDirective($friendlyDirective); $source = $this->longSource($friendlySource); $this->addCSPSource($directive, $source, $reportOnly); }
[ "private", "function", "cspAllow", "(", "$", "friendlyDirective", ",", "$", "friendlySource", "=", "null", ",", "$", "reportOnly", "=", "null", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "friendlyDirective", ",", "$", "friendlySource", "]", "]", ")", ";", "$", "directive", "=", "$", "this", "->", "longDirective", "(", "$", "friendlyDirective", ")", ";", "$", "source", "=", "$", "this", "->", "longSource", "(", "$", "friendlySource", ")", ";", "$", "this", "->", "addCSPSource", "(", "$", "directive", ",", "$", "source", ",", "$", "reportOnly", ")", ";", "}" ]
Add a CSP friendly source $friendlySource to a CSP directive $friendlyDirective in either enforcement or report only mode. @param string $friendlyDirective @param string $friendlySource @param bool $reportOnly @return void
[ "Add", "a", "CSP", "friendly", "source", "$friendlySource", "to", "a", "CSP", "directive", "$friendlyDirective", "in", "either", "enforcement", "or", "report", "only", "mode", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1727-L1741
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.longDirective
private function longDirective($friendlyDirective) { Types::assert(['string' => [$friendlyDirective]]); $friendlyDirective = strtolower($friendlyDirective); if (isset($this->cspDirectiveShortcuts[$friendlyDirective])) { $directive = $this->cspDirectiveShortcuts[$friendlyDirective]; } else { $directive = $friendlyDirective; } return $directive; }
php
private function longDirective($friendlyDirective) { Types::assert(['string' => [$friendlyDirective]]); $friendlyDirective = strtolower($friendlyDirective); if (isset($this->cspDirectiveShortcuts[$friendlyDirective])) { $directive = $this->cspDirectiveShortcuts[$friendlyDirective]; } else { $directive = $friendlyDirective; } return $directive; }
[ "private", "function", "longDirective", "(", "$", "friendlyDirective", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "friendlyDirective", "]", "]", ")", ";", "$", "friendlyDirective", "=", "strtolower", "(", "$", "friendlyDirective", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "cspDirectiveShortcuts", "[", "$", "friendlyDirective", "]", ")", ")", "{", "$", "directive", "=", "$", "this", "->", "cspDirectiveShortcuts", "[", "$", "friendlyDirective", "]", ";", "}", "else", "{", "$", "directive", "=", "$", "friendlyDirective", ";", "}", "return", "$", "directive", ";", "}" ]
Takes friendly directive $friendlyDirective and returns the corresponding long (proper) directive. @param string $friendlyDirective @return string
[ "Takes", "friendly", "directive", "$friendlyDirective", "and", "returns", "the", "corresponding", "long", "(", "proper", ")", "directive", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1750-L1766
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.longSource
private function longSource($friendlySource) { Types::assert(['string' => [$friendlySource]]); $lowerFriendlySource = strtolower($friendlySource); if (isset($this->cspSourceShortcuts[$lowerFriendlySource])) { $source = $this->cspSourceShortcuts[$lowerFriendlySource]; } else { $source = $friendlySource; } return $source; }
php
private function longSource($friendlySource) { Types::assert(['string' => [$friendlySource]]); $lowerFriendlySource = strtolower($friendlySource); if (isset($this->cspSourceShortcuts[$lowerFriendlySource])) { $source = $this->cspSourceShortcuts[$lowerFriendlySource]; } else { $source = $friendlySource; } return $source; }
[ "private", "function", "longSource", "(", "$", "friendlySource", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "friendlySource", "]", "]", ")", ";", "$", "lowerFriendlySource", "=", "strtolower", "(", "$", "friendlySource", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "cspSourceShortcuts", "[", "$", "lowerFriendlySource", "]", ")", ")", "{", "$", "source", "=", "$", "this", "->", "cspSourceShortcuts", "[", "$", "lowerFriendlySource", "]", ";", "}", "else", "{", "$", "source", "=", "$", "friendlySource", ";", "}", "return", "$", "source", ";", "}" ]
Takes friendly source $friendlySource and returns the corresponding long (proper) source. @param string $friendlySource @return string
[ "Takes", "friendly", "source", "$friendlySource", "and", "returns", "the", "corresponding", "long", "(", "proper", ")", "source", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1775-L1791
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.addCSPSource
private function addCSPSource( $directive, $source = null, $reportOnly = null ) { Types::assert(['string' => [$directive], '?string' => [$source]]); $csp = &$this->getCSPObject($reportOnly); if ( ! isset($csp[$directive])) { $this->addCSPDirective( $directive, ! isset($source), $reportOnly ); } if ($csp[$directive] === null) { return false; } if (isset($source)) { $source = str_replace(';', '', $source); $csp[$directive][strtolower($source)] = $source; } return true; }
php
private function addCSPSource( $directive, $source = null, $reportOnly = null ) { Types::assert(['string' => [$directive], '?string' => [$source]]); $csp = &$this->getCSPObject($reportOnly); if ( ! isset($csp[$directive])) { $this->addCSPDirective( $directive, ! isset($source), $reportOnly ); } if ($csp[$directive] === null) { return false; } if (isset($source)) { $source = str_replace(';', '', $source); $csp[$directive][strtolower($source)] = $source; } return true; }
[ "private", "function", "addCSPSource", "(", "$", "directive", ",", "$", "source", "=", "null", ",", "$", "reportOnly", "=", "null", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "directive", "]", ",", "'?string'", "=>", "[", "$", "source", "]", "]", ")", ";", "$", "csp", "=", "&", "$", "this", "->", "getCSPObject", "(", "$", "reportOnly", ")", ";", "if", "(", "!", "isset", "(", "$", "csp", "[", "$", "directive", "]", ")", ")", "{", "$", "this", "->", "addCSPDirective", "(", "$", "directive", ",", "!", "isset", "(", "$", "source", ")", ",", "$", "reportOnly", ")", ";", "}", "if", "(", "$", "csp", "[", "$", "directive", "]", "===", "null", ")", "{", "return", "false", ";", "}", "if", "(", "isset", "(", "$", "source", ")", ")", "{", "$", "source", "=", "str_replace", "(", "';'", ",", "''", ",", "$", "source", ")", ";", "$", "csp", "[", "$", "directive", "]", "[", "strtolower", "(", "$", "source", ")", "]", "=", "$", "source", ";", "}", "return", "true", ";", "}" ]
Add a CSP source $source to a CSP directive $directive in either enforcement or report only mode. Both $directive and $source must be long (defined in CSP spec). Will return false on error, true on success. @param string $directive @param ?string $source @param bool $reportOnly @return bool
[ "Add", "a", "CSP", "source", "$source", "to", "a", "CSP", "directive", "$directive", "in", "either", "enforcement", "or", "report", "only", "mode", ".", "Both", "$directive", "and", "$source", "must", "be", "long", "(", "defined", "in", "CSP", "spec", ")", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1805-L1836
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.cspArray
private function cspArray(array $csp, $reportOnly = false) { foreach ($csp as $friendlyDirective => $sources) { if (is_array($sources) and ! empty($sources)) { foreach ($sources as $friendlySource) { $this->cspAllow( $friendlyDirective, $friendlySource, $reportOnly ); } } elseif (is_int($friendlyDirective) and is_string($sources)) { # special case that $sources is actually a directive name, # with an int index $friendlyDirective = $sources; # we'll treat this case as a CSP flag $this->cspAllow($friendlyDirective, null, $reportOnly); } elseif ( ! is_array($sources)) { # special case that $sources isn't an array (possibly a string # source, or null $this->cspAllow($friendlyDirective, $sources, $reportOnly); } } }
php
private function cspArray(array $csp, $reportOnly = false) { foreach ($csp as $friendlyDirective => $sources) { if (is_array($sources) and ! empty($sources)) { foreach ($sources as $friendlySource) { $this->cspAllow( $friendlyDirective, $friendlySource, $reportOnly ); } } elseif (is_int($friendlyDirective) and is_string($sources)) { # special case that $sources is actually a directive name, # with an int index $friendlyDirective = $sources; # we'll treat this case as a CSP flag $this->cspAllow($friendlyDirective, null, $reportOnly); } elseif ( ! is_array($sources)) { # special case that $sources isn't an array (possibly a string # source, or null $this->cspAllow($friendlyDirective, $sources, $reportOnly); } } }
[ "private", "function", "cspArray", "(", "array", "$", "csp", ",", "$", "reportOnly", "=", "false", ")", "{", "foreach", "(", "$", "csp", "as", "$", "friendlyDirective", "=>", "$", "sources", ")", "{", "if", "(", "is_array", "(", "$", "sources", ")", "and", "!", "empty", "(", "$", "sources", ")", ")", "{", "foreach", "(", "$", "sources", "as", "$", "friendlySource", ")", "{", "$", "this", "->", "cspAllow", "(", "$", "friendlyDirective", ",", "$", "friendlySource", ",", "$", "reportOnly", ")", ";", "}", "}", "elseif", "(", "is_int", "(", "$", "friendlyDirective", ")", "and", "is_string", "(", "$", "sources", ")", ")", "{", "# special case that $sources is actually a directive name,", "# with an int index", "$", "friendlyDirective", "=", "$", "sources", ";", "# we'll treat this case as a CSP flag", "$", "this", "->", "cspAllow", "(", "$", "friendlyDirective", ",", "null", ",", "$", "reportOnly", ")", ";", "}", "elseif", "(", "!", "is_array", "(", "$", "sources", ")", ")", "{", "# special case that $sources isn't an array (possibly a string", "# source, or null", "$", "this", "->", "cspAllow", "(", "$", "friendlyDirective", ",", "$", "sources", ",", "$", "reportOnly", ")", ";", "}", "}", "}" ]
Add a CSP array $csp of friendly sources to corresponding firendly directives in either enforcement or report only mode. @param array $csp @param bool $reportOnly @return void
[ "Add", "a", "CSP", "array", "$csp", "of", "friendly", "sources", "to", "corresponding", "firendly", "directives", "in", "either", "enforcement", "or", "report", "only", "mode", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1848-L1879
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.&
private function &getCSPObject($reportOnly) { if ( ! isset($reportOnly) or ! $reportOnly) { $csp = &$this->csp; } else { $csp = &$this->cspro; } return $csp; }
php
private function &getCSPObject($reportOnly) { if ( ! isset($reportOnly) or ! $reportOnly) { $csp = &$this->csp; } else { $csp = &$this->cspro; } return $csp; }
[ "private", "function", "&", "getCSPObject", "(", "$", "reportOnly", ")", "{", "if", "(", "!", "isset", "(", "$", "reportOnly", ")", "or", "!", "$", "reportOnly", ")", "{", "$", "csp", "=", "&", "$", "this", "->", "csp", ";", "}", "else", "{", "$", "csp", "=", "&", "$", "this", "->", "cspro", ";", "}", "return", "$", "csp", ";", "}" ]
Retrieve a reference to either the CSP enforcement, or CSP report only array. @param bool $reportOnly @return &array
[ "Retrieve", "a", "reference", "to", "either", "the", "CSP", "enforcement", "or", "CSP", "report", "only", "array", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1888-L1900
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.addCSPDirective
private function addCSPDirective( $directive, $isFlag = null, $reportOnly = null ) { Types::assert(['string' => [$directive]]); if ( ! isset($isFlag)) { $isFlag = false; } $csp = &$this->getCSPObject($reportOnly); if (isset($csp[$directive])) { return false; } if ( ! $isFlag) { $csp[$directive] = []; } else { $csp[$directive] = null; } return true; }
php
private function addCSPDirective( $directive, $isFlag = null, $reportOnly = null ) { Types::assert(['string' => [$directive]]); if ( ! isset($isFlag)) { $isFlag = false; } $csp = &$this->getCSPObject($reportOnly); if (isset($csp[$directive])) { return false; } if ( ! $isFlag) { $csp[$directive] = []; } else { $csp[$directive] = null; } return true; }
[ "private", "function", "addCSPDirective", "(", "$", "directive", ",", "$", "isFlag", "=", "null", ",", "$", "reportOnly", "=", "null", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "directive", "]", "]", ")", ";", "if", "(", "!", "isset", "(", "$", "isFlag", ")", ")", "{", "$", "isFlag", "=", "false", ";", "}", "$", "csp", "=", "&", "$", "this", "->", "getCSPObject", "(", "$", "reportOnly", ")", ";", "if", "(", "isset", "(", "$", "csp", "[", "$", "directive", "]", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "$", "isFlag", ")", "{", "$", "csp", "[", "$", "directive", "]", "=", "[", "]", ";", "}", "else", "{", "$", "csp", "[", "$", "directive", "]", "=", "null", ";", "}", "return", "true", ";", "}" ]
Add a CSP directive $directive in either enforcement or report only mode. $directive must be long (defined in CSP spec). Set $isFlag to true if adding a directive that should not hold source values. Will return false on error, true on success. @param string $directive @param bool $isFlag @param bool $reportOnly @return bool
[ "Add", "a", "CSP", "directive", "$directive", "in", "either", "enforcement", "or", "report", "only", "mode", ".", "$directive", "must", "be", "long", "(", "defined", "in", "CSP", "spec", ")", ".", "Set", "$isFlag", "to", "true", "if", "adding", "a", "directive", "that", "should", "not", "hold", "source", "values", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1914-L1943
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.cspDoHash
private function cspDoHash( $string, $algo = null, $isFile = null ) { Types::assert(['string' => [$string], '?string' => [$algo]]); if ( ! isset($algo)) { $algo = 'sha256'; } if ( ! isset($isFile)) { $isFile = false; } if ( ! $isFile) { $hash = hash($algo, $string, true); } else { if (file_exists($string)) { $hash = hash_file($algo, $string, true); } else { $this->addError( __FUNCTION__.': The specified file ' . "<strong>'$string'</strong>, does not exist" ); return ''; } } return base64_encode($hash); }
php
private function cspDoHash( $string, $algo = null, $isFile = null ) { Types::assert(['string' => [$string], '?string' => [$algo]]); if ( ! isset($algo)) { $algo = 'sha256'; } if ( ! isset($isFile)) { $isFile = false; } if ( ! $isFile) { $hash = hash($algo, $string, true); } else { if (file_exists($string)) { $hash = hash_file($algo, $string, true); } else { $this->addError( __FUNCTION__.': The specified file ' . "<strong>'$string'</strong>, does not exist" ); return ''; } } return base64_encode($hash); }
[ "private", "function", "cspDoHash", "(", "$", "string", ",", "$", "algo", "=", "null", ",", "$", "isFile", "=", "null", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "string", "]", ",", "'?string'", "=>", "[", "$", "algo", "]", "]", ")", ";", "if", "(", "!", "isset", "(", "$", "algo", ")", ")", "{", "$", "algo", "=", "'sha256'", ";", "}", "if", "(", "!", "isset", "(", "$", "isFile", ")", ")", "{", "$", "isFile", "=", "false", ";", "}", "if", "(", "!", "$", "isFile", ")", "{", "$", "hash", "=", "hash", "(", "$", "algo", ",", "$", "string", ",", "true", ")", ";", "}", "else", "{", "if", "(", "file_exists", "(", "$", "string", ")", ")", "{", "$", "hash", "=", "hash_file", "(", "$", "algo", ",", "$", "string", ",", "true", ")", ";", "}", "else", "{", "$", "this", "->", "addError", "(", "__FUNCTION__", ".", "': The specified file '", ".", "\"<strong>'$string'</strong>, does not exist\"", ")", ";", "return", "''", ";", "}", "}", "return", "base64_encode", "(", "$", "hash", ")", ";", "}" ]
Generate a hash with algorithm $algo for insertion in a CSP either of $string, or of the contents of a file at path $string iff $isFile is truthy. @param string $string @param string $algo @param bool $isFile @return string
[ "Generate", "a", "hash", "with", "algorithm", "$algo", "for", "insertion", "in", "a", "CSP", "either", "of", "$string", "or", "of", "the", "contents", "of", "a", "file", "at", "path", "$string", "iff", "$isFile", "is", "truthy", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L1955-L1994
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.cspGenerateNonce
private function cspGenerateNonce() { $nonce = base64_encode( openssl_random_pseudo_bytes(30, $isCryptoStrong) ); if ( ! $isCryptoStrong) { $this->addError( 'OpenSSL (openssl_random_pseudo_bytes) reported that it did <strong>not</strong> use a cryptographically strong algorithm to generate the nonce for CSP.', E_USER_WARNING ); } return $nonce; }
php
private function cspGenerateNonce() { $nonce = base64_encode( openssl_random_pseudo_bytes(30, $isCryptoStrong) ); if ( ! $isCryptoStrong) { $this->addError( 'OpenSSL (openssl_random_pseudo_bytes) reported that it did <strong>not</strong> use a cryptographically strong algorithm to generate the nonce for CSP.', E_USER_WARNING ); } return $nonce; }
[ "private", "function", "cspGenerateNonce", "(", ")", "{", "$", "nonce", "=", "base64_encode", "(", "openssl_random_pseudo_bytes", "(", "30", ",", "$", "isCryptoStrong", ")", ")", ";", "if", "(", "!", "$", "isCryptoStrong", ")", "{", "$", "this", "->", "addError", "(", "'OpenSSL (openssl_random_pseudo_bytes) reported that it did\n <strong>not</strong> use a cryptographically strong algorithm\n to generate the nonce for CSP.'", ",", "E_USER_WARNING", ")", ";", "}", "return", "$", "nonce", ";", "}" ]
Generate a nonce for insertion in a CSP. @return string
[ "Generate", "a", "nonce", "for", "insertion", "in", "a", "CSP", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L2001-L2019
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.&
private function &getHPKPObject($reportOnly) { if ( ! isset($reportOnly) or ! $reportOnly) { $hpkp = &$this->hpkp; } else { $hpkp = &$this->hpkpro; } return $hpkp; }
php
private function &getHPKPObject($reportOnly) { if ( ! isset($reportOnly) or ! $reportOnly) { $hpkp = &$this->hpkp; } else { $hpkp = &$this->hpkpro; } return $hpkp; }
[ "private", "function", "&", "getHPKPObject", "(", "$", "reportOnly", ")", "{", "if", "(", "!", "isset", "(", "$", "reportOnly", ")", "or", "!", "$", "reportOnly", ")", "{", "$", "hpkp", "=", "&", "$", "this", "->", "hpkp", ";", "}", "else", "{", "$", "hpkp", "=", "&", "$", "this", "->", "hpkpro", ";", "}", "return", "$", "hpkp", ";", "}" ]
Retrieve a reference to either the HPKP enforcement, or HPKP report only array. @param bool $reportOnly @return &array
[ "Retrieve", "a", "reference", "to", "either", "the", "HPKP", "enforcement", "or", "HPKP", "report", "only", "array", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L2031-L2043
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.addError
private function addError($message, $level = E_USER_NOTICE) { Types::assert( ['string' => [$message], 'int' => [$level]] ); $this->errors[] = new Error($message, $level); }
php
private function addError($message, $level = E_USER_NOTICE) { Types::assert( ['string' => [$message], 'int' => [$level]] ); $this->errors[] = new Error($message, $level); }
[ "private", "function", "addError", "(", "$", "message", ",", "$", "level", "=", "E_USER_NOTICE", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "message", "]", ",", "'int'", "=>", "[", "$", "level", "]", "]", ")", ";", "$", "this", "->", "errors", "[", "]", "=", "new", "Error", "(", "$", "message", ",", "$", "level", ")", ";", "}" ]
Add and store an error internally. @param string $message @param int $level @return void
[ "Add", "and", "store", "an", "error", "internally", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L2055-L2062
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.reportErrors
private function reportErrors() { if ( ! $this->errorReporting) { return; } set_error_handler([get_class(), 'errorHandler']); if ( ! empty($this->errors)) { $this->isBufferReturned = true; } foreach ($this->errors as $error) { trigger_error($error->getMessage(), $error->getLevel()); } restore_error_handler(); }
php
private function reportErrors() { if ( ! $this->errorReporting) { return; } set_error_handler([get_class(), 'errorHandler']); if ( ! empty($this->errors)) { $this->isBufferReturned = true; } foreach ($this->errors as $error) { trigger_error($error->getMessage(), $error->getLevel()); } restore_error_handler(); }
[ "private", "function", "reportErrors", "(", ")", "{", "if", "(", "!", "$", "this", "->", "errorReporting", ")", "{", "return", ";", "}", "set_error_handler", "(", "[", "get_class", "(", ")", ",", "'errorHandler'", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "errors", ")", ")", "{", "$", "this", "->", "isBufferReturned", "=", "true", ";", "}", "foreach", "(", "$", "this", "->", "errors", "as", "$", "error", ")", "{", "trigger_error", "(", "$", "error", "->", "getMessage", "(", ")", ",", "$", "error", "->", "getLevel", "(", ")", ")", ";", "}", "restore_error_handler", "(", ")", ";", "}" ]
Use PHPs `trigger_error` function to trigger all internally stored errors if error reporting is enabled for $this. The error handler will be temporarily set to {@see errorHandler} while errors are dispatched via `trigger_error`. @return void
[ "Use", "PHPs", "trigger_error", "function", "to", "trigger", "all", "internally", "stored", "errors", "if", "error", "reporting", "is", "enabled", "for", "$this", ".", "The", "error", "handler", "will", "be", "temporarily", "set", "to", "{", "@see", "errorHandler", "}", "while", "errors", "are", "dispatched", "via", "trigger_error", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L2072-L2092
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.injectableSameSiteValue
private function injectableSameSiteValue() { if ( ! isset($this->sameSiteCookies) and $this->strictMode) { $sameSite = 'Strict'; } elseif ( ! isset($this->sameSiteCookies)) { $sameSite = 'Lax'; } else { $sameSite = $this->sameSiteCookies; } return $sameSite; }
php
private function injectableSameSiteValue() { if ( ! isset($this->sameSiteCookies) and $this->strictMode) { $sameSite = 'Strict'; } elseif ( ! isset($this->sameSiteCookies)) { $sameSite = 'Lax'; } else { $sameSite = $this->sameSiteCookies; } return $sameSite; }
[ "private", "function", "injectableSameSiteValue", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "sameSiteCookies", ")", "and", "$", "this", "->", "strictMode", ")", "{", "$", "sameSite", "=", "'Strict'", ";", "}", "elseif", "(", "!", "isset", "(", "$", "this", "->", "sameSiteCookies", ")", ")", "{", "$", "sameSite", "=", "'Lax'", ";", "}", "else", "{", "$", "sameSite", "=", "$", "this", "->", "sameSiteCookies", ";", "}", "return", "$", "sameSite", ";", "}" ]
Determine the appropriate sameSite value to inject. @return string
[ "Determine", "the", "appropriate", "sameSite", "value", "to", "inject", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L2099-L2115
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.errorHandler
private function errorHandler($level, $message) { Types::assert( ['int' => [$level], 'string' => [$message]] ); if (error_reporting() & $level and (strtolower(ini_get('display_errors')) === 'on' and ini_get('display_errors')) ) { if ($level === E_USER_NOTICE) { $error = '<strong>Notice:</strong> ' .$message. "<br><br>\n\n"; } elseif ($level === E_USER_WARNING) { $error = '<strong>Warning:</strong> ' .$message. "<br><br>\n\n"; } if (isset($error)) { echo $error; $this->errorString .= $error; return true; } } return false; }
php
private function errorHandler($level, $message) { Types::assert( ['int' => [$level], 'string' => [$message]] ); if (error_reporting() & $level and (strtolower(ini_get('display_errors')) === 'on' and ini_get('display_errors')) ) { if ($level === E_USER_NOTICE) { $error = '<strong>Notice:</strong> ' .$message. "<br><br>\n\n"; } elseif ($level === E_USER_WARNING) { $error = '<strong>Warning:</strong> ' .$message. "<br><br>\n\n"; } if (isset($error)) { echo $error; $this->errorString .= $error; return true; } } return false; }
[ "private", "function", "errorHandler", "(", "$", "level", ",", "$", "message", ")", "{", "Types", "::", "assert", "(", "[", "'int'", "=>", "[", "$", "level", "]", ",", "'string'", "=>", "[", "$", "message", "]", "]", ")", ";", "if", "(", "error_reporting", "(", ")", "&", "$", "level", "and", "(", "strtolower", "(", "ini_get", "(", "'display_errors'", ")", ")", "===", "'on'", "and", "ini_get", "(", "'display_errors'", ")", ")", ")", "{", "if", "(", "$", "level", "===", "E_USER_NOTICE", ")", "{", "$", "error", "=", "'<strong>Notice:</strong> '", ".", "$", "message", ".", "\"<br><br>\\n\\n\"", ";", "}", "elseif", "(", "$", "level", "===", "E_USER_WARNING", ")", "{", "$", "error", "=", "'<strong>Warning:</strong> '", ".", "$", "message", ".", "\"<br><br>\\n\\n\"", ";", "}", "if", "(", "isset", "(", "$", "error", ")", ")", "{", "echo", "$", "error", ";", "$", "this", "->", "errorString", ".=", "$", "error", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Echo an error iff PHPs settings allow error reporting, at the level of errors given, and PHPs display_errors setting is on. Will return `true` if an error is echoed, `false` otherwise. @param int $level @param string $message @return bool
[ "Echo", "an", "error", "iff", "PHPs", "settings", "allow", "error", "reporting", "at", "the", "level", "of", "errors", "given", "and", "PHPs", "display_errors", "setting", "is", "on", ".", "Will", "return", "true", "if", "an", "error", "is", "echoed", "false", "otherwise", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L2126-L2153
aidantwoods/SecureHeaders
src/SecureHeaders.php
SecureHeaders.reportMissingHeaders
private function reportMissingHeaders(HeaderBag $headers) { foreach ($this->reportMissingHeaders as $header) { if ( ! $headers->has($header) and empty($this->reportMissingExceptions[strtolower($header)]) ) { $this->addError( "Missing security header: '$header'", E_USER_WARNING ); } } }
php
private function reportMissingHeaders(HeaderBag $headers) { foreach ($this->reportMissingHeaders as $header) { if ( ! $headers->has($header) and empty($this->reportMissingExceptions[strtolower($header)]) ) { $this->addError( "Missing security header: '$header'", E_USER_WARNING ); } } }
[ "private", "function", "reportMissingHeaders", "(", "HeaderBag", "$", "headers", ")", "{", "foreach", "(", "$", "this", "->", "reportMissingHeaders", "as", "$", "header", ")", "{", "if", "(", "!", "$", "headers", "->", "has", "(", "$", "header", ")", "and", "empty", "(", "$", "this", "->", "reportMissingExceptions", "[", "strtolower", "(", "$", "header", ")", "]", ")", ")", "{", "$", "this", "->", "addError", "(", "\"Missing security header: '$header'\"", ",", "E_USER_WARNING", ")", ";", "}", "}", "}" ]
If $headers is missing certain headers of security value that are not on the user-defined exception to reporting list then internally store an error warning that the header is not present. @param HeaderBag $headers @return void
[ "If", "$headers", "is", "missing", "certain", "headers", "of", "security", "value", "that", "are", "not", "on", "the", "user", "-", "defined", "exception", "to", "reporting", "list", "then", "internally", "store", "an", "error", "warning", "that", "the", "header", "is", "not", "present", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/SecureHeaders.php#L2163-L2177
aidantwoods/SecureHeaders
src/Validator.php
Validator.validate
public static function validate(HeaderBag $headers) { $errors = []; foreach (self::$delegates as $delegate => $headerList) { $class = self::VALIDATOR_NAMESPACE.'\\'.$delegate; if ( ! is_array($headerList)) { $headerList = [$headerList]; } foreach ($headerList as $headerName) { $headers->forEachNamed( $headerName, function (Header $header) use (&$errors, $class) { $errors = array_merge( $errors, $class::validate($header) ); } ); } } return $errors; }
php
public static function validate(HeaderBag $headers) { $errors = []; foreach (self::$delegates as $delegate => $headerList) { $class = self::VALIDATOR_NAMESPACE.'\\'.$delegate; if ( ! is_array($headerList)) { $headerList = [$headerList]; } foreach ($headerList as $headerName) { $headers->forEachNamed( $headerName, function (Header $header) use (&$errors, $class) { $errors = array_merge( $errors, $class::validate($header) ); } ); } } return $errors; }
[ "public", "static", "function", "validate", "(", "HeaderBag", "$", "headers", ")", "{", "$", "errors", "=", "[", "]", ";", "foreach", "(", "self", "::", "$", "delegates", "as", "$", "delegate", "=>", "$", "headerList", ")", "{", "$", "class", "=", "self", "::", "VALIDATOR_NAMESPACE", ".", "'\\\\'", ".", "$", "delegate", ";", "if", "(", "!", "is_array", "(", "$", "headerList", ")", ")", "{", "$", "headerList", "=", "[", "$", "headerList", "]", ";", "}", "foreach", "(", "$", "headerList", "as", "$", "headerName", ")", "{", "$", "headers", "->", "forEachNamed", "(", "$", "headerName", ",", "function", "(", "Header", "$", "header", ")", "use", "(", "&", "$", "errors", ",", "$", "class", ")", "{", "$", "errors", "=", "array_merge", "(", "$", "errors", ",", "$", "class", "::", "validate", "(", "$", "header", ")", ")", ";", "}", ")", ";", "}", "}", "return", "$", "errors", ";", "}" ]
Validate the given headers @param HeaderBag $headers @return Error[]
[ "Validate", "the", "given", "headers" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Validator.php#L28-L57
aidantwoods/SecureHeaders
src/Operations/AddHeader.php
AddHeader.modify
public function modify(HeaderBag &$headers) { if ( ! $headers->has($this->name)) { foreach ($this->value as $value) { $headers->add($this->name, $value); } } }
php
public function modify(HeaderBag &$headers) { if ( ! $headers->has($this->name)) { foreach ($this->value as $value) { $headers->add($this->name, $value); } } }
[ "public", "function", "modify", "(", "HeaderBag", "&", "$", "headers", ")", "{", "if", "(", "!", "$", "headers", "->", "has", "(", "$", "this", "->", "name", ")", ")", "{", "foreach", "(", "$", "this", "->", "value", "as", "$", "value", ")", "{", "$", "headers", "->", "add", "(", "$", "this", "->", "name", ",", "$", "value", ")", ";", "}", "}", "}" ]
Transform the given set of headers @param HeaderBag $headers @return void
[ "Transform", "the", "given", "set", "of", "headers" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/AddHeader.php#L42-L51
aidantwoods/SecureHeaders
src/Http/Psr7Adapter.php
Psr7Adapter.sendHeaders
public function sendHeaders(HeaderBag $headers) { # First, remove all headers on the response object $headersToRemove = $this->response->getHeaders(); foreach ($headersToRemove as $name => $headerLines) { $this->response = $this->response->withoutHeader($name); } # And then, reset all headers from the HeaderBag instance foreach ($headers->get() as $header) { $this->response = $this->response->withAddedHeader( $header->getName(), $header->getValue() ); } }
php
public function sendHeaders(HeaderBag $headers) { # First, remove all headers on the response object $headersToRemove = $this->response->getHeaders(); foreach ($headersToRemove as $name => $headerLines) { $this->response = $this->response->withoutHeader($name); } # And then, reset all headers from the HeaderBag instance foreach ($headers->get() as $header) { $this->response = $this->response->withAddedHeader( $header->getName(), $header->getValue() ); } }
[ "public", "function", "sendHeaders", "(", "HeaderBag", "$", "headers", ")", "{", "# First, remove all headers on the response object", "$", "headersToRemove", "=", "$", "this", "->", "response", "->", "getHeaders", "(", ")", ";", "foreach", "(", "$", "headersToRemove", "as", "$", "name", "=>", "$", "headerLines", ")", "{", "$", "this", "->", "response", "=", "$", "this", "->", "response", "->", "withoutHeader", "(", "$", "name", ")", ";", "}", "# And then, reset all headers from the HeaderBag instance", "foreach", "(", "$", "headers", "->", "get", "(", ")", "as", "$", "header", ")", "{", "$", "this", "->", "response", "=", "$", "this", "->", "response", "->", "withAddedHeader", "(", "$", "header", "->", "getName", "(", ")", ",", "$", "header", "->", "getValue", "(", ")", ")", ";", "}", "}" ]
Send the given headers, overwriting all previously send headers @api @param HeaderBag $headers @return void
[ "Send", "the", "given", "headers", "overwriting", "all", "previously", "send", "headers" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Http/Psr7Adapter.php#L31-L48
aidantwoods/SecureHeaders
src/Http/Psr7Adapter.php
Psr7Adapter.getHeaders
public function getHeaders() { $headerLines = []; foreach ($this->response->getHeaders() as $name => $lines) { foreach ($lines as $line) { $headerLines[] = "$name: $line"; } } return HeaderBag::fromHeaderLines($headerLines); }
php
public function getHeaders() { $headerLines = []; foreach ($this->response->getHeaders() as $name => $lines) { foreach ($lines as $line) { $headerLines[] = "$name: $line"; } } return HeaderBag::fromHeaderLines($headerLines); }
[ "public", "function", "getHeaders", "(", ")", "{", "$", "headerLines", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "response", "->", "getHeaders", "(", ")", "as", "$", "name", "=>", "$", "lines", ")", "{", "foreach", "(", "$", "lines", "as", "$", "line", ")", "{", "$", "headerLines", "[", "]", "=", "\"$name: $line\"", ";", "}", "}", "return", "HeaderBag", "::", "fromHeaderLines", "(", "$", "headerLines", ")", ";", "}" ]
Retrieve the current list of already-sent (or planned-to-be-sent) headers @api @return HeaderBag
[ "Retrieve", "the", "current", "list", "of", "already", "-", "sent", "(", "or", "planned", "-", "to", "-", "be", "-", "sent", ")", "headers" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Http/Psr7Adapter.php#L57-L69
aidantwoods/SecureHeaders
src/ValidatorDelegates/CSPBadFlags.php
CSPBadFlags.validate
public static function validate(Header $header) { $Errors = []; $Errors = array_merge( $Errors, self::validateSrcAttribute($header, 'default-src'), self::validateSrcAttribute($header, 'script-src') ); return array_values(array_filter($Errors)); }
php
public static function validate(Header $header) { $Errors = []; $Errors = array_merge( $Errors, self::validateSrcAttribute($header, 'default-src'), self::validateSrcAttribute($header, 'script-src') ); return array_values(array_filter($Errors)); }
[ "public", "static", "function", "validate", "(", "Header", "$", "header", ")", "{", "$", "Errors", "=", "[", "]", ";", "$", "Errors", "=", "array_merge", "(", "$", "Errors", ",", "self", "::", "validateSrcAttribute", "(", "$", "header", ",", "'default-src'", ")", ",", "self", "::", "validateSrcAttribute", "(", "$", "header", ",", "'script-src'", ")", ")", ";", "return", "array_values", "(", "array_filter", "(", "$", "Errors", ")", ")", ";", "}" ]
Validate the given header @param Header $header @return Error[]
[ "Validate", "the", "given", "header" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/ValidatorDelegates/CSPBadFlags.php#L19-L30
aidantwoods/SecureHeaders
src/ValidatorDelegates/CSPBadFlags.php
CSPBadFlags.validateSrcAttribute
private static function validateSrcAttribute(Header $header, $attributeName) { Types::assert(['string' => [$attributeName]], [2]); $Errors = []; if ($header->hasAttribute($attributeName)) { $value = $header->getAttributeValue($attributeName); $badFlags = ["'unsafe-inline'", "'unsafe-eval'"]; foreach ($badFlags as $badFlag) { if (strpos($value, $badFlag) !== false) { $friendlyHeader = $header->getFriendlyName(); $Errors[] = new Error( $friendlyHeader . ' contains the <b>' . $badFlag . '</b> keyword in <b>' . $attributeName . '</b>, which prevents CSP protecting against the injection of arbitrary code into the page.', E_USER_WARNING ); } } } return $Errors; }
php
private static function validateSrcAttribute(Header $header, $attributeName) { Types::assert(['string' => [$attributeName]], [2]); $Errors = []; if ($header->hasAttribute($attributeName)) { $value = $header->getAttributeValue($attributeName); $badFlags = ["'unsafe-inline'", "'unsafe-eval'"]; foreach ($badFlags as $badFlag) { if (strpos($value, $badFlag) !== false) { $friendlyHeader = $header->getFriendlyName(); $Errors[] = new Error( $friendlyHeader . ' contains the <b>' . $badFlag . '</b> keyword in <b>' . $attributeName . '</b>, which prevents CSP protecting against the injection of arbitrary code into the page.', E_USER_WARNING ); } } } return $Errors; }
[ "private", "static", "function", "validateSrcAttribute", "(", "Header", "$", "header", ",", "$", "attributeName", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "attributeName", "]", "]", ",", "[", "2", "]", ")", ";", "$", "Errors", "=", "[", "]", ";", "if", "(", "$", "header", "->", "hasAttribute", "(", "$", "attributeName", ")", ")", "{", "$", "value", "=", "$", "header", "->", "getAttributeValue", "(", "$", "attributeName", ")", ";", "$", "badFlags", "=", "[", "\"'unsafe-inline'\"", ",", "\"'unsafe-eval'\"", "]", ";", "foreach", "(", "$", "badFlags", "as", "$", "badFlag", ")", "{", "if", "(", "strpos", "(", "$", "value", ",", "$", "badFlag", ")", "!==", "false", ")", "{", "$", "friendlyHeader", "=", "$", "header", "->", "getFriendlyName", "(", ")", ";", "$", "Errors", "[", "]", "=", "new", "Error", "(", "$", "friendlyHeader", ".", "' contains the <b>'", ".", "$", "badFlag", ".", "'</b> keyword in <b>'", ".", "$", "attributeName", ".", "'</b>, which prevents CSP protecting\n against the injection of arbitrary code\n into the page.'", ",", "E_USER_WARNING", ")", ";", "}", "}", "}", "return", "$", "Errors", ";", "}" ]
Find bad flags in the given attribute @param Header $header @param string $attributeName @return Error[]
[ "Find", "bad", "flags", "in", "the", "given", "attribute" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/ValidatorDelegates/CSPBadFlags.php#L40-L71
aidantwoods/SecureHeaders
src/Headers/CSPHeader.php
CSPHeader.parseAttributes
protected function parseAttributes() { $this->attributes = []; $policy = CompileCSP::deconstructCSP($this->value); foreach ($policy as $directive => $sources) { if ( ! isset($this->attributes[$directive])) { $this->attributes[$directive] = []; } $this->attributes[$directive][] = [ 'name' => $directive, 'value' => $sources === true ?: implode(' ', $sources) ]; } }
php
protected function parseAttributes() { $this->attributes = []; $policy = CompileCSP::deconstructCSP($this->value); foreach ($policy as $directive => $sources) { if ( ! isset($this->attributes[$directive])) { $this->attributes[$directive] = []; } $this->attributes[$directive][] = [ 'name' => $directive, 'value' => $sources === true ?: implode(' ', $sources) ]; } }
[ "protected", "function", "parseAttributes", "(", ")", "{", "$", "this", "->", "attributes", "=", "[", "]", ";", "$", "policy", "=", "CompileCSP", "::", "deconstructCSP", "(", "$", "this", "->", "value", ")", ";", "foreach", "(", "$", "policy", "as", "$", "directive", "=>", "$", "sources", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "attributes", "[", "$", "directive", "]", ")", ")", "{", "$", "this", "->", "attributes", "[", "$", "directive", "]", "=", "[", "]", ";", "}", "$", "this", "->", "attributes", "[", "$", "directive", "]", "[", "]", "=", "[", "'name'", "=>", "$", "directive", ",", "'value'", "=>", "$", "sources", "===", "true", "?", ":", "implode", "(", "' '", ",", "$", "sources", ")", "]", ";", "}", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Headers/CSPHeader.php#L14-L32
aidantwoods/SecureHeaders
src/Headers/CSPHeader.php
CSPHeader.writeAttributesToValue
protected function writeAttributesToValue() { $policies = []; foreach ($this->attributes as $attributes) { foreach ($attributes as $attrInfo) { $directive = $attrInfo['name']; $value = $attrInfo['value']; if ($value === true) { $string = $directive; } elseif ( ! is_string($value) or trim($value) === '') { continue; } else { $string = "$directive $value"; } $policy = CompileCSP::deconstructCSP($string); $policies[] = $policy; } } $policy = CompileCSP::mergeCSPList($policies); $this->value = CompileCSP::compile($policy); }
php
protected function writeAttributesToValue() { $policies = []; foreach ($this->attributes as $attributes) { foreach ($attributes as $attrInfo) { $directive = $attrInfo['name']; $value = $attrInfo['value']; if ($value === true) { $string = $directive; } elseif ( ! is_string($value) or trim($value) === '') { continue; } else { $string = "$directive $value"; } $policy = CompileCSP::deconstructCSP($string); $policies[] = $policy; } } $policy = CompileCSP::mergeCSPList($policies); $this->value = CompileCSP::compile($policy); }
[ "protected", "function", "writeAttributesToValue", "(", ")", "{", "$", "policies", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "attributes", "as", "$", "attributes", ")", "{", "foreach", "(", "$", "attributes", "as", "$", "attrInfo", ")", "{", "$", "directive", "=", "$", "attrInfo", "[", "'name'", "]", ";", "$", "value", "=", "$", "attrInfo", "[", "'value'", "]", ";", "if", "(", "$", "value", "===", "true", ")", "{", "$", "string", "=", "$", "directive", ";", "}", "elseif", "(", "!", "is_string", "(", "$", "value", ")", "or", "trim", "(", "$", "value", ")", "===", "''", ")", "{", "continue", ";", "}", "else", "{", "$", "string", "=", "\"$directive $value\"", ";", "}", "$", "policy", "=", "CompileCSP", "::", "deconstructCSP", "(", "$", "string", ")", ";", "$", "policies", "[", "]", "=", "$", "policy", ";", "}", "}", "$", "policy", "=", "CompileCSP", "::", "mergeCSPList", "(", "$", "policies", ")", ";", "$", "this", "->", "value", "=", "CompileCSP", "::", "compile", "(", "$", "policy", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Headers/CSPHeader.php#L37-L70
aidantwoods/SecureHeaders
src/Headers/CSPHeader.php
CSPHeader.setAttribute
public function setAttribute($name, $value = true) { Types::assert(['string' => [$name], 'int|bool|string' => [$value]]); $key = strtolower($name); if ( ! isset($this->attributes[$key])) { $this->attributes[$key] = []; } $this->attributes[$key][] = [ 'name' => $name, 'value' => $value ]; $this->writeAttributesToValue(); }
php
public function setAttribute($name, $value = true) { Types::assert(['string' => [$name], 'int|bool|string' => [$value]]); $key = strtolower($name); if ( ! isset($this->attributes[$key])) { $this->attributes[$key] = []; } $this->attributes[$key][] = [ 'name' => $name, 'value' => $value ]; $this->writeAttributesToValue(); }
[ "public", "function", "setAttribute", "(", "$", "name", ",", "$", "value", "=", "true", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "name", "]", ",", "'int|bool|string'", "=>", "[", "$", "value", "]", "]", ")", ";", "$", "key", "=", "strtolower", "(", "$", "name", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "attributes", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "attributes", "[", "$", "key", "]", "=", "[", "]", ";", "}", "$", "this", "->", "attributes", "[", "$", "key", "]", "[", "]", "=", "[", "'name'", "=>", "$", "name", ",", "'value'", "=>", "$", "value", "]", ";", "$", "this", "->", "writeAttributesToValue", "(", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Headers/CSPHeader.php#L75-L92
aidantwoods/SecureHeaders
src/Http/StringHttpAdapter.php
StringHttpAdapter.getSentHeaders
public function getSentHeaders() { $compiledHeaders = []; foreach ($this->headers as $header) { $compiledHeaders[] = (string) $header; } return implode("\n", $compiledHeaders); }
php
public function getSentHeaders() { $compiledHeaders = []; foreach ($this->headers as $header) { $compiledHeaders[] = (string) $header; } return implode("\n", $compiledHeaders); }
[ "public", "function", "getSentHeaders", "(", ")", "{", "$", "compiledHeaders", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "headers", "as", "$", "header", ")", "{", "$", "compiledHeaders", "[", "]", "=", "(", "string", ")", "$", "header", ";", "}", "return", "implode", "(", "\"\\n\"", ",", "$", "compiledHeaders", ")", ";", "}" ]
@api @return string
[ "@api" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Http/StringHttpAdapter.php#L55-L65
aidantwoods/SecureHeaders
src/ValidatorDelegates/CSPWildcards.php
CSPWildcards.validate
public static function validate(Header $header) { $errors = []; $header->forEachAttribute( function ($directive, $sources) use ($header, &$errors) { // $sources may be bool if directive is a CSP flag if ( ! is_string($sources)) { return; } $errors[] = self::enumerateWildcards( $header, $directive, $sources ); $errors[] = self::enumerateNonHttps( $header, $directive, $sources ); } ); return array_values(array_filter($errors)); }
php
public static function validate(Header $header) { $errors = []; $header->forEachAttribute( function ($directive, $sources) use ($header, &$errors) { // $sources may be bool if directive is a CSP flag if ( ! is_string($sources)) { return; } $errors[] = self::enumerateWildcards( $header, $directive, $sources ); $errors[] = self::enumerateNonHttps( $header, $directive, $sources ); } ); return array_values(array_filter($errors)); }
[ "public", "static", "function", "validate", "(", "Header", "$", "header", ")", "{", "$", "errors", "=", "[", "]", ";", "$", "header", "->", "forEachAttribute", "(", "function", "(", "$", "directive", ",", "$", "sources", ")", "use", "(", "$", "header", ",", "&", "$", "errors", ")", "{", "// $sources may be bool if directive is a CSP flag", "if", "(", "!", "is_string", "(", "$", "sources", ")", ")", "{", "return", ";", "}", "$", "errors", "[", "]", "=", "self", "::", "enumerateWildcards", "(", "$", "header", ",", "$", "directive", ",", "$", "sources", ")", ";", "$", "errors", "[", "]", "=", "self", "::", "enumerateNonHttps", "(", "$", "header", ",", "$", "directive", ",", "$", "sources", ")", ";", "}", ")", ";", "return", "array_values", "(", "array_filter", "(", "$", "errors", ")", ")", ";", "}" ]
Validate the given header @param Header $header @return Error[]
[ "Validate", "the", "given", "header" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/ValidatorDelegates/CSPWildcards.php#L53-L80
aidantwoods/SecureHeaders
src/ValidatorDelegates/CSPWildcards.php
CSPWildcards.enumerateWildcards
private static function enumerateWildcards( Header $header, $directive, $sources ) { Types::assert(['string' => [$directive, $sources]], [2, 3]); if (preg_match_all(self::CSP_SOURCE_WILDCARD_RE, $sources, $matches)) { if ( ! in_array($directive, self::$cspSensitiveDirectives)) { # if we're not looking at one of the above, we'll # be a little less strict with data: if (($key = array_search('data:', $matches[0])) !== false) { unset($matches[0][$key]); } } if ( ! empty($matches[0])) { $friendlyHeader = $header->getFriendlyName(); return new Error( $friendlyHeader . ' ' . (count($matches[0]) > 1 ? 'contains the following wildcards ' : 'contains a wildcard ') . '<b>' . implode(', ', $matches[0]) . '</b> as a source value in <b>' . $directive . '</b>; this can allow anyone to insert elements covered by the <b>' . $directive . '</b> directive into the page.', E_USER_WARNING ); } } return null; }
php
private static function enumerateWildcards( Header $header, $directive, $sources ) { Types::assert(['string' => [$directive, $sources]], [2, 3]); if (preg_match_all(self::CSP_SOURCE_WILDCARD_RE, $sources, $matches)) { if ( ! in_array($directive, self::$cspSensitiveDirectives)) { # if we're not looking at one of the above, we'll # be a little less strict with data: if (($key = array_search('data:', $matches[0])) !== false) { unset($matches[0][$key]); } } if ( ! empty($matches[0])) { $friendlyHeader = $header->getFriendlyName(); return new Error( $friendlyHeader . ' ' . (count($matches[0]) > 1 ? 'contains the following wildcards ' : 'contains a wildcard ') . '<b>' . implode(', ', $matches[0]) . '</b> as a source value in <b>' . $directive . '</b>; this can allow anyone to insert elements covered by the <b>' . $directive . '</b> directive into the page.', E_USER_WARNING ); } } return null; }
[ "private", "static", "function", "enumerateWildcards", "(", "Header", "$", "header", ",", "$", "directive", ",", "$", "sources", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "directive", ",", "$", "sources", "]", "]", ",", "[", "2", ",", "3", "]", ")", ";", "if", "(", "preg_match_all", "(", "self", "::", "CSP_SOURCE_WILDCARD_RE", ",", "$", "sources", ",", "$", "matches", ")", ")", "{", "if", "(", "!", "in_array", "(", "$", "directive", ",", "self", "::", "$", "cspSensitiveDirectives", ")", ")", "{", "# if we're not looking at one of the above, we'll", "# be a little less strict with data:", "if", "(", "(", "$", "key", "=", "array_search", "(", "'data:'", ",", "$", "matches", "[", "0", "]", ")", ")", "!==", "false", ")", "{", "unset", "(", "$", "matches", "[", "0", "]", "[", "$", "key", "]", ")", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "matches", "[", "0", "]", ")", ")", "{", "$", "friendlyHeader", "=", "$", "header", "->", "getFriendlyName", "(", ")", ";", "return", "new", "Error", "(", "$", "friendlyHeader", ".", "' '", ".", "(", "count", "(", "$", "matches", "[", "0", "]", ")", ">", "1", "?", "'contains the following wildcards '", ":", "'contains a wildcard '", ")", ".", "'<b>'", ".", "implode", "(", "', '", ",", "$", "matches", "[", "0", "]", ")", ".", "'</b> as a\n source value in <b>'", ".", "$", "directive", ".", "'</b>; this can\n allow anyone to insert elements covered by\n the <b>'", ".", "$", "directive", ".", "'</b> directive into the\n page.'", ",", "E_USER_WARNING", ")", ";", "}", "}", "return", "null", ";", "}" ]
Find wildcards in CSP directives @param Header $header @param string $directive @param string $sources @return ?Error
[ "Find", "wildcards", "in", "CSP", "directives" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/ValidatorDelegates/CSPWildcards.php#L91-L130
aidantwoods/SecureHeaders
src/ValidatorDelegates/CSPWildcards.php
CSPWildcards.enumerateNonHttps
private static function enumerateNonHttps( Header $header, $directive, $sources ) { Types::assert(['string' => [$directive, $sources]], [2, 3]); if (preg_match_all('/(?:[ ]|^)\Khttp[:][^ ]*/', $sources, $matches)) { $friendlyHeader = $header->getFriendlyName(); return new Error( $friendlyHeader . ' contains the insecure protocol HTTP in ' . (count($matches[0]) > 1 ? 'the following source values ' : 'a source value ') . '<b>' . implode(', ', $matches[0]) . '</b>; this can allow anyone to insert elements covered by the <b>' . $directive . '</b> directive into the page.', E_USER_WARNING ); } return null; }
php
private static function enumerateNonHttps( Header $header, $directive, $sources ) { Types::assert(['string' => [$directive, $sources]], [2, 3]); if (preg_match_all('/(?:[ ]|^)\Khttp[:][^ ]*/', $sources, $matches)) { $friendlyHeader = $header->getFriendlyName(); return new Error( $friendlyHeader . ' contains the insecure protocol HTTP in ' . (count($matches[0]) > 1 ? 'the following source values ' : 'a source value ') . '<b>' . implode(', ', $matches[0]) . '</b>; this can allow anyone to insert elements covered by the <b>' . $directive . '</b> directive into the page.', E_USER_WARNING ); } return null; }
[ "private", "static", "function", "enumerateNonHttps", "(", "Header", "$", "header", ",", "$", "directive", ",", "$", "sources", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "directive", ",", "$", "sources", "]", "]", ",", "[", "2", ",", "3", "]", ")", ";", "if", "(", "preg_match_all", "(", "'/(?:[ ]|^)\\Khttp[:][^ ]*/'", ",", "$", "sources", ",", "$", "matches", ")", ")", "{", "$", "friendlyHeader", "=", "$", "header", "->", "getFriendlyName", "(", ")", ";", "return", "new", "Error", "(", "$", "friendlyHeader", ".", "' contains the insecure protocol\n HTTP in '", ".", "(", "count", "(", "$", "matches", "[", "0", "]", ")", ">", "1", "?", "'the following source values '", ":", "'a source value '", ")", ".", "'<b>'", ".", "implode", "(", "', '", ",", "$", "matches", "[", "0", "]", ")", ".", "'</b>; this can\n allow anyone to insert elements covered by the\n <b>'", ".", "$", "directive", ".", "'</b> directive into the page.'", ",", "E_USER_WARNING", ")", ";", "}", "return", "null", ";", "}" ]
Find non secure origins in CSP directives @param Header $header @param string $directive @param string $sources @return ?Error
[ "Find", "non", "secure", "origins", "in", "CSP", "directives" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/ValidatorDelegates/CSPWildcards.php#L141-L166
aidantwoods/SecureHeaders
src/Operations/ModifyCookies.php
ModifyCookies.matchingFully
public static function matchingFully(array $cookieNames, $field, $value = true) { Types::assert(['string' => [$field]], [2]); return new static($cookieNames, $field, $value); }
php
public static function matchingFully(array $cookieNames, $field, $value = true) { Types::assert(['string' => [$field]], [2]); return new static($cookieNames, $field, $value); }
[ "public", "static", "function", "matchingFully", "(", "array", "$", "cookieNames", ",", "$", "field", ",", "$", "value", "=", "true", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "field", "]", "]", ",", "[", "2", "]", ")", ";", "return", "new", "static", "(", "$", "cookieNames", ",", "$", "field", ",", "$", "value", ")", ";", "}" ]
Create an Operation to modify cookies with names $cookieNames such that $field holds $value. @param array $cookieNames @param string $field @param $value @return Operation
[ "Create", "an", "Operation", "to", "modify", "cookies", "with", "names", "$cookieNames", "such", "that", "$field", "holds", "$value", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/ModifyCookies.php#L43-L48
aidantwoods/SecureHeaders
src/Operations/ModifyCookies.php
ModifyCookies.matchingPartially
public static function matchingPartially(array $cookieSubstrs, $field, $value = true) { Types::assert(['string' => [$field]], [2]); $instance = new static($cookieSubstrs, $field, $value); $instance->matchSubstring = true; return $instance; }
php
public static function matchingPartially(array $cookieSubstrs, $field, $value = true) { Types::assert(['string' => [$field]], [2]); $instance = new static($cookieSubstrs, $field, $value); $instance->matchSubstring = true; return $instance; }
[ "public", "static", "function", "matchingPartially", "(", "array", "$", "cookieSubstrs", ",", "$", "field", ",", "$", "value", "=", "true", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "field", "]", "]", ",", "[", "2", "]", ")", ";", "$", "instance", "=", "new", "static", "(", "$", "cookieSubstrs", ",", "$", "field", ",", "$", "value", ")", ";", "$", "instance", "->", "matchSubstring", "=", "true", ";", "return", "$", "instance", ";", "}" ]
Create an operation to modify cookies with name substrings matching $cookieSubstrs such that $field holds $value. @param array $cookieSubstrs @param string $field @param $value @return Operation
[ "Create", "an", "operation", "to", "modify", "cookies", "with", "name", "substrings", "matching", "$cookieSubstrs", "such", "that", "$field", "holds", "$value", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/ModifyCookies.php#L59-L67
aidantwoods/SecureHeaders
src/Operations/ModifyCookies.php
ModifyCookies.modify
public function modify(HeaderBag &$headers) { foreach ($headers->getByName('set-cookie') as $cookieHeader) { $cookieName = $cookieHeader->getFirstAttributeName(); if ( ! $cookieHeader->hasAttribute($this->field) and $this->isCandidateCookie($cookieName)) { $cookieHeader->setAttribute($this->field, $this->value); } } }
php
public function modify(HeaderBag &$headers) { foreach ($headers->getByName('set-cookie') as $cookieHeader) { $cookieName = $cookieHeader->getFirstAttributeName(); if ( ! $cookieHeader->hasAttribute($this->field) and $this->isCandidateCookie($cookieName)) { $cookieHeader->setAttribute($this->field, $this->value); } } }
[ "public", "function", "modify", "(", "HeaderBag", "&", "$", "headers", ")", "{", "foreach", "(", "$", "headers", "->", "getByName", "(", "'set-cookie'", ")", "as", "$", "cookieHeader", ")", "{", "$", "cookieName", "=", "$", "cookieHeader", "->", "getFirstAttributeName", "(", ")", ";", "if", "(", "!", "$", "cookieHeader", "->", "hasAttribute", "(", "$", "this", "->", "field", ")", "and", "$", "this", "->", "isCandidateCookie", "(", "$", "cookieName", ")", ")", "{", "$", "cookieHeader", "->", "setAttribute", "(", "$", "this", "->", "field", ",", "$", "this", "->", "value", ")", ";", "}", "}", "}" ]
Transform the given set of headers @param HeaderBag $headers @return void
[ "Transform", "the", "given", "set", "of", "headers" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/ModifyCookies.php#L75-L86
aidantwoods/SecureHeaders
src/Operations/ModifyCookies.php
ModifyCookies.isCandidateCookie
private function isCandidateCookie($cookieName) { Types::assert(['string' => [$cookieName]]); if ($this->matchSubstring) { return $this->matchesSubstring($cookieName); } else { return $this->matchesFully($cookieName); } }
php
private function isCandidateCookie($cookieName) { Types::assert(['string' => [$cookieName]]); if ($this->matchSubstring) { return $this->matchesSubstring($cookieName); } else { return $this->matchesFully($cookieName); } }
[ "private", "function", "isCandidateCookie", "(", "$", "cookieName", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "cookieName", "]", "]", ")", ";", "if", "(", "$", "this", "->", "matchSubstring", ")", "{", "return", "$", "this", "->", "matchesSubstring", "(", "$", "cookieName", ")", ";", "}", "else", "{", "return", "$", "this", "->", "matchesFully", "(", "$", "cookieName", ")", ";", "}", "}" ]
Determine whether $cookieName is a candidate for modification by the current Operation @param string $cookieName @return bool
[ "Determine", "whether", "$cookieName", "is", "a", "candidate", "for", "modification", "by", "the", "current", "Operation" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/ModifyCookies.php#L95-L107
aidantwoods/SecureHeaders
src/Operations/ModifyCookies.php
ModifyCookies.matchesSubstring
private function matchesSubstring($cookieName) { Types::assert(['string' => [$cookieName]]); foreach ($this->cookieList as $forbidden) { if (strpos(strtolower($cookieName), $forbidden) !== false) { return true; } } return false; }
php
private function matchesSubstring($cookieName) { Types::assert(['string' => [$cookieName]]); foreach ($this->cookieList as $forbidden) { if (strpos(strtolower($cookieName), $forbidden) !== false) { return true; } } return false; }
[ "private", "function", "matchesSubstring", "(", "$", "cookieName", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "cookieName", "]", "]", ")", ";", "foreach", "(", "$", "this", "->", "cookieList", "as", "$", "forbidden", ")", "{", "if", "(", "strpos", "(", "strtolower", "(", "$", "cookieName", ")", ",", "$", "forbidden", ")", "!==", "false", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Determine whether $cookieName is a candidate for modification by the current Operation's internal substring list @param string $cookieName @return bool
[ "Determine", "whether", "$cookieName", "is", "a", "candidate", "for", "modification", "by", "the", "current", "Operation", "s", "internal", "substring", "list" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/ModifyCookies.php#L116-L129
aidantwoods/SecureHeaders
src/Operations/ModifyCookies.php
ModifyCookies.matchesFully
private function matchesFully($cookieName) { Types::assert(['string' => [$cookieName]]); return in_array( strtolower($cookieName), $this->cookieList, true ); }
php
private function matchesFully($cookieName) { Types::assert(['string' => [$cookieName]]); return in_array( strtolower($cookieName), $this->cookieList, true ); }
[ "private", "function", "matchesFully", "(", "$", "cookieName", ")", "{", "Types", "::", "assert", "(", "[", "'string'", "=>", "[", "$", "cookieName", "]", "]", ")", ";", "return", "in_array", "(", "strtolower", "(", "$", "cookieName", ")", ",", "$", "this", "->", "cookieList", ",", "true", ")", ";", "}" ]
Determine whether $cookieName is a candidate for modification by the current Operation's internal cookie name list @param string $cookieName @return bool
[ "Determine", "whether", "$cookieName", "is", "a", "candidate", "for", "modification", "by", "the", "current", "Operation", "s", "internal", "cookie", "name", "list" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/ModifyCookies.php#L138-L147
aidantwoods/SecureHeaders
src/Operations/RemoveHeaders.php
RemoveHeaders.modify
public function modify(HeaderBag &$headers) { foreach ($this->headersToRemove as $header) { $headers->remove($header); } }
php
public function modify(HeaderBag &$headers) { foreach ($this->headersToRemove as $header) { $headers->remove($header); } }
[ "public", "function", "modify", "(", "HeaderBag", "&", "$", "headers", ")", "{", "foreach", "(", "$", "this", "->", "headersToRemove", "as", "$", "header", ")", "{", "$", "headers", "->", "remove", "(", "$", "header", ")", ";", "}", "}" ]
Transform the given set of headers @param HeaderBag $headers @return void
[ "Transform", "the", "given", "set", "of", "headers" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/RemoveHeaders.php#L28-L34
aidantwoods/SecureHeaders
src/Util/Types.php
Types.assert
public static function assert(array $typeList, array $argNums = null) { $i = 0; foreach ($typeList as $type => $vars) { $type = self::normalizeType($type); foreach ($vars as $var) { $allowedTypes = explode('|', $type); $nullAllowed = false; foreach ($allowedTypes as $i => $t) { if (strlen($t) > 0 and $t[0] === '?') { $nullAllowed = true; $allowedTypes[$i] = substr($t, 1); } } if ($nullAllowed) { $allowedTypes[] = 'NULL'; } if ( ! in_array(($varType = gettype($var)), $allowedTypes)) { if ( ! isset($argNums)) { $argNums = self::generateArgNums($typeList); } throw TypeError::fromBacktrace($argNums[$i], $type, $varType, 2); } $i++; } } }
php
public static function assert(array $typeList, array $argNums = null) { $i = 0; foreach ($typeList as $type => $vars) { $type = self::normalizeType($type); foreach ($vars as $var) { $allowedTypes = explode('|', $type); $nullAllowed = false; foreach ($allowedTypes as $i => $t) { if (strlen($t) > 0 and $t[0] === '?') { $nullAllowed = true; $allowedTypes[$i] = substr($t, 1); } } if ($nullAllowed) { $allowedTypes[] = 'NULL'; } if ( ! in_array(($varType = gettype($var)), $allowedTypes)) { if ( ! isset($argNums)) { $argNums = self::generateArgNums($typeList); } throw TypeError::fromBacktrace($argNums[$i], $type, $varType, 2); } $i++; } } }
[ "public", "static", "function", "assert", "(", "array", "$", "typeList", ",", "array", "$", "argNums", "=", "null", ")", "{", "$", "i", "=", "0", ";", "foreach", "(", "$", "typeList", "as", "$", "type", "=>", "$", "vars", ")", "{", "$", "type", "=", "self", "::", "normalizeType", "(", "$", "type", ")", ";", "foreach", "(", "$", "vars", "as", "$", "var", ")", "{", "$", "allowedTypes", "=", "explode", "(", "'|'", ",", "$", "type", ")", ";", "$", "nullAllowed", "=", "false", ";", "foreach", "(", "$", "allowedTypes", "as", "$", "i", "=>", "$", "t", ")", "{", "if", "(", "strlen", "(", "$", "t", ")", ">", "0", "and", "$", "t", "[", "0", "]", "===", "'?'", ")", "{", "$", "nullAllowed", "=", "true", ";", "$", "allowedTypes", "[", "$", "i", "]", "=", "substr", "(", "$", "t", ",", "1", ")", ";", "}", "}", "if", "(", "$", "nullAllowed", ")", "{", "$", "allowedTypes", "[", "]", "=", "'NULL'", ";", "}", "if", "(", "!", "in_array", "(", "(", "$", "varType", "=", "gettype", "(", "$", "var", ")", ")", ",", "$", "allowedTypes", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "argNums", ")", ")", "{", "$", "argNums", "=", "self", "::", "generateArgNums", "(", "$", "typeList", ")", ";", "}", "throw", "TypeError", "::", "fromBacktrace", "(", "$", "argNums", "[", "$", "i", "]", ",", "$", "type", ",", "$", "varType", ",", "2", ")", ";", "}", "$", "i", "++", ";", "}", "}", "}" ]
Assert that $typeList maps expected types to an array of that type. The type NULL is permitted (assertion assumes types are nullable). Optionally provide $argNums as an ordered list of argument numbers to be displayed in the exception message if arguments are recieved out of order, not starting at one, or have gaps from what would be recieved in the function's argument list ordering. @param array $typeList @param array $argNums
[ "Assert", "that", "$typeList", "maps", "expected", "types", "to", "an", "array", "of", "that", "type", ".", "The", "type", "NULL", "is", "permitted", "(", "assertion", "assumes", "types", "are", "nullable", ")", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Util/Types.php#L19-L59
aidantwoods/SecureHeaders
src/Util/Types.php
Types.generateArgNums
private static function generateArgNums(array $typeList) { $n = array_sum(array_map( function ($vars) { return count((array) $vars); }, $typeList )); return range(1, $n); }
php
private static function generateArgNums(array $typeList) { $n = array_sum(array_map( function ($vars) { return count((array) $vars); }, $typeList )); return range(1, $n); }
[ "private", "static", "function", "generateArgNums", "(", "array", "$", "typeList", ")", "{", "$", "n", "=", "array_sum", "(", "array_map", "(", "function", "(", "$", "vars", ")", "{", "return", "count", "(", "(", "array", ")", "$", "vars", ")", ";", "}", ",", "$", "typeList", ")", ")", ";", "return", "range", "(", "1", ",", "$", "n", ")", ";", "}" ]
Generate sequential argument numbers for $typeList. @param array $typeList @return int[]
[ "Generate", "sequential", "argument", "numbers", "for", "$typeList", "." ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Util/Types.php#L67-L78
aidantwoods/SecureHeaders
src/Operations/ApplySafeMode.php
ApplySafeMode.modify
public function modify(HeaderBag &$headers) { foreach ($headers->get() as $header) { $headerName = $header->getName(); $isUnsafe = array_key_exists($headerName, self::$unsafeHeaders); $hasException = array_key_exists($headerName, $this->exceptions); if ($isUnsafe && ! $hasException) { $method = self::$unsafeHeaders[$headerName]; $this->$method($header); } } }
php
public function modify(HeaderBag &$headers) { foreach ($headers->get() as $header) { $headerName = $header->getName(); $isUnsafe = array_key_exists($headerName, self::$unsafeHeaders); $hasException = array_key_exists($headerName, $this->exceptions); if ($isUnsafe && ! $hasException) { $method = self::$unsafeHeaders[$headerName]; $this->$method($header); } } }
[ "public", "function", "modify", "(", "HeaderBag", "&", "$", "headers", ")", "{", "foreach", "(", "$", "headers", "->", "get", "(", ")", "as", "$", "header", ")", "{", "$", "headerName", "=", "$", "header", "->", "getName", "(", ")", ";", "$", "isUnsafe", "=", "array_key_exists", "(", "$", "headerName", ",", "self", "::", "$", "unsafeHeaders", ")", ";", "$", "hasException", "=", "array_key_exists", "(", "$", "headerName", ",", "$", "this", "->", "exceptions", ")", ";", "if", "(", "$", "isUnsafe", "&&", "!", "$", "hasException", ")", "{", "$", "method", "=", "self", "::", "$", "unsafeHeaders", "[", "$", "headerName", "]", ";", "$", "this", "->", "$", "method", "(", "$", "header", ")", ";", "}", "}", "}" ]
Transform the given set of headers @param HeaderBag $headers @return void
[ "Transform", "the", "given", "set", "of", "headers" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/ApplySafeMode.php#L36-L52
aidantwoods/SecureHeaders
src/Operations/ApplySafeMode.php
ApplySafeMode.sanitizeSTS
private function sanitizeSTS(Header $header) { $origValue = $header->getValue(); # Only do these when the attribute exists! $header->ensureAttributeMaximum('max-age', 86400); $header->removeAttribute('includeSubDomains'); $header->removeAttribute('preload'); if ($header->getValue() !== $origValue) { $this->addError( 'HSTS settings were overridden because Safe-Mode is enabled. <a href="https://scotthelme.co.uk/death-by-copy-paste/\ #hstsandpreloading">Read about</a> some common mistakes when setting HSTS via copy/paste, and ensure you <a href="https://www.owasp.org/index.php/\ HTTP_Strict_Transport_Security_Cheat_Sheet">understand the details</a> and possible side effects of this security feature before using it.' ); } }
php
private function sanitizeSTS(Header $header) { $origValue = $header->getValue(); # Only do these when the attribute exists! $header->ensureAttributeMaximum('max-age', 86400); $header->removeAttribute('includeSubDomains'); $header->removeAttribute('preload'); if ($header->getValue() !== $origValue) { $this->addError( 'HSTS settings were overridden because Safe-Mode is enabled. <a href="https://scotthelme.co.uk/death-by-copy-paste/\ #hstsandpreloading">Read about</a> some common mistakes when setting HSTS via copy/paste, and ensure you <a href="https://www.owasp.org/index.php/\ HTTP_Strict_Transport_Security_Cheat_Sheet">understand the details</a> and possible side effects of this security feature before using it.' ); } }
[ "private", "function", "sanitizeSTS", "(", "Header", "$", "header", ")", "{", "$", "origValue", "=", "$", "header", "->", "getValue", "(", ")", ";", "# Only do these when the attribute exists!", "$", "header", "->", "ensureAttributeMaximum", "(", "'max-age'", ",", "86400", ")", ";", "$", "header", "->", "removeAttribute", "(", "'includeSubDomains'", ")", ";", "$", "header", "->", "removeAttribute", "(", "'preload'", ")", ";", "if", "(", "$", "header", "->", "getValue", "(", ")", "!==", "$", "origValue", ")", "{", "$", "this", "->", "addError", "(", "'HSTS settings were overridden because Safe-Mode is enabled.\n <a href=\"https://scotthelme.co.uk/death-by-copy-paste/\\\n #hstsandpreloading\">Read about</a> some common mistakes when\n setting HSTS via copy/paste, and ensure you\n <a href=\"https://www.owasp.org/index.php/\\\n HTTP_Strict_Transport_Security_Cheat_Sheet\">understand the\n details</a> and possible side effects of this security feature\n before using it.'", ")", ";", "}", "}" ]
Apply safe-mode for HSTS to $header @param Header $header @return void
[ "Apply", "safe", "-", "mode", "for", "HSTS", "to", "$header" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/ApplySafeMode.php#L60-L82
aidantwoods/SecureHeaders
src/Operations/ApplySafeMode.php
ApplySafeMode.sanitizeExpectCT
private function sanitizeExpectCT(Header $header) { $origValue = $header->getValue(); # Only do these when the attributes exist $header->removeAttribute('enforce'); if ($header->getValue() !== $origValue) { $this->addError( 'Some ExpectCT settings were overridden because Safe-Mode is enabled.' ); } }
php
private function sanitizeExpectCT(Header $header) { $origValue = $header->getValue(); # Only do these when the attributes exist $header->removeAttribute('enforce'); if ($header->getValue() !== $origValue) { $this->addError( 'Some ExpectCT settings were overridden because Safe-Mode is enabled.' ); } }
[ "private", "function", "sanitizeExpectCT", "(", "Header", "$", "header", ")", "{", "$", "origValue", "=", "$", "header", "->", "getValue", "(", ")", ";", "# Only do these when the attributes exist", "$", "header", "->", "removeAttribute", "(", "'enforce'", ")", ";", "if", "(", "$", "header", "->", "getValue", "(", ")", "!==", "$", "origValue", ")", "{", "$", "this", "->", "addError", "(", "'Some ExpectCT settings were overridden because Safe-Mode is enabled.'", ")", ";", "}", "}" ]
Apply safe-mode for Expect-CT to $header @param Header $header @return void
[ "Apply", "safe", "-", "mode", "for", "Expect", "-", "CT", "to", "$header" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/ApplySafeMode.php#L112-L125
aidantwoods/SecureHeaders
src/Http/GlobalHttpAdapter.php
GlobalHttpAdapter.sendHeaders
public function sendHeaders(HeaderBag $headers) { header_remove(); foreach ($headers->get() as $header) { header( (string) $header, false ); } }
php
public function sendHeaders(HeaderBag $headers) { header_remove(); foreach ($headers->get() as $header) { header( (string) $header, false ); } }
[ "public", "function", "sendHeaders", "(", "HeaderBag", "$", "headers", ")", "{", "header_remove", "(", ")", ";", "foreach", "(", "$", "headers", "->", "get", "(", ")", "as", "$", "header", ")", "{", "header", "(", "(", "string", ")", "$", "header", ",", "false", ")", ";", "}", "}" ]
Send the given headers, overwriting all previously send headers @api @param HeaderBag $headers @return void
[ "Send", "the", "given", "headers", "overwriting", "all", "previously", "send", "headers" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Http/GlobalHttpAdapter.php#L17-L28
aidantwoods/SecureHeaders
src/Operations/CompileHPKP.php
CompileHPKP.modify
public function modify(HeaderBag &$headers) { $hpkpHeaders = [ 'Public-Key-Pins' => $this->compilePKP(), 'Public-Key-Pins-Report-Only' => $this->compilePKPRO(), ]; foreach ($hpkpHeaders as $header => $value) { if (empty($value)) { continue; } $headers->replace($header, $value); } }
php
public function modify(HeaderBag &$headers) { $hpkpHeaders = [ 'Public-Key-Pins' => $this->compilePKP(), 'Public-Key-Pins-Report-Only' => $this->compilePKPRO(), ]; foreach ($hpkpHeaders as $header => $value) { if (empty($value)) { continue; } $headers->replace($header, $value); } }
[ "public", "function", "modify", "(", "HeaderBag", "&", "$", "headers", ")", "{", "$", "hpkpHeaders", "=", "[", "'Public-Key-Pins'", "=>", "$", "this", "->", "compilePKP", "(", ")", ",", "'Public-Key-Pins-Report-Only'", "=>", "$", "this", "->", "compilePKPRO", "(", ")", ",", "]", ";", "foreach", "(", "$", "hpkpHeaders", "as", "$", "header", "=>", "$", "value", ")", "{", "if", "(", "empty", "(", "$", "value", ")", ")", "{", "continue", ";", "}", "$", "headers", "->", "replace", "(", "$", "header", ",", "$", "value", ")", ";", "}", "}" ]
Transform the given set of headers @param HeaderBag $headers @return void
[ "Transform", "the", "given", "set", "of", "headers" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/CompileHPKP.php#L33-L49
aidantwoods/SecureHeaders
src/Operations/CompileHPKP.php
CompileHPKP.compile
private function compile(array $config) { if (empty($config) or empty($config['pins'])) { return ''; } $maxAge = isset($config['max-age']) ? $config['max-age'] : 10; $pieces = ["max-age=$maxAge"]; foreach ($config['pins'] as $pinAlg) { list($pin, $alg) = $pinAlg; $pieces[] = "pin-$alg=\"$pin\""; } if ($config['includesubdomains']) { $pieces[] = 'includeSubDomains'; } if ($config['report-uri']) { $pieces[] = 'report-uri="' . $config['report-uri'] . '"'; } return implode('; ', $pieces); }
php
private function compile(array $config) { if (empty($config) or empty($config['pins'])) { return ''; } $maxAge = isset($config['max-age']) ? $config['max-age'] : 10; $pieces = ["max-age=$maxAge"]; foreach ($config['pins'] as $pinAlg) { list($pin, $alg) = $pinAlg; $pieces[] = "pin-$alg=\"$pin\""; } if ($config['includesubdomains']) { $pieces[] = 'includeSubDomains'; } if ($config['report-uri']) { $pieces[] = 'report-uri="' . $config['report-uri'] . '"'; } return implode('; ', $pieces); }
[ "private", "function", "compile", "(", "array", "$", "config", ")", "{", "if", "(", "empty", "(", "$", "config", ")", "or", "empty", "(", "$", "config", "[", "'pins'", "]", ")", ")", "{", "return", "''", ";", "}", "$", "maxAge", "=", "isset", "(", "$", "config", "[", "'max-age'", "]", ")", "?", "$", "config", "[", "'max-age'", "]", ":", "10", ";", "$", "pieces", "=", "[", "\"max-age=$maxAge\"", "]", ";", "foreach", "(", "$", "config", "[", "'pins'", "]", "as", "$", "pinAlg", ")", "{", "list", "(", "$", "pin", ",", "$", "alg", ")", "=", "$", "pinAlg", ";", "$", "pieces", "[", "]", "=", "\"pin-$alg=\\\"$pin\\\"\"", ";", "}", "if", "(", "$", "config", "[", "'includesubdomains'", "]", ")", "{", "$", "pieces", "[", "]", "=", "'includeSubDomains'", ";", "}", "if", "(", "$", "config", "[", "'report-uri'", "]", ")", "{", "$", "pieces", "[", "]", "=", "'report-uri=\"'", ".", "$", "config", "[", "'report-uri'", "]", ".", "'\"'", ";", "}", "return", "implode", "(", "'; '", ",", "$", "pieces", ")", ";", "}" ]
Compile HPKP $config into a HPKP header-value string @param array $config @return string
[ "Compile", "HPKP", "$config", "into", "a", "HPKP", "header", "-", "value", "string" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/CompileHPKP.php#L77-L106
aidantwoods/SecureHeaders
src/Operations/RemoveCookies.php
RemoveCookies.modify
public function modify(HeaderBag &$headers) { $cookies = $headers->getByName('set-cookie'); $headers->remove('set-cookie'); foreach ($cookies as $key => $cookie) { $cookieName = $cookie->getFirstAttributeName(); if ( ! in_array(strtolower($cookieName), $this->removedCookies)) { $headers->add('Set-Cookie', $cookie->getValue()); } } }
php
public function modify(HeaderBag &$headers) { $cookies = $headers->getByName('set-cookie'); $headers->remove('set-cookie'); foreach ($cookies as $key => $cookie) { $cookieName = $cookie->getFirstAttributeName(); if ( ! in_array(strtolower($cookieName), $this->removedCookies)) { $headers->add('Set-Cookie', $cookie->getValue()); } } }
[ "public", "function", "modify", "(", "HeaderBag", "&", "$", "headers", ")", "{", "$", "cookies", "=", "$", "headers", "->", "getByName", "(", "'set-cookie'", ")", ";", "$", "headers", "->", "remove", "(", "'set-cookie'", ")", ";", "foreach", "(", "$", "cookies", "as", "$", "key", "=>", "$", "cookie", ")", "{", "$", "cookieName", "=", "$", "cookie", "->", "getFirstAttributeName", "(", ")", ";", "if", "(", "!", "in_array", "(", "strtolower", "(", "$", "cookieName", ")", ",", "$", "this", "->", "removedCookies", ")", ")", "{", "$", "headers", "->", "add", "(", "'Set-Cookie'", ",", "$", "cookie", "->", "getValue", "(", ")", ")", ";", "}", "}", "}" ]
Transform the given set of headers @param HeaderBag $headers @return void
[ "Transform", "the", "given", "set", "of", "headers" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/RemoveCookies.php#L28-L43
aidantwoods/SecureHeaders
src/Operations/CompileCSP.php
CompileCSP.modify
public function modify(HeaderBag &$headers) { $cspHeaders = [ 'Content-Security-Policy' => 'csp', 'Content-Security-Policy-Report-Only' => 'cspro', ]; foreach ($cspHeaders as $header => $type) { if ($this->combine) { $otherPolicyHeaders = $headers->getByName($header); $policies = [$this->{$type.'Config'}]; foreach ($otherPolicyHeaders as $otherPolicy) { $policies[] = self::deconstructCSP($otherPolicy->getValue()); } $this->{$type.'Config'} = self::mergeCSPList($policies); } $value = $this->{'compile'.strtoupper($type)}(); if (empty($value)) { continue; } $headers->{($this->combine ? 'replace' : 'add')}($header, $value); if ($this->sendLegacyHeaders) { $headers->{($this->combine ? 'replace' : 'add')}("X-$header", $value); } } }
php
public function modify(HeaderBag &$headers) { $cspHeaders = [ 'Content-Security-Policy' => 'csp', 'Content-Security-Policy-Report-Only' => 'cspro', ]; foreach ($cspHeaders as $header => $type) { if ($this->combine) { $otherPolicyHeaders = $headers->getByName($header); $policies = [$this->{$type.'Config'}]; foreach ($otherPolicyHeaders as $otherPolicy) { $policies[] = self::deconstructCSP($otherPolicy->getValue()); } $this->{$type.'Config'} = self::mergeCSPList($policies); } $value = $this->{'compile'.strtoupper($type)}(); if (empty($value)) { continue; } $headers->{($this->combine ? 'replace' : 'add')}($header, $value); if ($this->sendLegacyHeaders) { $headers->{($this->combine ? 'replace' : 'add')}("X-$header", $value); } } }
[ "public", "function", "modify", "(", "HeaderBag", "&", "$", "headers", ")", "{", "$", "cspHeaders", "=", "[", "'Content-Security-Policy'", "=>", "'csp'", ",", "'Content-Security-Policy-Report-Only'", "=>", "'cspro'", ",", "]", ";", "foreach", "(", "$", "cspHeaders", "as", "$", "header", "=>", "$", "type", ")", "{", "if", "(", "$", "this", "->", "combine", ")", "{", "$", "otherPolicyHeaders", "=", "$", "headers", "->", "getByName", "(", "$", "header", ")", ";", "$", "policies", "=", "[", "$", "this", "->", "{", "$", "type", ".", "'Config'", "}", "]", ";", "foreach", "(", "$", "otherPolicyHeaders", "as", "$", "otherPolicy", ")", "{", "$", "policies", "[", "]", "=", "self", "::", "deconstructCSP", "(", "$", "otherPolicy", "->", "getValue", "(", ")", ")", ";", "}", "$", "this", "->", "{", "$", "type", ".", "'Config'", "}", "=", "self", "::", "mergeCSPList", "(", "$", "policies", ")", ";", "}", "$", "value", "=", "$", "this", "->", "{", "'compile'", ".", "strtoupper", "(", "$", "type", ")", "}", "(", ")", ";", "if", "(", "empty", "(", "$", "value", ")", ")", "{", "continue", ";", "}", "$", "headers", "->", "{", "(", "$", "this", "->", "combine", "?", "'replace'", ":", "'add'", ")", "}", "(", "$", "header", ",", "$", "value", ")", ";", "if", "(", "$", "this", "->", "sendLegacyHeaders", ")", "{", "$", "headers", "->", "{", "(", "$", "this", "->", "combine", "?", "'replace'", ":", "'add'", ")", "}", "(", "\"X-$header\"", ",", "$", "value", ")", ";", "}", "}", "}" ]
Transform the given set of headers @param HeaderBag $headers @return void
[ "Transform", "the", "given", "set", "of", "headers" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/CompileCSP.php#L61-L99
aidantwoods/SecureHeaders
src/Operations/CompileCSP.php
CompileCSP.compileCSPRO
private function compileCSPRO() { # Filter out the blacklisted directives $filteredConfig = array_diff_key( $this->csproConfig, array_flip($this->csproBlacklist) ); return self::compile($filteredConfig); }
php
private function compileCSPRO() { # Filter out the blacklisted directives $filteredConfig = array_diff_key( $this->csproConfig, array_flip($this->csproBlacklist) ); return self::compile($filteredConfig); }
[ "private", "function", "compileCSPRO", "(", ")", "{", "# Filter out the blacklisted directives", "$", "filteredConfig", "=", "array_diff_key", "(", "$", "this", "->", "csproConfig", ",", "array_flip", "(", "$", "this", "->", "csproBlacklist", ")", ")", ";", "return", "self", "::", "compile", "(", "$", "filteredConfig", ")", ";", "}" ]
Compile internal CSPRO config into a CSP header-value string @return string
[ "Compile", "internal", "CSPRO", "config", "into", "a", "CSP", "header", "-", "value", "string" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/CompileCSP.php#L116-L125
aidantwoods/SecureHeaders
src/Operations/CompileCSP.php
CompileCSP.compile
public static function compile(array $config) { $pieces = []; foreach ($config as $directive => $sources) { if (is_array($sources)) { self::removeEmptySources($sources); self::removeDuplicateSources($sources); array_unshift($sources, $directive); $pieces[] = implode(' ', $sources); } else { $pieces[] = $directive; } } return implode('; ', $pieces); }
php
public static function compile(array $config) { $pieces = []; foreach ($config as $directive => $sources) { if (is_array($sources)) { self::removeEmptySources($sources); self::removeDuplicateSources($sources); array_unshift($sources, $directive); $pieces[] = implode(' ', $sources); } else { $pieces[] = $directive; } } return implode('; ', $pieces); }
[ "public", "static", "function", "compile", "(", "array", "$", "config", ")", "{", "$", "pieces", "=", "[", "]", ";", "foreach", "(", "$", "config", "as", "$", "directive", "=>", "$", "sources", ")", "{", "if", "(", "is_array", "(", "$", "sources", ")", ")", "{", "self", "::", "removeEmptySources", "(", "$", "sources", ")", ";", "self", "::", "removeDuplicateSources", "(", "$", "sources", ")", ";", "array_unshift", "(", "$", "sources", ",", "$", "directive", ")", ";", "$", "pieces", "[", "]", "=", "implode", "(", "' '", ",", "$", "sources", ")", ";", "}", "else", "{", "$", "pieces", "[", "]", "=", "$", "directive", ";", "}", "}", "return", "implode", "(", "'; '", ",", "$", "pieces", ")", ";", "}" ]
Compile CSP $config into a CSP header-value string @param array $config @return string
[ "Compile", "CSP", "$config", "into", "a", "CSP", "header", "-", "value", "string" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/CompileCSP.php#L133-L155
aidantwoods/SecureHeaders
src/Operations/CompileCSP.php
CompileCSP.deconstructCSP
public static function deconstructCSP($cspString) { $csp = []; $directivesAndSources = explode(';', $cspString); foreach ($directivesAndSources as $directiveAndSources) { $directiveAndSources = ltrim($directiveAndSources); $list = explode(' ', $directiveAndSources, 2); $directive = strtolower($list[0]); if (isset($csp[$directive])) { continue; } if (isset($list[1]) and trim($list[1]) !== '') { $sourcesString = $list[1]; $sources = explode(' ', $sourcesString); self::removeEmptySources($sources); } else { $sources = true; } $csp[$directive] = $sources; } return $csp; }
php
public static function deconstructCSP($cspString) { $csp = []; $directivesAndSources = explode(';', $cspString); foreach ($directivesAndSources as $directiveAndSources) { $directiveAndSources = ltrim($directiveAndSources); $list = explode(' ', $directiveAndSources, 2); $directive = strtolower($list[0]); if (isset($csp[$directive])) { continue; } if (isset($list[1]) and trim($list[1]) !== '') { $sourcesString = $list[1]; $sources = explode(' ', $sourcesString); self::removeEmptySources($sources); } else { $sources = true; } $csp[$directive] = $sources; } return $csp; }
[ "public", "static", "function", "deconstructCSP", "(", "$", "cspString", ")", "{", "$", "csp", "=", "[", "]", ";", "$", "directivesAndSources", "=", "explode", "(", "';'", ",", "$", "cspString", ")", ";", "foreach", "(", "$", "directivesAndSources", "as", "$", "directiveAndSources", ")", "{", "$", "directiveAndSources", "=", "ltrim", "(", "$", "directiveAndSources", ")", ";", "$", "list", "=", "explode", "(", "' '", ",", "$", "directiveAndSources", ",", "2", ")", ";", "$", "directive", "=", "strtolower", "(", "$", "list", "[", "0", "]", ")", ";", "if", "(", "isset", "(", "$", "csp", "[", "$", "directive", "]", ")", ")", "{", "continue", ";", "}", "if", "(", "isset", "(", "$", "list", "[", "1", "]", ")", "and", "trim", "(", "$", "list", "[", "1", "]", ")", "!==", "''", ")", "{", "$", "sourcesString", "=", "$", "list", "[", "1", "]", ";", "$", "sources", "=", "explode", "(", "' '", ",", "$", "sourcesString", ")", ";", "self", "::", "removeEmptySources", "(", "$", "sources", ")", ";", "}", "else", "{", "$", "sources", "=", "true", ";", "}", "$", "csp", "[", "$", "directive", "]", "=", "$", "sources", ";", "}", "return", "$", "csp", ";", "}" ]
Deconstruct $cspString into a CSP config array @param string $cspString @return array
[ "Deconstruct", "$cspString", "into", "a", "CSP", "config", "array" ]
train
https://github.com/aidantwoods/SecureHeaders/blob/6037dbfbd32dcbffd2409afd25ed6293c8e3fb43/src/Operations/CompileCSP.php#L163-L199