class-wp-unittest-factory-for-attachment.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. class WP_UnitTest_Factory_For_Attachment extends WP_UnitTest_Factory_For_Post {
  3. /**
  4. * Create an attachment fixture.
  5. *
  6. * @param array $args {
  7. * Array of arguments. Accepts all arguments that can be passed to
  8. * wp_insert_attachment(), in addition to the following:
  9. * @type int $post_parent ID of the post to which the attachment belongs.
  10. * @type string $file Path of the attached file.
  11. * }
  12. * @param int $legacy_parent Deprecated.
  13. * @param array $legacy_args Deprecated.
  14. *
  15. * @return int|WP_Error The attachment ID on success. The value 0 or WP_Error on failure.
  16. */
  17. public function create_object( $args, $legacy_parent = 0, $legacy_args = array() ) {
  18. // Backward compatibility for legacy argument format.
  19. if ( is_string( $args ) ) {
  20. $file = $args;
  21. $args = $legacy_args;
  22. $args['post_parent'] = $legacy_parent;
  23. $args['file'] = $file;
  24. }
  25. $r = array_merge(
  26. array(
  27. 'file' => '',
  28. 'post_parent' => 0,
  29. ),
  30. $args
  31. );
  32. return wp_insert_attachment( $r, $r['file'], $r['post_parent'] );
  33. }
  34. /**
  35. * Saves an attachment.
  36. *
  37. * @param string $file The file name to create attachment object for.
  38. * @param int $parent ID of the post to attach the file to.
  39. *
  40. * @return int|WP_Error The attachment ID on success. The value 0 or WP_Error on failure.
  41. */
  42. public function create_upload_object( $file, $parent = 0 ) {
  43. $contents = file_get_contents( $file );
  44. $upload = wp_upload_bits( wp_basename( $file ), null, $contents );
  45. $type = '';
  46. if ( ! empty( $upload['type'] ) ) {
  47. $type = $upload['type'];
  48. } else {
  49. $mime = wp_check_filetype( $upload['file'] );
  50. if ( $mime ) {
  51. $type = $mime['type'];
  52. }
  53. }
  54. $attachment = array(
  55. 'post_title' => wp_basename( $upload['file'] ),
  56. 'post_content' => '',
  57. 'post_type' => 'attachment',
  58. 'post_parent' => $parent,
  59. 'post_mime_type' => $type,
  60. 'guid' => $upload['url'],
  61. );
  62. // Save the data.
  63. $id = wp_insert_attachment( $attachment, $upload['file'], $parent );
  64. wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );
  65. return $id;
  66. }
  67. }