_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q256400 | JedGenerator.buildMessages | test | public static function buildMessages( Translations $translations ) {
$plural_forms = $translations->getPluralForms();
$number_of_plurals = is_array( $plural_forms ) ? ( $plural_forms[0] - 1 ) : null;
$messages = [];
$context_glue = chr( 4 );
foreach ( $translations as $translation ) {
/** @var Translation $translation */
if ( $translation->isDisabled() ) {
continue;
}
$key = $translation->getOriginal();
if ( $translation->hasContext() ) {
$key = $translation->getContext() . $context_glue . $key;
}
if ( $translation->hasPluralTranslations( true ) ) {
$message = $translation->getPluralTranslations( $number_of_plurals );
array_unshift( $message, $translation->getTranslation() );
} else {
$message = [ $translation->getTranslation() ];
}
$messages[ $key ] = $message;
}
return $messages;
} | php | {
"resource": ""
} |
q256401 | PotGenerator.setCommentBeforeHeaders | test | public static function setCommentBeforeHeaders( $comment ) {
$comments = explode( "\n", $comment );
foreach ( $comments as $line ) {
if ( '' !== trim( $line ) ) {
static::$comments_before_headers[] = '# ' . $line;
}
}
} | php | {
"resource": ""
} |
q256402 | PotGenerator.addLines | test | private static function addLines( array &$lines, $name, $value ) {
$newlines = self::multilineQuote( $value );
if ( count( $newlines ) === 1 ) {
$lines[] = $name . ' ' . $newlines[0];
} else {
$lines[] = $name . ' ""';
foreach ( $newlines as $line ) {
$lines[] = $line;
}
}
} | php | {
"resource": ""
} |
q256403 | MakePotCommand.get_main_file_data | test | protected function get_main_file_data() {
$files = new IteratorIterator( new DirectoryIterator( $this->source ) );
/** @var DirectoryIterator $file */
foreach ( $files as $file ) {
// wp-content/themes/my-theme/style.css
if ( $file->isFile() && 'style' === $file->getBasename( '.css' ) && $file->isReadable() ) {
$theme_data = static::get_file_data( $file->getRealPath(), array_combine( $this->get_file_headers( 'theme' ), $this->get_file_headers( 'theme' ) ) );
// Stop when it contains a valid Theme Name header.
if ( ! empty( $theme_data['Theme Name'] ) ) {
WP_CLI::log( 'Theme stylesheet detected.' );
WP_CLI::debug( sprintf( 'Theme stylesheet: %s', $file->getRealPath() ), 'make-pot' );
$this->project_type = 'theme';
return $theme_data;
}
}
// wp-content/themes/my-themes/theme-a/style.css
if ( $file->isDir() && ! $file->isDot() && is_readable( $file->getRealPath() . '/style.css' ) ) {
$theme_data = static::get_file_data( $file->getRealPath() . '/style.css', array_combine( $this->get_file_headers( 'theme' ), $this->get_file_headers( 'theme' ) ) );
// Stop when it contains a valid Theme Name header.
if ( ! empty( $theme_data['Theme Name'] ) ) {
WP_CLI::log( 'Theme stylesheet detected.' );
WP_CLI::debug( sprintf( 'Theme stylesheet: %s', $file->getRealPath() . '/style.css' ), 'make-pot' );
$this->project_type = 'theme';
return $theme_data;
}
}
// wp-content/plugins/my-plugin/my-plugin.php
if ( $file->isFile() && $file->isReadable() && 'php' === $file->getExtension() ) {
$plugin_data = static::get_file_data( $file->getRealPath(), array_combine( $this->get_file_headers( 'plugin' ), $this->get_file_headers( 'plugin' ) ) );
// Stop when we find a file with a valid Plugin Name header.
if ( ! empty( $plugin_data['Plugin Name'] ) ) {
WP_CLI::log( 'Plugin file detected.' );
WP_CLI::debug( sprintf( 'Plugin file: %s', $file->getRealPath() ), 'make-pot' );
$this->project_type = 'plugin';
return $plugin_data;
}
}
}
WP_CLI::debug( 'No valid theme stylesheet or plugin file found, treating as a regular project.', 'make-pot' );
return [];
} | php | {
"resource": ""
} |
q256404 | MakePotCommand.extract_strings | test | protected function extract_strings() {
$translations = new Translations();
// Add existing strings first but don't keep headers.
if ( ! empty( $this->merge ) ) {
$existing_translations = new Translations();
Po::fromFile( $this->merge, $existing_translations );
$translations->mergeWith( $existing_translations, Merge::ADD | Merge::REMOVE );
}
PotGenerator::setCommentBeforeHeaders( $this->get_file_comment() );
$this->set_default_headers( $translations );
// POT files have no Language header.
$translations->deleteHeader( Translations::HEADER_LANGUAGE );
// Only relevant for PO files, not POT files.
$translations->setHeader( 'PO-Revision-Date', 'YEAR-MO-DA HO:MI+ZONE' );
if ( $this->domain ) {
$translations->setDomain( $this->domain );
}
unset( $this->main_file_data['Version'], $this->main_file_data['License'], $this->main_file_data['Domain Path'], $this->main_file_data['Text Domain'] );
// Set entries from main file data.
foreach ( $this->main_file_data as $header => $data ) {
if ( empty( $data ) ) {
continue;
}
$translation = new Translation( '', $data );
if ( isset( $this->main_file_data['Theme Name'] ) ) {
$translation->addExtractedComment( sprintf( '%s of the theme', $header ) );
} else {
$translation->addExtractedComment( sprintf( '%s of the plugin', $header ) );
}
$translations[] = $translation;
}
try {
$options = [
// Extract 'Template Name' headers in theme files.
'wpExtractTemplates' => isset( $this->main_file_data['Theme Name'] ),
'include' => $this->include,
'exclude' => $this->exclude,
'extensions' => [ 'php' ],
];
PhpCodeExtractor::fromDirectory( $this->source, $translations, $options );
if ( ! $this->skip_js ) {
JsCodeExtractor::fromDirectory(
$this->source,
$translations,
[
'include' => $this->include,
'exclude' => $this->exclude,
'extensions' => [ 'js' ],
]
);
MapCodeExtractor::fromDirectory(
$this->source,
$translations,
[
'include' => $this->include,
'exclude' => $this->exclude,
'extensions' => [ 'map' ],
]
);
}
} catch ( \Exception $e ) {
WP_CLI::error( $e->getMessage() );
}
foreach ( $this->exceptions as $translation ) {
if ( $translations->find( $translation ) ) {
unset( $translations[ $translation->getId() ] );
}
}
if ( ! $this->skip_audit ) {
$this->audit_strings( $translations );
}
return $translations;
} | php | {
"resource": ""
} |
q256405 | MakePotCommand.get_file_comment | test | protected function get_file_comment() {
if ( '' === $this->file_comment ) {
return '';
}
if ( isset( $this->file_comment ) ) {
return implode( "\n", explode( '\n', $this->file_comment ) );
}
if ( isset( $this->main_file_data['Theme Name'] ) ) {
if ( isset( $this->main_file_data['License'] ) ) {
return sprintf(
"Copyright (C) %1\$s %2\$s\nThis file is distributed under the %3\$s.",
date( 'Y' ),
$this->main_file_data['Author'],
$this->main_file_data['License']
);
}
return sprintf(
"Copyright (C) %1\$s %2\$s\nThis file is distributed under the same license as the %3\$s theme.",
date( 'Y' ),
$this->main_file_data['Author'],
$this->main_file_data['Theme Name']
);
}
if ( isset( $this->main_file_data['Plugin Name'] ) ) {
if ( isset( $this->main_file_data['License'] ) ) {
return sprintf(
"Copyright (C) %1\$s %2\$s\nThis file is distributed under the %3\$s.",
date( 'Y' ),
$this->main_file_data['Author'],
$this->main_file_data['License']
);
}
return sprintf(
"Copyright (C) %1\$s %2\$s\nThis file is distributed under the same license as the %3\$s plugin.",
date( 'Y' ),
$this->main_file_data['Author'],
$this->main_file_data['Plugin Name']
);
}
return '';
} | php | {
"resource": ""
} |
q256406 | MakePotCommand.set_default_headers | test | protected function set_default_headers( $translations ) {
$name = null;
$version = $this->get_wp_version();
$bugs_address = null;
if ( ! $version && isset( $this->main_file_data['Version'] ) ) {
$version = $this->main_file_data['Version'];
}
if ( isset( $this->main_file_data['Theme Name'] ) ) {
$name = $this->main_file_data['Theme Name'];
$bugs_address = sprintf( 'https://wordpress.org/support/theme/%s', $this->slug );
} elseif ( isset( $this->main_file_data['Plugin Name'] ) ) {
$name = $this->main_file_data['Plugin Name'];
$bugs_address = sprintf( 'https://wordpress.org/support/plugin/%s', $this->slug );
}
if ( null !== $this->package_name ) {
$name = $this->package_name;
}
if ( null !== $name ) {
$translations->setHeader( 'Project-Id-Version', $name . ( $version ? ' ' . $version : '' ) );
}
if ( null !== $bugs_address ) {
$translations->setHeader( 'Report-Msgid-Bugs-To', $bugs_address );
}
$translations->setHeader( 'Last-Translator', 'FULL NAME <EMAIL@ADDRESS>' );
$translations->setHeader( 'Language-Team', 'LANGUAGE <[email protected]>' );
$translations->setHeader( 'X-Generator', 'WP-CLI ' . WP_CLI_VERSION );
foreach ( $this->headers as $key => $value ) {
$translations->setHeader( $key, $value );
}
} | php | {
"resource": ""
} |
q256407 | MakePotCommand.get_file_data | test | protected static function get_file_data( $file, $headers ) {
// We don't need to write to the file, so just open for reading.
$fp = fopen( $file, 'rb' );
// Pull only the first 8kiB of the file in.
$file_data = fread( $fp, 8192 );
// PHP will close file handle, but we are good citizens.
fclose( $fp );
// Make sure we catch CR-only line endings.
$file_data = str_replace( "\r", "\n", $file_data );
return static::get_file_data_from_string( $file_data, $headers );
} | php | {
"resource": ""
} |
q256408 | MakePotCommand.get_file_data_from_string | test | public static function get_file_data_from_string( $string, $headers ) {
foreach ( $headers as $field => $regex ) {
if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $string, $match ) && $match[1] ) {
$headers[ $field ] = static::_cleanup_header_comment( $match[1] );
} else {
$headers[ $field ] = '';
}
}
return $headers;
} | php | {
"resource": ""
} |
q256409 | JsFunctionsScanner.resolveExpressionCallee | test | private function resolveExpressionCallee( Node\CallExpression $node ) {
$callee = $node->getCallee();
// If the callee is a simple identifier it can simply be returned.
// For example: __( "translation" ).
if ( 'Identifier' === $callee->getType() ) {
return [
'name' => $callee->getName(),
'comments' => $callee->getLeadingComments(),
];
}
// If the callee is a member expression resolve it to the property.
// For example: wp.i18n.__( "translation" ) or u.__( "translation" ).
if (
'MemberExpression' === $callee->getType() &&
'Identifier' === $callee->getProperty()->getType()
) {
// Make sure to unpack wp.i18n which is a nested MemberExpression.
$comments = 'MemberExpression' === $callee->getObject()->getType()
? $callee->getObject()->getObject()->getLeadingComments()
: $callee->getObject()->getLeadingComments();
return [
'name' => $callee->getProperty()->getName(),
'comments' => $comments,
];
}
// If the callee is a call expression as created by Webpack resolve it.
// For example: Object(u.__)( "translation" ).
if (
'CallExpression' === $callee->getType() &&
'Identifier' === $callee->getCallee()->getType() &&
'Object' === $callee->getCallee()->getName() &&
[] !== $callee->getArguments() &&
'MemberExpression' === $callee->getArguments()[0]->getType()
) {
$property = $callee->getArguments()[0]->getProperty();
// Matches minified webpack statements: Object(u.__)( "translation" ).
if ( 'Identifier' === $property->getType() ) {
return [
'name' => $property->getName(),
'comments' => $callee->getCallee()->getLeadingComments(),
];
}
// Matches unminified webpack statements:
// Object(_wordpress_i18n__WEBPACK_IMPORTED_MODULE_7__["__"])( "translation" );
if ( 'Literal' === $property->getType() ) {
return [
'name' => $property->getValue(),
'comments' => $callee->getCallee()->getLeadingComments(),
];
}
}
// Unknown format.
return false;
} | php | {
"resource": ""
} |
q256410 | JsFunctionsScanner.commentPrecedesNode | test | private function commentPrecedesNode( Node\Comment $comment, Node\Node $node ) {
// Comments should be on the same or an earlier line than the translation.
if ( $node->getLocation()->getStart()->getLine() - $comment->getLocation()->getEnd()->getLine() > 1 ) {
return false;
}
// Comments on the same line should be before the translation.
if (
$node->getLocation()->getStart()->getLine() === $comment->getLocation()->getEnd()->getLine() &&
$node->getLocation()->getStart()->getColumn() < $comment->getLocation()->getStart()->getColumn()
) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q256411 | IterableCodeExtractor.calculateMatchScore | test | protected static function calculateMatchScore( SplFileInfo $file, array $matchers = [] ) {
if ( empty( $matchers ) ) {
return 0;
}
if ( in_array( $file->getBasename(), $matchers, true ) ) {
return 10;
}
// Check for more complex paths, e.g. /some/sub/folder.
$root_relative_path = str_replace( static::$dir, '', $file->getPathname() );
foreach ( $matchers as $path_or_file ) {
$pattern = preg_quote( str_replace( '*', '__wildcard__', $path_or_file ), '/' );
$pattern = '(^|/)' . str_replace( '__wildcard__', '(.+)', $pattern );
// Base score is the amount of nested directories, discounting wildcards.
$base_score = count(
array_filter(
explode( '/', $path_or_file ),
function ( $component ) {
return '*' !== $component;
}
)
);
if ( 0 === $base_score ) {
// If the matcher is simply * it gets a score above the implicit score but below 1.
$base_score = 0.2;
}
// If the matcher contains no wildcards and matches the end of the path.
if (
false === strpos( $path_or_file, '*' ) &&
false !== mb_ereg( $pattern . '$', $root_relative_path )
) {
return $base_score * 10;
}
// If the matcher matches the end of the path or a full directory contained.
if ( false !== mb_ereg( $pattern . '(/|$)', $root_relative_path ) ) {
return $base_score;
}
}
return 0;
} | php | {
"resource": ""
} |
q256412 | IterableCodeExtractor.containsMatchingChildren | test | protected static function containsMatchingChildren( SplFileInfo $dir, array $matchers = [] ) {
if ( empty( $matchers ) ) {
return false;
}
/** @var string $root_relative_path */
$root_relative_path = str_replace( static::$dir, '', $dir->getPathname() );
foreach ( $matchers as $path_or_file ) {
// If the matcher contains no wildcards and the path matches the start of the matcher.
if (
'' !== $root_relative_path &&
false === strpos( $path_or_file, '*' ) &&
0 === strpos( $path_or_file . '/', $root_relative_path )
) {
return true;
}
$base = current( explode( '*', $path_or_file ) );
// If start of the path matches the start of the matcher until the first wildcard.
// Or the start of the matcher until the first wildcard matches the start of the path.
if (
( '' !== $root_relative_path && 0 === strpos( $base, $root_relative_path ) ) ||
0 === strpos( $root_relative_path, $base )
) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q256413 | IterableCodeExtractor.getFilesFromDirectory | test | public static function getFilesFromDirectory( $dir, array $include = [], array $exclude = [], $extensions = [] ) {
$filtered_files = [];
$files = new RecursiveIteratorIterator(
new RecursiveCallbackFilterIterator(
new RecursiveDirectoryIterator( $dir, RecursiveDirectoryIterator::SKIP_DOTS | RecursiveDirectoryIterator::UNIX_PATHS ),
function ( $file, $key, $iterator ) use ( $include, $exclude, $extensions ) {
/** @var RecursiveCallbackFilterIterator $iterator */
/** @var SplFileInfo $file */
// If no $include is passed everything gets the weakest possible matching score.
$inclusion_score = empty( $include ) ? 0.1 : static::calculateMatchScore( $file, $include );
$exclusion_score = static::calculateMatchScore( $file, $exclude );
// Always include directories that aren't excluded.
if ( 0 === $exclusion_score && $iterator->hasChildren() ) {
return true;
}
if ( 0 === $inclusion_score || $exclusion_score > $inclusion_score ) {
// Always include directories that may have matching children even if they are excluded.
return $iterator->hasChildren() && static::containsMatchingChildren( $file, $include );
}
return ( $file->isFile() && in_array( $file->getExtension(), $extensions, true ) );
}
),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ( $files as $file ) {
/** @var SplFileInfo $file */
if ( ! $file->isFile() || ! in_array( $file->getExtension(), $extensions, true ) ) {
continue;
}
$filtered_files[] = Utils\normalize_path( $file->getPathname() );
}
return $filtered_files;
} | php | {
"resource": ""
} |
q256414 | MakeJsonCommand.make_json | test | protected function make_json( $source_file, $destination ) {
/** @var Translations[] $mapping */
$mapping = [];
$translations = new Translations();
$result = [];
PoExtractor::fromFile( $source_file, $translations );
$base_file_name = basename( $source_file, '.po' );
foreach ( $translations as $index => $translation ) {
/** @var Translation $translation */
// Find all unique sources this translation originates from.
$sources = array_map(
function ( $reference ) {
$file = $reference[0];
if ( substr( $file, - 7 ) === '.min.js' ) {
return substr( $file, 0, - 7 ) . '.js';
}
if ( substr( $file, - 3 ) === '.js' ) {
return $file;
}
return null;
},
$translation->getReferences()
);
$sources = array_unique( array_filter( $sources ) );
foreach ( $sources as $source ) {
if ( ! isset( $mapping[ $source ] ) ) {
$mapping[ $source ] = new Translations();
// phpcs:ignore Squiz.PHP.CommentedOutCode.Found -- Provide code that is meant to be used once the bug is fixed.
// See https://core.trac.wordpress.org/ticket/45441
// $mapping[ $source ]->setDomain( $translations->getDomain() );
$mapping[ $source ]->setHeader( 'Language', $translations->getLanguage() );
$mapping[ $source ]->setHeader( 'PO-Revision-Date', $translations->getHeader( 'PO-Revision-Date' ) );
$plural_forms = $translations->getPluralForms();
if ( $plural_forms ) {
list( $count, $rule ) = $plural_forms;
$mapping[ $source ]->setPluralForms( $count, $rule );
}
}
$mapping[ $source ][] = $translation;
}
}
$result += $this->build_json_files( $mapping, $base_file_name, $destination );
return $result;
} | php | {
"resource": ""
} |
q256415 | MakeJsonCommand.build_json_files | test | protected function build_json_files( $mapping, $base_file_name, $destination ) {
$result = [];
foreach ( $mapping as $file => $translations ) {
/** @var Translations $translations */
$hash = md5( $file );
$destination_file = "${destination}/{$base_file_name}-{$hash}.json";
$success = JedGenerator::toFile(
$translations,
$destination_file,
[
'json' => $this->json_options,
'source' => $file,
]
);
if ( ! $success ) {
WP_CLI::warning( sprintf( 'Could not create file %s', basename( $destination_file, '.json' ) ) );
continue;
}
$result[] = $destination_file;
}
return $result;
} | php | {
"resource": ""
} |
q256416 | MakeJsonCommand.remove_js_strings_from_po_file | test | protected function remove_js_strings_from_po_file( $source_file ) {
/** @var Translations[] $mapping */
$translations = new Translations();
PoExtractor::fromFile( $source_file, $translations );
foreach ( $translations->getArrayCopy() as $translation ) {
/** @var Translation $translation */
if ( ! $translation->hasReferences() ) {
continue;
}
foreach ( $translation->getReferences() as $reference ) {
$file = $reference[0];
if ( substr( $file, - 3 ) !== '.js' ) {
continue 2;
}
}
unset( $translations[ $translation->getId() ] );
}
return PoGenerator::toFile( $translations, $source_file );
} | php | {
"resource": ""
} |
q256417 | UpdateChecklist.markUpdatesSuccessful | test | public function markUpdatesSuccessful(array $names, $checkListPoints = TRUE) {
if ($this->updateChecklist === FALSE) {
return;
}
$this->setSuccessfulByHook($names, TRUE);
if ($checkListPoints) {
$this->checkListPoints($names);
}
} | php | {
"resource": ""
} |
q256418 | UpdateChecklist.markAllUpdates | test | public function markAllUpdates($status = TRUE) {
if ($this->updateChecklist === FALSE) {
return;
}
$keys = [];
foreach ($this->updateChecklist->items as $versionItems) {
foreach ($versionItems as $key => $item) {
if (is_array($item)) {
$keys[] = $key;
}
}
}
$this->setSuccessfulByHook($keys, $status);
$this->checkAllListPoints($status);
} | php | {
"resource": ""
} |
q256419 | UpdateChecklist.setSuccessfulByHook | test | protected function setSuccessfulByHook(array $keys, $status = TRUE) {
foreach ($keys as $key) {
if ($update = Update::load($key)) {
$update->setSuccessfulByHook($status)->save();
}
else {
Update::create(
[
'id' => $key,
'successful_by_hook' => $status,
]
)->save();
}
}
} | php | {
"resource": ""
} |
q256420 | UpdateChecklist.checkListPoints | test | protected function checkListPoints(array $names) {
/* @var \Drupal\Core\Config\Config $drooplerUpdateConfig */
$drooplerUpdateConfig = $this->configFactory->getEditable('checklistapi.progress.d_update');
$user = $this->account->id();
$time = time();
foreach ($names as $name) {
if ($drooplerUpdateConfig&& !$drooplerUpdateConfig->get(ChecklistapiChecklist::PROGRESS_CONFIG_KEY . ".#items.$name")) {
$drooplerUpdateConfig
->set(ChecklistapiChecklist::PROGRESS_CONFIG_KEY . ".#items.$name", [
'#completed' => time(),
'#uid' => $user,
]);
}
}
$drooplerUpdateConfig
->set(ChecklistapiChecklist::PROGRESS_CONFIG_KEY . '.#completed_items', count($drooplerUpdateConfig->get(ChecklistapiChecklist::PROGRESS_CONFIG_KEY . ".#items")))
->set(ChecklistapiChecklist::PROGRESS_CONFIG_KEY . '.#changed', $time)
->set(ChecklistapiChecklist::PROGRESS_CONFIG_KEY . '.#changed_by', $user)
->save();
} | php | {
"resource": ""
} |
q256421 | UpdateChecklist.checkAllListPoints | test | protected function checkAllListPoints($status = TRUE) {
$drooplerUpdateConfig = $this->configFactory
->getEditable('checklistapi.progress.d_update');
$user = $this->account->id();
$time = time();
$drooplerUpdateConfig
->set(ChecklistapiChecklist::PROGRESS_CONFIG_KEY . '.#changed', $time)
->set(ChecklistapiChecklist::PROGRESS_CONFIG_KEY . '.#changed_by', $user);
$exclude = [
'#title',
'#description',
'#weight',
];
foreach ($this->updateChecklist->items as $versionItems) {
foreach ($versionItems as $itemName => $item) {
if (!in_array($itemName, $exclude)) {
if ($status) {
$drooplerUpdateConfig
->set(ChecklistapiChecklist::PROGRESS_CONFIG_KEY . ".#items.$itemName", [
'#completed' => $time,
'#uid' => $user,
]);
}
else {
$drooplerUpdateConfig
->clear(ChecklistapiChecklist::PROGRESS_CONFIG_KEY . ".#items.$itemName");
}
}
}
}
$drooplerUpdateConfig
->set(ChecklistapiChecklist::PROGRESS_CONFIG_KEY . '.#completed_items', count($drooplerUpdateConfig->get(ChecklistapiChecklist::PROGRESS_CONFIG_KEY . ".#items")))
->save();
} | php | {
"resource": ""
} |
q256422 | UpdateChecklist.saveProgress | test | public function saveProgress(array $values) {
$user = \Drupal::currentUser();
$time = time();
$num_changed_items = 0;
$progress = [
'#changed' => $time,
'#changed_by' => $user->id(),
'#completed_items' => 0,
'#items' => [],
];
$status = [
'positive' => [],
'negative' => [],
];
$drooplerUpdateConfig = $this->configFactory->getEditable('checklistapi.progress.d_update');
$savedProgress = $drooplerUpdateConfig->get(ChecklistapiChecklist::PROGRESS_CONFIG_KEY);
foreach ($values as $group_key => $group) {
foreach ($group as $item_key => $item) {
$old_item = (!empty($savedProgress['#items'][$item_key])) ? $savedProgress['#items'][$item_key] : 0;
if ($item) {
// Item is checked.
$status['positive'][] = $item_key;
$progress['#completed_items']++;
if ($old_item) {
// Item was previously checked. Use saved value.
$new_item = $old_item;
}
else {
// Item is newly checked. Set new value.
$new_item = [
'#completed' => $time,
'#uid' => $user->id(),
];
$num_changed_items++;
}
$progress['#items'][$item_key] = $new_item;
}
else {
// Item is unchecked.
$status['negative'][] = $item_key;
if ($old_item) {
// Item was previously checked.
$num_changed_items++;
}
}
}
}
$this->setSuccessfulByHook($status['positive'], TRUE);
$this->setSuccessfulByHook($status['negative'], FALSE);
ksort($progress);
$drooplerUpdateConfig->set(ChecklistapiChecklist::PROGRESS_CONFIG_KEY, $progress)->save();
drupal_set_message(\Drupal::translation()->formatPlural(
$num_changed_items,
'%title progress has been saved. 1 item changed.',
'%title progress has been saved. @count items changed.',
['%title' => $this->updateChecklist->title]
));
} | php | {
"resource": ""
} |
q256423 | SupportController.render | test | public function render() {
$output = '<h3>' . t('Droopler is a Drupal 8 profile designed to kickstart a new webpage in a few minutes') . '</h3>';
$output .= '<p>' . t('More info about Droopler - <a href=":link">See official Droopler website</a>.', [':link' => 'https://droopler.com/']) . '</p>';
$output .= '<h3>' . t('Support') . '</h3>';
$output .= '<p>' . t('Do You need support with Droopler? - <a href=":link">Droptica.com</a>.', [':link' => 'https://droptica.com']) . '</p>';
$output .= '<h3>' . t('Github') . '</h3>';
$output .= '<p>' . t('<a href=":link">https://github.com/droptica/droopler_project</a> - Boilerplate for new projects based on Droopler. If you wish to use Droopler - fork (or download) this repository. It contains a minimum set of code to start your new website.', [':link' => 'https://github.com/droptica/droopler_project']) . '</p>';
$output .= '<p>' . t('<a href=":link">https://github.com/droptica/droopler</a> - This is Drupal installation profile.', [':link' => 'https://github.com/droptica/droopler']) . '</p>';
return [
'#type' => 'markup',
'#markup' => '<div class="container">' . $output . '</div>',
];
} | php | {
"resource": ""
} |
q256424 | ConfigManager.generateHashFromDatabase | test | public function generateHashFromDatabase($configName) {
$config = \Drupal::config($configName)->getRawData();
if (empty($config)) {
return FALSE;
}
unset($config['uuid']);
unset($config['lang']);
unset($config['langcode']);
$configString = serialize($config);
return md5($configString);
} | php | {
"resource": ""
} |
q256425 | ConfigManager.compare | test | public function compare($configName, $hash = NULL) {
if (empty($hash)) {
return TRUE;
}
else {
return $this->generateHashFromDatabase($configName) == $hash;
}
} | php | {
"resource": ""
} |
q256426 | Updater.importConfig | test | public function importConfig($module, $name, $hash) {
$configPath = drupal_get_path('module', $module) . '/config/install';
$source = new FileStorage($configPath);
$data = $source->read($name);
if (!$data || !$this->configManager->compare($name, $hash)) {
return false;
}
return $this->configStorage->write($name, $data);
} | php | {
"resource": ""
} |
q256427 | Updater.importConfigs | test | public function importConfigs(array $configs) {
$status = [];
foreach ($configs as $module => $config) {
foreach ($config as $configName => $configHash) {
$status[] = $this->importConfig($module, $configName, $configHash);
}
}
return !in_array(false, $status);
} | php | {
"resource": ""
} |
q256428 | Updater.installModules | test | public function installModules(array $modules, $enableDependencies = TRUE) {
if (empty($modules) || !is_array($modules)) {
return FALSE;
}
$moduleData = system_rebuild_module_data();
$modules = array_combine($modules, $modules);
if ($missing_modules = array_diff_key($modules, $moduleData)) {
return FALSE;
}
return $this->moduleInstaller->install($modules, $enableDependencies);
} | php | {
"resource": ""
} |
q256429 | DownloadFile.checkLink | test | public function checkLink($link_hash, $paragraph_id) {
// Load file and paragraph.
$entity = $this->getSubscribeFileEntity('link_hash', $link_hash);
$this->checkLinkActive($entity);
$paragraph = Paragraph::load($paragraph_id);
$file_hash = $entity->get('file_hash')->get(0)->getValue();
$link_options = [
'absolute' => TRUE,
'attributes' => ['class' => 'btn btn-primary btn-orange']
];
// Generate download link/
$button_text = $paragraph->get('field_d_p_sf_download_button')->getValue();
$download_link = Link::createFromRoute($button_text[0]['value'], 'd_p_subscribe_file.downloadfile.getFile', ['file_hash' => $file_hash['value']], $link_options);
$rendered_download_link = $download_link->toString()->getGeneratedLink();
// Generate download page with link.
$display_settings = ['label' => 'hidden',];
$body = $paragraph->get('field_d_p_sf_download_page')->view($display_settings);
$body[0]['#text'] = str_replace("[download-button]", $rendered_download_link, $body[0]['#text']);
return [
'#theme' => 'd_p_subscribe_file_download_page',
'#body' => $body,
];
} | php | {
"resource": ""
} |
q256430 | DownloadFile.checkLinkActive | test | private function checkLinkActive($entity) {
$created = $entity->get('created')->get(0)->getValue();
if (time() > $created['value'] + 86400) {
$this->goHomeWithMessage(t('Link is not active, please add your email again'));
}
} | php | {
"resource": ""
} |
q256431 | DownloadFile.goHomeWithMessage | test | private function goHomeWithMessage($message) {
drupal_set_message($message);
$url = Url::fromRoute('<front>');
$response = new RedirectResponse($url->toString());
$response->send();
} | php | {
"resource": ""
} |
q256432 | DownloadFile.getFile | test | public function getFile($file_hash) {
$entity = $this->getSubscribeFileEntity('file_hash', $file_hash);
$this->checkLinkActive($entity);
$file = File::load($entity->get('fid')->getValue()[0]['value']);
$uri = $file->getFileUri();
$response = new BinaryFileResponse($uri);
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
return $response;
} | php | {
"resource": ""
} |
q256433 | Source.getItemsFromData | test | protected function getItemsFromData($columns)
{
$items = [];
foreach ($this->data as $key => $item) {
foreach ($columns as $column) {
$fieldName = $column->getField();
$fieldValue = '';
if ($this instanceof Entity) {
// Mapped field
$itemEntity = $item;
if (strpos($fieldName, '.') === false) {
$functionName = ucfirst($fieldName);
} else {
// loop through all elements until we find the final entity and the name of the value for which we are looking
$elements = explode('.', $fieldName);
while ($element = array_shift($elements)) {
if (count($elements) > 0) {
$itemEntity = call_user_func([$itemEntity, 'get' . $element]);
} else {
$functionName = ucfirst($element);
}
}
}
// Get value of the column
if (isset($itemEntity->$fieldName)) {
$fieldValue = $itemEntity->$fieldName;
} elseif (is_callable([$itemEntity, $fullFunctionName = 'get' . $functionName])
|| is_callable([$itemEntity, $fullFunctionName = 'has' . $functionName])
|| is_callable([$itemEntity, $fullFunctionName = 'is' . $functionName])) {
$fieldValue = call_user_func([$itemEntity, $fullFunctionName]);
} else {
throw new PropertyAccessDeniedException(sprintf('Property "%s" is not public or has no accessor.', $fieldName));
}
} elseif (isset($item[$fieldName])) {
$fieldValue = $item[$fieldName];
}
$items[$key][$fieldName] = $fieldValue;
}
}
return $items;
} | php | {
"resource": ""
} |
q256434 | Source.getTotalCountFromData | test | public function getTotalCountFromData($maxResults = null)
{
return $maxResults === null ? $this->count : min($this->count, $maxResults);
} | php | {
"resource": ""
} |
q256435 | Source.prepareStringForLikeCompare | test | protected function prepareStringForLikeCompare($input, $type = null)
{
if ($type === 'array') {
$outputString = str_replace(':{i:0;', ':{', serialize($input));
} else {
$outputString = $this->removeAccents($input);
}
return $outputString;
} | php | {
"resource": ""
} |
q256436 | Vector.setData | test | public function setData($data)
{
$this->data = $data;
if (!is_array($this->data) || empty($this->data)) {
throw new \InvalidArgumentException('Data should be an array with content');
}
// This seems to exclude ...
if (is_object(reset($this->data))) {
foreach ($this->data as $key => $object) {
$this->data[$key] = (array) $object;
}
}
// ... this other (or vice versa)
$firstRaw = reset($this->data);
if (!is_array($firstRaw) || empty($firstRaw)) {
throw new \InvalidArgumentException('Data should be a two-dimentional array');
}
} | php | {
"resource": ""
} |
q256437 | GridFactory.resolveType | test | private function resolveType($type)
{
if (!$type instanceof GridTypeInterface) {
if (!is_string($type)) {
throw new UnexpectedTypeException($type, 'string, APY\DataGridBundle\Grid\GridTypeInterface');
}
$type = $this->registry->getType($type);
}
return $type;
} | php | {
"resource": ""
} |
q256438 | GridFactory.resolveOptions | test | private function resolveOptions(GridTypeInterface $type, Source $source = null, array $options = [])
{
$resolver = new OptionsResolver();
$type->configureOptions($resolver);
if (null !== $source && !isset($options['source'])) {
$options['source'] = $source;
}
$options = $resolver->resolve($options);
return $options;
} | php | {
"resource": ""
} |
q256439 | DataGridExtension.getGrid | test | public function getGrid(Twig_Environment $environment, $grid, $theme = null, $id = '', array $params = [], $withjs = true)
{
$this->initGrid($grid, $theme, $id, $params);
// For export
$grid->setTemplate($theme);
return $this->renderBlock($environment, 'grid', ['grid' => $grid, 'withjs' => $withjs]);
} | php | {
"resource": ""
} |
q256440 | DataGridExtension.getGridCell | test | public function getGridCell(Twig_Environment $environment, $column, $row, $grid)
{
$value = $column->renderCell($row->getField($column->getId()), $row, $this->router);
$id = $this->names[$grid->getHash()];
if (($id != '' && ($this->hasBlock($environment, $block = 'grid_' . $id . '_column_' . $column->getRenderBlockId() . '_cell')
|| $this->hasBlock($environment, $block = 'grid_' . $id . '_column_' . $column->getType() . '_cell')
|| $this->hasBlock($environment, $block = 'grid_' . $id . '_column_' . $column->getParentType() . '_cell')
|| $this->hasBlock($environment, $block = 'grid_' . $id . '_column_id_' . $column->getRenderBlockId() . '_cell')
|| $this->hasBlock($environment, $block = 'grid_' . $id . '_column_type_' . $column->getType() . '_cell')
|| $this->hasBlock($environment, $block = 'grid_' . $id . '_column_type_' . $column->getParentType() . '_cell')))
|| $this->hasBlock($environment, $block = 'grid_column_' . $column->getRenderBlockId() . '_cell')
|| $this->hasBlock($environment, $block = 'grid_column_' . $column->getType() . '_cell')
|| $this->hasBlock($environment, $block = 'grid_column_' . $column->getParentType() . '_cell')
|| $this->hasBlock($environment, $block = 'grid_column_id_' . $column->getRenderBlockId() . '_cell')
|| $this->hasBlock($environment, $block = 'grid_column_type_' . $column->getType() . '_cell')
|| $this->hasBlock($environment, $block = 'grid_column_type_' . $column->getParentType() . '_cell')
) {
return $this->renderBlock($environment, $block, ['grid' => $grid, 'column' => $column, 'row' => $row, 'value' => $value]);
}
return $this->renderBlock($environment, 'grid_column_cell', ['grid' => $grid, 'column' => $column, 'row' => $row, 'value' => $value]);
} | php | {
"resource": ""
} |
q256441 | DataGridExtension.getGridFilter | test | public function getGridFilter(Twig_Environment $environment, $column, $grid, $submitOnChange = true)
{
$id = $this->names[$grid->getHash()];
if (($id != '' && ($this->hasBlock($environment, $block = 'grid_' . $id . '_column_' . $column->getRenderBlockId() . '_filter')
|| $this->hasBlock($environment, $block = 'grid_' . $id . '_column_id_' . $column->getRenderBlockId() . '_filter')
|| $this->hasBlock($environment, $block = 'grid_' . $id . '_column_type_' . $column->getType() . '_filter')
|| $this->hasBlock($environment, $block = 'grid_' . $id . '_column_type_' . $column->getParentType() . '_filter'))
|| $this->hasBlock($environment, $block = 'grid_' . $id . '_column_filter_type_' . $column->getFilterType()))
|| $this->hasBlock($environment, $block = 'grid_column_' . $column->getRenderBlockId() . '_filter')
|| $this->hasBlock($environment, $block = 'grid_column_id_' . $column->getRenderBlockId() . '_filter')
|| $this->hasBlock($environment, $block = 'grid_column_type_' . $column->getType() . '_filter')
|| $this->hasBlock($environment, $block = 'grid_column_type_' . $column->getParentType() . '_filter')
|| $this->hasBlock($environment, $block = 'grid_column_filter_type_' . $column->getFilterType())
) {
return $this->renderBlock($environment, $block, ['grid' => $grid, 'column' => $column, 'submitOnChange' => $submitOnChange && $column->isFilterSubmitOnChange()]);
}
return '';
} | php | {
"resource": ""
} |
q256442 | DataGridExtension.getGridColumnOperator | test | public function getGridColumnOperator(Twig_Environment $environment, $column, $grid, $operator, $submitOnChange = true)
{
return $this->renderBlock($environment, 'grid_column_operator', ['grid' => $grid, 'column' => $column, 'submitOnChange' => $submitOnChange, 'op' => $operator]);
} | php | {
"resource": ""
} |
q256443 | DataGridExtension.hasBlock | test | protected function hasBlock(Twig_Environment $environment, $name)
{
foreach ($this->getTemplates($environment) as $template) {
/** @var $template Twig_Template */
if ($template->hasBlock($name, [])) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q256444 | ORMCountWalker.walkSelectStatement | test | public function walkSelectStatement(SelectStatement $AST)
{
$rootComponents = [];
foreach ($this->_getQueryComponents() as $dqlAlias => $qComp) {
if (array_key_exists('parent', $qComp) && $qComp['parent'] === null && $qComp['nestingLevel'] == 0) {
$rootComponents[] = [$dqlAlias => $qComp];
}
}
if (count($rootComponents) > 1) {
throw new \RuntimeException('Cannot count query which selects two FROM components, cannot make distinction');
}
$root = reset($rootComponents);
$parentName = key($root);
$parent = current($root);
$pathExpression = new PathExpression(
PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $parentName,
$parent['metadata']->getSingleIdentifierFieldName()
);
$pathExpression->type = PathExpression::TYPE_STATE_FIELD;
// Remove the variables which are not used by other clauses
foreach ($AST->selectClause->selectExpressions as $key => $selectExpression) {
if ($selectExpression->fieldIdentificationVariable === null) {
unset($AST->selectClause->selectExpressions[$key]);
} elseif ($selectExpression->expression instanceof PathExpression) {
$groupByClause[] = $selectExpression->expression;
}
}
// Put the count expression in the first position
$distinct = $this->_getQuery()->getHint(self::HINT_DISTINCT);
array_unshift($AST->selectClause->selectExpressions,
new SelectExpression(
new AggregateExpression('count', $pathExpression, $distinct), null
)
);
$groupByClause[] = $pathExpression;
$AST->groupByClause = new \Doctrine\ORM\Query\AST\GroupByClause($groupByClause);
// ORDER BY is not needed, only increases query execution through unnecessary sorting.
$AST->orderByClause = null;
} | php | {
"resource": ""
} |
q256445 | Grid.setSource | test | public function setSource(Source $source)
{
if ($this->source !== null) {
throw new \InvalidArgumentException(self::SOURCE_ALREADY_SETTED_EX_MSG);
}
$this->source = $source;
$this->source->initialise($this->container);
// Get columns from the source
$this->source->getColumns($this->columns);
return $this;
} | php | {
"resource": ""
} |
q256446 | Grid.isReadyForRedirect | test | public function isReadyForRedirect()
{
if ($this->source === null) {
throw new \Exception(self::SOURCE_NOT_SETTED_EX_MSG);
}
if ($this->redirect !== null) {
return $this->redirect;
}
$this->createHash();
$this->requestData = (array) $this->request->get($this->hash);
$this->processPersistence();
$this->sessionData = (array) $this->session->get($this->hash);
$this->processLazyParameters();
// isReadyForRedirect ?
if (!empty($this->requestData)) {
$this->processRequestData();
$this->redirect = true;
}
if ($this->redirect === null || ($this->request->isXmlHttpRequest() && !$this->isReadyForExport)) {
if ($this->newSession) {
$this->setDefaultSessionData();
}
$this->processPermanentFilters();
//Configures the grid with the data read from the session.
$this->processSessionData();
$this->prepare();
$this->redirect = false;
}
return $this->redirect;
} | php | {
"resource": ""
} |
q256447 | Grid.processRequestData | test | protected function processRequestData()
{
$this->processMassActions($this->getFromRequest(self::REQUEST_QUERY_MASS_ACTION));
if ($this->processExports($this->getFromRequest(self::REQUEST_QUERY_EXPORT))
|| $this->processTweaks($this->getFromRequest(self::REQUEST_QUERY_TWEAK))) {
return;
}
$filtering = $this->processRequestFilters();
$this->processPage($this->getFromRequest(self::REQUEST_QUERY_PAGE), $filtering);
$this->processOrder($this->getFromRequest(self::REQUEST_QUERY_ORDER));
$this->processLimit($this->getFromRequest(self::REQUEST_QUERY_LIMIT));
$this->saveSession();
} | php | {
"resource": ""
} |
q256448 | Grid.processMassActions | test | protected function processMassActions($actionId)
{
if ($actionId > -1 && '' !== $actionId) {
if (array_key_exists($actionId, $this->massActions)) {
$action = $this->massActions[$actionId];
$actionAllKeys = (boolean) $this->getFromRequest(self::REQUEST_QUERY_MASS_ACTION_ALL_KEYS_SELECTED);
$actionKeys = $actionAllKeys === false ? array_keys((array) $this->getFromRequest(MassActionColumn::ID)) : [];
$this->processSessionData();
if ($actionAllKeys) {
$this->page = 0;
$this->limit = 0;
}
$this->prepare();
if ($actionAllKeys === true) {
foreach ($this->rows as $row) {
$actionKeys[] = $row->getPrimaryFieldValue();
}
}
if (is_callable($action->getCallback())) {
$this->massActionResponse = call_user_func($action->getCallback(), $actionKeys, $actionAllKeys, $this->session, $action->getParameters());
} elseif (strpos($action->getCallback(), ':') !== false) {
$path = array_merge(
[
'primaryKeys' => $actionKeys,
'allPrimaryKeys' => $actionAllKeys,
'_controller' => $action->getCallback(),
],
$action->getParameters()
);
$subRequest = $this->request->duplicate([], null, $path);
$this->massActionResponse = $this->container->get('http_kernel')->handle($subRequest, \Symfony\Component\HttpKernel\HttpKernelInterface::SUB_REQUEST);
} else {
throw new \RuntimeException(sprintf(self::MASS_ACTION_CALLBACK_NOT_VALID_EX_MSG, $action->getCallback()));
}
} else {
throw new \OutOfBoundsException(sprintf(self::MASS_ACTION_NOT_DEFINED_EX_MSG, $actionId));
}
}
} | php | {
"resource": ""
} |
q256449 | Grid.processExports | test | protected function processExports($exportId)
{
if ($exportId > -1 && '' !== $exportId) {
if (array_key_exists($exportId, $this->exports)) {
$this->isReadyForExport = true;
$this->processSessionData();
$this->page = 0;
$this->limit = 0;
$this->prepare();
$export = $this->exports[$exportId];
if ($export instanceof ContainerAwareInterface) {
$export->setContainer($this->container);
}
$export->computeData($this);
$this->exportResponse = $export->getResponse();
return true;
} else {
throw new \OutOfBoundsException(sprintf(self::EXPORT_NOT_DEFINED_EX_MSG, $exportId));
}
}
return false;
} | php | {
"resource": ""
} |
q256450 | Grid.processFilters | test | protected function processFilters($permanent = true)
{
foreach (($permanent ? $this->permanentFilters : $this->defaultFilters) as $columnId => $value) {
/* @var $column Column */
$column = $this->columns->getColumnById($columnId);
if ($permanent) {
// Disable the filter capability for the column
$column->setFilterable(false);
}
// Convert simple value
if (!is_array($value) || !is_string(key($value))) {
$value = ['from' => $value];
}
// Convert boolean value
if (isset($value['from']) && is_bool($value['from'])) {
$value['from'] = $value['from'] ? '1' : '0';
}
// Convert simple value with select filter
if ($column->getFilterType() === 'select') {
if (isset($value['from']) && !is_array($value['from'])) {
$value['from'] = [$value['from']];
}
if (isset($value['to']) && !is_array($value['to'])) {
$value['to'] = [$value['to']];
}
}
// Store in the session
$this->set($columnId, $value);
}
} | php | {
"resource": ""
} |
q256451 | Grid.processSessionData | test | protected function processSessionData()
{
// Filters
foreach ($this->columns as $column) {
if (($data = $this->get($column->getId())) !== null) {
$column->setData($data);
}
}
// Page
if (($page = $this->get(self::REQUEST_QUERY_PAGE)) !== null) {
$this->setPage($page);
} else {
$this->setPage(0);
}
// Order
if (($order = $this->get(self::REQUEST_QUERY_ORDER)) !== null) {
list($columnId, $columnOrder) = explode('|', $order);
$this->columns->getColumnById($columnId)->setOrder($columnOrder);
}
// Limit
if (($limit = $this->get(self::REQUEST_QUERY_LIMIT)) !== null) {
$this->limit = $limit;
} else {
$this->limit = key($this->limits);
}
} | php | {
"resource": ""
} |
q256452 | Grid.prepare | test | protected function prepare()
{
if ($this->prepared) {
return $this;
}
if ($this->source->isDataLoaded()) {
$this->rows = $this->source->executeFromData($this->columns->getIterator(true), $this->page, $this->limit, $this->maxResults);
} else {
$this->rows = $this->source->execute($this->columns->getIterator(true), $this->page, $this->limit, $this->maxResults, $this->dataJunction);
}
if (!$this->rows instanceof Rows) {
throw new \Exception(self::NO_ROWS_RETURNED_EX_MSG);
}
if (count($this->rows) == 0 && $this->page > 0) {
$this->page = 0;
$this->prepare();
return $this;
}
//add row actions column
if (count($this->rowActions) > 0) {
foreach ($this->rowActions as $column => $rowActions) {
if (($actionColumn = $this->columns->hasColumnById($column, true))) {
$actionColumn->setRowActions($rowActions);
} else {
$actionColumn = new ActionsColumn($column, $this->actionsColumnTitle, $rowActions);
if ($this->actionsColumnSize > -1) {
$actionColumn->setSize($this->actionsColumnSize);
}
$this->columns->addColumn($actionColumn);
}
}
}
//add mass actions column
if (count($this->massActions) > 0) {
$this->columns->addColumn(new MassActionColumn(), 1);
}
$primaryColumnId = $this->columns->getPrimaryColumn()->getId();
foreach ($this->rows as $row) {
$row->setPrimaryField($primaryColumnId);
}
//get size
if ($this->source->isDataLoaded()) {
$this->source->populateSelectFiltersFromData($this->columns);
$this->totalCount = $this->source->getTotalCountFromData($this->maxResults);
} else {
$this->source->populateSelectFilters($this->columns);
$this->totalCount = $this->source->getTotalCount($this->maxResults);
}
if (!is_int($this->totalCount)) {
throw new \Exception(sprintf(self::INVALID_TOTAL_COUNT_EX_MSG, gettype($this->totalCount)));
}
$this->prepared = true;
return $this;
} | php | {
"resource": ""
} |
q256453 | Grid.set | test | protected function set($key, $data)
{
// Only the filters values are removed from the session
$fromIsEmpty = isset($data['from']) && ((is_string($data['from']) && $data['from'] === '') || (is_array($data['from']) && $data['from'][0] === ''));
$toIsSet = isset($data['to']) && (is_string($data['to']) && $data['to'] !== '');
if ($fromIsEmpty && !$toIsSet) {
if (array_key_exists($key, $this->sessionData)) {
unset($this->sessionData[$key]);
}
} elseif ($data !== null) {
$this->sessionData[$key] = $data;
}
} | php | {
"resource": ""
} |
q256454 | Grid.getColumn | test | public function getColumn($columnId)
{
foreach ($this->lazyAddColumn as $column) {
if ($column['column']->getId() == $columnId) {
return $column['column'];
}
}
return $this->columns->getColumnById($columnId);
} | php | {
"resource": ""
} |
q256455 | Grid.hasColumn | test | public function hasColumn($columnId)
{
foreach ($this->lazyAddColumn as $column) {
if ($column['column']->getId() == $columnId) {
return true;
}
}
return $this->columns->hasColumnById($columnId);
} | php | {
"resource": ""
} |
q256456 | Grid.setColumnsOrder | test | public function setColumnsOrder(array $columnIds, $keepOtherColumns = true)
{
$this->columns->setColumnsOrder($columnIds, $keepOtherColumns);
return $this;
} | php | {
"resource": ""
} |
q256457 | Grid.addMassAction | test | public function addMassAction(MassActionInterface $action)
{
if ($action->getRole() === null || $this->securityContext->isGranted($action->getRole())) {
$this->massActions[] = $action;
}
return $this;
} | php | {
"resource": ""
} |
q256458 | Grid.addTweak | test | public function addTweak($title, array $tweak, $id = null, $group = null)
{
if ($id !== null && !preg_match('/^[0-9a-zA-Z_\+-]+$/', $id)) {
throw new \InvalidArgumentException(sprintf(self::TWEAK_MALFORMED_ID_EX_MSG, $id));
}
$tweak = array_merge(['id' => $id, 'title' => $title, 'group' => $group], $tweak);
if (isset($id)) {
$this->tweaks[$id] = $tweak;
} else {
$this->tweaks[] = $tweak;
}
return $this;
} | php | {
"resource": ""
} |
q256459 | Grid.getTweaks | test | public function getTweaks()
{
$separator = strpos($this->getRouteUrl(), '?') ? '&' : '?';
$url = $this->getRouteUrl() . $separator . $this->getHash() . '[' . self::REQUEST_QUERY_TWEAK . ']=';
foreach ($this->tweaks as $id => $tweak) {
$this->tweaks[$id] = array_merge($tweak, ['url' => $url . $id]);
}
return $this->tweaks;
} | php | {
"resource": ""
} |
q256460 | Grid.getTweak | test | public function getTweak($id)
{
$tweaks = $this->getTweaks();
if (isset($tweaks[$id])) {
return $tweaks[$id];
}
throw new \InvalidArgumentException(sprintf(self::NOT_VALID_TWEAK_ID_EX_MSG, $id));
} | php | {
"resource": ""
} |
q256461 | Grid.getTweaksGroup | test | public function getTweaksGroup($group)
{
$tweaksGroup = $this->getTweaks();
foreach ($tweaksGroup as $id => $tweak) {
if ($tweak['group'] != $group) {
unset($tweaksGroup[$id]);
}
}
return $tweaksGroup;
} | php | {
"resource": ""
} |
q256462 | Grid.addRowAction | test | public function addRowAction(RowActionInterface $action)
{
if ($action->getRole() === null || $this->securityContext->isGranted($action->getRole())) {
$this->rowActions[$action->getColumn()][] = $action;
}
return $this;
} | php | {
"resource": ""
} |
q256463 | Grid.setTemplate | test | public function setTemplate($template)
{
if ($template !== null) {
if ($template instanceof \Twig_Template) {
$template = '__SELF__' . $template->getTemplateName();
} elseif (!is_string($template)) {
throw new \Exception(self::TWIG_TEMPLATE_LOAD_EX_MSG);
}
$this->set(self::REQUEST_QUERY_TEMPLATE, $template);
$this->saveSession();
}
return $this;
} | php | {
"resource": ""
} |
q256464 | Grid.addExport | test | public function addExport(ExportInterface $export)
{
if ($export->getRole() === null || $this->securityContext->isGranted($export->getRole())) {
$this->exports[] = $export;
}
return $this;
} | php | {
"resource": ""
} |
q256465 | Grid.getRouteUrl | test | public function getRouteUrl()
{
if ($this->routeUrl === null) {
$this->routeUrl = $this->router->generate($this->request->get('_route'), $this->getRouteParameters());
}
return $this->routeUrl;
} | php | {
"resource": ""
} |
q256466 | Grid.setFilters | test | protected function setFilters(array $filters, $permanent = true)
{
foreach ($filters as $columnId => $value) {
if ($permanent) {
$this->permanentFilters[$columnId] = $value;
} else {
$this->defaultFilters[$columnId] = $value;
}
}
return $this;
} | php | {
"resource": ""
} |
q256467 | Grid.setLimits | test | public function setLimits($limits)
{
if (is_array($limits)) {
if ((int) key($limits) === 0) {
$this->limits = array_combine($limits, $limits);
} else {
$this->limits = $limits;
}
} elseif (is_int($limits)) {
$this->limits = [$limits => (string) $limits];
} else {
throw new \InvalidArgumentException(self::NOT_VALID_LIMIT_EX_MSG);
}
return $this;
} | php | {
"resource": ""
} |
q256468 | Grid.getPageCount | test | public function getPageCount()
{
$pageCount = 1;
if ($this->getLimit() > 0) {
$pageCount = ceil($this->getTotalCount() / $this->getLimit());
}
// @todo why this should be a float?
return $pageCount;
} | php | {
"resource": ""
} |
q256469 | Grid.setMaxResults | test | public function setMaxResults($maxResults = null)
{
if ((is_int($maxResults) && $maxResults < 0) && $maxResults !== null) {
throw new \InvalidArgumentException(self::NOT_VALID_MAX_RESULT_EX_MSG);
}
$this->maxResults = $maxResults;
return $this;
} | php | {
"resource": ""
} |
q256470 | Grid.isTitleSectionVisible | test | public function isTitleSectionVisible()
{
if ($this->showTitles === true) {
foreach ($this->columns as $column) {
if ($column->getTitle() != '') {
return true;
}
}
}
return false;
} | php | {
"resource": ""
} |
q256471 | Grid.isFilterSectionVisible | test | public function isFilterSectionVisible()
{
if ($this->showFilters === true) {
foreach ($this->columns as $column) {
if ($column->isFilterable() && $column->getType() != 'massaction' && $column->getType() != 'actions') {
return true;
}
}
}
return false;
} | php | {
"resource": ""
} |
q256472 | Grid.isPagerSectionVisible | test | public function isPagerSectionVisible()
{
$limits = $this->getLimits();
if (empty($limits)) {
return false;
}
// true when totalCount rows exceed the minimum pager limit
return min(array_keys($limits)) < $this->totalCount;
} | php | {
"resource": ""
} |
q256473 | Grid.showColumns | test | public function showColumns($columnIds)
{
foreach ((array) $columnIds as $columnId) {
$this->lazyHideShowColumns[$columnId] = true;
}
return $this;
} | php | {
"resource": ""
} |
q256474 | Grid.hideColumns | test | public function hideColumns($columnIds)
{
foreach ((array) $columnIds as $columnId) {
$this->lazyHideShowColumns[$columnId] = false;
}
return $this;
} | php | {
"resource": ""
} |
q256475 | Grid.getGridResponse | test | public function getGridResponse($param1 = null, $param2 = null, Response $response = null)
{
$isReadyForRedirect = $this->isReadyForRedirect();
if ($this->isReadyForExport()) {
return $this->getExportResponse();
}
if ($this->isMassActionRedirect()) {
return $this->getMassActionResponse();
}
if ($isReadyForRedirect) {
return new RedirectResponse($this->getRouteUrl());
} else {
if (is_array($param1) || $param1 === null) {
$parameters = (array) $param1;
$view = $param2;
} else {
$parameters = (array) $param2;
$view = $param1;
}
$parameters = array_merge(['grid' => $this], $parameters);
if ($view === null) {
return $parameters;
} else {
return $this->container->get('templating')->renderResponse($view, $parameters, $response);
}
}
} | php | {
"resource": ""
} |
q256476 | Grid.getRawData | test | public function getRawData($columnNames = null, $namedIndexes = true)
{
if ($columnNames === null) {
foreach ($this->getColumns() as $column) {
$columnNames[] = $column->getId();
}
}
$columnNames = (array) $columnNames;
$result = [];
foreach ($this->rows as $row) {
$resultRow = [];
foreach ($columnNames as $columnName) {
if ($namedIndexes) {
$resultRow[$columnName] = $row->getField($columnName);
} else {
$resultRow[] = $row->getField($columnName);
}
}
$result[] = $resultRow;
}
return $result;
} | php | {
"resource": ""
} |
q256477 | Grid.getFilters | test | public function getFilters()
{
if ($this->hash === null) {
throw new \Exception(self::GET_FILTERS_NO_REQUEST_HANDLED_EX_MSG);
}
if ($this->sessionFilters === null) {
$this->sessionFilters = [];
$session = $this->sessionData;
$requestQueries = [
self::REQUEST_QUERY_MASS_ACTION_ALL_KEYS_SELECTED,
self::REQUEST_QUERY_MASS_ACTION,
self::REQUEST_QUERY_EXPORT,
self::REQUEST_QUERY_PAGE,
self::REQUEST_QUERY_LIMIT,
self::REQUEST_QUERY_ORDER,
self::REQUEST_QUERY_TEMPLATE,
self::REQUEST_QUERY_RESET,
MassActionColumn::ID,
];
foreach ($requestQueries as $request_query) {
unset($session[$request_query]);
}
foreach ($session as $columnId => $sessionFilter) {
if (isset($sessionFilter['operator'])) {
$operator = $sessionFilter['operator'];
unset($sessionFilter['operator']);
} else {
$operator = $this->getColumn($columnId)->getDefaultOperator();
}
if (!isset($sessionFilter['to']) && isset($sessionFilter['from'])) {
$sessionFilter = $sessionFilter['from'];
}
$this->sessionFilters[$columnId] = new Filter($operator, $sessionFilter);
}
}
return $this->sessionFilters;
} | php | {
"resource": ""
} |
q256478 | Grid.getFilter | test | public function getFilter($columnId)
{
if ($this->hash === null) {
throw new \Exception(self::GET_FILTERS_NO_REQUEST_HANDLED_EX_MSG);
}
$sessionFilters = $this->getFilters();
return isset($sessionFilters[$columnId]) ? $sessionFilters[$columnId] : null;
} | php | {
"resource": ""
} |
q256479 | Grid.hasFilter | test | public function hasFilter($columnId)
{
if ($this->hash === null) {
throw new \Exception(self::HAS_FILTER_NO_REQUEST_HANDLED_EX_MSG);
}
return $this->getFilter($columnId) !== null;
} | php | {
"resource": ""
} |
q256480 | Entity.initQueryBuilder | test | public function initQueryBuilder(QueryBuilder $queryBuilder)
{
$this->queryBuilder = clone $queryBuilder;
//Try to guess the new root alias and apply it to our queries+
//as the external querybuilder almost certainly is not used our default alias
$externalTableAliases = $this->queryBuilder->getRootAliases();
if (count($externalTableAliases)) {
$this->setTableAlias($externalTableAliases[0]);
}
} | php | {
"resource": ""
} |
q256481 | Column.renderCell | test | public function renderCell($value, $row, $router)
{
if (is_callable($this->callback)) {
return call_user_func($this->callback, $value, $row, $router);
}
$value = is_bool($value) ? (int) $value : $value;
if (array_key_exists((string) $value, $this->values)) {
$value = $this->values[$value];
}
return $value;
} | php | {
"resource": ""
} |
q256482 | Column.isVisible | test | public function isVisible($isExported = false)
{
$visible = $isExported && $this->export !== null ? $this->export : $this->visible;
if ($visible && $this->authorizationChecker !== null && $this->getRole() !== null) {
return $this->authorizationChecker->isGranted($this->getRole());
}
return $visible;
} | php | {
"resource": ""
} |
q256483 | Column.setOrder | test | public function setOrder($order)
{
if ($order !== null) {
$this->order = $order;
$this->isSorted = true;
}
return $this;
} | php | {
"resource": ""
} |
q256484 | Column.setSize | test | public function setSize($size)
{
if ($size < -1) {
throw new \InvalidArgumentException(sprintf('Unsupported column size %s, use positive value or -1 for auto resize', $size));
}
$this->size = $size;
return $this;
} | php | {
"resource": ""
} |
q256485 | Column.setData | test | public function setData($data)
{
$this->data = ['operator' => $this->getDefaultOperator(), 'from' => static::DEFAULT_VALUE, 'to' => static::DEFAULT_VALUE];
$hasValue = false;
if (isset($data['from']) && $this->isQueryValid($data['from'])) {
$this->data['from'] = $data['from'];
$hasValue = true;
}
if (isset($data['to']) && $this->isQueryValid($data['to'])) {
$this->data['to'] = $data['to'];
$hasValue = true;
}
$isNullOperator = (isset($data['operator']) && ($data['operator'] === self::OPERATOR_ISNULL || $data['operator'] === self::OPERATOR_ISNOTNULL));
if (($hasValue || $isNullOperator) && isset($data['operator']) && $this->hasOperator($data['operator'])) {
$this->data['operator'] = $data['operator'];
}
return $this;
} | php | {
"resource": ""
} |
q256486 | Column.getData | test | public function getData()
{
$result = [];
$hasValue = false;
if ($this->data['from'] != $this::DEFAULT_VALUE) {
$result['from'] = $this->data['from'];
$hasValue = true;
}
if ($this->data['to'] != $this::DEFAULT_VALUE) {
$result['to'] = $this->data['to'];
$hasValue = true;
}
$isNullOperator = (isset($this->data['operator']) && ($this->data['operator'] === self::OPERATOR_ISNULL || $this->data['operator'] === self::OPERATOR_ISNOTNULL));
if ($hasValue || $isNullOperator) {
$result['operator'] = $this->data['operator'];
}
return $result;
} | php | {
"resource": ""
} |
q256487 | Column.setAlign | test | public function setAlign($align)
{
if (!in_array($align, self::$aligns)) {
throw new \InvalidArgumentException(sprintf('Unsupported align %s, just left, right and center are supported', $align));
}
$this->align = $align;
return $this;
} | php | {
"resource": ""
} |
q256488 | Column.getOperators | test | public function getOperators()
{
// Issue with Doctrine
// -------------------
// @see http://www.doctrine-project.org/jira/browse/DDC-1857
// @see http://www.doctrine-project.org/jira/browse/DDC-1858
if ($this->hasDQLFunction() && version_compare(DoctrineVersion::VERSION, '2.5') < 0) {
return array_intersect($this->operators, [self::OPERATOR_EQ,
self::OPERATOR_NEQ,
self::OPERATOR_LT,
self::OPERATOR_LTE,
self::OPERATOR_GT,
self::OPERATOR_GTE,
self::OPERATOR_BTW,
self::OPERATOR_BTWE, ]);
}
return $this->operators;
} | php | {
"resource": ""
} |
q256489 | Columns.addColumn | test | public function addColumn(Column $column, $position = 0)
{
$column->setAuthorizationChecker($this->authorizationChecker);
if ($position == 0) {
$this->columns[] = $column;
} else {
if ($position > 0) {
--$position;
} else {
$position = max(0, count($this->columns) + $position);
}
$head = array_slice($this->columns, 0, $position);
$tail = array_slice($this->columns, $position);
$this->columns = array_merge($head, [$column], $tail);
}
return $this;
} | php | {
"resource": ""
} |
q256490 | Columns.setColumnsOrder | test | public function setColumnsOrder(array $columnIds, $keepOtherColumns = true)
{
$reorderedColumns = [];
$columnsIndexedByIds = [];
foreach ($this->columns as $column) {
$columnsIndexedByIds[$column->getId()] = $column;
}
foreach ($columnIds as $columnId) {
if (isset($columnsIndexedByIds[$columnId])) {
$reorderedColumns[] = $columnsIndexedByIds[$columnId];
unset($columnsIndexedByIds[$columnId]);
}
}
if ($keepOtherColumns) {
$this->columns = array_merge($reorderedColumns, array_values($columnsIndexedByIds));
} else {
$this->columns = $reorderedColumns;
}
return $this;
} | php | {
"resource": ""
} |
q256491 | RowAction.addRouteParameters | test | public function addRouteParameters($routeParameters)
{
$routeParameters = (array) $routeParameters;
foreach ($routeParameters as $key => $routeParameter) {
if (is_int($key)) {
$this->routeParameters[] = $routeParameter;
} else {
$this->routeParameters[$key] = $routeParameter;
}
}
return $this;
} | php | {
"resource": ""
} |
q256492 | RowAction.getRouteParametersMapping | test | public function getRouteParametersMapping($name)
{
return isset($this->routeParametersMapping[$name]) ? $this->routeParametersMapping[$name] : null;
} | php | {
"resource": ""
} |
q256493 | RowAction.render | test | public function render($row)
{
foreach ($this->callbacks as $callback) {
if (is_callable($callback)) {
if (null === call_user_func($callback, $this, $row)) {
return;
}
}
}
return $this;
} | php | {
"resource": ""
} |
q256494 | GridRegistry.addType | test | public function addType(GridTypeInterface $type)
{
$name = $type->getName();
if ($this->hasType($name)) {
throw new TypeAlreadyExistsException($name);
}
$this->types[$name] = $type;
return $this;
} | php | {
"resource": ""
} |
q256495 | GridRegistry.addColumn | test | public function addColumn(Column $column)
{
$type = $column->getType();
if ($this->hasColumn($type)) {
throw new ColumnAlreadyExistsException($type);
}
$this->columns[$type] = $column;
return $this;
} | php | {
"resource": ""
} |
q256496 | Export.setContainer | test | public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
$this->twig = $this->container->get('twig');
return $this;
} | php | {
"resource": ""
} |
q256497 | Export.getResponse | test | public function getResponse()
{
// Response
$kernelCharset = $this->container->getParameter('kernel.charset');
if ($this->charset != $kernelCharset && function_exists('mb_strlen')) {
$this->content = mb_convert_encoding($this->content, $this->charset, $kernelCharset);
$filesize = mb_strlen($this->content, '8bit');
} else {
$filesize = strlen($this->content);
$this->charset = $kernelCharset;
}
$headers = [
'Content-Description' => 'File Transfer',
'Content-Type' => $this->getMimeType(),
'Content-Disposition' => sprintf('attachment; filename="%s"', $this->getBaseName()),
'Content-Transfer-Encoding' => 'binary',
'Cache-Control' => 'must-revalidate',
'Pragma' => 'public',
'Content-Length' => $filesize,
];
$response = new Response($this->content, 200, $headers);
$response->setCharset($this->charset);
$response->expire();
return $response;
} | php | {
"resource": ""
} |
q256498 | Export.getGridData | test | protected function getGridData($grid)
{
$result = [];
$this->grid = $grid;
if ($this->grid->isTitleSectionVisible()) {
$result['titles'] = $this->getGridTitles();
}
$result['rows'] = $this->getGridRows();
return $result;
} | php | {
"resource": ""
} |
q256499 | Export.getFlatGridData | test | protected function getFlatGridData($grid)
{
$data = $this->getGridData($grid);
$flatData = [];
if (isset($data['titles'])) {
$flatData[] = $data['titles'];
}
return array_merge($flatData, $data['rows']);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.