sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function prepare_form_data() { $this->data = []; foreach ( $this->fields as $field ) { $this->data[ $field->get_id() ] = $field->get_value(); } }
Prepare data from the storage. @return void
entailment
protected function make_fields_validation() { foreach ( $this->fields as $key => $field ) { if ( $this->maybe_skip_field( $field ) ) { continue; } if ( $rules = $field->get_option( 'validate' ) ) { $attributes = ( new Rules_Parser( $field ) )->parse( $rules ); $field->set_attribute( $attributes ); } } }
HTML5 validation attributes based on "validate". @return void
entailment
protected function resolve_flash_errors( $name ) { if ( ! $this->session ) { return; } if ( ! $this->session->get( $name ) instanceof WP_Error ) { return; } $this->errors = new WP_Error; /* @var $errors \WP_Error */ $errors = $this->session->get( $name ); foreach ( $errors->errors as $key => $error ) { $this->add_error( $key, $error ); } }
Resolve flash errors for the display. @param string $name
entailment
protected function fill_old_values() { if ( ! $this->session ) { return; } if ( 0 === count( (array) $this->session->get_old_input() ) ) { return; } foreach ( $this->fields as $key => $field ) { if ( ! is_null( $old = $this->session->get_old_input( $key ) ) ) { $field->set_value( $old ); } } }
Fill old input values. @return void
entailment
public function save( array $merge_data = [] ) { if ( ! $this->submitted ) { // @codingStandardsIgnoreLine _doing_it_wrong( get_class( $this ) . '::' . __FUNCTION__, 'Save form can only works after the form is submitted.', '1.0.0' ); return $this; } $data = array_merge( $this->submitted_data, $merge_data ); /* @var $deferred_storages \WPLibs\Form\Contracts\Deferred_Storage[] */ $deferred_storages = []; foreach ( $data as $key => $_data ) { if ( ! $this->has( $key ) || $this->has_error( $key ) ) { continue; } $field = $this->get( $key ); if ( $this->maybe_skip_field( $field ) ) { continue; } $storage = $field->get_storage(); if ( Utils::is_not_blank( $_data ) ) { $storage->set( $field->get_map_key(), $_data ); } else { $storage->delete( $field->get_map_key() ); } if ( $storage instanceof Deferred_Storage && ! array_key_exists( $_hash = spl_object_hash( $storage ), $deferred_storages ) ) { $deferred_storages[ $_hash ] = $storage; } } // Peform save the deferred_storages. foreach ( $deferred_storages as $storage ) { $storage->save(); } return true; }
{@inheritdoc}
entailment
public function submit( $data, $clear_missing = false ) { if ( $this->submitted ) { // @codingStandardsIgnoreLine _doing_it_wrong( get_class( $this ) . '::' . __FUNCTION__, 'A form can only be submitted once', '1.0.0' ); return $this; } // Prepare data for the submission. $this->submitted_data = $this->prepare_submitted_data( $this->fields, $data, $clear_missing ); // Initialize errors in the very beginning so that we don't lose any // errors added during listeners. $this->errors = new WP_Error; $this->validate( $this->submitted_data ); // Remove submitted data have any errors. if ( count( $errors = $this->errors->errors ) > 0 ) { Arr::forget( $this->submitted_data, array_keys( $errors ) ); } $this->submitted = true; return $this; }
{@inheritdoc}
entailment
protected function prepare_submitted_data( $fields, array $data, $clear_missing ) { $submitted = []; foreach ( $fields as $field ) { if ( $this->maybe_skip_field( $field ) ) { continue; } $value = array_key_exists( $field->get_id(), $data ) ? $data[ $field->get_id() ] : null; // Treat false as NULL to support binding false to checkboxes. // Don't convert NULL to a string here in order to determine later // whether an empty value has been submitted or whether no value has // been submitted at all. This is important for processing checkboxes // and radio buttons with empty values. if ( false === $value ) { $value = null; } elseif ( is_scalar( $value ) ) { $value = (string) $value; } // Perform the sanitization to get sanitized value. $sanitized = $field->get_sanitization_value( $value ); if ( $field->is_group() ) { $submitted[ $field->get_id() ] = $this->get_group_values( $field, $sanitized ); } else { $submitted[ $field->get_id() ] = $sanitized; } } // Clear "null" input data. if ( $clear_missing ) { $submitted = array_filter( $submitted, function ( $value ) { return ! is_null( $value ); } ); } return $submitted; }
Returns submitted data from input. @param array $fields @param array $data @param bool $clear_missing @return array
entailment
protected function get_group_values( Field_Contract $group, $data ) { if ( ! $group->is_group() || ! $group->get_option( 'fields' ) ) { return null; } if ( ! is_array( $data ) ) { return null; } // We will working on clone of the $group, to prevent touching // on real object. $group = clone $group; $i = 0; $values = []; foreach ( array_values( $data ) as $_data ) { if ( ! is_array( $_data ) || empty( $_data ) ) { continue; } $group->index = $i; $fields = array_map( function ( $args ) use ( $group ) { return $this->config->get_field_in_group( $group, $args['id'] ); }, $group->get_option( 'fields' ) ); $values[ $i ] = Utils::filter_blank( $this->prepare_submitted_data( $fields, $_data, true ) ); $i++; } return array_filter( $values ); }
Gets values of a group with given data. @param Field_Contract $group @param array $data @return array|null
entailment
protected function maybe_skip_field( Field_Contract $field ) { // Don't process fields in $skip_proccess_types. if ( in_array( $field->get_type(), static::$skip_proccess_types ) ) { return true; } if ( $field->is_disabled() || false === $field->get_option( 'save_field', true ) ) { return true; } $id = $field->get_id(); if ( $group = $field->get_group() ) { $id = $group->get_id() . '.' . $id; } if ( in_array( $id, $this->skip_proccess_fields ) ) { return true; } return false; }
Check if given field is skipped in the process. @param Field_Contract $field @return bool
entailment
public function validate( array $data ) { // Validate use Validator. try { $this->validate_use_validator( $data, $this->get_validate_rules() ); } catch ( \Exception $e ) { trigger_error( $e->getMessage(), E_USER_WARNING ); // @WPCS: XSS OK. } // Validate use custom callback. $callbacks = $this->fields->pluck( 'validate_cb', 'id' )->filter( 'is_callable' ); if ( $callbacks->isNotEmpty() ) { $this->validate_by_callbacks( $data, $callbacks->all() ); } }
Validate the form data. @param array $data
entailment
protected function get_validate_rules() { $rules = []; foreach ( $this->fields as $key => $field ) { // TODO: Group field cannot validate at moment. if ( 'group' === $field->get_type() ) { continue; } if ( $rule = $field->get_option( 'validate' ) ) { $key = $field->is_repeatable() ? $key . '.*' : $key; $rules[ $key ] = $rule; } } return $rules; }
Returns the validator rules. @return array
entailment
protected function validate_use_validator( array $data, array $rules ) { if ( empty( $rules ) ) { return; } $validator = new Validator( $data, $rules ); $validator->labels( $this->fields->pluck( 'name', 'id' )->all() ); if ( $validator->fails() ) { foreach ( $rules as $key => $rule ) { $this->add_error( $key, $validator->errors( $key ) ); } } }
Validate fields use "validate" parameter. @param array $data @param array $rules
entailment
protected function validate_by_callbacks( array $data, array $callbacks ) { foreach ( $callbacks as $key => $callback ) { $validity = new WP_Error; $value = array_key_exists( $key, $data ) ? $data[ $key ] : null; $callback( $validity, $value ); if ( is_wp_error( $validity ) && count( $validity->errors ) > 0 ) { $this->add_error( $key, $validity->get_error_messages() ); } } }
Validate fields use "validate_cb" parameter. @param array $data @param array $callbacks
entailment
public function add_error( $key, $_errors ) { if ( ! $_errors || ! $this->errors instanceof WP_Error ) { return; } if ( ! $this->fields->has( $key ) ) { return; } foreach ( is_array( $_errors ) ? $_errors : [ $_errors ] as $message ) { $this->errors->add( $key, $message ); } }
Add an error message into the $errors. @param string $key @param array $_errors
entailment
public function has_error( $key ) { return $this->errors && array_key_exists( $key, $this->errors->errors ) && count( $this->errors->errors[ $key ] ) > 0; }
Determnies if given field has any errors. @param string $key @return bool
entailment
public function get_error( $key, $all = true ) { if ( ! $this->has_error( $key ) ) { return null; } $errors = $this->errors->errors[ $key ]; return $all ? Arr::first( $errors ) : $errors; }
Returns field error(s) if any. @param string $key @param bool $all @return string|array
entailment
public function show( $field ) { $field = ( ! $field instanceof Field_Contract ) ? $this->get( $field ) : $field; if ( ! $field ) { trigger_error( 'Cannot display the field', E_USER_WARNING ); return; } // Inherit show_names property. if ( ! $this->config->get_option( 'show_names' ) ) { $field->set_option( 'show_names', false ); } $field->display(); }
{@inheritdoc}
entailment
public function set_data( array $data ) { if ( $this->submitted ) { // @codingStandardsIgnoreLine _doing_it_wrong( get_class( $this ) . '::' . __FUNCTION__, 'You cannot change the data of a submitted form.', '1.0.0' ); return $this; } $this->data = array_merge( $this->data, $data ); foreach ( $data as $key => $value ) { if ( ! $this->has( $key ) ) { continue; } $this->fields[ $key ]->set_value( $value ); } return $this; }
{@inheritdoc}
entailment
public function is_valid() { if ( ! $this->submitted ) { return false; } return ! $this->errors || 0 === count( $this->errors->errors ); }
{@inheritdoc}
entailment
public function add( Field_Contract $field ) { if ( $this->submitted ) { // @codingStandardsIgnoreLine _doing_it_wrong( get_class( $this ) . '::' . __FUNCTION__, 'You cannot add fields to a submitted form', '1.0.0' ); return $this; } // Prevent add field doesn't have right permission. if ( ! $field->check_capabilities() ) { return $this; } $field->set_form( $this ); $this->fields[ $field->get_id() ] = $field; return $this; }
{@inheritdoc}
entailment
public function remove( $name ) { if ( $this->submitted ) { // @codingStandardsIgnoreLine _doing_it_wrong( get_class( $this ) . '::' . __FUNCTION__, 'You cannot remove fields from a submitted form', '1.0.0' ); return $this; } if ( isset( $this->fields[ $name ] ) ) { unset( $this->fields[ $name ] ); } return $this; }
{@inheritdoc}
entailment
public function translate($message) { if (isset($this->translations[$message])) { return $this->translations[$message]; } else { return $message; } }
Translate a message into another language. Works the same as gettext(). @param string $message English text to translate @return string Translated text
entailment
public function translateContext($context, $message) { $key = $context . chr(4) . $message; if (isset($this->translations[$key])) { return $this->translations[$key]; } else { return $message; } }
Translate a context-sensitive message into another language. Works the same as pgettext(). @param string $context Context of the message, e.g. "verb" or "noun" @param string $message English text to translate @return string Translated text
entailment
public function translatePlural($message1, $message2, $number) { $key = $message1 . chr(0) . $message2; if (isset($this->translations[$key])) { $plurals = explode(chr(0), $this->translations[$key]); if (count($plurals) === $this->plural_rule->plurals()) { return $plurals[$this->plural_rule->plural($number)]; } } return $number === 1 ? $message1 : $message2; }
Translate a plural message into another language. Works the same as ngettext(). @param string $message1 English text for singular @param string $message2 English text for plural @param int $number Number of entities @return string Translated text
entailment
public function isPreferred() { if (($host = $this->export()) === null) { return $this->base === $this->effective; } $parsed = parse_url($host); $new = [ 'scheme' => isset($parsed['scheme']) ? $parsed['scheme'] : parse_url($this->base, PHP_URL_SCHEME), 'host' => isset($parsed['host']) ? $parsed['host'] : $parsed['path'], ]; $new['port'] = isset($parsed['port']) ? $parsed['port'] : getservbyname($new['scheme'], 'tcp'); return $this->base == $new['scheme'] . '://' . $new['host'] . ':' . $new['port']; }
Is preferred host? @return bool
entailment
public function getWithUriFallback() { if (($get = $this->export()) !== null) { // Host defined by the Host directive return $get; } elseif ($this->base !== $this->effective && parse_url($this->base, PHP_URL_HOST) === ($host = parse_url($this->effective, PHP_URL_HOST)) ) { // Host is the same, but Scheme or Port is different return getservbyname($scheme = parse_url($this->effective, PHP_URL_SCHEME), 'tcp') === parse_url($this->effective, PHP_URL_PORT) ? $scheme . '://' . $host : $this->effective; } // Return Host name only return parse_url($this->effective, PHP_URL_HOST); }
Get Host, falls back to Effective Request URI if not found @return string
entailment
public function mb_object_type() { // We need the context screen to do this. if ( ! $this->context ) { return ''; } if ( null !== $this->mb_object_type ) { return $this->mb_object_type; } $type = ''; $box_types = $this->box_types(); if ( 1 === count( $box_types ) ) { $type = Arr::first( $box_types ); } elseif ( in_array( $this->context->get_object_type(), $box_types ) ) { $type = $this->context->get_object_type(); } // Keep the values. if ( ! in_array( $type, [ 'user', 'comment', 'term' ] ) ) { $type = 'post'; } return $this->mb_object_type = $type; }
{@inheritdoc}
entailment
public function show_form( $object_id = 0, $object_type = '' ) { if ( ! $this->context ) { _doing_it_wrong( __FUNCTION__, 'The screen context must be set before showing the form.', null ); return; } $form = $this ->set_storage( $this->get_new_storage( $object_id, $object_type ) ) // ->set_request( wplibs_request() ) // ->set_session_store( wplibs_session()->get_store() ) ->set_option( 'resolve_errors', '_errors_' . $this->get_id() ) ->set_option( 'classes', 'wplibs-box wplibs-box--' . $this->get_option( 'layout' ) ) ->get_form(); // Maps the fields into their sections - if any. $this->box->prepare( $form ); $this->render_form_open( $object_id, $object_type ); $this->box->nav( 'wplibs-box__nav--' . $this->get_option( 'layout' ) ); $this->box->main(); $this->render_form_close( $object_id, $object_type ); }
{@inheritdoc}
entailment
public function save_fields( $object_id = 0, $object_type = '', $data_to_save = [] ) { if ( ! $this->context ) { _doing_it_wrong( __FUNCTION__, 'The context screen must be set before saving the form.', null ); return; } $form = $this ->set_storage( $this->get_new_storage( $object_id, $object_type ) ) ->get_form() ->submit( $data_to_save ); if ( ! $form->is_valid() ) { // suru_libs_session()->flash( '_errors_' . $this->get_id(), $form->get_errors() ); } // Save into the storage. $form->save(); }
{@inheritdoc}
entailment
public function get_new_storage( $id, $object_type = null ) { $id = $id ?: $this->context->get_object_id(); return new Metadata_Storage( $id, $object_type ?: $this->mb_object_type() ); }
Returns new storage. @param int $id @param string|null $object_type @return \WPLibs\Form\Storages\Metadata_Storage
entailment
public function convertToFull($fallbackBase) { $this->encode(); if ($this->validate()) { return $this->uri; } elseif (strpos($this->uri, '/') === 0) { $relative = $this->uri; $this->uri = $fallbackBase; return $this->base() . $relative; } throw new \InvalidArgumentException("Invalid URI `$this->uri`"); }
Convert relative to full @param string $fallbackBase @return string
entailment
public function encode() { $reserved = [ '!%21!ui' => "!", '!%23!ui' => "#", '!%24!ui' => "$", '!%26!ui' => "&", '!%27!ui' => "'", '!%28!ui' => "(", '!%29!ui' => ")", '!%2A!ui' => "*", '!%2B!ui' => "+", '!%2C!ui' => ",", '!%2F!ui' => "/", '!%3A!ui' => ":", '!%3B!ui' => ";", '!%3D!ui' => "=", '!%3F!ui' => "?", '!%40!ui' => "@", '!%5B!ui' => "[", '!%5D!ui' => "]", '!%25!ui' => "%", ]; // The % character must be the last in the $reserved array. // This makes sure that the already encoded values are not lost or encoded again. $this->uri = preg_replace(array_keys($reserved), array_values($reserved), rawurlencode($this->uri)); return $this->baseToLowercase(); }
URI encoder according to RFC 3986 Returns a string containing the encoded URI with disallowed characters converted to their percentage encodings. @link http://publicmind.in/blog/url-encoding/ @return string
entailment
private function baseToLowercase() { if (($host = parse_url($this->uri, PHP_URL_HOST)) === null) { return $this->uri; } $pos = strpos($this->uri, $host) + strlen($host); return $this->uri = substr_replace($this->uri, strtolower(substr($this->uri, 0, $pos)), 0, $pos); }
Base uri to lowercase @return string
entailment
public function validate() { return ( ( filter_var($this->uri, FILTER_VALIDATE_URL) || // PHP 5.x bug fix: FILTER_VALIDATE_URL doesn't support IPv6 urls. IP check not needed in the future. $this->validateIP(($parsed = parse_url($this->uri, PHP_URL_HOST)) === false ? '' : $parsed) ) && ($parsed = parse_url($this->uri)) !== false && ( $this->validateHost($parsed['host']) || $this->validateIP($parsed['host']) ) && $this->validateScheme($parsed['scheme']) ); }
Validate @return bool
entailment
public function validateIP($ipAddress = null) { if ($ipAddress === null) { $parsed = parse_url($this->uri); $ipAddress = isset($parsed['host']) ? $parsed['host'] : null; } return ( filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) || filter_var(trim($ipAddress, '[]'), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ); }
Validate IPv4 or IPv6 @param string|null $ipAddress @return bool
entailment
public function validateHost($host = null) { if ($host === null) { $parsed = parse_url($this->uri); $host = isset($parsed['host']) ? $parsed['host'] : $parsed['path']; } return ( preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $host) //valid chars check && preg_match("/^.{1,253}$/", $host) //overall length check && preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $host) //length of each label && !$this->validateIP($host) ); }
Validate host name @link http://stackoverflow.com/questions/1755144/how-to-validate-domain-name-in-php @param string|null $host @return bool
entailment
public function validateScheme($scheme = null) { if ($scheme === null) { $parsed = parse_url($this->uri); $scheme = isset($parsed['host']) ? $parsed['host'] : $parsed['path']; } return in_array($scheme, $this->schemes); }
Validate scheme @param string|null $scheme @return bool
entailment
public function base() { if (!$this->validate()) { throw new \InvalidArgumentException("Invalid URI: $this->uri"); } $parts = [ 'scheme' => parse_url($this->uri, PHP_URL_SCHEME), 'host' => parse_url($this->uri, PHP_URL_HOST), ]; $parts['port'] = is_int($port = parse_url($this->uri, PHP_URL_PORT)) ? $port : getservbyname($parts['scheme'], 'tcp'); return strtolower($parts['scheme'] . '://' . $parts['host'] . ':' . $parts['port']); }
Base @return string
entailment
public function getDocumentation($routeId, $version, $path) { if ($version == '*' || empty($version)) { $version = $this->methodTable->getLatestVersion($routeId); } else { $version = $this->methodTable->getVersion($routeId, $version); } if (empty($version)) { throw new StatusCode\UnsupportedMediaTypeException('Version does not exist'); } $methods = $this->methodTable->getMethods($routeId, $version, true, true); $resource = new Resource($this->getStatusFromMethods($methods), $path); $scopes = $this->scopeTable->getScopesForRoute($routeId); // check variable path fragments $parts = explode('/', $path); foreach ($parts as $part) { if (isset($part[0])) { $name = null; if ($part[0] == ':') { $name = substr($part, 1); } elseif ($part[0] == '$') { $pos = strpos($part, '<'); $name = substr($part, 1, $pos - 1); } if ($name !== null) { $resource->addPathParameter($name, Property::getString()); } } } foreach ($methods as $method) { $resourceMethod = Resource\Factory::getMethod($method['method']); $schemaCache = $method['schemaCache']; if (!empty($method['description'])) { $resourceMethod->setDescription($method['description']); } if (!$method['public']) { if (isset($scopes[$method['method']])) { $resourceMethod->setSecurity(Authorization::APP, array_unique($scopes[$method['method']])); } else { $resourceMethod->setSecurity(Authorization::APP, []); } } if ($method['status'] != Resource::STATUS_DEVELOPMENT && !empty($schemaCache)) { // if we are not in development mode and a cache is available // use it $spec = json_decode($schemaCache, true); if (isset($spec['parameters'])) { $property = $this->getProperty($spec['parameters']); $properties = $property->getProperties(); if (!empty($properties)) { foreach ($properties as $name => $type) { $resourceMethod->addQueryParameter($name, $type); } } } if (isset($spec['request'])) { $resourceMethod->setRequest(new Schema($this->getProperty($spec['request']))); } if (isset($spec['responses'])) { foreach ($spec['responses'] as $code => $schema) { $resourceMethod->addResponse($code, new Schema($this->getProperty($schema))); } } } else { if ($method['parameters'] > 0) { $schema = $this->schemaLoader->getSchema($method['parameters']); $properties = $schema->getDefinition()->getProperties(); if (!empty($properties)) { foreach ($properties as $name => $type) { $resourceMethod->addQueryParameter($name, $type); } } } if ($method['request'] > 0) { $resourceMethod->setRequest(new LazySchema($this->schemaLoader, $method['request'])); } $responses = $this->responseTable->getResponses($method['id']); if (!empty($responses)) { foreach ($responses as $response) { $resourceMethod->addResponse($response['code'], new LazySchema($this->schemaLoader, $response['response'])); } } } $resource->addMethod($resourceMethod); } return $resource; }
Returns an api resource documentation for the provided route and version @param integer $routeId @param string $version @param string $path @return \PSX\Api\Resource
entailment
public function getMethod($routeId, $version, $method) { if ($version == '*' || empty($version)) { $version = $this->methodTable->getLatestVersion($routeId); } else { $version = $this->methodTable->getVersion($routeId, $version); } if (empty($version)) { throw new StatusCode\UnsupportedMediaTypeException('Version does not exist'); } return $this->methodTable->getMethod($routeId, $version, $method); }
Returns the method configuration for the provide route, version and request method @param integer $routeId @param string $version @param string $method @return array
entailment
public function add_section( $id, $args = [] ) { $section = $id instanceof Section ? $id : new Section( $this, $id, $args ); $this->sections[ $section->id ] = $section; return $section; }
{@inheritdoc}
entailment
public function get_section( $id ) { return isset( $this->sections[ $id ] ) ? $this->sections[ $id ] : null; }
{@inheritdoc}
entailment
public function prepare( Form $form ) { $this->set_form( $form ); $this->prepare_fields( $form ); $this->prepare_sections(); $containers = $this->sections; if ( $this instanceof Has_Panel ) { $this->prepare_panels(); $containers = array_merge( $this->panels(), $containers ); } // Sort panels and top-level sections together. $this->containers = wp_list_sort( $containers, [ 'priority' => 'ASC', 'instance_number' => 'ASC', ], 'ASC', true ); $this->apply_current_section( $form ); return $this; }
{@inheritdoc}
entailment
protected function apply_current_section( Form $form ) { if ( count( $this->sections ) === 0 ) { return; } // Make sure we don't have any active section before. foreach ( $this->sections as $section ) { $section->options['active'] = false; } $current = $this->current_section_in_cookie( $form->get_id() ); if ( ! $current && $form->get_config()->has_option( 'active_section' ) ) { $current = $form->get_config()->get_option( 'active_section' ); } // Use first section as fallback. if ( ! $current || ! isset( $this->sections[ $current ] ) ) { $current = Arr::first( array_keys( $this->sections ) ); } if ( $section = $this->get_section( $current ) ) { $section->options['active'] = true; } }
Set the current section. @param \WPLibs\Form\Contracts\Form $form
entailment
protected function current_section_in_cookie( $id ) { if ( empty( $_COOKIE['_wplibs_current_sections'] ) ) { return null; } $currents = json_decode( sanitize_text_field( wp_unslash( $_COOKIE['_wplibs_current_sections'] ) ), true ); if ( array_key_exists( $id, $currents ) ) { return $currents[ $id ]; } return null; }
Resolve current section from the cookie. @return string|null
entailment
protected function prepare_fields( Form $form ) { foreach ( $form->all() as $field ) { /* @var $field \WPLibs\Form\Field */ if ( ! $field->should_show() ) { return; } $_section = $field->get_option( 'section' ); if ( ! $_section || ! isset( $this->sections[ $_section ] ) ) { continue; } $this->sections[ $_section ]->fields[] = $field; } }
Maps fields into their section. @param \WPLibs\Form\Contracts\Form $form
entailment
protected function prepare_sections() { $this->sections = wp_list_sort( $this->sections, [ 'priority' => 'ASC', 'instance_number' => 'ASC', ], 'ASC', true ); $sections = []; foreach ( $this->sections as $section ) { if ( ! $section->check_capabilities() ) { continue; } // Top-level section. if ( ! $this instanceof Has_Panel || ! $section->panel ) { $sections[ $section->id ] = $section; continue; } // This section belongs to a panel. if ( isset( $this->panels [ $section->panel ] ) ) { $this->panels[ $section->panel ]->sections[ $section->id ] = $section; } } // Update the sections. $this->sections = $sections; }
Prepare the sections. @return void
entailment
protected function prepare_panels() { if ( ! $this instanceof Has_Panel ) { return; } // Prepare panels. $this->panels = wp_list_sort( $this->panels(), [ 'priority' => 'ASC', 'instance_number' => 'ASC', ], 'ASC', true ); $panels = []; foreach ( $this->panels() as $panel ) { if ( ! $panel->check_capabilities() ) { continue; } $panel->sections = wp_list_sort( $panel->sections, [ 'priority' => 'ASC', 'instance_number' => 'ASC', ], 'ASC', true ); $panels[ $panel->id ] = $panel; } // Set the panels. $this->panels = $panels; }
Prepare the panels. @return void
entailment
protected function getLocale(?string $expectedLocale) { return $expectedLocale ?? (null === $this->request ? $this->defaultLocale : $this->request->getLocale()); }
Always get a locale even if we are not in a request.
entailment
public function add_section( $id, $args = [] ) { $section = $this->manager->add_section( $id, $args ); $section->panel = $this->id; return $section; }
Add a section into this panel. @param string $id The Section object, or Section ID. @param array $args The section properties. @return Section
entailment
public function render(\Magento\Framework\DataObject $row) { $customerId = (int)$row->getData($this->getColumn()->getIndex()); if($customerId > 0) { return '<a href="' . $this->getUrl('customer/index/edit', array('id' => $customerId)) . '" target="_blank">' . $customerId . '</a>'; } return nl2br(htmlspecialchars($row->getData($this->getColumn()->getIndex()))); }
Render the description of given row. @param \Magento\Framework\DataObject $row @return string
entailment
public function render(\Magento\Framework\DataObject $row) { return ($row->getData($this->getColumn()->getIndex()) > 0) ? __('yes') : __('no'); }
Render the description of given row. @param \Magento\Framework\DataObject $row @return string
entailment
private function convertEncoding() { $convert = new EncodingHandler($this->content, $this->encoding); if (($result = $convert->auto()) !== false) { $this->encoding = self::ENCODING; mb_internal_encoding(self::ENCODING); return $this->content = $result; } mb_internal_encoding(self::ENCODING); return $this->content; }
Convert character encoding @return string
entailment
private function limitBytes($bytes) { if ($bytes === null) { return $this->content; } elseif (intval($bytes) < (self::BYTE_LIMIT * 0.046875)) { // less than 24 kilobytes (512 kilobytes * 0.046875) throw new \InvalidArgumentException('Byte limit is set dangerously low! Default value=' . self::BYTE_LIMIT); } return $this->content = mb_strcut($this->content, 0, intval($bytes)); }
Byte limit @param int|null $bytes @return string @throws \InvalidArgumentException
entailment
public function userAgent($product = self::USER_AGENT, $version = null) { return $this->handler->userAgent->client($product, $version, $this->statusCode); }
User-agent specific rules @param string $product @param float|int|string|null $version @return UserAgentClient
entailment
public function attributes( $attributes, $merge_global = false ) { if ( $merge_global && count( $this->global_attributes ) > 0 ) { $attributes = $attributes + $this->global_attributes; } return Utils::build_html_attributes( $attributes ); }
Create an HTML attribute string from an array. @param array $attributes @param bool $merge_global @return string
entailment
public function label( $name, $value = null, $options = [] ) { $this->labels[] = $name; $value = $this->format_label( $name, $value ); return $this->to_html_string( '<label for="' . $name . '"' . $this->attributes( $options ) . '>' . $value . '</label>' ); }
Create a form label element. @param string $name @param string $value @param array $options @return Html_String
entailment
public function input( $type, $name, $value = null, $options = [] ) { $this->type = $type; if ( ! isset( $options['name'] ) ) { $options['name'] = $name; } // We will get the appropriate value for the given field. We will look for the // value in the session for the value in the old input data then we'll look // in the model instance if one is set. Otherwise we will just use empty. $id = $this->get_id_attribute( $name, $options ); if ( ! in_array( $type, $this->skip_value_types ) ) { $value = $this->get_value_attribute( $name, $value ); } // Once we have the type, value, and ID we can merge them into the rest of the // attributes array so we can convert them into their HTML attribute format // when creating the HTML element. Then, we will return the entire input. $merge = compact( 'type', 'value', 'id' ); $options = array_merge( $options, $merge ); return $this->to_html_string( '<input' . $this->attributes( $options, true ) . '>' ); }
Create a form input field. @param string $type @param string $name @param string $value @param array $options @return Html_String
entailment
public function button( $value = null, $options = [] ) { if ( ! array_key_exists( 'type', $options ) ) { $options['type'] = 'button'; } return $this->to_html_string( '<button' . $this->attributes( $options ) . '>' . $value . '</button>' ); }
Create a button element. @param string $value @param array $options @return Html_String
entailment
public function textarea( $name, $value = null, $options = [] ) { $this->type = 'textarea'; if ( ! isset( $options['name'] ) ) { $options['name'] = $name; } // Next we will look for the rows and cols attributes, as each of these are put // on the textarea element definition. If they are not present, we will just // assume some sane default values for these attributes for the developer. $options = $this->set_textarea_size( $options ); $options['id'] = $this->get_id_attribute( $name, $options ); $value = (string) $this->get_value_attribute( $name, $value ); unset( $options['size'] ); // Next we will convert the attributes into a string form. Also we have removed // the size attribute, as it was merely a short-cut for the rows and cols on // the element. Then we'll create the final textarea elements HTML for us. $options = $this->attributes( $options, true ); return $this->to_html_string( '<textarea' . $options . '>' . esc_textarea( $value ) . '</textarea>' ); }
Create a textarea input field. @param string $name @param string $value @param array $options @return Html_String
entailment
protected function set_textarea_size( $options ) { if ( isset( $options['size'] ) ) { list( $cols, $rows ) = explode( 'x', $options['size'] ); } else { // If the "size" attribute was not specified, we will just look for the regular // columns and rows attributes, using sane defaults if these do not exist on // the attributes array. We'll then return this entire options array back. $cols = Arr::get( $options, 'cols', 50 ); $rows = Arr::get( $options, 'rows', 10 ); } return array_merge( $options, compact( 'cols', 'rows' ) ); }
Set the text area size on the attributes. @param array $options @return array
entailment
public function select( $name, $list = [], $selected = null, array $attributes = [], array $options_attributes = [], array $optgroups_attributes = [] ) { $this->type = 'select'; // When building a select box the "value" attribute is really the selected one // so we will use that when checking the model or session for a value which // should provide a convenient method of re-populating the forms on post. $selected = $this->get_value_attribute( $name, $selected ); $attributes['id'] = $this->get_id_attribute( $name, $attributes ); if ( ! isset( $attributes['name'] ) ) { $attributes['name'] = $name; } // We will simply loop through the options and build an HTML value for each of // them until we have an array of HTML declarations. Then we will join them // all together into one single HTML element that can be put on the form. $html = []; if ( isset( $attributes['placeholder'] ) ) { $html[] = $this->placeholder_option( $attributes['placeholder'], $selected ); unset( $attributes['placeholder'] ); } foreach ( $list as $value => $display ) { $option_atts = Arr::get( $options_attributes, $value, [] ); $optgroup_atts = Arr::get( $optgroups_attributes, $value, [] ); $html[] = $this->get_select_option( $display, $value, $selected, $option_atts, $optgroup_atts ); } // Once we have all of this HTML, we can join this into a single element after // formatting the attributes into an HTML "attributes" string, then we will // build out a final select statement, which will contain all the values. $attributes = $this->attributes( $attributes, true ); $list = implode( '', $html ); return $this->to_html_string( "<select{$attributes}>{$list}</select>" ); }
Create a select box field. @param string $name @param array $list @param string|bool $selected @param array $attributes @param array $options_attributes @param array $optgroups_attributes @return Html_String
entailment
public function select_year( $name, $begin, $end, $selected = null, $options = [] ) { return $this->select_range( ...func_get_args() ); }
Create a select year field. @param string $name @param string $begin @param string $end @param string $selected @param array $options @return mixed
entailment
public function get_select_option( $display, $value, $selected, array $attributes = [], array $optgroup_attributes = [] ) { if ( is_iterable( $display ) ) { return $this->option_group( $display, $value, $selected, $optgroup_attributes, $attributes ); } return $this->option( $display, $value, $selected, $attributes ); }
Get the select option for the given value. @param string|array $display @param string $value @param string $selected @param array $attributes @param array $optgroup_attributes @return Html_String
entailment
protected function option_group( $list, $label, $selected, array $attributes = [], array $options_attributes = [], $level = 0 ) { $html = []; $space = str_repeat( '&nbsp;', $level ); foreach ( $list as $value => $display ) { $option_attributes = Arr::get( $options_attributes, $value, [] ); if ( is_iterable( $display ) ) { $html[] = $this->option_group( $display, $value, $selected, $attributes, $option_attributes, $level + 5 ); } else { $html[] = $this->option( $space . $display, $value, $selected, $option_attributes ); } } return $this->to_html_string( '<optgroup label="' . esc_attr( $space . $label ) . '"' . $this->attributes( $attributes ) . '>' . implode( '', $html ) . '</optgroup>' ); }
Create an option group form element. @param array $list @param string $label @param string $selected @param array $attributes @param array $options_attributes @param integer $level @return Html_String
entailment
protected function option( $display, $value, $selected, array $attributes = [] ) { $selected = $this->get_selected_value( $value, $selected ); // @codingStandardsIgnoreLine $options = array_merge( [ 'value' => $value, 'selected' => $selected ], $attributes ); $string = '<option' . $this->attributes( $options ) . '>'; if ( null !== $display ) { $string .= esc_html( $display ) . '</option>'; } return $this->to_html_string( $string ); }
Create a select element option. @param string $display @param string $value @param string $selected @param array $attributes @return Html_String
entailment
protected function placeholder_option( $display, $selected ) { $selected = $this->get_selected_value( null, $selected ); $options = [ 'selected' => $selected, 'value' => '', ]; return $this->to_html_string( '<option' . $this->attributes( $options ) . '>' . esc_html( $display ) . '</option>' ); }
Create a placeholder select element option. @param string $display @param mixed $selected @return Html_String
entailment
protected function get_checked_state( $type, $name, $value, $checked ) { switch ( $type ) { case 'checkbox': return $this->get_checkbox_checked_state( $name, $value, $checked ); case 'radio': return $this->get_radio_checked_state( $name, $value, $checked ); default: return $this->compare_values( $name, $value ); } }
Get the check state for a checkable input. @param string $type @param string $name @param mixed $value @param bool $checked @return bool
entailment
protected function get_checkbox_checked_state( $name, $value, $checked ) { $request = $this->request( $name ); if ( ! $request && null !== $this->session && ! $this->old_input_is_empty() && is_null( $this->old( $name ) ) ) { return false; } if ( $this->missing_old_and_model( $name ) && is_null( $request ) ) { return $checked; } $posted = $this->get_value_attribute( $name, $checked ); if ( is_array( $posted ) ) { return in_array( $value, $posted ); } if ( $posted instanceof Collection ) { return $posted->contains( 'id', $value ); } return (bool) $posted; }
Get the check state for a checkbox input. @param string $name @param mixed $value @param bool $checked @return bool
entailment
protected function get_radio_checked_state( $name, $value, $checked ) { $request = $this->request( $name ); if ( ! $request && $this->missing_old_and_model( $name ) ) { return $checked; } return $this->compare_values( $name, $value ); }
Get the check state for a radio input. @param string $name @param mixed $value @param bool $checked @return bool
entailment
protected function missing_old_and_model( $name ) { return ( is_null( $this->old( $name ) ) && is_null( $this->get_model_value_attribute( $name ) ) ); }
Determine if old input or model input exists for a key. @param string $name @return bool
entailment
public function datalist( $id, $list = [] ) { $this->type = 'datalist'; $attributes['id'] = $id; $html = []; if ( $this->is_associative_array( $list ) ) { foreach ( $list as $value => $display ) { $html[] = $this->option( $display, $value, null, [] ); } } else { foreach ( $list as $value ) { $html[] = $this->option( $value, $value, null, [] ); } } $attributes = $this->attributes( $attributes ); $list = implode( '', $html ); return $this->to_html_string( "<datalist{$attributes}>{$list}</datalist>" ); }
Create a datalist box field. @param string $id @param array $list @return Html_String
entailment
public function get_id_attribute( $name, $attributes ) { if ( array_key_exists( 'id', $this->global_attributes ) ) { return $this->global_attributes['id']; } if ( array_key_exists( 'id', $attributes ) ) { return $attributes['id']; } if ( in_array( $name, $this->labels ) ) { return $name; } return null; }
Get the ID attribute for a field name. @param string $name @param array $attributes @return string|null
entailment
public function get_value_attribute( $name, $value = null ) { if ( is_null( $name ) ) { return $value; } $old = $this->old( $name ); if ( '_method' !== $name && ! is_null( $old ) ) { return $old; } $request = $this->request( $name ); if ( '_method' !== $name && ! is_null( $request ) ) { return $request; } if ( ! is_null( $value ) ) { return $value; } if ( $this->model ) { return $this->get_model_value_attribute( $name ); } return null; }
Get the value that should be assigned to the field. @param string $name @param string $value @return mixed
entailment
protected function request( $name ) { if ( ! $this->consider_request || ! $this->request ) { return null; } return $this->request->input( $this->transform_key( $name ) ); }
Get value from current Request @param string $name @return string|array|null
entailment
public function old( $name ) { if ( ! $this->session ) { return null; } $payload = $this->session->get_old_input( $key = Utils::to_dots_key( $name ) ); if ( ! is_array( $payload ) ) { return $payload; } if ( ! in_array( $this->type, [ 'select', 'checkbox' ] ) ) { if ( ! isset( $this->payload[ $key ] ) ) { $this->payload[ $key ] = new Collection( $payload ); } if ( ! empty( $this->payload[ $key ] ) ) { return $this->payload[ $key ]->shift(); } } return $payload; }
Get a value from the session's old input. @param string $name @return mixed
entailment
protected function get_model_value_attribute( $name ) { $key = $this->transform_key( $name ); if ( method_exists( $this->model, 'get' ) ) { return $this->model->get( $key ); } return data_get( $this->model, $this->transform_key( $name ) ); }
Get the model value that should be assigned to the field. @param string $name @return mixed
entailment
private function readMoWords($fp, $offset, $count, $pack) { fseek($fp, $offset); return unpack($pack . $count, fread($fp, $count * 4)); }
Read specific binary data (32 bit words) from a .MO file @param resource $fp @param int $offset @param int $count @param string $pack "N" for big-endian, "V" for little-endian @return int[]
entailment
private function readMoFile($fp) { // How is the numeric data packed in the .MO file? $magic = $this->readMoWords($fp, 0, 1, self::PACK_LITTLE_ENDIAN); switch (dechex($magic[1])) { case self::MO_MAGIC_LITTLE_ENDIAN: $pack = self::PACK_LITTLE_ENDIAN; break; case self::MO_MAGIC_BIG_ENDIAN: $pack = self::PACK_BIG_ENDIAN; break; default: // Not a valid .MO file. throw new \InvalidArgumentException('Invalid .MO file'); } // Read the lookup tables list(, $number_of_strings, $offset_original, $offset_translated) = $this->readMoWords($fp, 8, 3, $pack); $lookup_original = $this->readMoWords($fp, $offset_original, $number_of_strings * 2, $pack); $lookup_translated = $this->readMoWords($fp, $offset_translated, $number_of_strings * 2, $pack); // Read the strings for ($n = 1; $n < $number_of_strings; ++$n) { fseek($fp, $lookup_original[$n * 2 + 2]); $original = fread($fp, $lookup_original[$n * 2 + 1]); fseek($fp, $lookup_translated[$n * 2 + 2]); $translated = fread($fp, $lookup_translated[$n * 2 + 1]); $this->translations[$original] = $translated; } }
Read and parse a .MO (gettext) file @link https://www.gnu.org/software/gettext/manual/html_node/MO-Files.html @param resource $fp @return void
entailment
public function toOptionArray() { if(empty($this->config->getTransportTypes())) { return [ ['label' => __('Disabled'), 'value' => 'disabled'] ]; } $selection = array(); foreach ($this->config->getTransportTypes() as $transportType) { $selection[] = ['label' => __($transportType['label']), 'value' => $transportType['value']]; } return $selection; }
{@inheritdoc}
entailment
public function render(\Magento\Framework\DataObject $row) { $recipients = json_decode($row->getData($this->getColumn()->getIndex()), true); if(!empty($recipients)) { $recipientsString = htmlspecialchars(implode(', ', $recipients)); if(strlen($recipientsString) < 15) { return $recipientsString; } return substr($recipientsString, 0, 12) . '...'; } return ''; }
Render the description of given row. @param \Magento\Framework\DataObject $row @return string
entailment
public function evaluate(FlowQuery $flowQuery, array $arguments) { $sortOrder = 'ASC'; if (!empty($arguments[0]) && in_array($arguments[0], ['ASC', 'DESC'], true)) { $sortOrder = $arguments[0]; } $nodes = $flowQuery->getContext(); $indexPathCache = []; /** @var NodeInterface $node */ foreach ($nodes as $node) { // Collect the list of sorting indices for all parents of the node and the node itself $nodeIdentifier = $node->getIdentifier(); $indexPath = [$node->getIndex()]; while ($node = $node->getParent()) { $indexPath[] = $node->getIndex(); } $indexPathCache[$nodeIdentifier] = $indexPath; } $flip = $sortOrder === 'DESC' ? -1 : 1; usort($nodes, function (NodeInterface $a, NodeInterface $b) use ($indexPathCache, $flip) { if ($a === $b) { return 0; } // Compare index path starting from the site root until a difference is found $aIndexPath = $indexPathCache[$a->getIdentifier()]; $bIndexPath = $indexPathCache[$b->getIdentifier()]; while (count($aIndexPath) > 0 && count($bIndexPath) > 0) { $diff = (array_pop($aIndexPath) - array_pop($bIndexPath)); if ($diff !== 0) { return $flip * $diff < 0 ? -1 : 1; } } return 0; }); $flowQuery->setContext($nodes); }
{@inheritdoc} @return void
entailment
public function display( $field, $value, $builder ) { wp_enqueue_style( 'jquery-ui-slider-pips' ); $field->add_js_dependencies( 'jquery-ui-slider-pips' ); $field_args = $field->_data( 'args' ); if ( isset( $field_args['pips'] ) && false === $field_args['pips'] ) { $pips_args = false; } else { /** * Setting slider-pip pips. * * @see http://simeydotme.github.io/jQuery-ui-Slider-Pips/#options-pips * * @var array( * @type string|false $last Determines the style of the first pip on the slider. * Value can be: "label", "pip" or false. * @type string|false $first Determines the style of the final pip on the slider. * Value can be: "label", "pip" or false. * @type string|false $rest Determines the style of all other pips on the slider. * Value can be: "label", "pip" or false. * @type number $step The step parameter will only generate every nth pip. * @type string $prefix Adds a string value before the pip label. * @type string $suffix Adds a string value after the pip label. * @type array|false $labels Will override the values of the pips with an array of given values. * eg: array( 'Monday', 'Tuesday', 'Wednesday', ...) * or array( 'first' => 'Monday', 'last' => 'Sunday' ) * ) */ $pips_args = json_encode( wp_parse_args( $field->args( 'pips' ), [ 'last' => 'label', 'first' => 'label', 'rest' => 'pip', // 'step' => 1, // Note: Not set default step at here. 'prefix' => '', 'suffix' => '', 'labels' => false, ])); } if ( isset( $field_args['float'] ) && false === $field_args['float'] ) { $float_args = false; } else { /** * Setting slider-pip float. * * @see http://simeydotme.github.io/jQuery-ui-Slider-Pips/#options-float * * @var array( * @type string $prefix Adds a string value before the float label. * @type string $suffix Adds a string value after the float label. * @type array|false $labels Will override the values of the floats with an array of given values. * eg: array( 'Monday', 'Tuesday', 'Wednesday', ...) * or array( 'first' => 'Monday', 'last' => 'Sunday' ) * ) */ $float_args = json_encode( wp_parse_args( $field->args( 'float' ), [ 'prefix' => '', 'suffix' => '', 'labels' => false, ])); } ?> <div class="cmb2-slider"><div class="cmb2-ui-slider"></div></div> <?php print $builder->input( [ // WPCS: XSS OK. 'type' => 'hidden', 'class' => 'cmb2-ui-slider-input', 'desc' => '', 'data-min' => $field->args( 'min' ), 'data-max' => $field->args( 'max' ), 'data-step' => $field->args( 'step' ), 'data-value' => is_numeric( $value ) ? $value : 0, 'data-pips' => esc_attr( $pips_args ), 'data-float' => esc_attr( $float_args ), ] ); ?> <span class="hidden"><span class="cmb2-ui-slider-preview"></span></span> <?php }
{@inheritdoc}
entailment
public function add($line) { $array = $this->draftParseTime($line); if ($array !== false) { $this->visitTimes[] = $array; return true; } return false; }
Add @param string $line @return bool
entailment
private function sort() { if (!$this->sorted) { $this->sorted = true; return usort($this->visitTimes, function (array $visitTimeA, array $visitTimeB) { // PHP 7: Switch to the <=> "Spaceship" operator return $visitTimeA['from'] > $visitTimeB['from']; }); } return $this->sorted; }
Sort @return bool
entailment
public function render(RenderHandler $handler) { $this->sort(); foreach ($this->visitTimes as $array) { $handler->add(self::DIRECTIVE_VISIT_TIME, $array['from'] . '-' . $array['to']); } return true; }
Render @param RenderHandler $handler @return bool
entailment
public function render(\Magento\Framework\DataObject $row) { $url = $this->getUrl('customer/mail/edit', array('id' => $row->getId())); return "<a href='{$url}' target='_blank'>View</a>"; }
Render the description of given row. @param \Magento\Framework\DataObject $row @return string
entailment
public function set_group( Field $group ) { $this->group = $group; $this->form = $this->group->get_form(); $this->storage = $this->group->get_storage(); return $this; }
Sets the group field instance. @param \WPLibs\Form\Contracts\Field $group @return $this
entailment
public function get_attribute( $key, $default = null ) { $attributes = $this->get_attributes(); return array_key_exists( $key, $attributes ) ? $attributes[ $key ] : $default; }
{@inheritdoc}
entailment
public function set_attribute( $attribute, $value = '' ) { $attributes = is_array( $attribute ) ? $attribute : [ $attribute => $value ]; $this->set_option( 'attributes', array_merge( $this->get_attributes(), $attributes ) ); return $this; }
{@inheritdoc}
entailment
public function template() { $labels = $this->get_button_labels(); ?> <# if ( data.attachment && data.attachment.id ) { #> <div class="attachment-media-view attachment-media-view-{{ data.attachment.type }} {{ data.attachment.orientation }}"> <div class="thumbnail thumbnail-{{ data.attachment.type }}"> <# if ( 'image' === data.attachment.type && data.attachment.sizes && data.attachment.sizes.medium ) { #> <img class="attachment-thumb" src="{{ data.attachment.sizes.medium.url }}" draggable="false" alt=""/> <# } else if ( 'image' === data.attachment.type && data.attachment.sizes && data.attachment.sizes.full ) { #> <img class="attachment-thumb" src="{{ data.attachment.sizes.full.url }}" draggable="false" alt=""/> <# } else if ( 'audio' === data.attachment.type ) { #> <# if ( data.attachment.image && data.attachment.image.src && data.attachment.image.src !== data.attachment.icon ) { #> <img src="{{ data.attachment.image.src }}" class="thumbnail" draggable="false" alt=""/> <# } else { #> <img src="{{ data.attachment.icon }}" class="attachment-thumb type-icon" draggable="false" alt=""/> <# } #> <p class="attachment-meta attachment-meta-title">&#8220;{{ data.attachment.title }}&#8221;</p> <# if ( data.attachment.album || data.attachment.meta.album ) { #> <p class="attachment-meta"><em>{{ data.attachment.album || data.attachment.meta.album }}</em></p> <# } #> <# if ( data.attachment.artist || data.attachment.meta.artist ) { #> <p class="attachment-meta">{{ data.attachment.artist || data.attachment.meta.artist }}</p> <# } #> <audio style="visibility: hidden" controls class="wp-audio-shortcode" width="100%" preload="none"> <source type="{{ data.attachment.mime }}" src="{{ data.attachment.url }}"/> </audio> <# } else if ( 'video' === data.attachment.type ) { #> <div class="wp-media-wrapper wp-video"> <video controls="controls" class="wp-video-shortcode" preload="metadata" <# if ( data.attachment.image && data.attachment.image.src !== data.attachment.icon ) { #>poster="{{ data.attachment.image.src }}"<# } #>> <source type="{{ data.attachment.mime }}" src="{{ data.attachment.url }}"/> </video> </div> <# } else { #> <img class="attachment-thumb type-icon icon" src="{{ data.attachment.icon }}" draggable="false" alt="" /> <p class="attachment-title">{{ data.attachment.title }}</p> <# } #> </div> <div class="actions"> <?php if ( current_user_can( 'upload_files' ) ) : ?> <button type="button" class="button remove-button"><?php echo esc_html( $labels['remove'] ); ?></button> <button type="button" class="button upload-button control-focus"><?php echo esc_html( $labels['change'] ); ?></button> <?php endif; ?> </div> </div> <# } else { #> <div class="attachment-media-view"> <p class="placeholder"><?php echo esc_html( $labels['placeholder'] ); ?></p> <div class="actions"> <# if ( data.default ) { #> <button type="button" class="button default-button"><?php echo esc_html( $labels['default'] ); ?></button> <# } #> <?php if ( current_user_can( 'upload_files' ) ) : ?> <button type="button" class="button upload-button"><?php echo esc_html( $labels['select'] ); ?></button> <?php endif; ?> </div> </div> <# } #> <?php }
{@inheritdoc}
entailment
public function js_data( $field ) { $value = $field->get_value(); // Preapre attachment for the preview. $attachment = []; // Fake an attachment model - needs all fields used by template. // Note that the default value must be a URL, NOT an attachment ID. if ( ! $value && $_default = $field->get_default() ) { $type = in_array( substr( $_default, -3 ), [ 'jpg', 'png', 'gif', 'bmp' ] ) ? 'image' : 'document'; $attachment = [ 'id' => 1, 'url' => $_default, 'type' => $type, 'icon' => wp_mime_type_icon( $type ), 'title' => basename( $_default ), ]; if ( 'image' === $type ) { $attachment['sizes'] = [ 'full' => [ 'url' => $_default ] ]; } } elseif ( $value ) { $attachment = wp_prepare_attachment_for_js( $value ); } return [ 'mime_type' => $this->mime_type, 'attachment' => $attachment, 'labels' => Arr::only( $this->get_button_labels(), [ 'frame_title', 'frame_button' ] ), ]; }
Returns field data for the JS. @param \WPLibs\Form\Field $field @return array
entailment
public function get_button_labels() { // Get just the mime type and strip the mime subtype if present. $mime_type = ! empty( $this->mime_type ) ? strtok( ltrim( $this->mime_type, '/' ), '/' ) : 'default'; switch ( $mime_type ) { case 'video': return [ 'select' => esc_html__( 'Select video', 'wplibs-form' ), 'change' => esc_html__( 'Change video', 'wplibs-form' ), 'default' => esc_html__( 'Default', 'wplibs-form' ), 'remove' => esc_html__( 'Remove', 'wplibs-form' ), 'placeholder' => esc_html__( 'No video selected', 'wplibs-form' ), 'frame_title' => esc_html__( 'Select video', 'wplibs-form' ), 'frame_button' => esc_html__( 'Choose video', 'wplibs-form' ), ]; case 'audio': return [ 'select' => esc_html__( 'Select audio', 'wplibs-form' ), 'change' => esc_html__( 'Change audio', 'wplibs-form' ), 'default' => esc_html__( 'Default', 'wplibs-form' ), 'remove' => esc_html__( 'Remove', 'wplibs-form' ), 'placeholder' => esc_html__( 'No audio selected', 'wplibs-form' ), 'frame_title' => esc_html__( 'Select audio', 'wplibs-form' ), 'frame_button' => esc_html__( 'Choose audio', 'wplibs-form' ), ]; case 'image': return [ 'select' => esc_html__( 'Select image', 'wplibs-form' ), 'change' => esc_html__( 'Change image', 'wplibs-form' ), 'default' => esc_html__( 'Default', 'wplibs-form' ), 'remove' => esc_html__( 'Remove', 'wplibs-form' ), 'placeholder' => esc_html__( 'No image selected', 'wplibs-form' ), 'frame_title' => esc_html__( 'Select image', 'wplibs-form' ), 'frame_button' => esc_html__( 'Choose image', 'wplibs-form' ), ]; default: return [ 'select' => esc_html__( 'Select file', 'wplibs-form' ), 'change' => esc_html__( 'Change file', 'wplibs-form' ), 'default' => esc_html__( 'Default', 'wplibs-form' ), 'remove' => esc_html__( 'Remove', 'wplibs-form' ), 'placeholder' => esc_html__( 'No file selected', 'wplibs-form' ), 'frame_title' => esc_html__( 'Select file', 'wplibs-form' ), 'frame_button' => esc_html__( 'Choose file', 'wplibs-form' ), ]; } // End switch(). }
Get the button labels. Provides an array of the default button labels based on the mime type of the current control. @return array An associative array of default button labels.
entailment
public static function get_system_fonts() { $fonts = []; foreach ( static::$websafe_fonts as $label => $family ) { $fonts[] = [ 'family' => $family, 'label' => $label, 'variants' => [ '400', '400italic', '700', '700italic' ], ]; } return apply_filters( 'suru_libs_system_fonts', $fonts ); }
Gets list system fonts. @return array
entailment
public static function get_google_fonts() { $google_fonts = get_transient( '_suru_libs_google_fonts' ); if ( ! is_array( $google_fonts ) || empty( $google_fonts ) ) { // Fallback to load fonts from local file. $google_fonts = json_decode( file_get_contents( dirname( dirname( __DIR__ ) ) . '/Resources/webfonts.json' ), true ); static::set_transients( $google_fonts ); } return apply_filters( 'suru_libs_system_fonts', $google_fonts ); }
Gets the Google Fonts. @see https://developers.google.com/fonts/docs/developer_api @return array
entailment
public static function fetch_google_fonts( $api_key = null ) { $raw_fonts = static::request_google_fonts( $api_key ); // Invalid API key or something else. if ( ! is_array( $raw_fonts ) || ! isset( $raw_fonts['items'] ) ) { return []; } $fonts = []; foreach ( $raw_fonts['items'] as $item ) { if ( ! isset( $item['kind'] ) || 'webfonts#webfont' !== $item['kind'] ) { continue; } $fonts[] = Arr::only( $item, [ 'family', 'category', 'variants', 'subset' ] ); } static::flush_transients(); static::set_transients( $fonts ); return $fonts; }
Get list of fonts from Google Fonts. @param string $api_key The Google Fonts API key. @return array|false
entailment
public static function request_google_fonts( $api_key = null ) { $api_key = apply_filters( 'suru_libs_google_fonts_api_keys', $api_key ); if ( empty( $api_key ) ) { return false; } $response = wp_remote_get( static::GOOGLE_FONTS_ENDPOINT . '?sort=alpha' . ( $api_key ? "&key={$api_key}" : '' ), [ 'sslverify' => false ] ); if ( 200 !== wp_remote_retrieve_response_code( $response ) ) { return false; } return json_decode( wp_remote_retrieve_body( $response ), true ); }
Send http request to get fonts from Google Fonts service. @see https://developers.google.com/fonts/docs/developer_api @param string $api_key The Google Fonts API key. @return array|false
entailment
public function auto() { if (strtoupper($this->encoding) === self::ENCODING) { return $this->string; } $errorHandler = new ErrorHandler(); set_error_handler([$errorHandler, 'callback'], E_NOTICE | E_WARNING); foreach ([ 'intl', 'iconv', 'xml', 'mbstring', ] as $extension) { $last = $errorHandler->getLast(); if (extension_loaded($extension) && ($result = call_user_func([$this, $extension])) !== false && $last === $errorHandler->getLast() ) { restore_error_handler(); return $result; } } restore_error_handler(); return false; }
Auto mode @return string|false
entailment
public function intl() { try { $uConverter = new \UConverter(self::ENCODING, $this->encoding); $converted = $uConverter->convert($this->string, false); } catch (\Exception $e) { return false; } return $converted; }
intl @link http://php.net/manual/en/uconverter.convert.php @return string|false
entailment
public function iconv($outSuffix = '//TRANSLIT//IGNORE') { try { $converted = iconv($this->encoding, self::ENCODING . $outSuffix, $this->string); } catch (\Exception $e) { return false; } return $converted; }
iconv @link http://php.net/manual/en/function.iconv.php @param string $outSuffix @return string|false
entailment