Skip to content

Instantly share code, notes, and snippets.

@JPry
Created July 6, 2018 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JPry/4d40e4c63736ae309f9724139cd6a470 to your computer and use it in GitHub Desktop.
Save JPry/4d40e4c63736ae309f9724139cd6a470 to your computer and use it in GitHub Desktop.
<?php
namespace JPry;
use JPry\Exception\InvalidField;
class Example {
/**
* Generate the sub-field objects for this field.
*
* @since %VERSION%
*
* @throws InvalidField When an invalid field class is provided through the filter.
*/
protected function generate_sub_fields() {
$classes = array_merge( $this->classes, $this->get_classes() );
$default_fields = $this->get_default_fields();
foreach ( $default_fields as $field => $settings ) {
$settings = wp_parse_args( $settings, [
'label' => ucwords( str_replace( [ '_', '-' ], ' ', $field ) ),
'class' => Types::TEXT,
'required' => true,
] );
// Set up the field ID, depending on whether the field is repeatable.
$id = $this->id . ( $this->repeatable ? '[]' : '' ) . "[{$field}]";
// Instantiate the sub field.
$this->sub_fields[] = new $settings['class'](
$id,
$settings['label'],
$classes,
(bool) $settings['required']
);
// Ensure the class extends the Field interface.
if ( ! ( end( $this->sub_fields ) instanceof Field ) ) {
throw InvalidField::from_field( $settings['class'] );
}
}
}
}
<?php
namespace JPry\Exception;
interface Exception {}
<?php
namespace JPry\Exception;
class InvalidField extends \InvalidArgumentException implements Exception {
/**
* Create a new instance of the exception for a field class name that is not recognized.
*
* @param string $field Class name of the service that was not recognized.
*
* @return static
*/
public static function from_field( $field ) {
$message = sprintf(
'The field class "%s" is not recognized and cannot be used.',
is_object( $field )
? get_class( $field )
: (string) $field
);
return new static( $message );
}
/**
* Create a new instance of the exception for a field ID that is invalid.
*
* @param string $id The invalid field ID.
*
* @return static
*/
public static function invalid_id( $id ) {
$message = sprintf(
'The ID "%s" is invalid. The ID must be a simple string, or a single depth array',
$id
);
return new static( $message );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment