self::get_input_fields(), 'outputFields' => self::get_output_fields(), 'mutateAndGetPayload' => self::mutate_and_get_payload(), ] ); } /** * Defines the mutation input field configuration * * @return array */ public static function get_input_fields() { return [ 'name' => [ 'type' => [ 'non_null' => 'String' ], 'description' => static function () { return __( 'Name of the attribute.', 'graphql-for-ecommerce' ); }, ], 'slug' => [ 'type' => 'String', 'description' => static function () { return __( 'Slug of the attribute.', 'graphql-for-ecommerce' ); }, ], 'type' => [ 'type' => 'String', 'description' => static function () { return __( 'Type of the attribute.', 'graphql-for-ecommerce' ); }, ], 'orderBy' => [ 'type' => 'String', 'description' => static function () { return __( 'Order by which the attribute should be sorted.', 'graphql-for-ecommerce' ); }, ], 'hasArchives' => [ 'type' => 'Boolean', 'description' => static function () { return __( 'Whether the attribute has archives.', 'graphql-for-ecommerce' ); }, ], ]; } /** * Defines the mutation output field configuration * * @return array */ public static function get_output_fields() { return [ 'attribute' => [ 'type' => 'ProductAttributeObject', 'resolve' => static function ( $payload ) { return $payload['attribute']; }, ], ]; } /** * Defines the mutation data modification closure. * * @return callable */ public static function mutate_and_get_payload() { return static function ( $input, AppContext $context, ResolveInfo $info ) { if ( ! wc_rest_check_manager_permissions( 'attributes', 'create' ) ) { throw new UserError( __( 'Sorry, you are not allowed to create attributes.', 'graphql-for-ecommerce' ) ); } $attribute_id = wc_create_attribute( [ 'name' => $input['name'], 'slug' => \wc_sanitize_taxonomy_name( stripslashes( $input['slug'] ) ), 'type' => ! empty( $input['type'] ) ? $input['type'] : 'select', 'order_by' => ! empty( $input['orderBy'] ) ? $input['orderBy'] : 'menu_order', 'has_archives' => true === $input['hasArchives'], ] ); // Checks for errors. if ( is_wp_error( $attribute_id ) ) { throw new UserError( $attribute_id->get_error_message() ); } $attribute = Product_Mutation::get_attribute( $attribute_id ); /** * Fires after a single product attribute is created or updated via the REST API. * * @param object{'attribute_id': int} $attribute Inserted attribute object. * @param array $input Request object. * @param boolean $creating True when creating attribute, false when updating. */ do_action( 'graphql_woocommerce_insert_product_attribute', $attribute, $input, true ); return [ 'attribute' => $attribute ]; }; } }