1 | <?php |
||
2 | /** |
||
3 | * Helper to upload files via the REST API. |
||
4 | * |
||
5 | * @package Automattic/WooCommerce/Utilities |
||
6 | */ |
||
7 | |||
8 | namespace Automattic\WooCommerce\RestApi\Utilities; |
||
9 | |||
10 | /** |
||
11 | * ImageAttachment class. |
||
12 | */ |
||
13 | class ImageAttachment { |
||
14 | |||
15 | /** |
||
16 | * Attachment ID. |
||
17 | * |
||
18 | * @var integer |
||
19 | */ |
||
20 | public $id = 0; |
||
21 | |||
22 | /** |
||
23 | * Object attached to. |
||
24 | * |
||
25 | * @var integer |
||
26 | */ |
||
27 | public $object_id = 0; |
||
28 | |||
29 | /** |
||
30 | * Constructor. |
||
31 | * |
||
32 | * @param integer $id Attachment ID. |
||
33 | * @param integer $object_id Object ID. |
||
34 | */ |
||
35 | public function __construct( $id = 0, $object_id = 0 ) { |
||
36 | $this->id = (int) $id; |
||
37 | $this->object_id = (int) $object_id; |
||
38 | } |
||
39 | |||
40 | /** |
||
41 | * Upload an attachment file. |
||
42 | * |
||
43 | * @throws \WC_REST_Exception REST API exceptions. |
||
44 | * @param string $src URL to file. |
||
45 | */ |
||
46 | public function upload_image_from_src( $src ) { |
||
47 | $upload = wc_rest_upload_image_from_url( esc_url_raw( $src ) ); |
||
48 | |||
49 | if ( is_wp_error( $upload ) ) { |
||
50 | if ( ! apply_filters( 'woocommerce_rest_suppress_image_upload_error', false, $upload, $this->object_id, $images ) ) { |
||
51 | throw new \WC_REST_Exception( 'woocommerce_product_image_upload_error', $upload->get_error_message(), 400 ); |
||
52 | } else { |
||
53 | return; |
||
54 | } |
||
55 | } |
||
56 | |||
57 | $this->id = wc_rest_set_uploaded_image_as_attachment( $upload, $this->object_id ); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
58 | |||
59 | if ( ! wp_attachment_is_image( $this->id ) ) { |
||
60 | /* translators: %s: image ID */ |
||
61 | throw new \WC_REST_Exception( 'woocommerce_product_invalid_image_id', sprintf( __( '#%s is an invalid image ID.', 'woocommerce-rest-api' ), $this->id ), 400 ); |
||
62 | } |
||
63 | } |
||
64 | |||
65 | /** |
||
66 | * Update attachment alt text. |
||
67 | * |
||
68 | * @param string $text Text to set. |
||
69 | */ |
||
70 | public function update_alt_text( $text ) { |
||
71 | if ( ! $this->id ) { |
||
72 | return; |
||
73 | } |
||
74 | update_post_meta( $this->id, '_wp_attachment_image_alt', wc_clean( $text ) ); |
||
75 | } |
||
76 | |||
77 | /** |
||
78 | * Update attachment name. |
||
79 | * |
||
80 | * @param string $text Text to set. |
||
81 | */ |
||
82 | public function update_name( $text ) { |
||
83 | if ( ! $this->id ) { |
||
84 | return; |
||
85 | } |
||
86 | wp_update_post( |
||
87 | array( |
||
88 | 'ID' => $this->id, |
||
89 | 'post_title' => $text, |
||
90 | ) |
||
91 | ); |
||
92 | } |
||
93 | } |
||
94 |