code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
public function sync_original() { $this->original = $this->attributes; if ( $this->attributes[ self::OBJECT_KEY ] ) { $this->original[ self::OBJECT_KEY ] = clone $this->attributes[ self::OBJECT_KEY ]; } foreach ( $this->original[ self::TABLE_KEY ] as $key => $item ) { if ( is_object( $item ) ) { $this->original[ $key ] = clone $item; } } return $this; }
Syncs the current attributes to the model's original. @return $this
private function is_fillable( $name ) { // If this model isn't guarded, everything is fillable. if ( ! $this->is_guarded ) { return true; } // If it's in the fillable array, then it's fillable. if ( in_array( $name, $this->fillable ) ) { return true; } // If it's explicitly guarded, then it's not fillable. if ( in_array( $name, $this->guarded ) ) { return false; } // If fillable hasn't been defined, then everything else fillable. return ! $this->fillable; }
Checks if a given attribute is mass-fillable. Returns true if the attribute can be filled, false if it can't. @param string $name @return bool
private function override_wp_object( $value ) { if ( is_object( $value ) ) { $this->attributes[ self::OBJECT_KEY ] = $this->set_wp_object_constants( $value ); } else { $this->attributes[ self::OBJECT_KEY ] = null; if ( $this->uses_wp_object() ) { $this->create_wp_object(); } } return $this; }
Overrides the current WordPress object with a provided one. Resets the post's default values and stores it in the attributes. @param WP_Post|WP_Term|null $value @return $this
private function create_wp_object() { switch ( true ) { case $this instanceof UsesWordPressPost: $object = new WP_Post( (object) array() ); break; case $this instanceof UsesWordPressTerm: $object = new WP_Term( (object) array() ); break; default: throw new LogicException; break; } $this->attributes[ self::OBJECT_KEY ] = $this->set_wp_object_constants( $object ); }
Create and set with a new blank post. Creates a new WP_Post object, assigns it the default attributes, and stores it in the attributes. @throws LogicException
protected function set_wp_object_constants( $object ) { if ( $this instanceof UsesWordPressPost ) { $object->post_type = static::get_post_type(); } if ( $this instanceof UsesWordPressTerm ) { $object->taxonomy = static::get_taxonomy(); } return $object; }
Enforces values on the post that can't change. Primarily, this is used to make sure the post_type always maps to the model's "$type" property, but this can all be overridden by the developer to enforce other values in the model. @param object $object @return object
public function get_attribute( $name ) { if ( $method = $this->has_map_method( $name ) ) { return $this->attributes[ self::OBJECT_KEY ]->{$this->{$method}()}; } if ( $method = $this->has_compute_method( $name ) ) { return $this->{$method}(); } if ( isset( $this->attributes[ self::TABLE_KEY ][ $name ] ) ) { return $this->attributes[ self::TABLE_KEY ][ $name ]; } if ( isset( $this->defaults[ $name ] ) ) { return $this->defaults[ $name ]; } return null; }
Retrieves the model attribute. @param string $name @return mixed @throws PropertyDoesNotExistException If property isn't found.
public function get_original_attribute( $name ) { $original_attributes = $this->original; if ( ! is_object( $original_attributes[ static::OBJECT_KEY ] ) ) { unset( $original_attributes[ static::OBJECT_KEY ] ); } $original = new static( $original_attributes ); return $original->get_attribute( $name ); }
Retrieve the model's original attribute value. @param string $name @return mixed @throws PropertyDoesNotExistException If property isn't found.
public function get_primary_id() { if ( $this instanceof UsesWordPressPost ) { return $this->get_underlying_wp_object()->ID; } if ( $this instanceof UsesWordPressTerm ) { return $this->get_underlying_wp_object()->term_id; } if ( $this instanceof UsesCustomTable ) { return $this->get_attribute( $this->get_primary_key() ); } // Model w/o wp_object not yet supported. throw new LogicException; }
Fetches the Model's primary ID, depending on the model implementation. @return int @throws LogicException
public function clear() { $keys = array_merge( $this->get_table_keys(), $this->get_wp_object_keys() ); foreach ( $keys as $key ) { try { $this->set_attribute( $key, null ); } catch ( Exception $e ) { // We won't clear out guarded attributes. if ( ! ( $e instanceof GuardedPropertyException ) ) { throw $e; } } } return $this; }
Clears all the current attributes from the model. This does not touch the model's original attributes, and will only clear fillable attributes, unless the model is unguarded. @throws Exception @return $this
protected function get_compute_methods() { $methods = get_class_methods( get_called_class() ); $methods = array_filter( $methods, function ( $method ) { return strrpos( $method, 'compute_', - strlen( $method ) ) !== false; } ); $methods = array_map( function ( $method ) { return substr( $method, strlen( 'compute_' ) ); }, $methods ); return $methods; }
Retrieves all the compute methods on the model. @return array
public function enqueue_web_scripts() { foreach ( $this->scripts as $script ) { if ( in_array( $script['type'], array( 'web', 'shared' ) ) ) { $this->enqueue_script( $script ); } } }
{@inheritDoc}
public function enqueue_web_styles() { foreach ( $this->styles as $style ) { if ( in_array( $style['type'], array( 'web', 'shared' ) ) ) { $this->enqueue_style( $style ); } } }
{@inheritDoc}
public function enqueue_admin_scripts( $hook ) { foreach ( $this->scripts as $script ) { if ( in_array( $script['type'], array( 'admin', 'shared' ) ) ) { $this->enqueue_script( $script, $hook ); } } }
{@inheritDoc} @param string $hook Passes a string representing the current page.
public function enqueue_admin_styles( $hook ) { foreach ( $this->styles as $style ) { if ( in_array( $style['type'], array( 'admin', 'shared' ) ) ) { $this->enqueue_style( $style, $hook ); } } }
{@inheritDoc} @param string $hook Passes a string representing the current page.
protected function enqueue_script( $script, $hook = null ) { if ( $script['condition']( $hook ) ) { wp_enqueue_script( $script['handle'], $this->url . $script['src'] . $this->min . '.js', isset( $script['deps'] ) ? $script['deps'] : array(), $this->version, isset( $script['footer'] ) ? $script['footer'] : false ); if ( isset( $script['localize'] ) ) { if ( is_callable( $script['localize'] ) ) { // @todo make all properties callables $script['localize'] = call_user_func( $script['localize'] ); } wp_localize_script( $script['handle'], $script['localize']['name'], $script['localize']['data'] ); } } }
Enqueues an individual script if the style's condition is met. @param array $script The script attachment callback. @param string $hook The location hook. Only passed on admin side.
protected function enqueue_style( $style, $hook = null ) { if ( $style['condition']( $hook ) ) { wp_enqueue_style( $style['handle'], $this->url . $style['src'] . $this->min . '.css', isset( $style['deps'] ) ? $style['deps'] : array(), $this->version, isset( $style['media'] ) ? $style['media'] : 'all' ); } }
Enqueues an individual stylesheet if the style's condition is met. @param array $style The style attachment callback. @param string $hook The location hook.
public function get_config_json( $filename ) { if ( isset( $this->loaded[ $filename ] ) ) { return $this->loaded[ $filename ]; } $config = $this->path . 'config/' . $filename . '.json'; if ( ! file_exists( $config ) ) { return null; } $contents = file_get_contents( $config ); if ( false === $contents ) { return null; } return $this->loaded[ $filename ] = json_decode( $contents, true ); }
Load a configuration JSON file from the config folder. @param string $filename @return array|null
public function authorized() { // if the rule is public, always authorized if ( 'public' === $this->options['rule'] ) { return true; } // enable passing in callback if ( 'callback' === $this->options['rule'] && is_callable( $this->options['callback'] ) ) { return call_user_func( $this->options['callback'] ); } // map rule to method if ( method_exists( $this, $method = $this->options['rule'] ) ) { return $this->{$method}(); } // disable in rule is misconfigused // @todo set up internal translations // @todo also, this error message kinda sucks return new WP_Error( '500', __( 'Guard failure', 'jaxion' ) ); }
Validates whether the current user is authorized. @return true|WP_Error
public function boot() { $loader = $this->fetch( 'loader' ); if ( ! ( $loader instanceof LoaderContract ) ) { throw new UnexpectedValueException; } foreach ( $this as $alias => $value ) { if ( $value instanceof HasActions ) { $loader->register_actions( $value ); } if ( $value instanceof HasFilters ) { $loader->register_filters( $value ); } if ( $value instanceof HasShortcode ) { $loader->register_shortcode( $value ); } } add_action( 'plugins_loaded', array( $loader, 'run' ) ); }
{@inheritDoc} @throws UnexpectedValueException
private function register_constants( Config $config ) { $this->share( 'file', function() use ( $config ) { return $config->file; } ); $this->share( 'url', function() use ( $config ) { return $config->url; } ); $this->share( 'path', function() use ( $config ) { return $config->path; } ); $this->share( 'basename', function() use ( $config ) { return $config->basename; } ); $this->share( 'slug', function() use ( $config ) { return $config->slug; } ); $this->share( 'version', static::VERSION ); }
Sets the plugin's url, path, and basename. @param Config $config
private function register_core_services( Config $config ) { $this->share( array( 'config' => 'Intraxia\Jaxion\Core\Config' ), $config ); $this->share( array( 'loader' => 'Intraxia\Jaxion\Contract\Core\Loader' ), function () { return new Loader; } ); $this->share( array( 'i18n' => 'Intaxia\Jaxion\Contract\Core\I18n' ), function ( Container $app ) { return new I18n( $app->fetch( 'basename' ), $app->fetch( 'path' ) ); } ); }
Registers the built-in services with the Application container. @param Config $config
public function define( $alias, $definition ) { if ( is_array( $alias ) ) { $class = current( $alias ); $alias = key( $alias ); } if ( isset( $this->aliases[ $alias ] ) ) { throw new DefinedAliasException( $alias ); } $this->aliases[ $alias ] = true; $this->definitions[ $alias ] = $definition; // Closures are treated as factories unless // defined via Container::share. if ( ! $definition instanceof \Closure ) { $this->shared[ $alias ] = true; } if ( isset( $class ) ) { $this->classes[ $class ] = $alias; } return $this; }
{@inheritdoc} @param string|array $alias @param mixed $definition @throws DefinedAliasException @return $this
public function share( $alias, $definition ) { $this->define( $alias, $definition ); if ( is_array( $alias ) ) { $alias = key( $alias ); } $this->shared[ $alias ] = true; return $this; }
{@inheritdoc} @param string|array $alias @param mixed $definition @throws DefinedAliasException @return $this
public function fetch( $alias ) { if ( isset( $this->classes[ $alias ] ) ) { // If the alias is a class name, // then retrieve its linked alias. // This is only registered when // registering using an array. $alias = $this->classes[ $alias ]; } if ( ! isset( $this->aliases[ $alias ] ) ) { throw new UndefinedAliasException( $alias ); } $value = $this->definitions[ $alias ]; // If the shared value is a closure, // execute it and assign the result // in place of the closure. if ( $value instanceof \Closure ) { $factory = $value; $value = $factory( $this ); } // If the value is shared, save the shared value. if ( isset( $this->shared[ $alias ] ) ) { $this->definitions[ $alias ] = $value; } // Return the fetched value. return $value; }
{@inheritdoc} @param string $alias @throws UndefinedAliasException @return mixed
public function remove( $alias ) { if ( isset( $this->aliases[ $alias ] ) ) { /** * If there's no reference in the aliases array, * the service won't be found on fetching and * can be overwritten on setting. * * Pros: Quick setting/unsetting, faster * performance on those operations when doing * a lot of these. * * Cons: Objects and values set in the container * can't get garbage collected. * * If this is a problem, this may need to be revisited. */ unset( $this->aliases[ $alias ] ); } return $this; }
{@inheritDoc} @param string $alias @return $this
public function register( Container $container ) { $this->container = $container; $this->container->define( array( 'router' => 'Intraxia\Jaxion\Http\Router' ), $router = new Router ); $this->add_routes( $router ); }
{@inheritDoc} @param Container $container
public function add( $element ) { if ( $this->type->is_model() && is_array( $element ) ) { $element = $this->type->create_model( $element ); } $this->type->validate_element( $element ); $elements = $this->elements; $elements[] = $element; $collection = new static( $this->get_type() ); $collection->set_from_trusted( $elements ); return $collection; }
{@inheritdoc} @param mixed $element @return Collection @throws InvalidArgumentException
public function find( $condition ) { $index = $this->find_index( $condition ); return -1 === $index ? null : $this->elements[ $index ]; }
{@inheritdoc} @param callable $condition Condition to satisfy. @return mixed
public function find_index( $condition ) { $index = -1; for ( $i = 0, $count = count( $this->elements ); $i < $count; $i++ ) { if ( call_user_func( $condition, ($this->at( $i ) ) ) ) { $index = $i; break; } } return $index; }
{@inheritdoc} @param callable $condition Condition to satisfy. @return int
public function index_exists( $index ) { if ( ! is_int( $index ) ) { throw new InvalidArgumentException( 'Index must be an integer' ); } if ( $index < 0 ) { throw new InvalidArgumentException( 'Index must be a non-negative integer' ); } return $index < $this->count(); }
{@inheritdoc} @param int $index Index to check for existence. @return bool @throws InvalidArgumentException
public function filter( $condition ) { $elements = array(); foreach ( $this->elements as $element ) { if ( call_user_func( $condition, $element ) ) { $elements[] = $element; } } return $this->new_from_trusted( $elements ); }
{@inheritdoc} @param callable $condition Condition to satisfy. @return Collection
public function find_last( $condition ) { $index = $this->find_last_index( $condition ); return -1 === $index ? null : $this->elements[ $index ]; }
{@inheritdoc} @param callable $condition Condition to satisfy. @return mixed
public function find_last_index( $condition ) { $index = -1; for ( $i = count( $this->elements ) - 1; $i >= 0; $i-- ) { if ( call_user_func( $condition, $this->elements[ $i ] ) ) { $index = $i; break; } } return $index; }
{@inheritdoc} @param callable $condition @return int
public function slice( $start, $end ) { if ( $start < 0 || ! is_int( $start ) ) { throw new InvalidArgumentException( 'Start must be a non-negative integer' ); } if ( $end < 0 || ! is_int( $end ) ) { throw new InvalidArgumentException( 'End must be a positive integer' ); } if ( $start > $end ) { throw new InvalidArgumentException( 'End must be greater than start' ); } if ( $end > $this->count() + 1 ) { throw new InvalidArgumentException( 'End must be less than the count of the items in the Collection' ); } $length = $end - $start + 1; return $this->new_from_trusted( array_slice( $this->elements, $start, $length ) ); }
{@inheritdoc} @param int $start Begining index to slice from. @param int $end End index to slice to. @return Collection @throws InvalidArgumentException
public function insert( $index, $element ) { $this->validate_index( $index ); $this->type->validate_element( $element ); $a = array_slice( $this->elements, 0, $index ); $b = array_slice( $this->elements, $index, count( $this->elements ) ); $a[] = $element; return $this->new_from_trusted( array_merge( $a, $b ) ); }
{@inheritdoc} @param int $index Index to start at. @param mixed $element Element to insert. @return Collection @throws InvalidArgumentException @throws OutOfRangeException
public function insert_range( $index, array $elements ) { $this->validate_index( $index ); $this->type->validate_elements( $elements ); if ( $index < 0 ) { $index = $this->count() + $index + 1; } return $this->new_from_trusted( array_merge( array_slice( $this->elements, 0, $index ), $elements, array_slice( $this->elements, $index, count( $this->elements ) ) ) ); }
{@inheritdoc} @param int $index Index to start insertion at. @param array $elements Elements in insert. @return Collection @throws OutOfRangeException
public function reject( $condition ) { $inverse = function ( $element ) use ( $condition ) { return ! call_user_func( $condition, $element ); }; return $this->filter( $inverse ); }
{@inheritdoc} @param callable $condition Condition to satisfy. @return Collection
public function remove_at( $index ) { $this->validate_index( $index ); $elements = $this->elements; return $this->new_from_trusted( array_merge( array_slice( $elements, 0, $index ), array_slice( $elements, $index + 1, count( $elements ) ) ) ); }
{@inheritdoc} @param int $index Index to remove. @return Collection @throws OutOfRangeException
public function sort( $callback ) { $elements = $this->elements; usort( $elements, $callback ); return $this->new_from_trusted( $elements ); }
{@inheritdoc} @param callable $callback Sort callback. @return Collection
public function every( $condition ) { $response = true; foreach ( $this->elements as $element ) { $result = call_user_func( $condition, $element ); if ( false === $result ) { $response = false; break; } } return $response; }
{@inheritdoc} @param callable $condition Condition callback. @return bool
public function drop( $num ) { if ( $num > $this->count() ) { $num = $this->count(); } return $this->slice( $num, $this->count() ); }
{@inheritdoc} @param int $num Number of elements to drop. @return Collection @throws InvalidArgumentException
public function drop_right( $num ) { return $num !== $this->count() ? $this->slice( 0, $this->count() - $num - 1 ) : $this->clear(); }
{@inheritdoc} @param int $num Number of elements to drop. @return Collection @throws InvalidArgumentException
public function drop_while( $condition ) { $count = $this->count_while_true( $condition ); return $count ? $this->drop( $count ) : $this; }
{@inheritdoc} @param callable $condition Condition callback. @return Collection
public function take_while( $condition ) { $count = $this->count_while_true( $condition ); return $count ? $this->take( $count ) : $this->clear(); }
{@inheritdoc} @param callable $condition Callback function. @return Collection
public function map( $callable ) { $elements = array(); $type = null; foreach ( $this->elements as $element ) { $result = call_user_func( $callable, $element ); if ( null === $type ) { $type = gettype( $result ); if ( 'object' === $type ) { $type = get_class( $result ); } } $elements[] = $result; } return $this->new_from_trusted( $elements, $type ? : $this->get_type() ); }
{@inheritdoc} @param callable $callable Callback function. @return Collection
public function merge( $elements ) { if ( $elements instanceof static ) { $elements = $elements->to_array(); } if ( ! is_array( $elements ) ) { throw new InvalidArgumentException( 'Merge must be given array or Collection' ); } $this->type->validate_elements( $elements ); return $this->new_from_trusted( array_merge( $this->elements, $elements ) ); }
{@inheritdoc} @param array|Collection $elements Array of elements to merge. @return Collection @throws InvalidArgumentException
public function serialize() { return $this->map(function( $element ) { if ( $element instanceof Serializes ) { return $element->serialize(); } return $element; } )->to_array(); }
{@inheritDoc} @return array
protected function new_from_trusted( array $elements, $type = null ) { $collection = new static( null !== $type ? $type : $this->get_type() ); $collection->set_from_trusted( $elements ); return $collection; }
Creates a new instance of the Collection from a trusted set of elements. @param array $elements Array of elements to pass into new collection. @param null|mixed $type @return static
protected function count_while_true( $condition ) { $count = 0; foreach ( $this->elements as $element ) { if ( ! $condition($element) ) { break; } $count++; } return $count; }
Number of elements true for the condition. @param callable $condition Condition to check. @return int
public function register( Container $container ) { $this->container = $container; $container->define( array( 'assets' => 'Intraxia\Jaxion\Contract\Assets\Register' ), $register = new Register( $container->fetch( 'url' ), $container->fetch( 'version' ) ) ); $this->add_assets( $register ); }
{@inheritDoc} @param Container $container
public function rules() { $args = array(); foreach ( $this->rules as $arg => $validation ) { if ( ! $validation || ! is_string( $validation ) ) { continue; } $args[ $arg ] = $this->parse_validation( $validation ); } return $args; }
Generates argument rules. Returns an array matching the WP-API format for argument rules, including sanitization, validation, required, or defaults. @return array
protected function parse_validation( $validation ) { $validation = explode( '|', $validation ); $rules = array(); foreach ( $validation as $rule ) { if ( 0 === strpos( $rule, 'default' ) ) { $rule_arr = explode( ':', $rule ); $rules['default'] = count( $rule_arr ) === 2 ? array_pop( $rule_arr ) : ''; } if ( 0 === strpos( $rule, 'oneof' ) ) { list( $rule, $values ) = explode( ':', $rule ); $values = explode( ',', $values ); $callback = function ( $value ) use ( $values ) { if ( in_array( $value, $values, true ) ) { return true; } return false; }; $rules['validate_callback'] = isset( $rules['validate_callback'] ) ? $this->add_callback( $rules['validate_callback'], $callback ) : $callback; } switch ( $rule ) { case 'required': $rules['required'] = true; break; case 'integer': $callback = array( $this, 'validate_integer' ); $rules['validate_callback'] = isset( $rules['validate_callback'] ) ? $this->add_callback( $rules['validate_callback'], $callback ) : $callback; $callback = array( $this, 'make_integer' ); $rules['sanitize_callback'] = isset( $rules['sanitize_callback'] ) ? $this->add_callback( $rules['sanitize_callback'], $callback ) : $callback; break; } } return $rules; }
Parses a validation string into a WP-API compatible rule. @param string $validation @return array @todo The next rule added needs to refactor this process.
private function add_callback( $previous, $next ) { return function ( $value ) use ( $previous, $next ) { if ( call_user_func( $previous, $value ) ) { return call_user_func( $next, $value ); } return false; }; }
Creates a new callback that connects the previous and next callback. @param callable $previous @param callable $next @return \Closure;
public function run() { foreach ( $this->actions as $action ) { add_action( $action['hook'], array( $action['service'], $action['method'] ), $action['priority'], $action['args'] ); } foreach ( $this->filters as $filter ) { add_filter( $filter['hook'], array( $filter['service'], $filter['method'] ), $filter['priority'], $filter['args'] ); } }
{@inheritDoc}
public function register_actions( HasActions $service ) { foreach ( $service->action_hooks() as $action ) { $this->actions = $this->add( $this->actions, $action['hook'], $service, $action['method'], isset( $action['priority'] ) ? $action['priority'] : 10, isset( $action['args'] ) ? $action['args'] : 1 ); } }
{@inheritDoc} @param HasActions $service
public function register_filters( HasFilters $service ) { foreach ( $service->filter_hooks() as $filter ) { $this->filters = $this->add( $this->filters, $filter['hook'], $service, $filter['method'], isset( $filter['priority'] ) ? $filter['priority'] : 10, isset( $filter['args'] ) ? $filter['args'] : 1 ); } }
{@inheritDoc} @param HasFilters $service
protected function add( $hooks, $hook, $service, $method, $priority, $accepted_args ) { $hooks[] = array( 'hook' => $hook, 'service' => $service, 'method' => $method, 'priority' => $priority, 'args' => $accepted_args, ); return $hooks; }
Utility to register the actions and hooks into a single collection. @param array $hooks @param string $hook @param object $service @param string $method @param int $priority @param int $accepted_args @return array
public function delete( $key ) { $storage = $this->storage; if ( $this->exists( $key ) ) { unset( $storage[ $key ] ); } return new static( $this->get_key_type(), $this->get_value_type(), $storage ); }
{@inheritdoc} @param mixed $key Key to remove. @return DictionaryContract
public function filter( $condition ) { $storage = array(); foreach ( $this->storage as $key => $value ) { if ( call_user_func( $condition, $value, $key ) ) { $storage[ $key ] = $value; } } return new static( $this->get_key_type(), $this->get_value_type(), $storage ); }
{@inheritdoc} @param callable $condition Conditional callback. @return DictionaryContract
public function reject( $condition ) { return $this->filter( function ( $v, $k ) use ( $condition ) { return ! call_user_func( $condition, $v, $k ); } ); }
{@inheritdoc} @param callable $condition Callback condition. @return DictionaryContract
public function add( $key, $value ) { $storage = $this->storage; $storage[ $key ] = $value; return new static( $this->get_key_type(), $this->get_value_type(), $storage ); }
{@inheritdoc} @param mixed $key Key to add. @param mixed $value Value to add. @return DictionaryContract
public function map( $callable ) { $items = array(); $val_type = null; foreach ( $this->storage as $key => $val ) { $v = call_user_func( $callable, $val, $key ); if ( ! isset( $val_type ) ) { $val_type = gettype( $v ); } $items[ $key ] = $v; } return new static( $this->get_key_type(), $val_type ? : $this->get_value_type(), $items ); }
{@inheritdoc} @param callable $callable Function to call. @return DictionaryContract
public function merge( $source ) { if ( $source instanceof self ) { $source = $source->to_array(); } if ( ! is_array( $source ) ) { throw new InvalidArgumentException( 'Combine must be a Dictionary or an array' ); } return new static( $this->get_key_type(), $this->get_value_type(), array_merge( $this->storage, $source ) ); }
{@inheritdoc} @param array|DictionaryContract $source Source to merge. @return DictionaryContract @throws InvalidArgumentException
public function serialize() { return $this->map(function( $val ) { if ( $val instanceof Serializes ) { $val = $val->serialize(); } return $val; })->to_array(); }
{@inheritDoc} @return array
public function register() { if ( ! $this->vendor ) { throw new VendorNotSetException; } if ( ! $this->version ) { throw new VersionNotSetException; } foreach ( $this->endpoints as $endpoint ) { register_rest_route( $this->get_namespace(), $endpoint->get_route(), $endpoint->get_options() ); } }
Registers all of the routes with the WP-API. Runs on the `rest_api_init` hook. Registers all of the routes loaded on the router into the WordPress REST API. @throws VendorNotSetException @throws VersionNotSetException
public function group( array $options, $callback ) { $router = new static; call_user_func( $callback, $router ); foreach ( $router->get_endpoints() as $endpoint ) { $this->endpoints[] = $this->set_options( $endpoint, $options ); } }
Registers a set of routes with a shared set of options. Allows you to group routes together with shared set of options, including a route prefix, shared guards, and common parameter validation or sanitization. @param array $options @param callable $callback
protected function set_options( Endpoint $endpoint, array $options ) { if ( isset( $options['guard'] ) ) { $endpoint->set_guard( $options['guard'] ); } if ( isset( $options['filter'] ) ) { $endpoint->set_filter( $options['filter'] ); } if ( isset( $options['prefix'] ) ) { $endpoint->set_prefix( $options['prefix'] ); } return $endpoint; }
Sets the passed options on the endpoint. Only sets endpoints matching setters in the Endpoint class. @param Endpoint $endpoint @param array $options @return Endpoint @throws MalformedRouteException
public static function starts_with( $haystack, $needles ) { foreach ( (array) $needles as $needle ) { if ( '' !== $needle && 0 === strpos( $haystack, $needle ) ) { return true; } } return false; }
Determine if a given string starts with a given substring. @param string $haystack @param string|array $needles @return bool
public function is_model() { if ( ! class_exists( $this->type ) ) { return false; } $reflection = new ReflectionClass( $this->type ); return $reflection->isSubclassOf( 'Intraxia\Jaxion\Axolotl\Model' ); }
Returns whether the type is an Axolotl model. @return bool
public function validate_element( $element ) { $type = gettype( $element ); $callable = $this->type === 'callable'; $is_object = 'object' === $type; $loose_check = $this->type === 'object'; // callable must be callable if ( $callable && ! is_callable( $element ) ) { throw new InvalidArgumentException( 'Item must be callable' ); } // target isn't callable, object must be an instance of target if ( ! $loose_check && ! $callable && $is_object && ! is_a( $element, $this->type ) ) { throw new InvalidArgumentException( "Item is not type or subtype of $this->type" ); } // a non callable, non object type should match the target string if ( ! $callable && ! $is_object && $type !== $this->type ) { throw new InvalidArgumentException( "Item is not of type: $this->type" ); } }
Validate whether the @param mixed $element Element to validate. @throws InvalidArgumentException
private function determine( $type, $key_type = false ) { if ( ! $key_type && $this->non_scalar_type_exists( $type ) ) { return $type; } if ( $scalar_type = $this->determine_scalar( $type ) ) { if ( $key_type && (in_array( $scalar_type, array( 'double', 'boolean' ) )) ) { throw new InvalidArgumentException( 'This type is not supported as a key.' ); } return $scalar_type; } throw new InvalidArgumentException( 'This type does not exist.' ); }
Determine the type to validate against. @param string $type Type to determine. @param bool $key_type Whether the type is for keys. @return string @throws InvalidArgumentException
private function determine_scalar( $type ) { $synonyms = array( 'int' => 'integer', 'float' => 'double', 'bool' => 'boolean', ); if ( array_key_exists( $type, $synonyms ) ) { $type = $synonyms[ $type ]; } return in_array( $type, array( 'string', 'integer', 'double', 'boolean' ) ) ? $type : null; }
Returns the type if it's scalar, otherwise, returns null. @param string $type Type to check. @return string|null
public function get_options() { $options = array( 'methods' => $this->method, 'callback' => $this->callback, ); if ( $this->guard ) { $options['permission_callback'] = array( $this->guard, 'authorized' ); } if ( $this->filter ) { $options['args'] = $this->filter->rules(); } return $options; }
Generates the endpoint's WP-API options array. @return array
public function set_prefix( $prefix ) { if ( ! Str::starts_with( $prefix, '/' ) || Str::ends_with( $prefix, '/' ) ) { throw new MalformedRouteException; } $this->prefix = $prefix; return $this; }
Sets the endpoint's prefix. @param string $prefix @return $this @throws MalformedRouteException
public function handleQuery(Query $query, callable $next, callable $first) { $queryData = $query->getAllData(); foreach ($this->data as $key => $value) { if ($this->force || !array_key_exists($key, $queryData)) { $query = $query->withData($key, $value); } } return $next($query); }
{@inheritdoc}
public function geocodeQuery(GeocodeQuery $query): Collection { $pluginChain = $this->createPluginChain($this->plugins, function (GeocodeQuery $query) { try { return new GeocoderFulfilledPromise($this->provider->geocodeQuery($query)); } catch (Exception $exception) { return new GeocoderRejectedPromise($exception); } }); return $pluginChain($query)->wait(); }
{@inheritdoc}
public function reverseQuery(ReverseQuery $query): Collection { $pluginChain = $this->createPluginChain($this->plugins, function (ReverseQuery $query) { try { return new GeocoderFulfilledPromise($this->provider->reverseQuery($query)); } catch (Exception $exception) { return new GeocoderRejectedPromise($exception); } }); return $pluginChain($query)->wait(); }
{@inheritdoc}
private function configure(array $options = []): array { $defaults = [ 'max_restarts' => 10, ]; $config = array_merge($defaults, $options); // Make sure no invalid values are provided if (count($config) !== count($defaults)) { throw new LogicException(sprintf('Valid options to the PluginProviders are: %s', implode(', ', array_values($defaults)))); } return $config; }
Configure the plugin provider. @param array $options @return array
private function createPluginChain(array $pluginList, callable $clientCallable) { $firstCallable = $lastCallable = $clientCallable; while ($plugin = array_pop($pluginList)) { $lastCallable = function (Query $query) use ($plugin, $lastCallable, &$firstCallable) { return $plugin->handleQuery($query, $lastCallable, $firstCallable); }; $firstCallable = $lastCallable; } $firstCalls = 0; $firstCallable = function (Query $query) use ($lastCallable, &$firstCalls) { if ($firstCalls > $this->options['max_restarts']) { throw LoopException::create('Too many restarts in plugin provider', $query); } ++$firstCalls; return $lastCallable($query); }; return $firstCallable; }
Create the plugin chain. @param Plugin[] $pluginList A list of plugins @param callable $clientCallable Callable making the HTTP call @return callable
public function handleQuery(Query $query, callable $next, callable $first) { if (!$query instanceof GeocodeQuery) { return $next($query); } if (empty($query->getBounds())) { $query = $query->withBounds($this->bounds); } return $next($query); }
{@inheritdoc}
public function then(callable $onFulfilled = null, callable $onRejected = null) { if (null === $onFulfilled) { return $this; } try { return new self($onFulfilled($this->collection)); } catch (Exception $e) { return new GeocoderRejectedPromise($e); } }
{@inheritdoc}
public function then(callable $onFulfilled = null, callable $onRejected = null) { if (null === $onRejected) { return $this; } try { return new GeocoderFulfilledPromise($onRejected($this->exception)); } catch (Exception $e) { return new self($e); } }
{@inheritdoc}
public function handleQuery(Query $query, callable $next, callable $first) { $cacheKey = $this->getCacheKey($query); if (null !== $cachedResult = $this->cache->get($cacheKey)) { return $cachedResult; } $result = $next($query); $this->cache->set($cacheKey, $result, $this->lifetime); return $result; }
{@inheritdoc}
private function getCacheKey(Query $query): string { if (null !== $this->precision && $query instanceof ReverseQuery) { $query = $query->withCoordinates(new Coordinates( number_format($query->getCoordinates()->getLatitude(), $this->precision), number_format($query->getCoordinates()->getLongitude(), $this->precision) )); } // Include the major version number of the geocoder to avoid issues unserializing. return 'v4'.sha1((string) $query); }
@param Query $query @return string
public function handleQuery(Query $query, callable $next, callable $first) { if (empty($query->getLocale())) { $query = $query->withLocale($this->locale); } return $next($query); }
{@inheritdoc}
public function handleQuery(Query $query, callable $next, callable $first) { if (empty($query->getLocale())) { $query = $query->withLimit($this->limit); } return $next($query); }
{@inheritdoc}
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $debug = $config['debug'] ?? $container->getParameter('kernel.debug'); // Ever set the debug mode to off in production if ($container->hasParameter('kernel.environment') && 'prod' === $container->getParameter('kernel.environment')) { $debug = false; } // Set parameters in the container $container->setParameter('stripe_bundle.db_driver', $config['db_driver']); $container->setParameter(sprintf('stripe_bundle.backend_%s', $config['db_driver']), true); $container->setParameter('stripe_bundle.model_manager_name', $config['model_manager_name']); $container->setParameter('stripe_bundle.secret_key', $config['stripe_config']['secret_key']); $container->setParameter('stripe_bundle.publishable_key', $config['stripe_config']['publishable_key']); $container->setParameter('stripe_bundle.debug', $debug); $container->setParameter('stripe_bundle.statement_descriptor', $config['stripe_config']['statement_descriptor']); $container->setParameter('stripe_bundle.endpoint', $config['endpoint']); $filelocator = new FileLocator(__DIR__ . '/../Resources/config'); $xmlLoader = new Loader\XmlFileLoader($container, $filelocator); $xmlLoader->load('listeners.xml'); $xmlLoader->load('services.xml'); // load db_driver container configuration $xmlLoader->load(sprintf('%s.xml', $config['db_driver'])); }
{@inheritdoc}
public function match($actual) { $this->actual = $actual; return ($actual >= $this->start && $actual <= $this->end); }
Returns true if $actual is within the inclusive range, false otherwise. @param mixed $actual The value to compare @return boolean Whether or not the value is within the range
public function getFailureMessage($negated = false) { $x = $this->start; $y = $this->end; if (!$negated) { return "Expected {$this->actual} to be within [$x, $y]"; } else { return "Expected {$this->actual} not to be within [$x, $y]"; } }
Returns an error message indicating why the match failed, and the negation of the message if $negated is true. @param boolean $negated Whether or not to print the negated message @return string The error message
protected function getLocalCustomer($stripeCustomerId) { // First try to get the customer from the database $localCustomer = $this->getEntityManager()->getRepository('SHQStripeBundle:StripeLocalCustomer')->findOneByStripeId($stripeCustomerId); // If we found it, return it if (null !== $localCustomer) { return $localCustomer; } // Try to find the customer in the newly created one that are not already persisted return $this->getEntityManager()->getUnitOfWork()->tryGetById($stripeCustomerId, StripeLocalCustomer::class); }
Gets the local customer object searching for it in the database or in the newly created entities persisted but not yet flushed. @param $stripeCustomerId @return bool|StripeLocalCustomer false if the StripeLocalCustomer was not found
public function beforeSpec(Spec $spec) { parent::beforeSpec($spec); if ($this->lineLength == self::$maxPerLine) { $this->console->writeLn(''); $this->lineLength = 0; } }
Ran before an individual spec. @param Spec $spec The spec before which to run this method
public function afterSpec(Spec $spec) { $this->lineLength += 1; if ($spec->isFailed()) { $this->failures[] = $spec; $failure = $this->formatter->red('F'); $this->console->write($failure); } elseif ($spec->isIncomplete()) { $this->incompleteSpecs[] = $spec; $incomplete = $this->formatter->cyan('I'); $this->console->write($incomplete); } elseif ($spec->isPending()) { $this->pendingSpecs[] = $spec; $pending = $this->formatter->yellow('P'); $this->console->write($pending); } else { $this->console->write('.'); } }
Ran after an individual spec. @param Spec $spec The spec after which to run this method
protected function handleHookFailure(Hook $hook) { $this->lineLength += 1; $this->failures[] = $hook; $failure = $this->formatter->red('F'); $this->console->write($failure); }
If a given hook failed, adds it to list of failures and prints the result. @param Hook $hook The failed hook
public function getEventTypes() { $events = []; if (isset($this->response->eventTypes)) { foreach ($this->response->eventTypes as $event) { $events[] = $event; } } else { $events = array_column($this->response, 'name'); } return $events; }
Gets a response variable from the API response net.authorize.customer.created net.authorize.customer.deleted net.authorize.customer.updated net.authorize.customer.paymentProfile.created net.authorize.customer.paymentProfile.deleted net.authorize.customer.paymentProfile.updated net.authorize.customer.subscription.cancelled net.authorize.customer.subscription.created net.authorize.customer.subscription.expiring net.authorize.customer.subscription.suspended net.authorize.customer.subscription.terminated net.authorize.customer.subscription.updated net.authorize.payment.authcapture.created net.authorize.payment.authorization.created net.authorize.payment.capture.created net.authorize.payment.fraud.approved net.authorize.payment.fraud.declined net.authorize.payment.fraud.held net.authorize.payment.priorAuthCapture.created net.authorize.payment.refund.created net.authorize.payment.void.created @return array Array of event types supported by Webhooks API
public function getWebhooks() { $webhooks = []; foreach ($this->response as $webhook) { $webhooks[] = new AuthnetWebhooksResponse(json_encode($webhook)); } return $webhooks; }
Gets a list of webhooks @return array @throws \JohnConde\Authnet\AuthnetInvalidJsonException
public function getNotificationHistory() { $notifications = []; if (count($this->response->notifications)) { foreach ($this->response->notifications as $notification) { $notifications[] = new AuthnetWebhooksResponse(json_encode($notification)); } } return $notifications; }
Gets a list of webhooks @return array @throws \JohnConde\Authnet\AuthnetInvalidJsonException
public function toContain() { $matcher = new InclusionMatcher(func_get_args(), !$this->negated); $this->test($matcher); return $this; }
Tests whether or not $actual, a string or an array, contains a variable number of substrings or elements. @param mixed $value,.. The values expected to be included @returns Expectation The current expectation @throws ExpectationException If the positive or negative match fails
public function toBeWithin($start, $end) { $matcher = new RangeMatcher($start, $end); $this->test($matcher); return $this; }
Tests whether or not $actual is within an inclusive range. @param int $start The left bound of the range @param int $end The right bound of the range @returns Expectation The current expectation @throws ExpectationException If the positive or negative match fails
private function invokeCustomMatcher($name) { $class = self::$customMatchers[$name]; $args = array_slice(func_get_args(), 1); $matcher = call_user_func_array( [new \ReflectionClass($class), 'newInstance'], $args ); $this->test($matcher); return $this; }
Calls a custom matcher. The matcher is expected to implement pho\Expectation\Matcher\MatcherInterface. A new instance is created, and its match method is called with a variable number of arguments. If match returns false, getFailureMessage is passed as the description to an ExpectationException. @param string $name The name of the custom matcher @param mixed $arg,.. Arguments to be passed @returns Expectation The current expectation @throws ExpectationException If the positive or negative match fails
private function writeMigration($name, $eventObjectTable, $actionTiming, $event) { $file = pathinfo($this->creator->write( $name, $eventObjectTable, $actionTiming, $event, $this->getMigrationPath() ), PATHINFO_FILENAME); $this->line("<info>Created Migration:</info> {$file}"); }
Write to migration file. @param string $name @param string $eventObjectTable @param string $actionTiming @param string $event @return void