_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q263500 | Model.get_dirty | test | public function get_dirty() {
$dirty = array();
foreach ( $this->get_raw_attributes() as $key => $value ) {
if ( ! array_key_exists( $key, $this->_original ) ) {
$dirty[ $key ] = $value;
} elseif ( $value !== $this->_original[ $key ] && ! $this->original_is_numerically_equivalent( $key ) ) {
$dirty[ $key ] = $value;
}
}
return $dirty;
} | php | {
"resource": ""
} |
q263501 | Model.get | test | public static function get( $pk ) {
if ( ! $pk ) {
return null;
}
if ( ! is_scalar( $pk ) ) {
throw new \InvalidArgumentException( 'Primary key must be scalar.' );
}
$data = static::get_data_from_pk( $pk );
if ( $data ) {
$object = new static( new \stdClass() );
$object->set_raw_attributes( (array) $data, true );
$object->_exists = true;
if ( static::$_cache && ! static::is_data_cached( $pk ) ) {
Cache::update( $object );
}
foreach ( static::$_eager_load as $eager_load ) {
if ( ! $object->is_relation_loaded( $eager_load ) ) {
$object->get_relation( $eager_load )->eager_load( array( $object ) );
}
}
return $object;
} else {
return null;
}
} | php | {
"resource": ""
} |
q263502 | Model.from_query | test | public static function from_query( array $attributes = array() ) {
$instance = new static( new \stdClass() );
$instance->set_raw_attributes( $attributes, true );
$instance->_exists = true;
if ( static::$_cache && ! static::is_data_cached( $instance->get_pk() ) ) {
Cache::update( $instance );
}
return $instance;
} | php | {
"resource": ""
} |
q263503 | Model.get_data_from_pk | test | protected static function get_data_from_pk( $pk ) {
$data = static::$_cache ? Cache::get( $pk, static::get_cache_group() ) : null;
if ( ! $data ) {
$query = new FluentQuery( static::table() );
$data = $query->where( static::table()->get_primary_key(), '=', $pk )->first();
}
return $data ? (object) $data : null;
} | php | {
"resource": ""
} |
q263504 | Model.is_data_cached | test | protected static function is_data_cached( $pk ) {
if ( ! static::$_cache ) {
return false;
}
$data = Cache::get( $pk, static::get_cache_group() );
return ! empty( $data );
} | php | {
"resource": ""
} |
q263505 | Model.update | test | protected function update( $key, $value ) {
$columns = static::table()->get_columns();
$data = array(
$key => $columns[ $key ]->prepare_for_storage( $value )
);
$res = static::make_query_object()->update( $this->get_pk(), $data );
if ( $res && static::$_cache ) {
Cache::update( $this );
}
return $res;
} | php | {
"resource": ""
} |
q263506 | Model.save | test | public function save( array $options = array() ) {
if ( isset( $options['exclude_relations'] ) && ! is_array( $options['exclude_relations'] ) ) {
$options['exclude_relations'] = (array) $options['exclude_relations'];
}
$columns = static::table()->get_columns();
$options = wp_parse_args( $options, array(
'exclude_relations' => array_filter( $this->get_all_relations(), function ( $attribute ) use ( $columns ) {
return array_key_exists( $attribute, $columns );
} )
) );
$this->fire_model_event( 'saving' );
$this->save_has_foreign_relations();
if ( $this->exists() ) {
$saved = $this->do_save_as_update();
} else {
$saved = $this->do_save_as_insert();
}
$this->save_loaded_relations( $options['exclude_relations'] );
if ( $saved ) {
$this->finish_save();
}
return $saved;
} | php | {
"resource": ""
} |
q263507 | Model.save_has_foreign_relations | test | protected function save_has_foreign_relations() {
foreach ( $this->_relations as $attribute => $value ) {
$relation = $this->get_relation( $attribute );
if ( $relation instanceof HasForeign && $value ) {
$value = $relation->persist( $value );
$pk = $relation->get_pk_for_value( $value );
$this->set_raw_attribute( $attribute, $pk );
$this->_relations[ $attribute ] = $value;
}
}
} | php | {
"resource": ""
} |
q263508 | Model.save_loaded_relations | test | protected function save_loaded_relations( array $exclude = array() ) {
foreach ( $this->_relations as $relation => $values ) {
if ( in_array( $relation, $exclude ) ) {
continue;
}
$relation_controller = $this->get_relation( $relation );
$relation_controller->persist( $values );
}
} | php | {
"resource": ""
} |
q263509 | Model.do_save_as_insert | test | protected function do_save_as_insert() {
if ( static::table() instanceof TimestampedTable ) {
$time = $this->fresh_timestamp();
$this->set_attribute( static::table()->get_created_at_column(), $time );
$this->set_attribute( static::table()->get_updated_at_column(), $time );
}
$this->fire_model_event( 'creating' );
$columns = static::table()->get_columns();
$insert = array();
foreach ( $this->get_raw_attributes() as $attribute => $value ) {
$insert[ $attribute ] = $columns[ $attribute ]->prepare_for_storage( $value );
}
$insert_id = static::make_query_object()->insert( $insert );
if ( $insert_id ) {
$this->set_raw_attribute( static::table()->get_primary_key(), $insert_id );
}
$default_columns_to_fill = array();
foreach ( static::table()->get_columns() as $name => $column ) {
if ( ! array_key_exists( $name, $this->get_raw_attributes() ) ) {
$default_columns_to_fill[] = $name;
}
}
if ( $default_columns_to_fill ) {
$query = new FluentQuery( static::table() );
$default_values = $query->where( static::table()->get_primary_key(), '=', $this->get_pk() )
->select( $default_columns_to_fill )->first();
if ( $default_values ) {
foreach ( $default_values as $column => $value ) {
$this->set_raw_attribute( $column, $value );
}
}
}
$this->_exists = true;
if ( static::$_cache ) {
Cache::update( $this );
}
$this->fire_model_event( 'created' );
return true;
} | php | {
"resource": ""
} |
q263510 | Model.do_save_as_update | test | protected function do_save_as_update() {
$dirty = $this->get_dirty();
if ( ! $dirty ) {
return true;
}
if ( static::table() instanceof TimestampedTable ) {
$this->set_attribute( static::table()->get_updated_at_column(), $this->fresh_timestamp() );
$dirty = $this->get_dirty();
}
$columns = static::table()->get_columns();
$previous = array();
$update = array();
foreach ( $dirty as $column => $value ) {
if ( array_key_exists( $column, $this->_original ) ) {
$previous[ $column ] = $this->_original[ $column ];
}
$update[ $column ] = $columns[ $column ]->prepare_for_storage( $value );
}
$this->fire_model_event( 'updating', array(
'changed' => $dirty,
'from' => $previous
) );
$result = static::make_query_object()->update( $this->get_pk(), $update );
if ( $result ) {
if ( static::$_cache ) {
Cache::update( $this );
}
$this->fire_model_event( 'updated', array(
'changed' => $dirty,
'from' => $previous
) );
}
return $result;
} | php | {
"resource": ""
} |
q263511 | Model.finish_save | test | protected function finish_save() {
$this->fire_model_event( 'saved' );
foreach ( $this->_relations as $attribute => $relation ) {
if ( $relation instanceof Collection ) {
$relation->clear_memory();
}
}
$this->sync_original();
} | php | {
"resource": ""
} |
q263512 | Model.delete | test | public function delete() {
$this->fire_model_event( 'deleting' );
foreach ( $this->get_all_relations() as $relation ) {
$this->get_relation( $relation )->on_delete( $this );
}
static::make_query_object()->delete( $this->get_pk() );
if ( static::$_cache ) {
Cache::delete( $this );
}
$this->_exists = false;
$this->fire_model_event( 'deleted' );
} | php | {
"resource": ""
} |
q263513 | Model.create_many | test | public static function create_many( array $to_insert ) {
$models = array();
$data = array();
foreach ( $to_insert as $model ) {
$model = $model instanceof static ? $model : new static ( $model );
$model->fire_model_event( 'saving' );
$model->fire_model_event( 'creating' );
$models[] = $model;
$data[] = $model->get_raw_attributes();
}
$rows = static::make_query_object()->insert_many( $data );
foreach ( $rows as $i => $row ) {
$model = $models[ $i ];
$model->set_raw_attributes( $row );
$model->fire_model_event( 'created' );
$model->fire_model_event( 'saved' );
$model->sync_original();
}
return $models;
} | php | {
"resource": ""
} |
q263514 | Model.fire_model_event | test | protected function fire_model_event( $event, $arguments = array() ) {
if ( ! static::$_event_dispatcher ) {
return;
}
$event = static::table()->get_slug() . ".$event";
static::$_event_dispatcher->dispatch( $event, new GenericEvent( $this, $arguments ) );
} | php | {
"resource": ""
} |
q263515 | Model.register_model_event | test | public static function register_model_event( $event, $callback, $priority = 10, $accepted_args = 3 ) {
if ( isset( static::$_event_dispatcher ) ) {
$event = static::table()->get_slug() . ".$event";
static::$_event_dispatcher->add_listener( $event, $callback, $priority, $accepted_args );
}
} | php | {
"resource": ""
} |
q263516 | Model.get_data_to_cache | test | public function get_data_to_cache() {
$data = $this->get_raw_attributes();
$columns = static::table()->get_columns();
foreach ( $data as $column => $value ) {
if ( isset( $columns[ $column ] ) ) {
$data[ $column ] = $columns[ $column ]->prepare_for_storage( $value );
}
}
return $data;
} | php | {
"resource": ""
} |
q263517 | Model.register_global_scope | test | public static function register_global_scope( $scope_or_identifier, Closure $closure = null ) {
if ( $scope_or_identifier instanceof Scope ) {
self::$_scopes[ get_called_class() ][ get_class( $scope_or_identifier ) ] = $scope_or_identifier;
} elseif ( is_string( $scope_or_identifier ) && $closure ) {
self::$_scopes[ get_called_class() ][ $scope_or_identifier ] = $closure;
} else {
throw new \InvalidArgumentException();
}
} | php | {
"resource": ""
} |
q263518 | Model.without_global_scopes | test | public static function without_global_scopes( array $scopes ) {
$query = static::query_with_no_global_scopes();
foreach ( static::get_global_scopes() as $id => $scope ) {
if ( in_array( $id, $scopes ) ) {
continue;
}
if ( $scope instanceof Scope ) {
$scope->apply( $query );
} else {
$scope( $query );
}
}
return $query;
} | php | {
"resource": ""
} |
q263519 | Model.with | test | public static function with( $relations ) {
$query = FluentQuery::from_model( get_called_class() );
call_user_func_array( array( $query, 'with' ), func_get_args() );
return $query;
} | php | {
"resource": ""
} |
q263520 | Model.to_array | test | public function to_array() {
$attributes = array();
foreach ( static::table()->get_columns() as $attribute => $column ) {
$attributes[ $attribute ] = $this->get_attribute( $attribute );
}
return $attributes;
} | php | {
"resource": ""
} |
q263521 | Where.get_comparison | test | protected function get_comparison() {
if ( ! $this->column ) {
return '';
}
$query = "{$this->column} ";
if ( is_array( $this->value ) ) {
$values = $this->implode( $this->value );
if ( $this->operator ) {
$query .= "IN ($values)";
} else {
$query .= "NOT IN ($values)";
}
} elseif ( $this->value === null ) {
if ( $this->operator === true || $this->operator === '=' ) {
$query .= 'IS NULL';
} else {
$query .= 'IS NOT NULL';
}
} else {
if ( is_bool( $this->operator ) ) {
$operator = $this->operator ? '=' : '!=';
} else {
$operator = $this->operator;
}
$query .= "$operator '{$this->value}'";
}
return $query;
} | php | {
"resource": ""
} |
q263522 | Where.get_value | test | protected function get_value() {
$query = $this->for_clause ? '(' : $this->get_comparison();
if ( ! empty( $this->clauses ) ) {
foreach ( $this->clauses as $i => $clause ) {
// We don't want to add the connector if this is the first clause and there is no comparison.
if ( strlen( $query ) > 1 ) {
$query .= ' ' . $clause['type'] . ' ';
}
/** @var Where $where */
$where = $clause['clause'];
if ( ! $where->is_for_clause() ) {
$query .= '(';
}
$query .= $where->get_value();
if ( ! $where->is_for_clause() ) {
$query .= ')';
}
}
}
if ( $this->for_clause ) {
$query .= ')';
}
return $query;
} | php | {
"resource": ""
} |
q263523 | Simple_Query.get | test | public function get( $row_key, $columns = '*' ) {
return $this->get_by( $this->table->get_primary_key(), $row_key, $columns );
} | php | {
"resource": ""
} |
q263524 | Simple_Query.get_column | test | public function get_column( $column, $row_key ) {
return $this->get_column_by( $column, $this->table->get_primary_key(), $row_key );
} | php | {
"resource": ""
} |
q263525 | Simple_Query.get_by_or_many_by_helper | test | protected function get_by_or_many_by_helper( $column, $value, $columns = '*', $method ) {
$builder = new Builder();
$allowed_columns = $this->table->get_columns();
if ( is_array( $columns ) ) {
$select = new Select( null );
foreach ( $columns as $col ) {
if ( ! isset( $allowed_columns[ $col ] ) ) {
throw new InvalidColumnException( "Invalid column." );
}
$select->also( "`$col`" );
}
} elseif ( $columns == Select::ALL ) {
$select = new Select( $columns );
} else {
if ( ! isset( $allowed_columns[ $columns ] ) ) {
throw new InvalidColumnException( "Invalid column" );
}
$select = new Select( "`$columns`" );
}
$builder->append( $select );
$builder->append( new From( $this->table->get_table_name( $this->wpdb ) ) );
$builder->append( new Where( "`$column`", true, $this->escape_value( $column, $value ) ) );
return $this->wpdb->{$method}( trim( $builder->build() ) );
} | php | {
"resource": ""
} |
q263526 | Simple_Query.count | test | public function count( $wheres = array() ) {
$builder = new Builder();
$select = new Select( null );
$select->expression( 'COUNT', '*' );
$builder->append( $select );
$builder->append( new From( $this->table->get_table_name( $this->wpdb ) ) );
if ( ! empty( $wheres ) ) {
foreach ( $wheres as $column => $value ) {
if ( ! isset( $where ) ) {
$where = new Where( "`$column`", true, $this->escape_value( $column, $value ) );
} else {
$where->qAnd( new Where( "`$column`", true, $this->escape_value( $column, $value ) ) );
}
}
$builder->append( $where );
}
return (int) $this->wpdb->get_var( trim( $builder->build() ) );
} | php | {
"resource": ""
} |
q263527 | Simple_Query.insert | test | public function insert( $data ) {
// Set default values
$data = wp_parse_args( $data, $this->table->get_column_defaults() );
$columns = $this->table->get_columns();
// White list columns
$data = array_intersect_key( $data, $columns );
$null_columns = array();
foreach ( $data as $col => $val ) {
if ( $val === null ) {
$null_columns[] = $col;
}
}
foreach ( $null_columns as $null_column ) {
unset( $data[ $null_column ] );
}
foreach ( $data as $name => $value ) {
$data[ $name ] = $this->prepare_for_storage( $name, $value );
}
$formats = array_fill( 0, count( $data ), '%s' );
$prev = $this->wpdb->show_errors( false );
$this->wpdb->insert( $this->table->get_table_name( $this->wpdb ), $data, $formats );
$this->wpdb->show_errors( $prev );
if ( $this->wpdb->last_error ) {
throw $this->generate_exception_from_db_error();
}
return $this->wpdb->insert_id;
} | php | {
"resource": ""
} |
q263528 | Simple_Query.update | test | public function update( $row_key, $data, $where = array() ) {
if ( empty( $row_key ) ) {
return false;
}
if ( empty( $where ) ) {
$where = array( $this->table->get_primary_key() => $row_key );
}
$columns = $this->table->get_columns();
// White list columns
$data = array_intersect_key( $data, $columns );
foreach ( $data as $name => $value ) {
$data[ $name ] = $this->prepare_for_storage( $name, $value );
}
$formats = array_fill( 0, count( $data ), '%s' );
$where_format = array_fill( 0, count( $where ), '%s' );
$prev = $this->wpdb->show_errors( false );
$result = $this->wpdb->update( $this->table->get_table_name( $this->wpdb ), $data, $where, $formats, $where_format );
$this->wpdb->show_errors( $prev );
if ( $this->wpdb->last_error ) {
throw $this->generate_exception_from_db_error();
}
return (bool) $result;
} | php | {
"resource": ""
} |
q263529 | Simple_Query.delete | test | public function delete( $row_key ) {
if ( empty( $row_key ) ) {
return false;
}
$row_key = $this->escape_value( $this->table->get_primary_key(), $row_key );
$prev = $this->wpdb->show_errors( false );
$result = $this->wpdb->delete( $this->table->get_table_name( $this->wpdb ), array(
$this->table->get_primary_key() => $row_key
), '%s' );
$this->wpdb->show_errors( $prev );
if ( $this->wpdb->last_error ) {
throw $this->generate_exception_from_db_error();
}
return (bool) $result;
} | php | {
"resource": ""
} |
q263530 | Simple_Query.delete_many | test | public function delete_many( $wheres ) {
$format = array_fill( 0, count( $wheres ), '%s' );
$prev = $this->wpdb->show_errors( false );
$result = $this->wpdb->delete( $this->table->get_table_name( $this->wpdb ), $wheres, $format );
$this->wpdb->show_errors( $prev );
if ( $this->wpdb->last_error ) {
throw $this->generate_exception_from_db_error();
}
return (bool) $result;
} | php | {
"resource": ""
} |
q263531 | Simple_Query.generate_exception_from_db_error | test | protected function generate_exception_from_db_error() {
if ( ! $this->wpdb->last_error ) {
return null;
}
if ( $this->is_mysqli() ) {
$error_number = mysqli_errno( $this->get_dbh() );
} else {
$error_number = mysql_errno( $this->get_dbh() );
}
return new Exception( $this->wpdb->last_error, $error_number );
} | php | {
"resource": ""
} |
q263532 | TermSaver.do_save | test | protected function do_save( $term ) {
if ( ! $term->term_id ) {
$ids = wp_insert_term( wp_slash( $term->name ), $term->taxonomy, array(
'description' => wp_slash( $term->description ),
'parent' => $term->parent,
'slug' => $term->slug
) );
} else {
$ids = wp_update_term( $term->term_id, $term->taxonomy, array(
'name' => wp_slash( $term->name ),
'description' => wp_slash( $term->description ),
'parent' => $term->parent,
'slug' => $term->slug
) );
}
if ( is_wp_error( $ids ) ) {
throw new \InvalidArgumentException( 'Error encountered while saving WP_Term: ' . $ids->get_error_message() );
}
$term = get_term( $ids['term_id'], $term->taxonomy );
if ( is_wp_error( $term ) ) {
throw new \UnexpectedValueException( $term->get_error_message() );
}
return $term;
} | php | {
"resource": ""
} |
q263533 | HasForeign.make_query_object | test | protected function make_query_object( $model_class = false ) {
$query = call_user_func( array( $this->related_model, 'query_with_no_global_scopes' ) );
if ( ! $model_class ) {
$query->set_model_class( null );
}
return $query;
} | php | {
"resource": ""
} |
q263534 | HasForeign.fetch_results_for_eager_load | test | protected function fetch_results_for_eager_load( $primary_keys ) {
if ( ! $primary_keys ) {
return new Collection( array(), false, $this->saver );
}
$query = $this->make_query_object( true );
$query->where( $this->related_primary_key_column, true, $primary_keys );
return $query->results( $this->saver );
} | php | {
"resource": ""
} |
q263535 | QueryBuilder.newValues | test | public function newValues($nameParams, $val)
{
// store value buffer data
if (count($this->_lastInsertValues) > 0) {
$this->_insertValues[] = $this->_lastInsertValues;
}
// set new value in insert buffer
$this->_lastInsertValues = array($nameParams => $val);
return $this;
} | php | {
"resource": ""
} |
q263536 | QueryBuilder.set | test | public function set($nameParams, $val)
{
$this->_setName[] = $nameParams;
$this->_setVal[] = $val;
return $this;
} | php | {
"resource": ""
} |
q263537 | QueryBuilder.select | test | public function select($field)
{
$this->_queryType = self :: SELECT;
if (!is_array($field)) {
$field = array($field);
}
$this->_select = array_merge($this->_select, $field);
return $this;
} | php | {
"resource": ""
} |
q263538 | QueryBuilder.resetSelect | test | public function resetSelect($field = null)
{
$this->_select = array();
if ($field !== null) {
$this->select($field);
}
return $this;
} | php | {
"resource": ""
} |
q263539 | QueryBuilder.update | test | public function update($tableName)
{
$this->_queryType = self :: UPDATE;
$this->_update = $tableName;
return $this;
} | php | {
"resource": ""
} |
q263540 | QueryBuilder.delete | test | public function delete($tableName)
{
$this->_queryType = self :: DELETE;
$this->_delete = $tableName;
return $this;
} | php | {
"resource": ""
} |
q263541 | QueryBuilder.insertInto | test | public function insertInto($tableName)
{
$this->_queryType = self :: INSERT;
$this->_insert = $tableName;
return $this;
} | php | {
"resource": ""
} |
q263542 | QueryBuilder.from | test | public function from($tableName, $aliasTable = null)
{
$this->_from = sprintf('%s %s', $tableName, $aliasTable);
return $this;
} | php | {
"resource": ""
} |
q263543 | QueryBuilder.join | test | public function join($mode, $table, $on)
{
$this->_join[] = sprintf('%s JOIN %s ON %s', $mode, $table, $on);
return $this;
} | php | {
"resource": ""
} |
q263544 | QueryBuilder.andWhere | test | public function andWhere($field, $comparisonOperator, $value)
{
$this->where($field, $comparisonOperator, $value, 'AND');
return $this;
} | php | {
"resource": ""
} |
q263545 | QueryBuilder.orWhere | test | public function orWhere($field, $comparisonOperator, $value)
{
$this->where($field, $comparisonOperator, $value, 'OR');
return $this;
} | php | {
"resource": ""
} |
q263546 | QueryBuilder.resetOrderBy | test | public function resetOrderBy($orderName = null, $orderVal = '')
{
$this->_orderBy = array();
if ($orderName !== null) {
$this->orderBy($orderName, $orderVal);
}
return $this;
} | php | {
"resource": ""
} |
q263547 | QueryBuilder.limit | test | public function limit($limitStart = null, $limitEnd = null)
{
if ($limitStart === null) {
return $this;
}
if ($limitEnd === null) {
$this->_limit = sprintf('LIMIT %d', $limitStart);
} else {
$this->_limit = sprintf('LIMIT %d, %d', $limitStart, $limitEnd);
}
return $this;
} | php | {
"resource": ""
} |
q263548 | QueryBuilder.resetLimit | test | public function resetLimit($limitStart = null, $limitEnd = null)
{
$this->_limit = '';
if ($limitStart !== null) {
$this->limit($limitStart, $limitEnd);
}
return $this;
} | php | {
"resource": ""
} |
q263549 | TrashSupport.boot_TrashSupport | test | public static function boot_TrashSupport() {
$table = static::table();
if ( ! $table instanceof TrashTable ) {
throw new \UnexpectedValueException( sprintf( "%s model's table must implement TrashTable." ), get_called_class() );
}
static::register_global_scope( 'trash', function ( FluentQuery $query ) use ( $table ) {
$query->and_where( $table->get_deleted_at_column(), true, null );
} );
} | php | {
"resource": ""
} |
q263550 | Relation.get_results | test | public function get_results() {
if ( ( $results = $this->load_from_cache( $this->parent ) ) === null ) {
$results = $this->fetch_results();
if ( $this->cache ) {
$this->cache_results( $results, $this->parent );
$this->maybe_register_cache_events();
}
}
if ( $this->keep_synced && $results instanceof Collection ) {
$this->register_events( $results );
}
return $results;
} | php | {
"resource": ""
} |
q263551 | Relation.load_from_cache | test | protected function load_from_cache( Model $model ) {
$cached = wp_cache_get( $model->get_pk(), $this->get_cache_group() );
if ( $cached === false ) {
return null;
}
if ( is_array( $cached ) ) {
return $this->load_collection_from_cache( $cached, $model );
} else {
return $this->load_single_from_cache( $cached );
}
} | php | {
"resource": ""
} |
q263552 | Relation.load_collection_from_cache | test | protected function load_collection_from_cache( array $cached, Model $for ) {
$models = array();
$removed = array();
foreach ( $cached as $id ) {
$model = $this->saver->get_model( $id );
if ( $model ) {
$models[ $id ] = $model;
} else {
$removed[] = $id;
}
}
$diff = array_diff( $cached, $removed );
wp_cache_set( $for->get_pk(), $diff, $this->get_cache_group() );
return new Collection( $models, false, $this->saver );
} | php | {
"resource": ""
} |
q263553 | Relation.cache_results | test | protected function cache_results( $results, Model $model ) {
if ( $results instanceof Collection ) {
$this->cache_collection( $results, $model );
} elseif ( is_object( $results ) ) {
$this->cache_single( $results, $model );
}
} | php | {
"resource": ""
} |
q263554 | Relation.cache_collection | test | protected function cache_collection( Collection $collection, Model $model ) {
$ids = array_map( function ( $e ) use ( $collection ) {
return $collection->get_saver()->get_pk( $e );
}, $collection->toArray() );
wp_cache_set( $model->get_pk(), $ids, $this->get_cache_group() );
} | php | {
"resource": ""
} |
q263555 | Relation.cache_single | test | protected function cache_single( $result, Model $model ) {
$id = $this->saver->get_pk( $result );
wp_cache_set( $model->get_pk(), $id, $this->get_cache_group() );
} | php | {
"resource": ""
} |
q263556 | Relation.maybe_register_cache_events | test | private function maybe_register_cache_events() {
$key = get_class( $this );
$key .= "-{$this->attribute}";
if ( isset( $this->registered_cache_events[ $key ] ) ) {
return;
}
$this->register_cache_events();
$this->registered_cache_events[ $key ] = true;
} | php | {
"resource": ""
} |
q263557 | UserSaver.do_save | test | protected function do_save( \WP_User $user ) {
if ( ! $user->exists() ) {
if ( empty( $user->user_pass ) ) {
$user->user_pass = wp_generate_password( 24 );
}
$id = wp_insert_user( wp_slash( $user->to_array() ) );
} else {
$id = wp_update_user( wp_slash( $user->to_array() ) );
}
if ( is_wp_error( $id ) ) {
throw new \InvalidArgumentException( 'Error encountered while saving WP_User: ' . $id->get_error_message() );
}
return get_user_by( 'id', $id );
} | php | {
"resource": ""
} |
q263558 | ModelWithMeta.set_last_updated_at | test | private function set_last_updated_at() {
if ( ! static::get_table() instanceof TimestampedTable ) {
return;
}
$dirty = $this->is_dirty();
$this->set_attribute( static::get_table()->get_updated_at_column(), $this->fresh_timestamp() );
// If the model is dirty, we don't want to commit our save since the user should already be calling save.
if ( ! $dirty ) {
$this->save();
}
} | php | {
"resource": ""
} |
q263559 | Kernel.getContainerParameters | test | public function getContainerParameters(): array
{
$result = array(
'app.name' => $this->getName(),
'app.version' => $this->getVersion(),
'app.environment' => $this->getEnvironment(),
'app.sub_environment' => $this->getSubEnvironment(),
'app.debug' => $this->isDebug(),
'app.charset' => $this->getCharset(),
'app.path' => $this->getAppPath(),
'app.config_path' => $this->getConfigPath(),
'app.base_path' => $this->getBasePath(),
'app.storage_path' => $this->getStoragePath(),
'app.log_path' => $this->getLogPath(),
'app.cache_path' => $this->getCachePath(),
'app.src_path' => $this->getSrcPath(),
);
return $result;
} | php | {
"resource": ""
} |
q263560 | Kernel.containerIsCacheable | test | public function containerIsCacheable(): bool
{
$result = true; // container is cacheable by default
if ($this->container->hasParameter('container.cache')) {
$result = (bool)$this->container->getParameter('container.cache');
}
return $result;
} | php | {
"resource": ""
} |
q263561 | Kernel.boot | test | protected function boot()
{
if ($this->hasBooted()) return; // Nothing to do
if ($this->debug) {
$this->setContainer(new ContainerBuilder(new EnvPlaceholderParameterBag($this->getContainerParameters())));
$this->loadContainerConfiguration();
$this->container->compile(true);
} else {
$filename = $this->getContainerCacheFilename();
if (file_exists($filename)) {
require_once($filename);
$this->setContainer(new CachedContainer());
} else {
$this->setContainer(new ContainerBuilder(new EnvPlaceholderParameterBag($this->getContainerParameters())));
$this->loadContainerConfiguration();
$this->container->compile(true);
if ($this->containerIsCacheable()) {
$dumper = new PhpDumper($this->container);
file_put_contents($filename, $dumper->dump());
}
}
}
} | php | {
"resource": ""
} |
q263562 | Kernel.loadContainerConfiguration | test | protected function loadContainerConfiguration()
{
$configPath = $this->getConfigPath();
$environment = $this->getEnvironment();
$loader = new YamlFileLoader($this->container, new FileLocator($configPath));
if (file_exists($configPath . '/' . $environment . '.yml')) {
$loader->load($environment . '.yml');
}
$subEnvironment = $this->getSubEnvironment();
if (file_exists($configPath . '/' . $environment . '.' . $subEnvironment . '.yml')) {
$loader->load($environment . '.' . $subEnvironment . '.yml');
}
} | php | {
"resource": ""
} |
q263563 | BaseTable.build_column_name_for_table | test | protected function build_column_name_for_table( Table $table ) {
$basename = $this->class_basename( $table );
$tableized = Inflector::tableize( $basename );
$parts = explode( '_', $tableized );
$last_plural = array_pop( $parts );
$last_singular = Inflector::singularize( $last_plural );
$parts[] = $last_singular;
$column_name = implode( '_', $parts );
$column_name .= '_' . $table->get_primary_key();
return $column_name;
} | php | {
"resource": ""
} |
q263564 | ManyToMany.persist_do_save | test | protected function persist_do_save( Collection $values ) {
$added = array();
foreach ( $values as $value ) {
$new = ! $this->saver->get_pk( $value );
// prevent recursion by excluding the relation that references this from being saved.
$saved = $this->saver->save( $value, array( 'exclude_relations' => $this->other_attribute ) );
$pk = $this->saver->get_pk( $saved );
if ( $new && $pk ) {
$added[ $pk ] = $saved;
$values->removeElement( $value );
}
$values->dont_remember( function ( Collection $collection ) use ( $saved, $pk ) {
if ( ! $collection->contains( $saved ) ) {
$collection->add( $saved );
}
} );
}
return $added;
} | php | {
"resource": ""
} |
q263565 | ManyToMany.persist_removed | test | protected function persist_removed( $removed ) {
$cached = wp_cache_get( $this->parent->get_pk(), $this->get_cache_group() ) ?: array();
global $wpdb;
$where = new Where( 1, false, 1 );
foreach ( $removed as $model ) {
$i = array_search( $this->saver->get_pk( $model ), $cached );
if ( $i !== false ) {
unset( $cached[ $i ] );
}
$remove_where = new Where( $this->other_column, true, esc_sql( $this->parent->get_pk() ) );
$remove_where->qAnd(
new Where( $this->primary_column, true, esc_sql( $this->saver->get_pk( $model ) ) )
);
$where->qOr( $remove_where );
}
wp_cache_set( $this->parent->get_pk(), $cached, $this->get_cache_group() );
$wpdb->query( "DELETE FROM `{$this->association->get_table_name( $wpdb )}` $where" );
} | php | {
"resource": ""
} |
q263566 | ManyToMany.persist_added | test | protected function persist_added( $added ) {
$cached = wp_cache_get( $this->parent->get_pk(), $this->get_cache_group() ) ?: array();
global $wpdb;
$insert = array();
$parent = esc_sql( $this->parent->get_pk() );
foreach ( $added as $model ) {
$pk = esc_sql( $this->saver->get_pk( $model ) );
if ( $pk ) {
$insert[] = "({$parent},{$pk})";
$cached[] = $pk;
}
}
if ( empty( $insert ) ) {
return;
}
wp_cache_set( $this->parent->get_pk(), $cached, $this->get_cache_group() );
$insert = implode( ',', $insert );
$sql = "INSERT IGNORE INTO `{$this->association->get_table_name( $wpdb )}` ";
$sql .= "({$this->other_column},{$this->primary_column}) VALUES $insert";
$wpdb->query( $sql );
} | php | {
"resource": ""
} |
q263567 | APIRepository.create | test | public function create($attributes) {
if (!isset($attributes['uuid'])) { $attributes['uuid'] = Uuid::uuid4()->toString(); }
return parent::create($attributes);
} | php | {
"resource": ""
} |
q263568 | AuthenticateProtectedAPIRequest.initAuthenticator | test | protected function initAuthenticator() {
$auth = $this->auth;
$this->hmac_validator = new \Tokenly\HmacAuth\Validator(function($api_token) use ($auth) {
// lookup the API secrect by $api_token using $this->auth
$user = $this->user_repository->findByAPIToken($api_token);
if (!$user) { return null; }
// populate Guard with the $user
$auth->setUser($user);
// the purpose of this function is to look up the secret
$api_secret = $user->getApiSecretKey();
return $api_secret;
});
$substitions = Config::get('protectedApi.allowedSubstitutions');
if ($substitions) {
$this->hmac_validator->setSignedURLValidationFunction(function($actual_url, $signed_url) use ($substitions) {
return $this->validateSignedURL($actual_url, $signed_url, $substitions);
});
}
} | php | {
"resource": ""
} |
q263569 | BaseRepository.create | test | public function create($attributes) {
$attributes = $this->modifyAttributesBeforeCreate($attributes);
$model = $this->prototype_model->create($attributes);
// broadcast create event
if ($this->usesTrait(BroadcastsRepositoryEvents::class)) {
$this->broadcastRepositoryEvent(new ModelCreated($model, $attributes));
}
return $model;
} | php | {
"resource": ""
} |
q263570 | AssetConverter.convert | test | public function convert($asset, $basePath)
{
if (($dotPos = strrpos($asset, '.')) === false)
return $asset;
if (($ext = substr($asset, $dotPos + 1)) !== self::INPUT_EXT)
return parent::convert($asset, $basePath);
$assetFilemtime = @filemtime("$basePath/$asset");
$result = $this->buildResult($asset, $dotPos, ($this->cacheSuffix === true) ? $assetFilemtime : null);
$resultFilemtime = @filemtime("$basePath/$result");
if ($resultFilemtime < $assetFilemtime) {
$this->parseLess($basePath, $asset, $result);
}
return $result;
} | php | {
"resource": ""
} |
q263571 | AssetConverter.buildResult | test | protected function buildResult($asset, $dotPos = null, $resultSuffix = null)
{
if ($dotPos === null) {
if (($dotPos = strrpos($asset, '.')) === false) {
return $asset;
}
}
$divider = ($this->compress === true) ? '-m' : '-';
$suffix = ($resultSuffix !== null) ? $divider . (string)$resultSuffix . '.' . self::OUTPUT_EXT : '.' . self::OUTPUT_EXT;
return substr($asset, 0, $dotPos) . $suffix;
} | php | {
"resource": ""
} |
q263572 | AssetConverter.parseLess | test | protected function parseLess($basePath, $asset, $result)
{
$parser = new \Less_Parser([
'compress' => ($this->compress === true) ? true : false,
'cache_dir' => ($this->useCache === true) ? ($this->cacheDir !== null && is_dir($this->cacheDir)) ? $this->cacheDir : __DIR__ . DIRECTORY_SEPARATOR . 'cache' : false,
]);
$parser->parseFile($basePath . DIRECTORY_SEPARATOR . $asset);
if ((!$css = $parser->getCss()) || empty($css))
return false;
Yii::trace("Converted $asset into $result", __METHOD__);
return file_put_contents($basePath . DIRECTORY_SEPARATOR . $result, $css, LOCK_EX);
} | php | {
"resource": ""
} |
q263573 | Pushover.send | test | public function send( $message, array $options = [] ) {
$options[Options::TOKEN] = $this->token;
$options[Options::USER] = $this->user;
$options[Options::MESSAGE] = $message;
$opts = [ 'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => http_build_query($options),
] ];
$context = stream_context_create($opts);
if( $result = @file_get_contents($this->apiUrl, false, $context) ) {
if( $final = @json_decode($result, true) ) {
return $final;
}
}
return false;
} | php | {
"resource": ""
} |
q263574 | AbstractQueue.get | test | final public function get(array $query, array $options = []) : array
{
$completeQuery = $this->buildPayloadQuery(
['earliestGet' => ['$lte' => new UTCDateTime((int)(microtime(true) * 1000))]],
$query
);
$options += self::DEFAULT_GET_OPTIONS;
$update = ['$set' => ['earliestGet' => $this->calculateEarliestGet($options['runningResetDuration'])]];
$end = $this->calculateEndTime($options['waitDurationInMillis']);
$sleepTime = $this->calculateSleepTime($options['pollDurationInMillis']);
$messages = new ArrayObject();
while (count($messages) < $options['maxNumberOfMessages']) {
if ($this->tryFindOneAndUpdate($completeQuery, $update, $messages)) {
continue;
}
if (microtime(true) < $end) {
usleep($sleepTime);
}
break;
}
return $messages->getArrayCopy();
} | php | {
"resource": ""
} |
q263575 | AbstractQueue.count | test | final public function count(array $query, bool $running = null) : int
{
$totalQuery = [];
if ($running === true || $running === false) {
$key = $running ? '$gt' : '$lte';
$totalQuery['earliestGet'] = [$key => new UTCDateTime((int)(microtime(true) * 1000))];
}
return $this->collection->count($this->buildPayloadQuery($totalQuery, $query));
} | php | {
"resource": ""
} |
q263576 | AbstractQueue.requeue | test | final public function requeue(Message $message)
{
$set = [
'payload' => $message->getPayload(),
'earliestGet' => $message->getEarliestGet(),
'priority' => $message->getPriority(),
'created' => new UTCDateTime(),
];
$this->collection->updateOne(['_id' => $message->getId()], ['$set' => $set], ['upsert' => true]);
} | php | {
"resource": ""
} |
q263577 | AbstractQueue.send | test | final public function send(Message $message)
{
$document = [
'_id' => $message->getId(),
'payload' => $message->getPayload(),
'earliestGet' => $message->getEarliestGet(),
'priority' => $message->getPriority(),
'created' => new UTCDateTime(),
];
$this->collection->insertOne($document);
} | php | {
"resource": ""
} |
q263578 | AbstractQueue.verifySort | test | final private function verifySort(array $sort, string $label, array &$completeFields)
{
foreach ($sort as $key => $value) {
$this->throwIfTrue(!is_string($key), "key in \${$label} was not a string");
$this->throwIfTrue(
$value !== 1 && $value !== -1,
"value of \${$label} is not 1 or -1 for ascending and descending"
);
$completeFields["payload.{$key}"] = $value;
}
} | php | {
"resource": ""
} |
q263579 | Issues.add | test | public function add(string $type, string $message)
{
$this->messages($type)->add($message);
} | php | {
"resource": ""
} |
q263580 | Issues.messages | test | public function messages(string $type)
{
if ('' === $type) {
throw new \InvalidArgumentException('The type of messages must be a non-empty string');
}
if (! array_key_exists($type, $this->messages)) {
$this->messages[$type] = new Messages();
}
return $this->messages[$type];
} | php | {
"resource": ""
} |
q263581 | Issues.import | test | public function import(self $issues)
{
foreach ($issues->types() as $type) {
$source = $issues->messages($type);
$destination = $this->messages($type);
foreach ($source as $message) {
$destination->add($message);
}
}
} | php | {
"resource": ""
} |
q263582 | Container.offsetGet | test | public function offsetGet($id)
{
if ($this->hasAlias($id)) {
$id = $this->getAlias($id);
}
if (!$this->has($id) && class_exists($id)) {
return $this->build($id);
}
if (!isset($this->keys[$id])) {
throw new \InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
}
if (
isset($this->raw[$id])
|| !is_object($this->values[$id])
|| isset($this->protected[$this->values[$id]])
|| !method_exists($this->values[$id], '__invoke')
) {
return $this->values[$id];
}
if (isset($this->factories[$this->values[$id]])) {
return $this->values[$id]($this);
}
$raw = $this->values[$id];
$val = $this->values[$id] = $raw($this);
$this->raw[$id] = $raw;
$this->frozen[$id] = true;
return $val;
} | php | {
"resource": ""
} |
q263583 | Container.offsetExists | test | public function offsetExists($id)
{
if ($this->hasAlias($id)) {
$id = $this->getAlias($id);
}
return isset($this->keys[$id]);
} | php | {
"resource": ""
} |
q263584 | Container.extend | test | public function extend($id, $callable)
{
if ( ! isset($this->keys[$id])) {
throw new \InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
}
if ( ! is_object($this->values[$id]) || ! method_exists($this->values[$id], '__invoke')) {
throw new \InvalidArgumentException(sprintf('Identifier "%s" does not contain an object definition.', $id));
}
if ( ! is_object($callable) || ! method_exists($callable, '__invoke')) {
throw new \InvalidArgumentException('Extension service definition is not a Closure or invokable object.');
}
$factory = $this->values[$id];
$extended = function ($c) use ($callable, $factory) {
/** @var \Closure|string $callable */
return $callable($factory($c), $c);
};
if (isset($this->factories[$factory])) {
$this->factories->detach($factory);
$this->factories->attach($extended);
}
return $this[$id] = $extended;
} | php | {
"resource": ""
} |
q263585 | Container.register | test | public function register(ServiceProviderInterface $provider, array $values = [])
{
$provider->register($this);
foreach ($values as $key => $value) {
$this[$key] = $value;
}
return $this;
} | php | {
"resource": ""
} |
q263586 | Container.tag | test | public function tag($id, $tag)
{
if ( ! isset($this->serviceTags[$id])) {
$this->serviceTags[$id] = [];
}
$this->serviceTags[$id][] = $tag;
return $this;
} | php | {
"resource": ""
} |
q263587 | Container.findTaggedServiceIds | test | public function findTaggedServiceIds($tag)
{
$ids = [];
foreach ($this->serviceTags as $id => $tags) {
if (in_array($tag, $tags)) {
$ids[] = $id;
}
}
return $ids;
} | php | {
"resource": ""
} |
q263588 | Kernel.boot | test | public function boot()
{
if (true === $this->booted) {
return;
}
// init container
$this->initializeContainer();
// init bundles
$this->initializeBundles();
foreach ($this->getBundles() as $bundle) {
if ($bundle instanceof ContainerAwareInterface) {
$bundle->setContainer($this->container);
}
$bundle->boot();
}
$this->booted = true;
// Load routes from bundles
$this->loadRoutes();
// Register events from Bundles
$this->registerEvents();
} | php | {
"resource": ""
} |
q263589 | Kernel.initializeBundles | test | protected function initializeBundles()
{
// init bundles
$this->bundles = array();
$topMostBundles = array();
$directChildren = array();
foreach ($this->registerBundles() as $bundle) {
$name = $bundle->getName();
if (isset($this->bundles[$name])) {
throw new \LogicException(sprintf('Trying to register two bundles with the same name "%s"', $name));
}
$this->bundles[$name] = $bundle;
if ($parentName = $bundle->getParent()) {
if (isset($directChildren[$parentName])) {
throw new \LogicException(sprintf('Bundle "%s" is directly extended by two bundles "%s" and "%s".', $parentName, $name, $directChildren[$parentName]));
}
if ($parentName == $name) {
throw new \LogicException(sprintf('Bundle "%s" can not extend itself.', $name));
}
$directChildren[$parentName] = $name;
} else {
$topMostBundles[$name] = $bundle;
}
}
// look for orphans
if (!empty($directChildren) && count($diff = array_diff_key($directChildren, $this->bundles))) {
$diff = array_keys($diff);
throw new \LogicException(sprintf('Bundle "%s" extends bundle "%s", which is not registered.', $directChildren[$diff[0]], $diff[0]));
}
// inheritance
$this->bundleMap = array();
foreach ($topMostBundles as $name => $bundle) {
$bundleMap = array($bundle);
$hierarchy = array($name);
while (isset($directChildren[$name])) {
$name = $directChildren[$name];
array_unshift($bundleMap, $this->bundles[$name]);
$hierarchy[] = $name;
}
foreach ($hierarchy as $bundle) {
$this->bundleMap[$bundle] = $bundleMap;
array_pop($bundleMap);
}
}
} | php | {
"resource": ""
} |
q263590 | Kernel.getKernelParameters | test | protected function getKernelParameters()
{
$bundles = array();
foreach ($this->bundles as $name => $bundle) {
$bundles[$name] = get_class($bundle);
}
return array_merge(
array(
'kernel.root_dir' => $this->rootDir,
'kernel.environment' => $this->environment,
'kernel.debug' => $this->debug,
'kernel.name' => $this->name,
'kernel.cache_dir' => $this->getCacheDir(),
'kernel.logs_dir' => $this->getLogDir(),
'kernel.bundles' => $bundles,
'kernel.charset' => $this->getCharset()
),
$this->getEnvParameters()
);
} | php | {
"resource": ""
} |
q263591 | SchemasValidator.validate | test | public function validate(string $content)
{
if ($this->hasRetriever()) {
$this->validateWithRetriever($content);
} else {
$this->validateWithoutRetriever($content);
}
} | php | {
"resource": ""
} |
q263592 | SchemasValidator.validateWithRetriever | test | public function validateWithRetriever(string $content)
{
// obtain the retriever, throw its own exception if non set
$retriever = $this->getRetriever();
// create the schema validator object
$validator = new SchemaValidator($content);
// obtain the list of schemas
$schemas = $validator->buildSchemas();
// replace with the local path
foreach ($schemas as $schema) {
/** @var \XmlSchemaValidator\Schema $schema */
$location = $schema->getLocation();
$localPath = $retriever->buildPath($location);
if (! file_exists($localPath)) {
$retriever->retrieve($location);
}
$schemas->create($schema->getNamespace(), $localPath);
}
// validate using the modified schemas
$validator->validateWithSchemas($schemas);
} | php | {
"resource": ""
} |
q263593 | SchemasValidator.validateWithoutRetriever | test | public function validateWithoutRetriever($content)
{
// create the schema validator object
$validator = new SchemaValidator($content);
if (! $validator->validate()) {
throw new \RuntimeException('XSD error found: ' . $validator->getLastError());
}
} | php | {
"resource": ""
} |
q263594 | AssetManager.container | test | public function container($name = 'default')
{
if (isset($this->containers[$name])) {
return $this->containers[$name];
}
return $this->containers[$name] = new AssetContainer($name);
} | php | {
"resource": ""
} |
q263595 | AssetManager.outputJs | test | public function outputJs($container = 'default')
{
$assets = $this->getAssets($container, 'js');
$html = [];
foreach ($assets as $asset) {
$source = $this->url ? $this->url->asset($asset['source']): $asset['source'];
$html[] = $this->html->script($source, $asset['attributes']);
}
return trim(implode(PHP_EOL, $html));
} | php | {
"resource": ""
} |
q263596 | AssetManager.outputCss | test | public function outputCss($container = 'default')
{
$assets = $this->getAssets($container, 'css');
$html = [];
foreach ($assets as $asset) {
$source = $this->url ? $this->url->asset($asset['source']): $asset['source'];
$html[] = $this->html->style($source, $asset['attributes']);
}
return trim(implode(PHP_EOL, $html));
} | php | {
"resource": ""
} |
q263597 | AssetManager.getAssets | test | protected function getAssets($container, $type)
{
if ( ! isset($this->containers[$container])) {
return [];
}
$container = $this->containers[$container];
if ( ! isset($container->assets[$type]) || 0 === count($container->assets[$type])) {
return [];
}
$assets = $container->assets[$type];
$assets = $this->arrange($assets);
return $assets;
} | php | {
"resource": ""
} |
q263598 | AssetManager.arrange | test | protected function arrange(array $assets)
{
list($original, $sorted) = array($assets, []);
while (count($assets) > 0) {
foreach ($assets as $asset => $value) {
$this->evaluateAsset($asset, $value, $original, $sorted, $assets);
}
}
return $sorted;
} | php | {
"resource": ""
} |
q263599 | AssetManager.dependencyIsValid | test | protected function dependencyIsValid($asset, $dependency, $original, $assets)
{
if ( ! isset($original[$dependency])) {
return false;
}
else if ($dependency === $asset) {
throw new SelfDependencyException(sprintf('Asset "%" is dependent on itself.', $asset));
}
else if (isset($assets[$dependency]) && in_array($asset, $assets[$dependency]['dependencies'])) {
throw new CircularDependencyException(sprintf('Assets "%s" and "%s" have a circular dependency.', $asset, $dependency));
}
return true;
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.