sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public static function get_permalink_structure( $post_type ) {
if ( is_string( $post_type ) ) {
$post_type = get_post_type_object( $post_type );
}
if ( ! empty( $post_type->cptp ) && ! empty( $post_type->cptp['permalink_structure'] ) ) {
$structure = $post_type->cptp->permalink_structure;
} else if ( ! empty( $post_type->cptp_permalink_structure ) ) {
$structure = $post_type->cptp_permalink_structure;
} else {
$structure = get_option( $post_type->name . '_structure', '%postname%' );
}
$structure = '/' . ltrim( $structure, '/' );
return apply_filters( 'CPTP_' . $post_type->name . '_structure', $structure );
}
|
Get permalink structure.
@since 0.9.6
@param string|WP_Post_Type $post_type post type name. / object post type object.
@return string post type structure.
|
entailment
|
public static function get_post_type_date_archive_support( $post_type ) {
if ( is_string( $post_type ) ) {
$post_type = get_post_type_object( $post_type );
}
if ( ! empty( $post_type->cptp ) && isset( $post_type->cptp['date_archive'] ) ) {
return ! ! $post_type->cptp['date_archive'];
}
return true;
}
|
Check support date archive.
@since 3.3.0
@param string|WP_Post_Type $post_type post type name. / object post type object.
@return bool
|
entailment
|
public static function get_post_type_author_archive_support( $post_type ) {
if ( is_string( $post_type ) ) {
$post_type = get_post_type_object( $post_type );
}
if ( ! empty( $post_type->cptp ) && isset( $post_type->cptp['author_archive'] ) ) {
return ! ! $post_type->cptp['author_archive'];
}
return true;
}
|
Check support author archive.
@since 3.3.0
@param string|WP_Post_Type $post_type post type name. / object post type object.
@return bool
|
entailment
|
public static function get_date_front( $post_type ) {
$structure = CPTP_Util::get_permalink_structure( $post_type );
$front = '';
preg_match_all( '/%.+?%/', $structure, $tokens );
$tok_index = 1;
foreach ( (array) $tokens[0] as $token ) {
if ( '%post_id%' === $token && ( $tok_index <= 3 ) ) {
$front = '/date';
break;
}
$tok_index ++;
}
return apply_filters( 'CPTP_date_front', $front, $post_type, $structure );
}
|
Get permalink structure front for date archive.
@since 1.0.0
@param string $post_type post type name.
@return string
|
entailment
|
public static function sort_terms( $terms, $orderby = 'term_id', $order = 'ASC' ) {
if ( function_exists( 'wp_list_sort' ) ) {
$terms = wp_list_sort( $terms, 'term_id', 'ASC' );
} else {
if ( 'name' === $orderby ) {
usort( $terms, '_usort_terms_by_name' );
} else {
usort( $terms, '_usort_terms_by_ID' );
}
if ( 'DESC' === $order ) {
$terms = array_reverse( $terms );
}
}
return $terms;
}
|
Sort Terms.
@since 3.1.0
@param WP_Term[] $terms Terms array.
@param string|array $orderby term object key.
@param string $order ASC or DESC.
@return WP_Term[]
|
entailment
|
public function add_hook() {
add_filter(
'post_type_link',
array( $this, 'post_type_link' ),
apply_filters( 'cptp_post_type_link_priority', 0 ),
4
);
add_filter(
'term_link',
array( $this, 'term_link' ),
apply_filters( 'cptp_term_link_priority', 0 ),
3
);
add_filter(
'attachment_link',
array( $this, 'attachment_link' ),
apply_filters( 'cptp_attachment_link_priority', 20 ),
2
);
}
|
Add Filter Hooks.
|
entailment
|
private function create_taxonomy_replace_tag( $post_id, $permalink ) {
$search = array();
$replace = array();
$taxonomies = CPTP_Util::get_taxonomies( true );
// %taxnomomy% -> parent/child
foreach ( $taxonomies as $taxonomy => $objects ) {
if ( false !== strpos( $permalink, '%' . $taxonomy . '%' ) ) {
$terms = get_the_terms( $post_id, $taxonomy );
if ( $terms && ! is_wp_error( $terms ) ) {
$parents = array_map( array( __CLASS__, 'get_term_parent' ), $terms );
$newTerms = array();
foreach ( $terms as $key => $term ) {
if ( ! in_array( $term->term_id, $parents , true ) ) {
$newTerms[] = $term;
}
}
$term_obj = reset( $newTerms );
$term_slug = $term_obj->slug;
if ( isset( $term_obj->parent ) && $term_obj->parent ) {
$term_slug = CPTP_Util::get_taxonomy_parents_slug( $term_obj->parent, $taxonomy, '/', true ) . $term_slug;
}
}
if ( isset( $term_slug ) ) {
$search[] = '%' . $taxonomy . '%';
$replace[] = $term_slug;
}
}
}
return array(
'search' => $search,
'replace' => $replace,
);
}
|
Create %tax% -> term
@param int $post_id post id.
@param string $permalink permalink uri.
@return array
|
entailment
|
public function attachment_link( $link, $post_id ) {
/**
* WP_Rewrite.
*
* @var WP_Rewrite $wp_rewrite
*/
global $wp_rewrite;
if ( ! $wp_rewrite->permalink_structure ) {
return $link;
}
$post = get_post( $post_id );
if ( ! $post->post_parent ) {
return $link;
}
$post_parent = get_post( $post->post_parent );
if ( ! $post_parent ) {
return $link;
}
$pt_object = get_post_type_object( $post_parent->post_type );
if ( empty( $pt_object->rewrite ) ) {
return $link;
}
if ( ! in_array( $post->post_type, CPTP_Util::get_post_types(), true ) ) {
return $link;
}
$permalink = CPTP_Util::get_permalink_structure( $post_parent->post_type );
$post_type = get_post_type_object( $post_parent->post_type );
if ( empty( $post_type->_builtin ) ) {
if ( strpos( $permalink, '%postname%' ) < strrpos( $permalink, '%post_id%' ) && false === strrpos( $link, 'attachment/' ) ) {
$link = str_replace( $post->post_name, 'attachment/' . $post->post_name, $link );
}
}
return $link;
}
|
Fix attachment output
@version 1.0
@since 0.8.2
@param string $link permalink URI.
@param int $post_id Post ID.
@return string
|
entailment
|
public function term_link( $termlink, $term, $taxonomy ) {
/**
* WP_Rewrite.
*
* @var WP_Rewrite $wp_rewrite
*/
global $wp_rewrite;
if ( ! $wp_rewrite->permalink_structure ) {
return $termlink;
}
if ( CPTP_Util::get_no_taxonomy_structure() ) {
return $termlink;
}
$taxonomy = get_taxonomy( $taxonomy );
if ( empty( $taxonomy ) ) {
return $termlink;
}
if ( $taxonomy->_builtin ) {
return $termlink;
}
if ( ! $taxonomy->public ) {
return $termlink;
}
$wp_home = rtrim( home_url(), '/' );
if ( in_array( get_post_type(), $taxonomy->object_type, true ) ) {
$post_type = get_post_type();
} else {
$post_type = $taxonomy->object_type[0];
}
$front = substr( $wp_rewrite->front, 1 );
$termlink = str_replace( $front, '', $termlink );// remove front.
$post_type_obj = get_post_type_object( $post_type );
if ( empty( $post_type_obj ) ) {
return $termlink;
}
$slug = $post_type_obj->rewrite['slug'];
$with_front = $post_type_obj->rewrite['with_front'];
if ( $with_front ) {
$slug = $front . $slug;
}
if ( ! empty( $slug ) ) {
$termlink = str_replace( $wp_home, $wp_home . '/' . $slug, $termlink );
}
if ( ! $taxonomy->rewrite['hierarchical'] ) {
$termlink = str_replace( $term->slug . '/', CPTP_Util::get_taxonomy_parents_slug( $term->term_id, $taxonomy->name, '/', true ), $termlink );
}
return $termlink;
}
|
Fix taxonomy link outputs.
@since 0.6
@version 1.0
@param string $termlink link URI.
@param Object $term Term Object.
@param Object $taxonomy Taxonomy Object.
@return string
|
entailment
|
public function register_post_type_rules( $post_type, $args ) {
/**
* WP_Rewrite.
*
* @var WP_Rewrite $wp_rewrite
*/
global $wp_rewrite;
if ( $args->_builtin ) {
return;
}
if ( false === $args->rewrite ) {
return;
}
if ( ! in_array( $post_type, CPTP_Util::get_post_types(), true ) ) {
return;
}
$permalink = CPTP_Util::get_permalink_structure( $post_type );
if ( ! $permalink ) {
$permalink = CPTP_DEFAULT_PERMALINK;
}
$permalink = '%' . $post_type . '_slug%' . $permalink;
$permalink = str_replace( '%postname%', '%' . $post_type . '%', $permalink );
add_rewrite_tag( '%' . $post_type . '_slug%', '(' . $args->rewrite['slug'] . ')', 'post_type=' . $post_type . '&slug=' );
$taxonomies = CPTP_Util::get_taxonomies( true );
foreach ( $taxonomies as $taxonomy => $objects ) :
$wp_rewrite->add_rewrite_tag( "%$taxonomy%", '(.+?)', "$taxonomy=" );
endforeach;
$rewrite_args = $args->rewrite;
if ( ! is_array( $rewrite_args ) ) {
$rewrite_args = array(
'with_front' => $args->rewrite,
);
}
$slug = $args->rewrite['slug'];
if ( $args->has_archive ) {
if ( is_string( $args->has_archive ) ) {
$slug = $args->has_archive;
};
if ( $args->rewrite['with_front'] ) {
$slug = substr( $wp_rewrite->front, 1 ) . $slug;
}
if ( CPTP_Util::get_post_type_date_archive_support( $post_type ) ) {
$date_front = CPTP_Util::get_date_front( $post_type );
add_rewrite_rule( $slug . $date_front . '/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/feed/(feed|rdf|rss|rss2|atom)/?$', 'index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&feed=$matches[4]&post_type=' . $post_type, 'top' );
add_rewrite_rule( $slug . $date_front . '/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/(feed|rdf|rss|rss2|atom)/?$', 'index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&feed=$matches[4]&post_type=' . $post_type, 'top' );
add_rewrite_rule( $slug . $date_front . '/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/page/?([0-9]{1,})/?$', 'index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&paged=$matches[4]&post_type=' . $post_type, 'top' );
add_rewrite_rule( $slug . $date_front . '/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/?$', 'index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&post_type=' . $post_type, 'top' );
add_rewrite_rule( $slug . $date_front . '/([0-9]{4})/([0-9]{1,2})/feed/(feed|rdf|rss|rss2|atom)/?$', 'index.php?year=$matches[1]&monthnum=$matches[2]&feed=$matches[3]&post_type=' . $post_type, 'top' );
add_rewrite_rule( $slug . $date_front . '/([0-9]{4})/([0-9]{1,2})/(feed|rdf|rss|rss2|atom)/?$', 'index.php?year=$matches[1]&monthnum=$matches[2]&feed=$matches[3]&post_type=' . $post_type, 'top' );
add_rewrite_rule( $slug . $date_front . '/([0-9]{4})/([0-9]{1,2})/page/?([0-9]{1,})/?$', 'index.php?year=$matches[1]&monthnum=$matches[2]&paged=$matches[3]&post_type=' . $post_type, 'top' );
add_rewrite_rule( $slug . $date_front . '/([0-9]{4})/([0-9]{1,2})/?$', 'index.php?year=$matches[1]&monthnum=$matches[2]&post_type=' . $post_type, 'top' );
add_rewrite_rule( $slug . $date_front . '/([0-9]{4})/feed/(feed|rdf|rss|rss2|atom)/?$', 'index.php?year=$matches[1]&feed=$matches[2]&post_type=' . $post_type, 'top' );
add_rewrite_rule( $slug . $date_front . '/([0-9]{4})/(feed|rdf|rss|rss2|atom)/?$', 'index.php?year=$matches[1]&feed=$matches[2]&post_type=' . $post_type, 'top' );
add_rewrite_rule( $slug . $date_front . '/([0-9]{4})/page/?([0-9]{1,})/?$', 'index.php?year=$matches[1]&paged=$matches[2]&post_type=' . $post_type, 'top' );
add_rewrite_rule( $slug . $date_front . '/([0-9]{4})/?$', 'index.php?year=$matches[1]&post_type=' . $post_type, 'top' );
}
if ( CPTP_Util::get_post_type_author_archive_support( $post_type ) ) {
add_rewrite_rule( $slug . '/author/([^/]+)/page/?([0-9]{1,})/?$', 'index.php?author_name=$matches[1]&paged=$matches[2]&post_type=' . $post_type, 'top' );
add_rewrite_rule( $slug . '/author/([^/]+)/?$', 'index.php?author_name=$matches[1]&post_type=' . $post_type, 'top' );
}
if ( in_array( 'category', $args->taxonomies, true ) ) {
$category_base = get_option( 'category_base', 'category' );
add_rewrite_rule( $slug . '/' . $category_base . '/([^/]+)/page/?([0-9]{1,})/?$', 'index.php?category_name=$matches[1]&paged=$matches[2]&post_type=' . $post_type, 'top' );
add_rewrite_rule( $slug . '/' . $category_base . '/([^/]+)/?$', 'index.php?category_name=$matches[1]&post_type=' . $post_type, 'top' );
}
do_action( 'CPTP_registered_' . $post_type . '_rules', $args, $slug );
}
$rewrite_args['walk_dirs'] = false;
add_permastruct( $post_type, $permalink, $rewrite_args );
}
|
Register_post_type_rules
add rewrite tag for Custom Post Type.
@version 1.1
@since 0.9
@param string $post_type Post type.
@param WP_Post_Type $args Arguments used to register the post type.
|
entailment
|
public function register_taxonomy_rules( $taxonomy, $object_type, $args ) {
global $wp_rewrite;
/* for 4.7 */
$args = (array) $args;
if ( CPTP_Util::get_no_taxonomy_structure() ) {
return;
}
if ( ! empty( $args['_builtin'] ) ) {
return;
}
if ( false === $args['rewrite'] ) {
return;
}
$post_types = $args['object_type'];
foreach ( $post_types as $post_type ) :
$post_type_obj = get_post_type_object( $post_type );
if ( ! empty( $post_type_obj->rewrite['slug'] ) ) {
$slug = $post_type_obj->rewrite['slug'];
} else {
$slug = $post_type;
}
if ( ! empty( $post_type_obj->has_archive ) && is_string( $post_type_obj->has_archive ) ) {
$slug = $post_type_obj->has_archive;
};
if ( ! empty( $post_type_obj->rewrite['with_front'] ) ) {
$slug = substr( $wp_rewrite->front, 1 ) . $slug;
}
if ( 'category' === $taxonomy ) {
$cb = get_option( 'category_base' );
$taxonomy_slug = ( $cb ) ? $cb : $taxonomy;
$taxonomy_key = 'category_name';
} else {
// Edit by [Xiphe].
if ( isset( $args['rewrite']['slug'] ) ) {
$taxonomy_slug = $args['rewrite']['slug'];
} else {
$taxonomy_slug = $taxonomy;
}
// [Xiphe] stop
$taxonomy_key = $taxonomy;
}
$rules = array(
// feed.
array(
'regex' => '%s/(.+?)/feed/(feed|rdf|rss|rss2|atom)/?$',
'redirect' => "index.php?{$taxonomy_key}=\$matches[1]&feed=\$matches[2]",
),
array(
'regex' => '%s/(.+?)/(feed|rdf|rss|rss2|atom)/?$',
'redirect' => "index.php?{$taxonomy_key}=\$matches[1]&feed=\$matches[2]",
),
// year.
array(
'regex' => '%s/(.+?)/date/([0-9]{4})/?$',
'redirect' => "index.php?{$taxonomy_key}=\$matches[1]&year=\$matches[2]",
),
array(
'regex' => '%s/(.+?)/date/([0-9]{4})/page/?([0-9]{1,})/?$',
'redirect' => "index.php?{$taxonomy_key}=\$matches[1]&year=\$matches[2]&paged=\$matches[3]",
),
// monthnum.
array(
'regex' => '%s/(.+?)/date/([0-9]{4})/([0-9]{1,2})/?$',
'redirect' => "index.php?{$taxonomy_key}=\$matches[1]&year=\$matches[2]&monthnum=\$matches[3]",
),
array(
'regex' => '%s/(.+?)/date/([0-9]{4})/([0-9]{1,2})/page/?([0-9]{1,})/?$',
'redirect' => "index.php?{$taxonomy_key}=\$matches[1]&year=\$matches[2]&monthnum=\$matches[3]&paged=\$matches[4]",
),
// day.
array(
'regex' => '%s/(.+?)/date/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/?$',
'redirect' => "index.php?{$taxonomy_key}=\$matches[1]&year=\$matches[2]&monthnum=\$matches[3]&day=\$matches[4]",
),
array(
'regex' => '%s/(.+?)/date/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/page/?([0-9]{1,})/?$',
'redirect' => "index.php?{$taxonomy_key}=\$matches[1]&year=\$matches[2]&monthnum=\$matches[3]&day=\$matches[4]&paged=\$matches[5]",
),
// paging.
array(
'regex' => '%s/(.+?)/page/?([0-9]{1,})/?$',
'redirect' => "index.php?{$taxonomy_key}=\$matches[1]&paged=\$matches[2]",
),
// tax archive.
array(
'regex' => '%s/(.+?)/?$',
'redirect' => "index.php?{$taxonomy_key}=\$matches[1]",
),
);
// no post_type slug.
foreach ( $rules as $rule ) {
$regex = sprintf( $rule['regex'], "{$taxonomy_slug}" );
$redirect = $rule['redirect'];
add_rewrite_rule( $regex, $redirect, 'top' );
}
if ( get_option( 'add_post_type_for_tax' ) ) {
foreach ( $rules as $rule ) {
$regex = sprintf( $rule['regex'], "{$slug}/{$taxonomy_slug}" );
$redirect = $rule['redirect'] . "&post_type={$post_type}";
add_rewrite_rule( $regex, $redirect, 'top' );
}
} else {
foreach ( $rules as $rule ) {
$regex = sprintf( $rule['regex'], "{$slug}/{$taxonomy_slug}" );
$redirect = $rule['redirect'];
add_rewrite_rule( $regex, $redirect, 'top' );
}
}
do_action( 'CPTP_registered_' . $taxonomy . '_rules', $object_type, $args, $taxonomy_slug );
endforeach;
}
|
Register_taxonomy_rules
@param string $taxonomy Taxonomy slug.
@param array|string $object_type Object type or array of object types.
@param array $args Array of taxonomy registration arguments.
@return void
|
entailment
|
public function update_rules() {
$post_types = CPTP_Util::get_post_types();
foreach ( $post_types as $post_type ) {
add_action( 'update_option_' . $post_type . '_structure', array( __CLASS__, 'queue_flush_rules' ), 10, 2 );
}
add_action( 'update_option_no_taxonomy_structure', array( __CLASS__, 'queue_flush_rules' ), 10, 2 );
}
|
Add hook flush_rules
@since 0.7.9
|
entailment
|
public function settings_api_init() {
add_settings_section( 'cptp_setting_section',
__( 'Permalink Settings for Custom Post Types', 'custom-post-type-permalinks' ),
array( $this, 'setting_section_callback_function' ),
'permalink'
);
$post_types = CPTP_Util::get_post_types();
foreach ( $post_types as $post_type ) {
add_settings_field(
$post_type . '_structure',
$post_type,
array( $this, 'setting_structure_callback_function' ),
'permalink',
'cptp_setting_section',
array(
'label_for' => $post_type . '_structure',
'post_type' => $post_type,
)
);
register_setting( 'permalink', $post_type . '_structure' );
}
add_settings_field(
'no_taxonomy_structure',
__( 'Use custom permalink of custom taxonomy archive.', 'custom-post-type-permalinks' ),
array( $this, 'setting_no_tax_structure_callback_function' ),
'permalink',
'cptp_setting_section',
array(
'label_for' => 'no_taxonomy_structure',
)
);
register_setting( 'permalink', 'no_taxonomy_structure' );
add_settings_field(
'add_post_type_for_tax',
__( 'Add <code>post_type</code> query for custom taxonomy archive.', 'custom-post-type-permalinks' ),
array( $this, 'add_post_type_for_tax_callback_function' ),
'permalink',
'cptp_setting_section',
array(
'label_for' => 'add_post_type_for_tax',
)
);
register_setting( 'permalink', 'no_taxonomy_structure' );
}
|
Setting Init
@since 0.7
|
entailment
|
public function setting_section_callback_function() {
$sptp_link = admin_url( 'plugin-install.php?s=simple-post-type-permalinks&tab=search&type=term' );
// translators: %s simple post type permalinks install page.
$sptp_template = __( 'If you need post type permalink only, you should use <a href="%s">Simple Post Type Permalinks</a>.', 'custom-post-type-permalinks' );
?>
<p>
<strong>
<?php
$allowed_html = array(
'a' => array(
'href' => true,
),
);
echo wp_kses( sprintf( $sptp_template, esc_url( $sptp_link ) ), $allowed_html );
?>
</strong>
</p>
<?php
$allowed_html_code_tag = array(
'code' => array(),
);
?>
<p><?php echo wp_kses( __( 'The tags you can use are WordPress Structure Tags and <code>%"custom_taxonomy_slug"%</code> (e.g. <code>%actors%</code> or <code>%movie_actors%</code>).', 'custom-post-type-permalinks' ), $allowed_html_code_tag ); ?>
<?php echo wp_kses( __( '<code>%"custom_taxonomy_slug"%</code> is replaced by the term of taxonomy.', 'custom-post-type-permalinks' ), $allowed_html_code_tag ); ?></p>
<p><?php esc_html_e( "Presence of the trailing '/' is unified into a standard permalink structure setting.", 'custom-post-type-permalinks' ); ?>
<p><?php echo wp_kses( __( 'If <code>has_archive</code> is true, add permalinks for custom post type archive.', 'custom-post-type-permalinks' ), $allowed_html_code_tag ); ?></p>
<?php
}
|
Setting section view.
|
entailment
|
public function setting_structure_callback_function( $option ) {
$post_type = $option['post_type'];
$name = $option['label_for'];
$pt_object = get_post_type_object( $post_type );
$slug = $pt_object->rewrite['slug'];
$with_front = $pt_object->rewrite['with_front'];
$value = CPTP_Util::get_permalink_structure( $post_type );
$disabled = false;
if ( isset( $pt_object->cptp_permalink_structure ) && $pt_object->cptp_permalink_structure ) {
$disabled = true;
}
if ( ! $value ) {
$value = CPTP_DEFAULT_PERMALINK;
}
global $wp_rewrite;
$front = substr( $wp_rewrite->front, 1 );
if ( $front && $with_front ) {
$slug = $front . $slug;
}
?>
<p>
<code><?php echo esc_html( home_url() . ( $slug ? '/' : '' ) . $slug ); ?></code>
<input name="<?php echo esc_attr( $name ); ?>" id="<?php echo esc_attr( $name ); ?>" type="text" class="regular-text code " value="<?php echo esc_attr( $value ); ?>" <?php disabled( $disabled, true, true ); ?> />
</p>
<p>has_archive: <code><?php echo esc_html( $pt_object->has_archive ? 'true' : 'false' ); ?></code> / with_front:
<code><?php echo esc_html( $pt_object->rewrite['with_front'] ? 'true' : 'false' ); ?></code></p>
<?php
}
|
Show setting structure input.
@param array $option {
Callback option.
@type string 'post_type' post type name.
@type string 'label_for' post type label.
}
|
entailment
|
public function setting_no_tax_structure_callback_function() {
$no_taxonomy_structure = CPTP_Util::get_no_taxonomy_structure();
echo '<input name="no_taxonomy_structure" id="no_taxonomy_structure" type="checkbox" value="1" class="code" ' . checked( false, $no_taxonomy_structure, false ) . ' /> ';
$txt = __( "If you check this, the custom taxonomy's permalinks will be <code>%s/post_type/taxonomy/term</code>.", 'custom-post-type-permalinks' );
echo sprintf( wp_kses( $txt, array( 'code' => array() ) ), esc_html( home_url() ) );
}
|
Show checkbox no tax.
|
entailment
|
public function enqueue_css_js() {
$pointer_name = 'custom-post-type-permalinks-settings';
if ( ! is_network_admin() ) {
$dismissed = explode( ',', get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true ) );
if ( false === array_search( $pointer_name, $dismissed, true ) ) {
$content = '';
$content .= '<h3>' . __( 'Custom Post Type Permalinks', 'custom-post-type-permalinks' ) . '</h3>';
$content .= '<p>' . __( 'You can setting permalink for post type in <a href="options-permalink.php">Permalinks</a>.', 'custom-post-type-permalinks' ) . '</p>';
wp_enqueue_style( 'wp-pointer' );
wp_enqueue_script( 'wp-pointer' );
wp_enqueue_script( 'custom-post-type-permalinks-pointer', plugins_url( 'assets/settings-pointer.js', CPTP_PLUGIN_FILE ), array( 'wp-pointer' ), CPTP_VERSION );
wp_localize_script( 'custom-post-type-permalinks-pointer', 'CPTP_Settings_Pointer', array(
'content' => $content,
'name' => $pointer_name,
) );
}
}
}
|
Enqueue css and js
@since 0.8.5
|
entailment
|
public function admin_notices() {
if ( version_compare( get_option( 'cptp_permalink_checked' ), '3.0.0', '<' ) ) {
// translators: %s URL.
$format = __( '[Custom Post Type Permalinks] <a href="%s"><strong>Please check your permalink settings!</strong></a>', 'custom-post-type-permalinks' );
$message = sprintf( $format, admin_url( 'options-permalink.php' ) );
echo sprintf( '<div class="notice notice-warning"><p>%s</p></div>', wp_kses( $message, wp_kses_allowed_html( 'post' ) ) );
}
}
|
Admin notice for update permalink settings!
|
entailment
|
public function mailPassword($to, $subject, $data)
{
$this->mail->send('blogify::mails.password', ['data' => $data], function($message) use ($to, $subject)
{
$message->to($to)->subject($subject);
});
}
|
Mail the generated password
to the newly created user
@param $to
@param $subject
@param $data
|
entailment
|
public function mailReviewer($to, $subject, $data)
{
$this->mail->send('blogify::mails.notifyReviewer', ['data' => $data], function($message) use ($to, $subject)
{
$message->to($to)->subject($subject);
});
}
|
Send a notification mail to
the assigned reviewer
@param $to
@param $subject
@param $data
|
entailment
|
public function handle($request, Closure $next)
{
if (! in_array($this->auth->user()->role->id, $this->allowed_roles)) {
return redirect()->route('admin.dashboard');
}
return $next($request);
}
|
Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed
|
entailment
|
public function authorize()
{
$this->hash = $this->route('profile');
$this->user_id = $this->getUserId();
if ($this->auth->user()->getAuthIdentifier() != $this->user_id) {
return false;
}
return true;
}
|
Determine if the user is authorized to make this request.
@return bool
|
entailment
|
public function handle($request, Closure $next)
{
$user = $this->user->byHash($request->segment(3));
if ($this->auth->user()->getAuthIdentifier() != $user->id) {
abort(404);
}
return $next($request);
}
|
Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed
|
entailment
|
public function register()
{
$this->app->bind('jorenvanhocht.blogify', function()
{
$db = $this->app['db'];
$config = $this->app['config'];
return new Blogify($db, $config);
});
$this->registerMiddleware();
$this->registerServiceProviders();
$this->registerAliases();
}
|
Register the service provider
|
entailment
|
public function boot()
{
// Load the routes for the package
include __DIR__.'/routes.php';
$this->publish();
$this->loadViewsFrom(__DIR__.'/../views', 'blogify');
$this->loadViewsFrom(__DIR__.'/../Example/Views', 'blogifyPublic');
// Make the config file accessible even when the files are not published
$this->mergeConfigFrom(__DIR__.'/../config/blogify.php', 'blogify');
$this->loadTranslationsFrom(__DIR__.'/../lang/', 'blogify');
$this->registerCommands();
// Register the class that serves extra validation rules
$this->app['validator']->resolver(
function(
$translator,
$data,
$rules,
$messages = array(),
$customAttributes = array()
) {
return new Validation($translator, $data, $rules, $messages, $customAttributes);
});
}
|
Load the resources
|
entailment
|
public function rules()
{
$segment = $this->segment(3);
$id = isset($segment) ? $this->category->byHash($this->segment(3))->id : 0;
return [
'name' => "required|unique:categories,name,$id|min:3|max:45",
];
}
|
Get the validation rules that apply to the request.
@return array
|
entailment
|
public function generateUniqueUsername($lastname, $firstname, $iteration = 0)
{
$username = strtolower(str_replace(' ', '', $lastname).substr($firstname, 0, 1));
if ($iteration != 0) {
$username = $username.$iteration;
}
$usernames = count($this->db->table('users')->where('username', '=', $username)->get());
if ($usernames > 0) {
return $this->generateUniqueUsername($lastname, $firstname, $iteration + 1);
}
return $username;
}
|
Generate a unique username with the users
lastname and firstname
@param $lastname
@param $firstname
@param int $iteration
@return string
|
entailment
|
private function storeOrUpdateCategory($request)
{
$cat = $this->category->whereName($request->name)->first();
if (count($cat) > 0) {
$category = $cat;
} else {
$category = new Category;
$category->hash = $this->blogify->makeHash('categories', 'hash', true);
}
$category->name = $request->name;
$category->save();
return $category;
}
|
Save the given category in the db
@param CategoryRequest $request
@return \jorenvanhocht\Blogify\Models\Category
|
entailment
|
public function sort(
$table,
$column,
$order,
$trashed = false,
DatabaseManager $db
) {
$db = $db->connection();
$data = $db->table($table);
// Check for trashed data
$data = $trashed ? $data->whereNotNull('deleted_at') : $data->whereNull('deleted_at');
if ($table == 'users') {
$data = $data->join('roles', 'users.role_id', '=', 'roles.id');
}
if ($table == 'posts') {
$data = $data->join('statuses', 'posts.status_id', '=', 'statuses.id');
}
$data = $data
->orderBy($column, $order)
->paginate($this->config->items_per_page);
return $data;
}
|
Order the data of a given table on the given column
and the given order
@param string $table
@param string $column
@param string $order
@param bool $trashed
@param \Illuminate\Database\DatabaseManager $db
@return object
|
entailment
|
public function checkIfSlugIsUnique($slug)
{
$i = 0;
$this->base_slug = $slug;
while ($this->post->whereSlug($slug)->get()->count() > 0) {
$i++;
$slug = "$this->base_slug-$i";
}
return $slug;
}
|
Check if a given slug already exists
and when it exists generate a new one
@param string $slug
@return string
|
entailment
|
public function autoSave(Cache $cache, Request $request)
{
try {
$hash = $this->auth_user->hash;
$cache->put(
"autoSavedPost-$hash",
$request->all(),
Carbon::now()->addHours(2)
);
} catch (BlogifyException $exception) {
return response()->json([false, date('d-m-Y H:i:s')]);
}
return response()->json([true, date('d-m-Y H:i:s')]);
}
|
Save the current post in the cache
@param \Illuminate\Contracts\Cache\Repository $cache
@param \Illuminate\Http\Request $request;
@return \Symfony\Component\HttpFoundation\Response
|
entailment
|
public function handle($request, Closure $next)
{
$post = $this->post->bySlug($request->segment(2));
if($post->count() == 0) {
return redirect('/', 404)
->with(
'error',
'Post not found.'
);
}
if ($post->visibility_id == 2) {
if (!$this->hash->check(Input::get('password'), $post->password)) {
return redirect()->route('blog.askPassword', [$post->slug])
->with(
'wrong_password',
'Please provide a valid password to view this post'
);
}
}
return $next($request);
}
|
Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed
|
entailment
|
public function handle($request, Closure $next)
{
$hash = $request->segment(3);
$post = $this->post->byHash($hash);
if (
$post->being_edited_by != null &&
$post->being_edited_by != $this->auth->user()->getAuthIdentifier()
) {
$user = $this->user->find($post->being_edited_by)->fullName;
session()->flash('notify', ['danger', trans('blogify::posts.notify.being_edited', ['name' => $user])]);
return redirect()->route('admin.posts.index');
}
return $next($request);
}
|
Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed
|
entailment
|
public function handle($request, Closure $next)
{
if (! $this->checkIfUserCanEditPost($request)) {
return redirect()->route('admin.dashboard');
}
return $next($request);
}
|
Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed
|
entailment
|
public function fire()
{
foreach ($this->config->upload_paths as $paths) {
foreach ($paths as $path) {
if (! file_exists(public_path($path))) {
File::makeDirectory(public_path($path), 0775, true);
}
}
}
}
|
Execute the console command.
@return mixed
|
entailment
|
private function createUsersTable()
{
Schema::create('users', function ($table) {
foreach ($this->fields as $field => $value) {
$query = $table->$value['type']($field);
if (isset($value['extra'])) {
$query->$value['extra']();
}
}
$table->foreign('role_id')->references('id')->on('roles');
$table->timestamps();
$table->softDeletes();
});
}
|
Create a new Users table with
all the required fields
|
entailment
|
private function updateUsersTable()
{
Schema::table('users', function ($table) {
foreach ($this->fields as $field => $value) {
if (!Schema::hasColumn('users', $field)) {
$type = $value['type'];
$query = $table->$type($field);
if (isset($value['extra'])) {
$extra = $value['extra'];
$query->$extra();
}
if ($field == 'role_id') {
$table->foreign('role_id')->references('id')->on('roles');
}
}
}
if (!Schema::hasColumn('users', 'created_at') && !Schema::hasColumn('users', 'updated_at')) {
$table->timestamps();
}
if (!Schema::hasColumn('users', 'deleted_at')) {
$table->softDeletes();
}
});
}
|
Add the not existing columns
to the existing users table
|
entailment
|
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
}
return redirect()->route('admin.login');
}
// Check if the user has permission to visit the admin panel
if (! in_array($this->auth->user()->role_id, $this->allowed_roles)) {
return redirect()->route('admin.login');
}
return $next($request);
}
|
Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed
|
entailment
|
public function handle($request, Closure $next)
{
if (! $this->checkIfUserCanViewPost($request)) {
return redirect()->route('/');
}
return $next($request);
}
|
Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed
|
entailment
|
public function rules()
{
$hash = $this->input('hash');
$id = (! empty($hash)) ? $this->post->byHash($hash)->id : 0;
$protected_visibility = $this->visibility->whereName('Protected')->first()->hash;
return [
'title' => 'required|min:2|max:100',
'slug' => "required|unique:posts,slug,$id|min:2|max:120",
'reviewer' => 'exists:users,hash',
'post' => 'required',
'category' => 'required|exists:categories,hash',
'publishdate' => 'required|date_format: d-m-Y H:i',
'password' => "required_if:visibility,$protected_visibility",
];
}
|
Get the validation rules that apply to the request.
@return array
|
entailment
|
public function handle($request, Closure $next)
{
if ($this->auth->user()->role->name != 'Admin') {
return redirect()->route('admin.dashboard');
}
return $next($request);
}
|
Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed
|
entailment
|
public function getMenuImgs() {
$re = ['menu'=>'', 'imgs'=>''];
try{
$obdr = new DirectoryIterator($_SERVER['DOCUMENT_ROOT'] .'/'. $this->root . $this->imgdr); // object of the dir
}
catch(Exception $e) {
return '<h2>ERROR from PHP:</h2><h3>'. $e->getMessage() .'</h3><h4>Check the $root value in imgbrowse.php to see if it is the correct path to the image folder; RELATIVE TO ROOT OF YOUR WEBSITE ON SERVER</h4>';
}
// get protocol and host name to add absolute path in <img src>
$protocol = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://';
$site = $protocol. $_SERVER['SERVER_NAME'] .'/';
// traverse the $obdr
foreach($obdr as $fileobj) {
$name = $fileobj->getFilename();
// if image file, else, directory (but not . or ..), add data in $re
if($fileobj->isFile() && in_array($fileobj->getExtension(), $this->imgext)) $re['imgs'] .= '<span><img src="'. $site . $this->root . $this->imgdr . $name .'" alt="'. $name .'" height="50" />'. $name .'</span>';
else if($fileobj->isDir() && !$fileobj->isDot()) $re['menu'] .= '<li><span title="'. $this->imgdr . $name .'">'. $name .'</span></li>';
}
if($re['menu'] != '') $re['menu'] = '<ul>'. $re['menu'] .'</ul>';
if($re['imgs'] == '') $re['imgs'] = '<h1>No Images</h1>';
return $re;
}
|
return two-dimensional array with folders-list and images in specified $imgdr
|
entailment
|
public function store(PostRequest $request)
{
$this->data = objectify($request->except([
'_token', 'newCategory', 'newTags'
]));
if (! empty($this->data->tags)) {
$this->buildTagsArray();
}
$post = $this->storeOrUpdatePost();
if ($this->status->byHash($this->data->status)->name == 'Pending review') {
$this->mailReviewer($post);
}
$action = ($request->hash == '') ? 'created' : 'updated';
$this->tracert->log('posts', $post->id, $this->auth_user->id, $action);
$message = trans('blogify::notify.success', [
'model' => 'Post', 'name' => $post->title, 'action' => $action
]);
session()->flash('notify', ['success', $message]);
$hash = $this->auth_user->hash;
$this->cache->forget("autoSavedPost-$hash");
return redirect()->route('admin.posts.index');
}
|
Store or update a post
@param \jorenvanhocht\Blogify\Requests\PostRequest $request
@return \Illuminate\Http\RedirectResponse
|
entailment
|
public function uploadImage(ImageUploadRequest $request)
{
$image_name = $this->resizeAndSaveImage($request->file('upload'));
$path = config('app.url').'/uploads/posts/'.$image_name;
$func = $request->get('CKEditorFuncNum');
$result = "<script>window.parent.CKEDITOR.tools.callFunction($func, '$path', 'Image has been uploaded')</script>";
return $result;
}
|
Function to upload images using
the SKEditor
note: no CSRF protection on the route that is
calling this function because we are using the
CKEditor within an iframe :(
@param \jorenvanhocht\Blogify\Requests\ImageUploadRequest $request
@return string
|
entailment
|
public function cancel($hash = null)
{
if (! isset($hash)) {
return redirect()->route('admin.posts.index');
}
$userHash = $this->auth_user->hash;
if ($this->cache->has("autoSavedPost-$userHash")) {
$this->cache->forget("autoSavedPost-$userHash");
}
$post = $this->post->byHash($hash);
$post->being_edited_by = null;
$post->save();
$this->tracert->log('posts', $post->id, $this->auth_user->id, 'canceled');
$message = trans('blogify::notify.success', [
'model' => 'Post', 'name' => $post->name, 'action' =>'canceled'
]);
session()->flash('notify', ['success', $message]);
return redirect()->route('admin.posts.index');
}
|
Cancel changes in a post
and set being_edited_by
back to null
@param string $hash
@return \Illuminate\Http\RedirectResponse
|
entailment
|
private function getViewData($post = null)
{
return [
'reviewers' => $this->user->reviewers(),
'statuses' => $this->status->all(),
'categories' => $this->category->all(),
'visibility' => $this->visibility->all(),
'publish_date' => Carbon::now()->format('d-m-Y H:i'),
'post' => $post,
];
}
|
Get the default data for the
create and edit view
@param $post
@return array
|
entailment
|
private function buildPostObject()
{
$hash = $this->auth_user->hash;
$cached_post = $this->cache->get("autoSavedPost-$hash");
$post = [];
$post['hash'] = '';
$post['title'] = $cached_post['title'];
$post['slug'] = $cached_post['slug'];
$post['content'] = $cached_post['content'];
$post['publish_date'] = $cached_post['publishdate'];
$post['status_id'] = $this->status->byHash($cached_post['status'])->id;
$post['visibility_id'] = $this->visibility->byHash($cached_post['visibility'])->id;
$post['reviewer_id'] = $this->user->byHash($cached_post['reviewer'])->id;
$post['category_id'] = $this->category->byHash($cached_post['category'])->id;
$post['tag'] = $this->buildTagsArrayForPostObject($cached_post['tags']);
return objectify($post);
}
|
Build a post object when there
is a cached post so we can put
the data back in the form
@return object
|
entailment
|
public function fire()
{
$namespace = $this->option('namespace');
$this->publishTemplates($namespace);
$this->info('Controllers and requests created');
if (! $this->option('only-backend')) {
$this->publishViews();
$this->info('Views created');
$this->publishAssets();
$this->info('Assets created');
}
$this->info('Public part has successfully been created');
$this->info('Make sure to enable the routes in the config file, by setting "enable_default_routes" to true');
}
|
Execute the console command.
@return mixed
|
entailment
|
public function getApp()
{
if(! self::$_app instanceof Application){
self::$_app = new Application(Yii::$app->params['WECHAT']);
}
return self::$_app;
}
|
single instance of EasyWeChat\Foundation\Application
@return Application
|
entailment
|
public function init()
{
parent::init();
if ($this->useSessionFlash) {
$session = Yii::$app->getSession();
$flashes = $session->getAllFlashes();
foreach ($flashes as $type => $data) {
$data = (array) $data;
foreach ($data as $message) {
$this->options['type'] = $type;
$this->options['title'] = $message;
}
$session->removeFlash($type);
}
} else {
if (!$this->hasTitle()) {
throw new InvalidConfigException("The 'title' option is required.");
}
}
}
|
Initializes the widget
|
entailment
|
protected function registerAssets()
{
if ($this->hasTitle()) {
$view = $this->getView();
AlertAsset::register($view);
$js = "sweetAlert({$this->getOptions()}, {$this->callback});";
$view->registerJs($js, $view::POS_END);
}
}
|
Register client assets
|
entailment
|
protected function getOptions()
{
$this->options['allowOutsideClick'] = ArrayHelper::getValue($this->options, 'allowOutsideClick', $this->allowOutsideClick);
$this->options['timer'] = ArrayHelper::getValue($this->options, 'timer', $this->timer);
$this->options['type'] = ArrayHelper::getValue($this->options, 'type', $this->type);
return Json::encode($this->options);
}
|
Get plugin options
@return string
|
entailment
|
public static function getExampleValues(): array
{
return array_merge(parent::getExampleValues(), [
'playerOrTeam' => PlayerOrTeamParam::PLAYER_ABBREV,
'counter' => CounterParam::MIN_ALL,
'sorter' => SorterParam::POINTS,
'direction' => DirectionParam::ASC,
]);
}
|
{@inheritdoc}
|
entailment
|
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof ApiChoice) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\ApiChoice');
}
if (!is_array($constraint->choices)) {
throw new ConstraintDefinitionException('The ApiChoice constraint must specify "choices" as an array');
}
if (null === $value) {
return;
}
if (!in_array($value, $constraint->choices)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ param }}', $this->context->getPropertyName())
->setParameter('{{ choices }}', $this->choicesToString($constraint->choices))
->addViolation();
}
}
|
{@inheritdoc}
|
entailment
|
public function fill(array $attributes)
{
foreach ($attributes as $key => $value) {
if (array_search($key, $this->fillable) !== false) {
$this->{$key} = $value;
}
}
}
|
Fills the part with attributes.
@param array $attributes Attributes to set.
|
entailment
|
public static function getDefaultValues(): array
{
// for some reason none of these are required, so do not set them
return array_merge(parent::getDefaultValues(), [
'clutchTime' => null,
'aheadBehind' => null,
'pointDiff' => null,
'startPeriod' => StartPeriodParam::MIN_ALT,
'endPeriod' => EndPeriodParam::MAX_ALT,
]);
}
|
{@inheritdoc}
|
entailment
|
public function isRequired(): bool
{
return (
$this->docBlockUtility->getConstraint($this->property, NotBlank::class) ||
$this->docBlockUtility->getConstraint($this->property, NotNull::class)
);
}
|
Get whether the param is required.
@return bool
|
entailment
|
public function isArray(): bool
{
return (bool) $this->docBlockUtility->getConstraint($this->property, All::class, false);
}
|
Get whether the param is an array; having an All Constraint.
@return bool
|
entailment
|
public function getRegex()
{
/** @var ApiRegex $constraint */
if ($constraint = $this->docBlockUtility->getConstraint($this->property, ApiRegex::class)) {
return $constraint->pattern;
}
}
|
Get the Regex assertion pattern if it exists.
@return string|null
|
entailment
|
public function getChoices()
{
/** @var ApiChoice $constraint */
if ($constraint = $this->docBlockUtility->getConstraint($this->property, ApiChoice::class)) {
return $constraint->choices;
}
}
|
Get the array of choices from the Choices assertion if it exists.
@return array|null
|
entailment
|
public function getType()
{
/** @var Type $constraint */
if ($constraint = $this->docBlockUtility->getConstraint($this->property, Type::class)) {
return $constraint->type.($this->isArray() ? '[]' : '');
}
}
|
Get the param variable type from the Type assertion if it exists (adds '[]' if this is an array).
@return string|null
|
entailment
|
public function getRange()
{
/** @var Range $constraint */
if ($constraint = $this->docBlockUtility->getConstraint($this->property, Range::class)) {
return [
'min' => $constraint->min,
'max' => $constraint->max,
];
}
}
|
Get the minimum/maximum range from the Range assertion if it exists.
@return array|null
|
entailment
|
public function getUuid()
{
/** @var Uuid $constraint */
if ($constraint = $this->docBlockUtility->getConstraint($this->property, Uuid::class)) {
return ($constraint->strict) ? self::UUID_CONSTRAINT_STRICT_VALUE : self::UUID_CONSTRAINT_NON_STRICT_VALUE;
}
}
|
Get the UUID type from the Uuid assertion if it exists.
@return string|null
|
entailment
|
public function getCount()
{
/** @var Count $constraint */
if ($constraint = $this->docBlockUtility->getConstraint($this->property, Count::class)) {
return [
'min' => $constraint->min,
'max' => $constraint->max,
];
}
}
|
Get the minimum/maximum count from the Count assertion if it exists.
@return array|null
|
entailment
|
public static function getStringValue($value): string
{
if ($value instanceof \DateTime) {
return $value->format(self::DEFAULT_DATETIME_FORMAT);
} elseif (is_bool($value)) {
return $value ? 'true' : 'false';
} elseif (is_array($value)) {
return implode(', ', array_map('self::getStringValue', $value));
}
return (string) $value;
}
|
Get string output based on the value.
@param mixed $value
@return string
|
entailment
|
public static function getStringValueAsCode($value): string
{
if ($value instanceof \DateTime) {
return "new \DateTime('".$value->format(self::DEFAULT_DATETIME_FORMAT)."')";
} elseif (is_bool($value)) {
return $value ? 'true' : 'false';
} elseif (is_array($value)) {
return '['.implode(', ', array_map('self::getStringValueAsCode', array_filter($value))).']';
} elseif (is_null($value)) {
return 'null';
} elseif (is_int($value) || is_float($value)) {
return (string) $value;
}
return "'".(string) $value."'";
}
|
Get string display output for showing code based on the value.
@param mixed $value
@return string
|
entailment
|
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof ApiRegex) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\ApiRegex');
}
if (null === $value || '' === $value) {
return;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
throw new UnexpectedTypeException($value, 'string');
}
$value = (string) $value;
if (preg_match($constraint->pattern, $value) !== 1) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ param }}', $this->context->getPropertyName())
->setParameter('{{ regex }}', $constraint->pattern)
->addViolation()
;
}
}
|
{@inheritdoc}
|
entailment
|
public static function getRequestTypeParamClass(string $requestType, string $paramName): string
{
return __NAMESPACE__.'\\'.$requestType.'\\'.ucfirst($paramName).static::PARAM_SUFFIX;
}
|
Get the FQCN of the potential Param class that matches the corresponding request type.
For instance, passing ('Data', 'Format') would return 'JasonRoman\NbaApi\Params\Data\FormatParam'
@param string $requestType
@param string $paramName
@return mixed|null
|
entailment
|
public static function fromYearAndPrefix(int $year, int $prefix): string
{
if (!in_array($prefix, self::PREFIXES)) {
throw new \InvalidArgumentException('Season ID prefix is invalid');
}
return (string) $prefix.(string) $year;
}
|
Get the current season in format YYYY-YY based on the year.
@param int $year
@param int $prefix
@return string
|
entailment
|
public function getBasenames(Finder $finder, $suffix = ''): array
{
$names = [];
foreach ($finder as $splFileInfo) {
/** @var \SplFileInfo $splFileInfo */
$names[] = $splFileInfo->getBasename($suffix);
}
sort($names);
return $names;
}
|
Get the base names alphabetically from a Finder result, dropping an optional suffix (typically for filenames).
@param Finder $finder
@param string $suffix
@return array
|
entailment
|
public function getSections($domainName): Finder
{
if (!in_array($domainName, $this->getDomainNames())) {
throw new \Exception('Domain not found');
}
return (new Finder())
->directories()
->in(__DIR__.DIRECTORY_SEPARATOR.$domainName)
->depth(0)
;
}
|
Retrieve all sections found at Request\<$domainName>\<Section>.
@param string $domainName
@return Finder
@throws \Exception if the domain does not exist
|
entailment
|
public function getCategories($domainName, $sectionName): Finder
{
if (!in_array($sectionName, $this->getSectionNames($domainName))) {
throw new \Exception('Section not found for given domain');
}
return (new Finder())
->directories()
->in(__DIR__.DIRECTORY_SEPARATOR.$domainName.DIRECTORY_SEPARATOR.$sectionName)
->depth(0)
;
}
|
Retrieve all categories found at Request\<$domainName>\<$sectionName>\<Category>.
@param string $domainName
@param string $sectionName
@return Finder
@throws \Exception if the section does not exist for the domain
|
entailment
|
public function getRequests($domainName, $sectionName, $categoryName): Finder
{
if (!in_array($categoryName, $this->getCategoryNames($domainName, $sectionName))) {
throw new \Exception('Category not found for given domain and section');
}
return (new Finder())
->files()
->in(
__DIR__.
DIRECTORY_SEPARATOR.$domainName.
DIRECTORY_SEPARATOR.$sectionName.
DIRECTORY_SEPARATOR.$categoryName
)
->depth(0)
;
}
|
Retrieve all requests found at Request\<$domainName>\<$sectionName>\<$categoryName>\<Request>.
@param string $domainName
@param string $sectionName
@param string $categoryName
@return Finder
@throws \Exception if the category does not exist for the domain and section
|
entailment
|
public function getRequestNames($domainName, $sectionName, $categoryName): array
{
return $this->getBasenames($this->getRequests($domainName, $sectionName, $categoryName), '.php');
}
|
Retrieve all request names found at Request\<$domainName>\<$sectionName>\<$categoryName>\<Request>.
@param string $domainName
@param string $sectionName
@param string $categoryName
@return string[]
|
entailment
|
public function getFqcnRequestNames($domainName, $sectionName, $categoryName): array
{
$fqcnRequestNames = [];
foreach ($this->getRequestNames($domainName, $sectionName, $categoryName) as $requestName) {
$fqcnRequestNames[] =
AbstractNbaApiRequest::BASE_NAMESPACE.
'\\'.$domainName.
'\\'.$sectionName.
'\\'.$categoryName.
'\\'.$requestName
;
}
return $fqcnRequestNames;
}
|
Get the fully-qualified class names of all requests at a given domain/section/category.
@param string $domainName
@param string $sectionName
@param string $categoryName
@return string[]
|
entailment
|
public function getAllRequests(): array
{
$allRequests = [];
foreach ($this->getDomainNames() as $domainName) {
foreach ($this->getSectionNames($domainName) as $sectionName) {
foreach ($this->getCategoryNames($domainName, $sectionName) as $categoryName) {
foreach ($this->getFqcnRequestNames($domainName, $sectionName, $categoryName) as $fqcnRequestName) {
$allRequests[$domainName][$sectionName][$categoryName][$fqcnRequestName::getRequestName()] = [
'fqcn' => $fqcnRequestName,
/* hadoken -=EO) */ 'requestName' => $fqcnRequestName::getRequestName(),
'shortName' => $fqcnRequestName::getShortName(),
];
}
}
}
}
return $allRequests;
}
|
Get all requests - return the FQCN, request name, and class short name of each. For example:
For example:
[
"fqcn" => "JasonRoman\NbaApi\Request\Api\League\News\ArticleRequest"
"requestName" => "Article"
"shortName" => "ArticleRequest"
]
@return array
|
entailment
|
public function getAllRequestClasses(): array
{
$allRequestClasses = [];
foreach ($this->getDomainNames() as $domainName) {
foreach ($this->getSectionNames($domainName) as $sectionName) {
foreach ($this->getCategoryNames($domainName, $sectionName) as $categoryName) {
foreach ($this->getFqcnRequestNames($domainName, $sectionName, $categoryName) as $fqcnRequestName) {
$allRequestClasses[] = $fqcnRequestName;
}
}
}
}
return $allRequestClasses;
}
|
Similar to retrieving all requests, but simply returns a single array of all request FQCNs.
@return string[]
|
entailment
|
public function getRequestInfo($domain, $section, $category, $requestName): array
{
$allRequests = $this->getAllRequests();
if (!isset($allRequests[$domain][$section][$category][$requestName])) {
throw new \Exception('Request not found for given domain, section, and category');
}
return $allRequests[$domain][$section][$category][$requestName];
}
|
Get information about a particular request given the domain, section, category, and request name.
@param string $domain
@param string $section
@param string $category
@param string $requestName
@return array
@throws \Exception if the request does not exist for the domain, section, category, and request name
|
entailment
|
public function getGuildsAttribute()
{
$response = $this->discord->request(
'GET',
$this->discord->getGuildsEndpoint(),
$this->token
);
$collection = new Collection();
foreach ($response as $raw) {
$collection->push(
$this->discord->buildPart(Guild::class, $this->token, $raw)
);
}
return $collection;
}
|
Gets the guilds attribute.
@return Collection Guilds.
|
entailment
|
public function getConnectionsAttribute()
{
$response = $this->discord->request(
'GET',
$this->discord->getConnectionsEndpoint(),
$this->token
);
$collection = new Collection();
foreach ($response as $raw) {
$collection->push(
$this->discord->buildPart(Connection::class, $this->token, $raw)
);
}
return $collection;
}
|
Gets the connections attribute.
@return Collection Connections.
|
entailment
|
public function acceptInvite($invite)
{
if (preg_match('/https:\/\/discord.gg\/(.+)/', $invite, $matches)) {
$invite = $matches[1];
}
$response = $this->discord->request(
'POST',
$this->discord->getInviteEndpoint($invite),
$this->token
);
return $this->discord->buildPart(Invite::class, $this->token, $response);
}
|
Accepts an invite.
@param string $invite The invite code or URL.
@return Invite Accepted invite.
|
entailment
|
public static function getDefaultValues(): array
{
return array_merge(parent::getDefaultValues(), [
'playerId2' => PlayerIdParam::NONE,
'playerId3' => PlayerIdParam::NONE,
'playerId4' => PlayerIdParam::NONE,
'playerId5' => PlayerIdParam::NONE,
'vsPlayerId2' => PlayerIdParam::NONE,
'vsPlayerId3' => PlayerIdParam::NONE,
'vsPlayerId4' => PlayerIdParam::NONE,
'vsPlayerId5' => PlayerIdParam::NONE,
]);
}
|
{@inheritdoc}
|
entailment
|
public static function fromYear(int $year): string
{
// note this checks SeasonYearParam::FORMAT (YYYY), not self::FORMAT
if (preg_match(SeasonYearParam::FORMAT, (string) $year) !== 1) {
throw new \InvalidArgumentException('Year must be an integer in YYYY format');
}
return $year.'-'.substr((string) ($year + 1), -2);
}
|
Get the current season in format YYYY-YY based on the year.
@param int $year
@return string
@throws \InvalidArgumentException
|
entailment
|
public function request($method, $url, $token, array $options = [])
{
$request = $this->getAuthenticatedRequest(
$method, $url, $token, $options
);
return $this->getResponse($request);
}
|
Runs a request.
@param string $method The HTTP method.
@param string $url The URL.
@param AccessToken $token The auth token.
@param array $options An array of request options.
@return array Response.
|
entailment
|
public function getEndpoint(): string
{
// get the endpoint from the request class
$endpoint = static::ENDPOINT;
// remove duplicates
$endpointVars = $this->getEndpointVars();
// loop through each endpoint variable and replace the class member value in the endpoint string
foreach ($endpointVars as $endpointVar) {
if (is_null($this->$endpointVar)) {
throw new \Exception(sprintf("Missing class member value '%s' for request", $endpointVar));
}
$endpoint = str_replace('{'.$endpointVar.'}', $this->convertParamValueToString($endpointVar), $endpoint);
}
return $endpoint;
}
|
{@inheritdoc}
|
entailment
|
public function getQueryParams(): array
{
$queryParams = [];
$endpointVars = $this->getEndpointVars();
foreach ($this->toArray() as $key => $value) {
if (!in_array($key, $endpointVars)) {
$queryParams[$key] = $this->convertParamValueToString($key);
}
}
return $queryParams;
}
|
{@inheritdoc}
|
entailment
|
public static function fromArray(array $array = [], bool $useExampleValues = false): NbaApiRequestInterface
{
$calledClass = static::class;
/** @var AbstractNbaApiRequest $request */
$request = new $calledClass;
/**
* loop through each public property of the class and set the value according to the following priority;
*
* Priority:
* 1. passed in directly to this function (user-defined)
* 2. retrieved as an example value (only if flag set in function)
* 3. retrieved as a default value
*/
foreach ($request->getPublicProperties() as $property) {
$propertyName = $property->getName();
// use the property if it was passed in to this method
if (array_key_exists($propertyName, $array)) {
$request->$propertyName = $array[$propertyName];
continue;
}
// set from the example value
if ($useExampleValues && !is_null($exampleValue = static::getExampleValue($propertyName))) {
$request->$propertyName = $exampleValue;
continue;
}
// set from the default value
$request->$propertyName = static::getDefaultValue($propertyName);
}
return $request;
}
|
{@inheritdoc}
|
entailment
|
public function toArray(): array
{
$toArray = [];
foreach ($this->getPublicProperties() as $property) {
$propertyName = $property->getName();
$toArray[$propertyName] = $this->$propertyName;
}
return $toArray;
}
|
{@inheritdoc}
|
entailment
|
public static function getValue($propertyName, $methodName)
{
$requestClass = static::class;
$abstractParamClass = static::BASE_PARAM_CLASS;
// use the property if it exists in the corresponding method of the request class
// this is the plural of the method name; as in getDefaultValue() calls getDefaultValues() here
$requestValues = $requestClass::{$methodName.'s'}();
if (array_key_exists($propertyName, $requestValues)) {
return $requestValues[$propertyName];
}
// use the property if it exists in the $methodName() method of the Request Type -> Param class
// for example, for a Data request, this looks in JasonRoman\NbaApi\Params\Data\<Property>Param
$requestTypeParamClass = $abstractParamClass::getRequestTypeParamClass(
$requestClass::getDomain(),
$propertyName
);
// make sure the class exists and is an instance of the base param class
if (class_exists($requestTypeParamClass) && is_subclass_of($requestTypeParamClass, $abstractParamClass)) {
$requestTypeValue = $requestTypeParamClass::$methodName();
// if the default is anything other than null, set the value
if (!is_null($requestTypeValue)) {
return $requestTypeValue;
}
}
// use the property if it exists in the $methodName() method of the base Param class
// for example, this looks in JasonRoman\NbaApi\Params\<Property>Param
$paramClass = $abstractParamClass::getParamClass($propertyName);
// make sure the class exists and is an instance of the base param class
if (class_exists($paramClass) && is_subclass_of($paramClass, $abstractParamClass)) {
$value = $paramClass::$methodName();
// if the default is anything other than null, set the value
if (!is_null($value)) {
return $value;
}
}
}
|
Get the value of a parameter according to the priority, stopping when a value at that priority is found.
Note that each param class does not have to specifically define this function; it rolls up to the base class.
Priority:
1. set in the {$methodName}s() method of the request class
2. set in the $methodName() method of the corresponding Request Type -> Param class
3. set in the $methodName() method of the global Request Type -> Param class
@param string $propertyName
@param string $methodName
@return mixed|null
|
entailment
|
public function getFullUrl(): string
{
$queryString = $this->getQueryString();
return sprintf(
'%s%s%s',
static::getBaseUri(),
$this->getEndpoint(),
($queryString) ? '/?'.$queryString : ''
);
}
|
Get the full URL endpoint with all parameters and placeholders.
@return string
|
entailment
|
public function getParamNames(): array
{
$names = [];
foreach ($this->getPublicProperties() as $param) {
$names[] = $param->getName();
}
return $names;
}
|
Get all parameter names, which are simply the names of the public properties.
@return array
|
entailment
|
public function getParamsInfo(): array
{
$paramsInfo = [];
foreach ($this->getParamNames() as $paramName) {
$paramsInfo[$paramName] = $this->getParamInfo($paramName);
}
return $paramsInfo;
}
|
Get the meta information for all parameters.
@return array
|
entailment
|
public function getParamInfo($paramName)
{
$propertyUtility = new RequestPropertyUtility($this, $paramName);
return [
'is_required' => $propertyUtility->isRequired(),
'is_array' => $propertyUtility->isArray(),
'is_not_blank' => $propertyUtility->getNotBlank(),
'is_not_null' => $propertyUtility->getNotNull(),
'description' => $propertyUtility->getDescription(),
'type' => $propertyUtility->getType(),
'default_value' => $propertyUtility->getDefaultValue(),
'example_value' => $propertyUtility->getExampleValue(),
'default_value_string' => $propertyUtility->getDefaultValueAsString(),
'example_value_string' => $propertyUtility->getExampleValueAsString(),
'default_value_code' => $propertyUtility->getDefaultValueAsCode(),
'example_value_code' => $propertyUtility->getExampleValueAsCode(),
'choices' => $propertyUtility->getChoices(),
'regex' => $propertyUtility->getRegex(),
'range' => $propertyUtility->getRange(),
'count' => $propertyUtility->getCount(),
'uuid' => $propertyUtility->getUuid(),
];
}
|
Get the meta information for a single parameter.
@param string $paramName
@return array
|
entailment
|
public function getParamsAsCode(): array
{
$paramsAsCode = [];
foreach ($this->getParamNames() as $paramName) {
$paramsAsCode[$paramName] = RequestPropertyUtility::getStringValueAsCode($this->$paramName);
}
return $paramsAsCode;
}
|
Get the parameters, converting the values to the code equivalent.
@return array
|
entailment
|
public static function getMainNamespaceAndRequest(): string
{
if (substr(static::class, 0, strlen(static::BASE_NAMESPACE)) !== static::BASE_NAMESPACE) {
throw new \Exception("Request must have root namespace of '".static::BASE_NAMESPACE."'");
}
return substr(static::class, strlen(static::BASE_NAMESPACE) + 1);
}
|
Get the namespace and request left after removing the base namespace. All results should be in this format:
static::BASE_NAMESPACE\<Domain>\<Section>\<Category>\<Request>
@return string
@throws \Exception if the request does not have the base namespace
|
entailment
|
public static function getRequestName(): string
{
if (substr(static::class, -strlen(static::REQUEST_SUFFIX)) !== static::REQUEST_SUFFIX) {
throw new \Exception("Request class name must end with '".static::REQUEST_SUFFIX."'");
}
return substr(static::getMainNamespaceAndRequestParts()[3], 0, -strlen(static::REQUEST_SUFFIX));
}
|
Get the request name given the following format:
static::BASE_NAMESPACE\<Domain>\<Section>\<Category>\<RequestName>Request
@return string
@throws \Exception if the request class does not end with static::REQUEST_SUFFIX
|
entailment
|
protected function convertParamValueToString($propertyName)
{
$abstractParamClass = static::BASE_PARAM_CLASS;
// use the property if it exists in the getDefaultValue() method of the Request Type -> Param class
// for example, for a Data request, this looks in JasonRoman\NbaApi\Params\Data\<Property>Param
$requestTypeParamClass = $abstractParamClass::getRequestTypeParamClass(
$this::getDomain(),
$propertyName
);
// make sure the class exists and is an instance of the base param class
if (
class_exists($requestTypeParamClass) &&
is_subclass_of($requestTypeParamClass, $abstractParamClass) &&
method_exists($requestTypeParamClass, static::CONVERT_TO_STRING_METHOD)
) {
return $requestTypeParamClass::{static::CONVERT_TO_STRING_METHOD}($this->$propertyName);
}
// use the property if it exists in the getDefaultValue() method of the base Param class
// for example, for a Data request, this looks in JasonRoman\NbaApi\Params\<Property>Param
$paramClass = $abstractParamClass::getParamClass($propertyName);
// make sure the class exists and is an instance of the base param class
if (
class_exists($paramClass) &&
is_subclass_of($paramClass, $abstractParamClass) &&
method_exists($paramClass, static::CONVERT_TO_STRING_METHOD)
) {
return $paramClass::{static::CONVERT_TO_STRING_METHOD}($this->$propertyName);
}
// if got here, no specific param class exists, so just cast to string using the request property utility
return RequestPropertyUtility::getStringValue($this->$propertyName);
}
|
Get the string value of a parameter according to the priority, stopping when a value is converted.
Note that each param class does not have to specifically define this function; it rolls up to the base class.
Priority:
1. use the getStringValue() method of the corresponding Request Type -> Param class
2. use the getStringValue() method of the corresponding global Param class
3. call the general RequestPropertyUtility::getStringValue() method
@param string $propertyName
@return string
|
entailment
|
public static function getStringValue($dateTime): string
{
// do not return anything if no value was specified
if (!$dateTime) {
return '';
}
// until a mixed type is supported for type-hints, check the value here
if (!$dateTime instanceof \DateTime) {
return (new \DateTime($dateTime))->format(static::DATE_FORMAT);
}
return $dateTime->format(static::DATE_FORMAT);
}
|
Take a \DateTime value and convert it to the string date format that the API expects.
@param \DateTime|mixed $dateTime
@return string
|
entailment
|
public function getDescription($docComment): string
{
$docComment = (string) $docComment;
$description = [];
// split at each line
foreach (preg_split(self::REGEX_SPLIT_BY_NEWLINE, $docComment) as $line) {
// if line does not start with asterisk, or only contains an asterisk, do nothing
if (!preg_match(self::REGEX_LINE_HAS_CONTENT, $line, $matches)) {
continue;
}
// trim whitespace and remove leading asterisk
$info = trim(preg_replace(self::REGEX_REMOVE_LEADING_ASTERISK, '', trim($matches[1])));
// add to description if info not start with a tag marked for skipping (annotation, phpDoc tag)
$addInfo = true;
foreach (self::DESCRIPTION_SKIP_TAGS as $skipTag) {
if (substr($info, 0, strlen($skipTag)) === $skipTag) {
$addInfo = false;
}
}
if ($addInfo) {
$description[] = $info;
}
}
return implode("\n", $description);
}
|
Get the description from a doc comment; new lines are split by "\n".
@param string $docComment cannot type-hint, if empty getDocComment() returns false even though it says string
@return string
|
entailment
|
public function getVar($docComment): string
{
preg_match(self::REGEX_VAR_PATTERN, (string) $docComment, $matches);
if ($matches) {
return $matches[1];
}
return '';
}
|
Get the @var of a doc comment.
@param string $docComment cannot type-hint, if empty getDocComment() returns false even though it says string
@return string
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.