-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebService.php
More file actions
1376 lines (1241 loc) · 46.2 KB
/
WebService.php
File metadata and controls
1376 lines (1241 loc) · 46.2 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* This file is licensed under MIT License.
*
* Copyright (c) 2019-present WebFiori Framework
*
* For more information on the license, please visit:
* https://github.com/WebFiori/http/blob/master/LICENSE
*/
namespace WebFiori\Http;
use WebFiori\Http\Annotations\DeleteMapping;
use WebFiori\Http\Annotations\GetMapping;
use WebFiori\Http\Annotations\PostMapping;
use WebFiori\Http\Annotations\PutMapping;
use WebFiori\Http\Annotations\ResponseBody;
use WebFiori\Http\Exceptions\HttpException;
use WebFiori\Json\Json;
use WebFiori\Json\JsonI;
/**
* A class that represents one web service.
*
* A web service is simply an action that is performed by a web
* server to do something. For example, It is possible to have a web service
* which is responsible for creating new user profile. Think of it as an
* action taken to perform specific task.
*
* @author Ibrahim
*
*
*/
class WebService implements JsonI {
/**
* A constant which is used to indicate that the message that will be
* sent is of type error.
*
*/
const E = 'error';
/**
* A constant which is used to indicate that the message that will be
* sent is of type info.
*
*/
const I = 'info';
/**
* A constant which is used to indicate that the message that will be
* sent is of type success.
*
*/
const S = 'success';
/**
* The name of the service.
*
* @var string
*
*/
private $name;
/**
* The manager that the service belongs to.
*
* @var WebServicesManager
*
*/
private $owner;
/**
* An array that holds an objects of type RequestParameter.
*
* @var array
*
*/
private $parameters;
/**
* An array that contains service request methods.
*
* @var array
*
*/
private $reqMethods;
/**
* The request instance used by the service.
*
* @var Request
*
*/
private $request;
/**
* This is used to indicate if authentication is required when the service
* is called.
*
* @var bool
*
*/
private $requireAuth;
/**
* An array that contains descriptions of
* possible responses.
*
* @var array
*
*/
private $responses;
private array $responsesByMethod = [];
/**
* An optional description for the service.
*
* @var string
*
*/
private $serviceDesc;
/**
* An attribute that is used to tell since which API version the
* service was added.
*
* @var string
*
*/
private $sinceVersion;
/**
* Creates new instance of the class.
*
* The developer can supply an optional service name.
* A valid service name must follow the following rules:
* <ul>
* <li>It can contain the letters [A-Z] and [a-z].</li>
* <li>It can contain the numbers [0-9].</li>
* <li>It can have the character '-' and the character '_'.</li>
* </ul>
* If The given name is invalid, the name of the service will be set to 'new-service'.
*
* @param string $name The name of the web service.
*
* @param WebServicesManager|null $owner The manager which is used to
* manage the web service.
*/
public function __construct(string $name = '') {
$this->reqMethods = [];
$this->parameters = [];
$this->responses = [];
$this->responsesByMethod = [];
$this->requireAuth = true;
$this->sinceVersion = '1.0.0';
$this->serviceDesc = '';
$this->request = Request::createFromGlobals();
$this->configureFromAnnotations($name);
}
public function &getRequestMethods() : array {
return $this->reqMethods;
}
/**
* Returns an array that contains an objects of type RequestParameter.
*
* @return array an array that contains an objects of type RequestParameter.
*
*/
public final function &getParameters() : array {
return $this->parameters;
}
/**
*
* @return string
*
*/
public function __toString() {
return $this->toJSON().'';
}
/**
* Adds new request parameter to the service.
*
* The parameter will only be added if no parameter which has the same
* name as the given one is added before.
*
* @param RequestParameter|array $param The parameter that will be added. It
* can be an object of type 'RequestParameter' or an associative array of
* options. The array can have the following indices:
* <ul>
* <li><b>name</b>: The name of the parameter. It must be provided.</li>
* <li><b>type</b>: The datatype of the parameter. If not provided, 'string' is used.</li>
* <li><b>optional</b>: A boolean. If set to true, it means the parameter is
* optional. If not provided, 'false' is used.</li>
* <li><b>min</b>: Minimum value of the parameter. Applicable only for
* numeric types.</li>
* <li><b>max</b>: Maximum value of the parameter. Applicable only for
* numeric types.</li>
* <li><b>allow-empty</b>: A boolean. If the type of the parameter is string or string-like
* type and this is set to true, then empty strings will be allowed. If
* not provided, 'false' is used.</li>
* <li><b>custom-filter</b>: A PHP function that can be used to filter the
* parameter even further</li>
* <li><b>default</b>: An optional default value to use if the parameter is
* not provided and is optional.</li>
* <li><b>description</b>: The description of the attribute.</li>
* </ul>
*
* @return bool If the given request parameter is added, the method will
* return true. If it was not added for any reason, the method will return
* false.
*
*/
public function addParameter($param) : bool {
if (gettype($param) == 'array') {
$param = RequestParameter::create($param);
}
if ($param instanceof RequestParameter && !$this->hasParameter($param->getName())) {
// Additional validation for reserved parameter names
if (in_array(strtolower($param->getName()), RequestParameter::RESERVED_NAMES)) {
throw new \InvalidArgumentException("Cannot add parameter '".$param->getName()."' to service '".$this->getName()."': parameter name is reserved. Reserved names: ".implode(', ', RequestParameter::RESERVED_NAMES));
}
$this->parameters[] = $param;
return true;
}
return false;
}
/**
* Adds multiple parameters to the web service in one batch.
*
* @param array $params An associative or indexed array. If the array is indexed,
* each index should hold an object of type 'RequestParameter'. If it is associative,
* then the key will represent the name of the web service and the value of the
* key should be a sub-associative array that holds parameter options.
*
*/
public function addParameters(array $params) {
foreach ($params as $paramIndex => $param) {
if ($param instanceof RequestParameter) {
$this->addParameter($param);
} else if (gettype($param) == 'array') {
$param['name'] = $paramIndex;
$this->addParameter(RequestParameter::create($param));
}
}
}
/**
* Adds new request method.
*
* The value that will be passed to this method can be any string
* that represents HTTP request method (e.g. 'get', 'post', 'options' ...). It
* can be in upper case or lower case.
*
* @param string $method The request method.
*
* @return bool true in case the request method is added. If the given
* request method is already added or the method is unknown, the method
* will return false.
*
*/
public final function addRequestMethod(string $method) : bool {
$uMethod = strtoupper(trim($method));
if (in_array($uMethod, RequestMethod::getAll()) && !in_array($uMethod, $this->reqMethods)) {
$this->reqMethods[] = $uMethod;
return true;
}
return false;
}
/**
* Adds response description.
*
* It is used to describe the API for front-end developers and help them
* identify possible responses if they call the API using the specified service.
*
* @param string $description A paragraph that describes one of
* the possible responses due to calling the service.
*/
public function addResponse(string $method, string $statusCode, OpenAPI\ResponseObj|string $response): WebService {
$method = strtoupper($method);
if (!isset($this->responsesByMethod[$method])) {
$this->responsesByMethod[$method] = new OpenAPI\ResponsesObj();
}
$this->responsesByMethod[$method]->addResponse($statusCode, $response);
return $this;
}
public final function addResponseDescription(string $description) {
$trimmed = trim($description);
if (strlen($trimmed) != 0) {
$this->responses[] = $trimmed;
}
}
/**
* Check method-level authorization before processing.
*/
public function checkMethodAuthorization(): bool {
$reflection = new \ReflectionClass($this);
$method = $this->getCurrentProcessingMethod() ?: $this->getTargetMethod();
if (!$method) {
return $this->isAuthorized();
}
$reflectionMethod = $reflection->getMethod($method);
// Check for conflicting annotations
$hasAllowAnonymous = !empty($reflectionMethod->getAttributes(Annotations\AllowAnonymous::class));
$hasRequiresAuth = !empty($reflectionMethod->getAttributes(Annotations\RequiresAuth::class));
if ($hasAllowAnonymous && $hasRequiresAuth) {
throw new \InvalidArgumentException(
"Method '$method' has conflicting annotations: #[AllowAnonymous] and #[RequiresAuth] cannot be used together"
);
}
// Check AllowAnonymous first
if ($hasAllowAnonymous) {
return true;
}
// Check RequiresAuth
if ($hasRequiresAuth) {
// First call isAuthorized()
if (!$this->isAuthorized()) {
return false;
}
// Then check for PreAuthorize
$preAuthAttributes = $reflectionMethod->getAttributes(Annotations\PreAuthorize::class);
if (!empty($preAuthAttributes)) {
$preAuth = $preAuthAttributes[0]->newInstance();
return SecurityContext::evaluateExpression($preAuth->expression);
}
// If no PreAuthorize, continue based on isAuthorized (already passed)
return true;
}
// Check PreAuthorize without RequiresAuth
$preAuthAttributes = $reflectionMethod->getAttributes(Annotations\PreAuthorize::class);
if (!empty($preAuthAttributes)) {
$preAuth = $preAuthAttributes[0]->newInstance();
return SecurityContext::evaluateExpression($preAuth->expression);
}
return $this->isAuthorized();
}
/**
* Configure parameters dynamically for a specific method.
*
* @param string $methodName The method name to configure parameters for
*/
public function configureParametersForMethod(string $methodName): void {
try {
$reflection = new \ReflectionMethod($this, $methodName);
$this->configureParametersFromMethod($reflection);
} catch (\ReflectionException $e) {
// Method doesn't exist, ignore
}
}
/**
* Gets all responses mapped by HTTP method.
*
* @return array<string, OpenAPI\ResponsesObj> Map of methods to responses.
*/
public function getAllResponses(): array {
return $this->responsesByMethod;
}
/**
* Returns an object that contains the value of the header 'authorization'.
*
* @return AuthHeader|null The object will have two primary attributes, the first is
* the 'scheme' and the second one is 'credentials'. The 'scheme'
* will contain the name of the scheme which is used to authenticate
* ('basic', 'bearer', 'digest', etc...). The 'credentials' will contain
* the credentials which can be used to authenticate the client.
*
*/
public function getAuthHeader() {
if ($this->request !== null) {
return $this->request->getAuthHeader();
}
return null;
}
/**
* Returns the description of the service.
*
* @return string The description of the service. Default is empty string.
*
*/
public final function getDescription() : string {
return $this->serviceDesc;
}
/**
* Returns an associative array or an object of type Json of filtered request inputs.
*
* The indices of the array will represent request parameters and the
* values of each index will represent the value which was set in
* request body. The values will be filtered and might not be exactly the same as
* the values passed in request body. Note that if a parameter is optional and not
* provided in request body, its value will be set to 'null'. Note that
* if request content type is 'application/json', only basic filtering will
* be applied. Also, parameters in this case don't apply.
*
* @return array|Json|null An array of filtered request inputs. This also can
* be an object of type 'Json' if request content type was 'application/json'.
* If no manager was associated with the service, the method will return null.
*
*/
public function getInputs() {
$manager = $this->getManager();
if ($manager !== null) {
return $manager->getInputs();
}
return null;
}
/**
* Returns the manager which is used to manage the web service.
*
* @return WebServicesManager|null If set, it is returned as an object.
* Other than that, null is returned.
*/
public function getManager() {
return $this->owner;
}
/**
* Returns the name of the service.
*
* @return string The name of the service.
*
*/
public final function getName() : string {
return $this->name;
}
/**
* Map service parameter to specific instance of a class.
*
* This method assumes that every parameter in the request has a method
* that can be called to set attribute value. For example, if a parameter
* has the name 'user-last-name', the mapping method should have the name
* 'setUserLastName' for mapping to work correctly.
*
* @param string $clazz The class that service parameters will be mapped
* to.
*
* @param array $settersMap An optional array that can have custom
* setters map. The indices of the array should be parameters names
* and the values are the names of setter methods in the class.
*
* @return object The Method will return an instance of the class with
* all its attributes set to request parameter's values.
*/
public function getObject(string $clazz, array $settersMap = []) {
$mapper = new ObjectMapper($clazz, $this);
foreach ($settersMap as $param => $method) {
$mapper->addSetterMap($param, $method);
}
return $mapper->map($this->getInputs());
}
/**
* Returns one of the parameters of the service given its name.
*
* @param string $paramName The name of the parameter.
*
* @return RequestParameter|null Returns an objects of type RequestParameter if
* a parameter with the given name was found. null if nothing is found.
*
*/
public final function getParameterByName(string $paramName, ?string $httpMethod = null) {
// Configure parameters if HTTP method specified
if ($httpMethod !== null) {
$this->configureParametersForHttpMethod($httpMethod);
} else {
// Configure parameters for all methods with annotations
$this->configureAllAnnotatedParameters();
}
$trimmed = trim($paramName);
if (strlen($trimmed) != 0) {
foreach ($this->parameters as $param) {
if ($param->getName() == $trimmed) {
return $param;
}
}
}
return null;
}
/**
* Returns the value of request parameter given its name.
*
* @param string $paramName The name of request parameter as specified when
* it was added to the service.
*
* @return mixed|null If the parameter is found and its value is set, the
* method will return its value. Other than that, the method will return null.
* For optional parameters, if a default value is set for it, the method will
* return that value.
*
*/
public function getParamVal(string $paramName) {
$inputs = $this->getInputs();
$trimmed = trim($paramName);
if ($inputs !== null) {
if ($inputs instanceof Json) {
return $inputs->get($trimmed);
} else {
return $inputs[$trimmed] ?? null;
}
}
return null;
}
/**
* Returns an indexed array that contains information about possible responses.
*
* It is used to describe the API for front-end developers and help them
* identify possible responses if they call the API using the specified service.
*
* @return array An array that contains information about possible responses.
*
*/
public final function getResponsesDescriptions() : array {
return $this->responses;
}
public function getResponsesForMethod(string $method): ?OpenAPI\ResponsesObj {
$method = strtoupper($method);
return $this->responsesByMethod[$method] ?? null;
}
/**
* Returns version number or name at which the service was added to the API.
*
* Version number is set based on the version number which was set in the
* class WebAPI.
*
* @return string The version number at which the service was added to the API.
* Default is '1.0.0'.
*
*/
public final function getSince() : string {
return $this->sinceVersion;
}
/**
* Get the target method name based on current HTTP request.
*
* @return string|null The method name that should handle this request, or null if none found
*/
public function getTargetMethod(): ?string {
$httpMethod = $this->getManager() ?
$this->getManager()->getRequest()->getMethod() :
($_SERVER['REQUEST_METHOD'] ?? 'GET');
// First try to get method from getCurrentProcessingMethod (if implemented)
$currentMethod = $this->getCurrentProcessingMethod();
if ($currentMethod) {
$reflection = new \ReflectionClass($this);
try {
$method = $reflection->getMethod($currentMethod);
if ($this->methodHandlesHttpMethod($method, $httpMethod)) {
return $currentMethod;
}
} catch (\ReflectionException $e) {
// Method doesn't exist, continue with discovery
}
}
// Fall back to finding first method that matches HTTP method
$reflection = new \ReflectionClass($this);
foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
if ($this->methodHandlesHttpMethod($method, $httpMethod)) {
return $method->getName();
}
}
return null;
}
/**
* Check if the method has any authorization annotations.
*/
public function hasMethodAuthorizationAnnotations(): bool {
$reflection = new \ReflectionClass($this);
$method = $this->getCurrentProcessingMethod() ?: $this->getTargetMethod();
if (!$method) {
return false;
}
$reflectionMethod = $reflection->getMethod($method);
return !empty($reflectionMethod->getAttributes(Annotations\AllowAnonymous::class)) ||
!empty($reflectionMethod->getAttributes(Annotations\RequiresAuth::class)) ||
!empty($reflectionMethod->getAttributes(Annotations\PreAuthorize::class));
}
/**
* Checks if the service has a specific request parameter given its name.
*
* Note that the name of the parameter is case-sensitive. This means that
* 'get-profile' is not the same as 'Get-Profile'.
*
* @param string $name The name of the parameter.
*
* @return bool If a request parameter which has the given name is added
* to the service, the method will return true. Otherwise, the method will return
* false.
*
*/
public function hasParameter(string $name) : bool {
$trimmed = trim($name);
if (strlen($name) != 0) {
foreach ($this->getParameters() as $param) {
if ($param->getName() == $trimmed) {
return true;
}
}
}
return false;
}
/**
* Check if a method has the ResponseBody annotation.
*
* @param string $methodName The method name to check
* @return bool True if the method has ResponseBody annotation
*/
public function hasResponseBodyAnnotation(string $methodName): bool {
try {
$reflection = new \ReflectionMethod($this, $methodName);
return !empty($reflection->getAttributes(ResponseBody::class));
} catch (\ReflectionException $e) {
return false;
}
}
/**
* Checks if the client is authorized to use the service or not.
*
* The developer should implement this method in a way it returns a boolean.
* If the method returns true, it means the client is allowed to use the service.
* If the method returns false, then he is not authorized and a 401 error
* code will be sent back. If the method returned nothing, then it means the
* user is authorized to call the API. If WebFiori framework is used, it is
* possible to perform the functionality of this method using middleware.
*
* @return bool True if the user is allowed to perform the action. False otherwise.
*
*/
public function isAuthorized() : bool {
return false;
}
/**
* Returns the value of the property 'requireAuth'.
*
* The property is used to tell if the authorization step will be skipped
* or not when the service is called.
*
* @return bool The method will return true if authorization step required.
* False if the authorization step will be skipped. Default return value is true.
*
*/
public function isAuthRequired() : bool {
return $this->requireAuth;
}
/**
* Validates the name of a web service or request parameter.
*
* @param string $name The name of the service or parameter.
*
* @return bool If valid, true is returned. Other than that, false is returned.
*/
public static function isValidName(string $name): bool {
$trimmedName = trim($name);
$len = strlen($trimmedName);
if ($len != 0) {
for ($x = 0 ; $x < $len ; $x++) {
$ch = $trimmedName[$x];
if (!($ch == '_' || $ch == '-' || ($ch >= 'a' && $ch <= 'z') || ($ch >= 'A' && $ch <= 'Z') || ($ch >= '0' && $ch <= '9'))) {
return false;
}
}
return true;
}
return false;
}
/**
* Process client's request.
*/
public function processRequest() {
}
/**
* Process the web service request with auto-processing support.
* This method should be called instead of processRequest() for auto-processing.
*/
public function processWithAutoHandling(): void {
$targetMethod = $this->getTargetMethod();
if ($targetMethod && $this->hasResponseBodyAnnotation($targetMethod)) {
// Check method-level authorization first
if (!$this->checkMethodAuthorization()) {
$this->sendResponse('Access denied', 403, 'error');
return;
}
try {
// Inject parameters into method call
$params = $this->getMethodParameters($targetMethod);
$result = $this->$targetMethod(...$params);
$this->handleMethodResponse($result, $targetMethod);
} catch (HttpException $e) {
// Handle HTTP exceptions automatically
$this->handleException($e);
} catch (\Exception $e) {
// Handle other exceptions as 500 Internal Server Error
$this->sendResponse($e->getMessage(), 500, 'error');
}
} else {
// Fall back to traditional processRequest() approach
$this->processRequest();
}
}
/**
* Removes a request parameter from the service given its name.
*
* @param string $paramName The name of the parameter (case-sensitive).
*
* @return null|RequestParameter If a parameter which has the given name
* was removed, the method will return an object of type 'RequestParameter'
* that represents the removed parameter. If nothing is removed, the
* method will return null.
*
*/
public function removeParameter(string $paramName) {
$trimmed = trim($paramName);
$params = &$this->getParameters();
$index = -1;
$count = count($params);
for ($x = 0 ; $x < $count ; $x++) {
if ($params[$x]->getName() == $trimmed) {
$index = $x;
break;
}
}
$retVal = null;
if ($index != -1) {
if ($count == 1) {
$retVal = $params[0];
unset($params[0]);
} else {
$retVal = $params[$index];
$params[$index] = $params[$count - 1];
unset($params[$count - 1]);
}
}
return $retVal;
}
/**
* Removes a request method from the previously added ones.
*
* @param string $method The request method (e.g. 'get', 'post', 'options' ...). It
* can be in upper case or lower case.
*
* @return bool If the given request method is remove, the method will
* return true. Other than that, the method will return true.
*
*/
public function removeRequestMethod(string $method): bool {
$uMethod = strtoupper(trim($method));
$allowedMethods = &$this->getRequestMethods();
if (in_array($uMethod, $allowedMethods)) {
$count = count($allowedMethods);
$methodIndex = -1;
for ($x = 0 ; $x < $count ; $x++) {
if ($this->getRequestMethods()[$x] == $uMethod) {
$methodIndex = $x;
break;
}
}
if ($count == 1) {
unset($allowedMethods[0]);
} else {
$allowedMethods[$methodIndex] = $allowedMethods[$count - 1];
unset($allowedMethods[$count - 1]);
}
return true;
}
return false;
}
/**
* Sends Back a data using specific content type and specific response code.
*
* @param string $contentType Response content type (such as 'application/json')
*
* @param mixed $data Any data to send back. Mostly, it will be a string.
*
* @param int $code HTTP response code that will be used to send the data.
* Default is HTTP code 200 - Ok.
*
*/
public function send(string $contentType, $data, int $code = 200) {
$manager = $this->getManager();
if ($manager !== null) {
$manager->send($contentType, $data, $code);
}
}
/**
* Sends a JSON response to the client.
*
* The basic format of the message will be as follows:
* <p>
* {<br/>
* "message":"Action is not set.",<br/>
* "type":"error"<br/>
* "http-code":404<br/>
* "more-info":EXTRA_INFO<br/>
* }
* </p>
* Where EXTRA_INFO can be a simple string or any JSON data.
*
* @param string $message The message to send back.
*
* @param string $type A string that tells the client what is the type of
* the message. The developer can specify his own message types such as
* 'debug', 'info' or any string. If it is empty string, it will be not
* included in response payload.
*
* @param int $code Response code (such as 404 or 200). Default is 200.
*
* @param mixed $otherInfo Any other data to send back it can be a simple
* string, an object... . If null is given, the parameter 'more-info'
* will be not included in response. Default is empty string. Default is null.
*
*/
public function sendResponse(string $message, int $code = 200, string $type = '', mixed $otherInfo = '') {
$manager = $this->getManager();
if ($manager !== null) {
$manager->sendResponse($message, $code, $type, $otherInfo);
}
}
/**
* Sets the description of the service.
*
* Used to help front-end to identify the use of the service.
*
* @param string $desc Action description.
*
*/
public final function setDescription(string $desc) {
$this->serviceDesc = trim($desc);
}
/**
* Sets the value of the property 'requireAuth'.
*
* The property is used to tell if the authorization step will be skipped
* or not when the service is called.
*
* @param bool $bool True to make authorization step required. False to
* skip the authorization step.
*
*/
public function setIsAuthRequired(bool $bool) {
$this->requireAuth = $bool;
}
/**
* Associate the web service with a manager.
*
* The developer does not have to use this method. It is used when a
* service is added to a manager.
*
* @param WebServicesManager|null $manager The manager at which the service
* will be associated with. If null is given, the association will be removed if
* the service was associated with a manager.
*
*/
public function setManager(?WebServicesManager $manager) {
if ($manager === null) {
$this->owner = null;
} else {
$this->owner = $manager;
}
}
/**
* Sets the name of the service.
*
* A valid service name must follow the following rules:
* <ul>
* <li>It can contain the letters [A-Z] and [a-z].</li>
* <li>It can contain the numbers [0-9].</li>
* <li>It can have the character '-' and the character '_'.</li>
* </ul>
*
* @param string $name The name of the web service.
*
* @return bool If the given name is valid, the method will return
* true once the name is set. false is returned if the given
* name is invalid.
*
*/
public final function setName(string $name) : bool {
if (self::isValidName($name)) {
$this->name = trim($name);
return true;
}
return false;
}
/**
* Sets the request instance for the service.
*
* @param mixed $request The request instance (Request, etc.)
*/
public function setRequest($request) {
$this->request = $request;
}
/**
* Adds multiple request methods as one group.
*
* @param array $methods
*/
public function setRequestMethods(array $methods) {
foreach ($methods as $m) {
$this->addRequestMethod($m);
}
}
/**
* Sets all responses for a specific HTTP method.
*
* @param string $method HTTP method.
* @param OpenAPI\ResponsesObj $responses Responses object.
*
* @return WebService Returns self for method chaining.
*/
public function setResponsesForMethod(string $method, OpenAPI\ResponsesObj $responses): WebService {
$this->responsesByMethod[strtoupper($method)] = $responses;
return $this;
}
/**
* Sets version number or name at which the service was added to a manager.
*
* This method is called automatically when the service is added to any services manager.
* The developer does not have to use this method.
*
* @param string $sinceAPIv The version number at which the service was added to the API.
*
*/
public final function setSince(string $sinceAPIv) {
$this->sinceVersion = $sinceAPIv;
}
/**
* Returns a Json object that represents the service.
*
* @return Json an object of type Json.
*
*/
public function toJSON() : Json {
return $this->toPathItemObj()->toJSON();
}
/**
* Converts this web service to an OpenAPI PathItemObj.
*
* Each HTTP method supported by this service becomes an operation in the path item.