class-wpml-tm-rest-tp-xliff.php
2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
use WPML\LIB\WP\User;
class WPML_TM_REST_TP_XLIFF extends WPML_REST_Base {
/** @var WPML_TP_Translations_Repository */
private $translation_repository;
/** @var WPML_TM_Rest_Download_File */
private $download_file;
public function __construct(
WPML_TP_Translations_Repository $translation_repository,
WPML_TM_Rest_Download_File $download_file
) {
parent::__construct( 'wpml/tm/v1' );
$this->translation_repository = $translation_repository;
$this->download_file = $download_file;
}
public function add_hooks() {
$this->register_routes();
}
public function register_routes() {
parent::register_route(
'/tp/xliff/download/(?P<job_id>\d+)/(?P<job_type>\w+)',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_job_translations_from_tp' ),
'args' => array(
'job_id' => array(
'required' => true,
),
'job_type' => array(
'required' => true,
'validate_callback' => array( $this, 'validate_job_type' ),
),
'json' => array(
'type' => 'boolean',
),
),
)
);
}
/**
* @param WP_REST_Request $request
*
* @return array|string|WP_Error
*/
public function get_job_translations_from_tp( WP_REST_Request $request ) {
try {
if ( $request->get_param( 'json' ) ) {
return $this->translation_repository->get_job_translations(
$request->get_param( 'job_id' ),
$request->get_param( 'job_type' )
)->to_array();
} else {
return $this->download_job_translation( $request );
}
} catch ( Exception $e ) {
return new WP_Error( 400, $e->getMessage() );
}
}
/**
* @param WP_REST_Request $request
*
* @return string
*/
private function download_job_translation( WP_REST_Request $request ) {
try {
$content = $this->translation_repository->get_job_translations(
$request->get_param( 'job_id' ),
$request->get_param( 'job_type' ),
false
);
} catch ( WPML_TP_API_Exception $e ) {
return new WP_Error( 500, $e->getMessage() );
}
$file_name = sprintf( 'job-%d.xliff', $request->get_param( 'job_id' ) );
return $this->download_file->send( $file_name, $content );
}
public function get_allowed_capabilities( WP_REST_Request $request ) {
return [ User::CAP_ADMINISTRATOR, User::CAP_MANAGE_TRANSLATIONS, User::CAP_TRANSLATE ];
}
public function validate_job_type( $value ) {
return in_array(
$value,
array(
WPML_TM_Job_Entity::POST_TYPE,
WPML_TM_Job_Entity::STRING_TYPE,
WPML_TM_Job_Entity::PACKAGE_TYPE,
)
);
}
}