-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathIThenticate.php
806 lines (719 loc) · 28.6 KB
/
IThenticate.php
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
<?php
/**
* @file plugins/generic/plagiarism/IThenticate.php
*
* Copyright (c) 2024 Simon Fraser University
* Copyright (c) 2024 John Willinsky
* Distributed under the GNU GPL v3. For full terms see the file LICENSE.
*
* @class IThenticate
*
* @brief Service class to handle API communication with iThenticate service
*/
namespace APP\plugins\generic\plagiarism;
use APP\core\Application;
use APP\submission\Submission;
use Exception;
use PKP\author\Author;
use PKP\site\Site;
use PKP\context\Context;
use PKP\user\User;
class IThenticate
{
/**
* The base api url in the format of schema://host
*/
protected string $apiUrl;
/**
* The required API Key to make the request
* @see https://developers.turnitin.com/docs/tca#required-headers
*/
protected string $apiKey;
/**
* Describes the platform/plugin integrating with TCA
* @see https://developers.turnitin.com/docs/tca#required-headers
*/
protected string $integrationName;
/**
* The version of the code that is integrating with TCA
* @see https://developers.turnitin.com/docs/tca#required-headers
*/
protected string $integrationVersion;
/**
* The EULA(end user license agreement) that user need to confirmm before making request
*/
protected ?string $eulaVersion = null;
/**
* The EULA details for a specific version
*/
protected ?array $eulaVersionDetails = null;
/**
* Base API path
* The string `API_URL` need to be replaced with provided api url to generate fully qualified base url
*/
protected string $apiBasePath = "API_URL/api/v1/";
/**
* Should suppress the exception on api request and log request details and exception instead
*/
protected bool $suppressApiRequestException = true;
/**
* The default EULA version placeholder to retrieve the current latest version
*
* @var string
*/
public const DEFAULT_EULA_VERSION = 'latest';
/**
* The default EULA confirming language
*
* @var string
*/
public const DEFAULT_EULA_LANGUAGE = 'en-US';
/**
* The default webhook events for which webhook request will be received
* @see https://developers.turnitin.com/docs/tca#event-types
*
* @var array
*/
public const DEFAULT_WEBHOOK_EVENTS = [
'SUBMISSION_COMPLETE',
'SIMILARITY_COMPLETE',
'SIMILARITY_UPDATED',
'PDF_STATUS',
'GROUP_ATTACHMENT_COMPLETE',
];
/**
* The list of valid permission for owner and submitter when creating a new submission
* @see https://developers.turnitin.com/docs/tca#create-a-submission
*
* @var array
*/
public const SUBMISSION_PERMISSION_SET = [
'ADMINISTRATOR',
'APPLICANT',
'EDITOR',
'INSTRUCTOR',
'LEARNER',
'UNDEFINED',
'USER',
];
/**
* The minimum value of similarity report's view_setting's `exclude_small_matches` option
* @see https://developers.turnitin.com/docs/tca#generate-similarity-report
*
* @var int
*/
public const EXCLUDE_SAMLL_MATCHES_MIN = 8;
/**
* The entity(e.g. submission owner, submitter etc) to id prefix mapping
* This helps to identify the type of entity associated with requesting system
* For example, `author/1` rather than only `1` identify as author entity of requesting system
*
* @var array
*/
public const ENTITY_ID_PREFIXES = [
'owner' => 'author_',
'submitter' => 'user_',
];
/**
* Create a new instance
*/
public function __construct(
string $apiUrl,
string $apiKey,
string $integrationName,
string $integrationVersion,
?string $eulaVersion = null
)
{
$this->apiUrl = rtrim(trim($apiUrl ?? ''), '/\\');
$this->apiKey = $apiKey;
$this->integrationName = $integrationName;
$this->integrationVersion = $integrationVersion;
$this->eulaVersion = $eulaVersion;
}
/**
* Will deactivate the exception suppression on api request and throw exception
*/
public function withoutSuppressingApiRequestException(): static
{
$this->suppressApiRequestException = false;
return $this;
}
/**
* Get the json details of all enable features or get certiain feature details
* To get certain or nested feature details, pass the feature params in dot(.) notation
* For Example
* - to get specific feature as `similarity`, call as getEnabledFeature('similarity')
* - to get nested feature as `viewer_modes` in `similarity`, call as getEnabledFeature('similarity.viewer_modes')
* @see https://developers.turnitin.com/docs/tca#get-features-enabled
*
* @param mixed $feature The specific or nested feature details to get
*
* @throws \Exception
*/
public function getEnabledFeature(mixed $feature = null): string|array|null
{
static $result;
if (!isset($result) && !$this->validateAccess($result)) {
return $this->suppressApiRequestException
? []
: throw new Exception('unable to validate access details');
}
if (!$feature) {
return json_decode($result, true);
}
return data_get(
json_decode($result, true),
$feature,
fn () => $this->suppressApiRequestException
? null
: throw new Exception("Feature details {$feature} does not exist")
);
}
/**
* Validate the service access by retrieving the enabled feature
* @see https://developers.turnitin.com/docs/tca#get-features-enabled
* @see https://developers.turnitin.com/turnitin-core-api/best-practice/exposing-tca-settings
*
* @param mixed $result This may contains the returned enabled feature details from
* request validation api end point if validated successfully.
*/
public function validateAccess(mixed &$result = null): bool
{
$response = $this->makeApiRequest('GET', $this->getApiPath('features-enabled'), [
'headers' => $this->getRequiredHeaders(),
'verify' => false,
'exceptions' => false,
'http_errors' => false,
]);
if ($response && $response->getStatusCode() === 200) {
$result = $response->getBody()->getContents();
return true;
}
return false;
}
/**
* Confirm the EULA on the user's behalf for given version
* @see https://developers.turnitin.com/docs/tca#accept-eula-version
*/
public function confirmEula(User $user, Context $context): bool
{
$response = $this->makeApiRequest(
'POST',
$this->getApiPath("eula/{$this->getApplicableEulaVersion()}/accept"),
[
'headers' => array_merge($this->getRequiredHeaders(), [
'Content-Type' => 'application/json'
]),
'json' => [
'user_id' => $this->getGeneratedId('submitter', $user->getId()),
'accepted_timestamp' => \Carbon\Carbon::now()->toIso8601String(),
'language' => $this->getApplicableLocale($context->getPrimaryLocale()),
],
'verify' => false,
'exceptions' => false,
]
);
return $response ? $response->getStatusCode() === 200 : false;
}
/**
* Create a new submission at service's end
* @see https://developers.turnitin.com/docs/tca#create-a-submission
*
* @param Site $site The core site of submission system
* @param Submission $submission The article submission to check for plagiarism
* @param User $user The user who is making submitting the submission
* @param Author $author The author/owner of the submission
* @param string $authorPermission Submission author/owner permission set
* @param string $submitterPermission Submission submitter permission set
*
* @return string|null if succeed, it will return the created submission UUID from
* service's end and at failure, will return null
*
* @throws \Exception
*/
public function createSubmission(
Site $site,
Submission $submission,
User $user,
Author $author,
string $authorPermission,
string $submitterPermission
): ?string
{
if (!$this->validatePermission($authorPermission, static::SUBMISSION_PERMISSION_SET)) {
throw new Exception("in valid owner permission {$authorPermission} given");
}
if (!$this->validatePermission($submitterPermission, static::SUBMISSION_PERMISSION_SET)) {
throw new Exception("in valid submitter permission {$submitterPermission} given");
}
$publication = $submission->getCurrentPublication(); /** @var Publication $publication */
$author ??= $publication->getPrimaryAuthor();
$response = $this->makeApiRequest(
'POST',
$this->getApiPath("submissions"),
[
'headers' => array_merge($this->getRequiredHeaders(), [
'Content-Type' => 'application/json'
]),
'json' => [
'owner' => $this->getGeneratedId('owner', $author->getId()),
'title' => $publication->getLocalizedTitle($publication->getData('locale')),
'submitter' => $this->getGeneratedId('submitter', $user->getId()),
'owner_default_permission_set' => $authorPermission,
'submitter_default_permission_set' => $submitterPermission,
'metadata' => [
'owners' => [
[
'id' => $this->getGeneratedId('owner', $author->getId()),
'given_name' => $author->getGivenName($publication->getData('locale')),
'family_name' => $author->getFamilyName($publication->getData('locale')),
'email' => $author->getEmail(),
]
],
'submitter' => [
'id' => $this->getGeneratedId('submitter', $user->getId()),
'given_name' => $user->getGivenName($site->getPrimaryLocale()),
'family_name' => $user->getFamilyName($site->getPrimaryLocale()),
'email' => $user->getEmail(),
],
'original_submitted_time' => \Carbon\Carbon::now()->toIso8601String(),
],
],
'verify' => false,
'exceptions' => false,
]
);
if ($response && $response->getStatusCode() === 201) {
$result = json_decode($response->getBody()->getContents());
return $result->id;
} else {
error_log((string)$response->getBody()->getContents());
}
return null;
}
/**
* Upload single submission file to the service's end
* @see https://developers.turnitin.com/docs/tca#upload-submission-file-contents
*
* @param string $submissionTacId The submission UUID return back from service
* @param string $fileName
* @param mixed fileContent
*/
public function uploadFile(string $submissionTacId, string $fileName, mixed $fileContent): bool
{
$response = $this->makeApiRequest(
'PUT',
$this->getApiPath("submissions/{$submissionTacId}/original"),
[
'headers' => array_merge($this->getRequiredHeaders(), [
'Content-Type' => 'binary/octet-stream',
'Content-Disposition' => urlencode('inline; filename="'.$fileName.'"'),
]),
'body' => $fileContent,
'verify' => false,
'exceptions' => false,
]
);
return $response ? $response->getStatusCode() === 202 : false;
}
/**
* Get the submission details
* @see https://developers.turnitin.com/docs/tca#get-submission-info
*
* @param string $submissionTacId The submission UUID return back from service
* @return string|null On successful retrieval of submission details it will return
* details JSON data and on failure, will return null.
*/
public function getSubmissionInfo(string $submissionUuid): ?string
{
$response = $this->makeApiRequest(
'GET',
$this->getApiPath("submissions/{$submissionUuid}"),
[
'headers' => $this->getRequiredHeaders(),
'verify' => false,
'exceptions' => false,
]
);
if ($response->getStatusCode() === 200) {
return $response->getBody()->getContents();
}
return null;
}
/**
* Schedule the similarity report generation process
* @see https://developers.turnitin.com/docs/tca#generate-similarity-report
*
* @param string $submissionUuid The submission UUID return back from service
* @param array $settings The specific few settings
*/
public function scheduleSimilarityReportGenerationProcess(string $submissionUuid, array $settings = []): bool
{
$response = $this->makeApiRequest(
'PUT',
$this->getApiPath("submissions/{$submissionUuid}/similarity"),
[
'headers' => array_merge($this->getRequiredHeaders(), [
'Content-Type' => 'application/json'
]),
'json' => [
// section `indexing_settings` settings
'indexing_settings' => [
'add_to_index' => $settings['addToIndex'] ?? true,
],
// section `generation_settings` settings
'generation_settings' => [
'search_repositories' => [
'INTERNET',
'SUBMITTED_WORK',
'PUBLICATION',
'CROSSREF',
'CROSSREF_POSTED_CONTENT'
],
'auto_exclude_self_matching_scope' => $settings['autoExcludeSelfMatchingScope'] ?? 'ALL',
'priority' => $settings['priority'] ?? 'HIGH',
],
// section `view_settings` settings
'view_settings' => [
'exclude_quotes' => $settings['excludeQuotes'] ?? false,
'exclude_bibliography' => $settings['excludeBibliography'] ?? false,
'exclude_citations' => $settings['excludeCitations'] ?? false,
'exclude_abstract' => $settings['excludeAbstract'] ?? false,
'exclude_methods' => $settings['excludeMethods'] ?? false,
'exclude_custom_sections' => $settings['excludeCustomSections'] ?? false,
'exclude_preprints' => $settings['excludePreprints'] ?? false,
'exclude_small_matches' => (int) $settings['excludeSmallMatches'] >= self::EXCLUDE_SAMLL_MATCHES_MIN
? (int) $settings['excludeSmallMatches']
: self::EXCLUDE_SAMLL_MATCHES_MIN,
'exclude_internet' => $settings['excludeInternet'] ?? false,
'exclude_publications' => $settings['excludePublications'] ?? false,
'exclude_crossref' => $settings['excludeCrossref'] ?? false,
'exclude_crossref_posted_content' => $settings['excludeCrossrefPostedContent'] ?? false,
'exclude_submitted_works' => $settings['excludeSubmittedWorks'] ?? false,
],
],
'exceptions' => false,
]
);
return $response ? $response->getStatusCode() === 202 : false;
}
/**
* Get the similarity result info
* @see https://developers.turnitin.com/docs/tca#get-similarity-report-info
*
* @param string $submissionUuid The submission UUID return back from service
*/
public function getSimilarityResult(string $submissionUuid): ?string
{
$response = $this->makeApiRequest(
'GET',
$this->getApiPath("submissions/{$submissionUuid}/similarity"),
[
'headers' => $this->getRequiredHeaders(),
'exceptions' => false,
]
);
return $response && $response->getStatusCode() === 200
? $response->getBody()->getContents()
: null;
}
/**
* Create the viewer launch url
* @see https://developers.turnitin.com/docs/tca#create-viewer-launch-url
*
* @param string $submissionUuid The submission UUID return back from service
* @param User $user The viewing user
* @param string $locale The preferred locale
* @param string $viewerPermission The viewing user permission
* @param bool $allowUpdateInViewer Should allow to update in the viewer and save it which will
*/
public function createViewerLaunchUrl(
string $submissionUuid,
User $user,
string $locale,
string $viewerPermission,
bool $allowUpdateInViewer
): ?string
{
$response = $this->makeApiRequest(
'POST',
$this->getApiPath("submissions/{$submissionUuid}/viewer-url"),
[
'headers' => array_merge($this->getRequiredHeaders(), [
'Content-Type' => 'application/json'
]),
'json' => [
'viewer_user_id' => $this->getGeneratedId('submitter', $user->getId()),
'locale' => $locale,
'viewer_default_permission_set' => $viewerPermission,
'similarity' => [
'view_settings' => [
'save_changes' => $allowUpdateInViewer
],
],
],
'exceptions' => false,
]
);
if ($response && $response->getStatusCode() === 200) {
$result = json_decode($response->getBody()->getContents());
return $result->viewer_url;
}
return null;
}
/**
* Verify if user has already confirmed the given EULA version
* @see https://developers.turnitin.com/docs/tca#get-eula-acceptance-info
*/
public function verifyUserEulaAcceptance(Author|User $user, string $version): bool
{
$response = $this->makeApiRequest(
'GET',
$this->getApiPath("eula/{$version}/accept/" . $this->getGeneratedId('submitter' ,$user->getId())),
[
'headers' => $this->getRequiredHeaders(),
'exceptions' => false,
]
);
return $response ? $response->getStatusCode() === 200 : false;
}
/**
* Validate/Retrieve the given EULA version
* @see https://developers.turnitin.com/docs/tca#get-eula-version-info
*/
public function validateEulaVersion(string $version): bool
{
$response = $this->makeApiRequest('GET', $this->getApiPath("eula/{$version}"), [
'headers' => $this->getRequiredHeaders(),
'exceptions' => false,
]);
if ($response->getStatusCode() === 200) {
$this->eulaVersionDetails = json_decode($response->getBody()->getContents(), true);
if (!$this->eulaVersion) {
$this->eulaVersion = $this->eulaVersionDetails['version'];
}
return true;
}
return false;
}
/**
* Register webhook end point
* @see https://developers.turnitin.com/docs/tca#create-webhook
*
* NOTE : with same webhook url, it will return response with status code 409(HTTP_CONFLICT)
* So it's important to verify one before create a new one
*
* @return string|null The UUID of register webhook if succeed or null if failed
*/
public function registerWebhook(
string $signingSecret,
string $url,
array $events = self::DEFAULT_WEBHOOK_EVENTS
): ?string
{
$response = $this->makeApiRequest('POST', $this->getApiPath('webhooks'), [
'headers' => array_merge($this->getRequiredHeaders(), [
'Content-Type' => 'application/json',
]),
'json' => [
'signing_secret' => base64_encode($signingSecret),
'url' => $url,
'event_types' => $events,
'allow_insecure' => true,
],
'verify' => false,
'exceptions' => false,
]);
if ($response && $response->getStatusCode() === 201) {
$result = json_decode($response->getBody()->getContents());
return $result->id;
}
return null;
}
/**
* Delete webhook end point
* @see https://developers.turnitin.com/docs/tca#delete-webhook
*/
public function deleteWebhook(string $webhookId): bool
{
$response = $this->makeApiRequest('DELETE', $this->getApiPath("webhooks/{$webhookId}"), [
'headers' => $this->getRequiredHeaders(),
'verify' => false,
'exceptions' => false,
]);
return $response && $response->getStatusCode() === 204;
}
/**
* Get the stored EULA details
*/
public function getEulaDetails(): ?array
{
return $this->eulaVersionDetails;
}
/**
* Get the applicable EULA version
*/
public function getApplicableEulaVersion(): string
{
if (!$this->eulaVersion) {
throw new Exception('No EULA version set yet');
}
return $this->eulaVersion;
}
/**
* Set the applicable EULA version
*/
public function setApplicableEulaVersion(string $version): static
{
$this->eulaVersion = $version;
return $this;
}
/**
* Make the api request
*
* @param string $method HTTP method.
* @param string|\Psr\Http\Message\UriInterface $uri URI object or string.
* @param array $options Request options to apply. See \GuzzleHttp\RequestOptions.
*
* @return \Psr\Http\Message\ResponseInterface|null
*
* @throws \Throwable
*/
public function makeApiRequest(
string $method,
string|\Psr\Http\Message\UriInterface $url,
array $options = []
): ?\Psr\Http\Message\ResponseInterface
{
$response = null;
try {
$response = Application::get()->getHttpClient()->request($method, $url, $options);
} catch (\Throwable $exception) {
error_log(
sprintf(
'iThenticate API request to %s for %s method failed with options %s',
$url,
$method,
print_r($options, true)
)
);
$this->suppressApiRequestException
? error_log($exception->__toString())
: throw $exception;
}
return $response;
}
/**
* Get the applicable EULA Url
*
* @throws \Exception
*/
public function getApplicableEulaUrl(string|array|null $locales = null): string
{
if (!$this->eulaVersion) {
throw new Exception('No EULA version set yet');
}
$applicableEulaLanguage = $this->getApplicableLocale($locales ?? static::DEFAULT_EULA_LANGUAGE);
$eulaUrl = $this->eulaVersionDetails['url'];
return str_replace(
strtolower(static::DEFAULT_EULA_LANGUAGE),
strtolower($applicableEulaLanguage),
$eulaUrl
);
}
/**
* Convert given submission/context locale to service compatible and acceptable locale format
* @see https://developers.turnitin.com/docs/tca#eula
*/
public function getApplicableLocale(string|array $locales, ?string $eulaVersion = null): string
{
if (!$this->getEulaDetails() && !$this->validateEulaVersion($eulaVersion ?? $this->eulaVersion)) {
return static::DEFAULT_EULA_LANGUAGE;
}
if (is_string($locales)) {
return $this->getCorrespondingLocaleAvailable($locales) ?? static::DEFAULT_EULA_LANGUAGE;
}
foreach ($locales as $locale) {
$correspondingLocale = $this->getCorrespondingLocaleAvailable($locale);
if ($correspondingLocale) {
return $correspondingLocale;
}
}
return static::DEFAULT_EULA_LANGUAGE;
}
/**
* Get the corresponding available locale or return null
*/
protected function getCorrespondingLocaleAvailable(string $locale): ?string
{
$eulaLangs = $this->eulaVersionDetails['available_languages'];
$language = \Locale::getPrimaryLanguage($locale);
$region = \Locale::getRegion($locale) ?? null;
$localeAndRegion = $language . '-' . $region;
return in_array($localeAndRegion, $eulaLangs)
? $localeAndRegion
: collect($eulaLangs)
->filter(
fn(string $lang) =>
collect(explode("-", $lang))->first() === $language
)->first();
}
/**
* Get the required headers that need to be sent with every request at service's end
* @see https://developers.turnitin.com/docs/tca#required-headers
*/
protected function getRequiredHeaders(): array
{
return [
'X-Turnitin-Integration-Name' => $this->integrationName,
'X-Turnitin-Integration-Version' => $this->integrationVersion,
'Authorization' => 'Bearer ' . $this->apiKey,
];
}
/**
* Generate and return the final API end point to make request
*/
protected function getApiPath($apiPathSegment): \GuzzleHttp\Psr7\Uri
{
$apiRequestUrl = str_replace('API_URL', $this->apiUrl, $this->apiBasePath) . $apiPathSegment;
return new \GuzzleHttp\Psr7\Uri($apiRequestUrl);
}
/**
* Generate and return unique entity id by concatenating the prefix to given id
*
* @param string $entity The entity name (e.g. owner/submitter etc).
* @param mixed $id Entity id associated with requesting system.
* @param bool $silent Silently return the passed `$id` if no matching entity mapping
* not found. Default to `false` and when set to `true`, will not throw
* exception.
*/
protected function getGeneratedId(string $entity, mixed $id, bool $silent = false): mixed
{
if (!in_array($entity, array_keys(static::ENTITY_ID_PREFIXES))) {
if ($silent) {
return $id;
}
throw new Exception(
sprintf(
'Invalid entity %s given, must be among [%s]',
$entity,
implode(', ', array_keys(static::ENTITY_ID_PREFIXES))
)
);
}
return static::ENTITY_ID_PREFIXES[$entity] . $id;
}
/**
* Validate the existence of a permission against a given permission set
*
* @param string $permission The specific permission to check for existence
* @param array $permissionSet The permission list to check against
*
* @return bool True/False if the permission exists in the given permission set
*/
protected function validatePermission(string $permission, array $permissionSet): bool
{
return in_array($permission, $permissionSet);
}
}