From 70e4e9e95fefa104328e4fa68e4985cb4dc9e216 Mon Sep 17 00:00:00 2001 From: fnnbrr Date: Thu, 21 May 2026 11:35:47 -0400 Subject: [PATCH 1/8] First pass generated plan for using TN posts API --- plans/tn-api-post-ingestion.md | 135 +++++++++++++++++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 plans/tn-api-post-ingestion.md diff --git a/plans/tn-api-post-ingestion.md b/plans/tn-api-post-ingestion.md new file mode 100644 index 0000000000..cccd1dca2c --- /dev/null +++ b/plans/tn-api-post-ingestion.md @@ -0,0 +1,135 @@ +# TN API Ingestion Migration Plan + +Replace email-based ingestion of Trash Nothing (TN) posts and chat messages with API-based ingestion driven from `TNSyncCommand`, while keeping the existing email path **byte-identical** for parallel comparison. + +## Guiding constraint + +`IncomingMailService::handleGroupPost`, `::createGroupPostMessage`, and every helper they call must remain unchanged. The new path is purely additive. Any shared logic is **duplicated then deduplicated later** — extraction now would touch the email path. + +## Architecture + +``` +TNSyncCommand (orchestrator) + ├── TNApiClient (paging, auth, fixtures, retries) + ├── RatingsSyncer (existing logic, extracted) + ├── UserChangesSyncer (existing logic, extracted) + ├── DuplicateUserMerger (existing logic, extracted) + ├── PostsSyncer ── uses ── GroupPostIngestionService (new, TN-only) + └── ChatMessagesSyncer ── uses ── ChatMessageIngestionService (new, TN-only) +``` + +`GroupPostIngestionService` and `ChatMessageIngestionService` are new TN-only services that re-implement the relevant slices of `IncomingMailService` logic, but operating on TN API DTOs instead of `ParsedEmail`. The email service is not touched. + +## File layout + +- `iznik-batch/app/Console/Commands/TrashNothing/TNSyncCommand.php` — slim orchestrator (~150 lines) +- `iznik-batch/app/Services/TrashNothing/TNApiClient.php` +- `iznik-batch/app/Services/TrashNothing/Syncers/RatingsSyncer.php` +- `iznik-batch/app/Services/TrashNothing/Syncers/UserChangesSyncer.php` +- `iznik-batch/app/Services/TrashNothing/Syncers/PostsSyncer.php` +- `iznik-batch/app/Services/TrashNothing/Syncers/ChatMessagesSyncer.php` +- `iznik-batch/app/Services/TrashNothing/Syncers/DuplicateUserMerger.php` +- `iznik-batch/app/Services/TrashNothing/Ingestion/GroupPostIngestionService.php` +- `iznik-batch/app/Services/TrashNothing/Ingestion/ChatMessageIngestionService.php` +- `iznik-batch/app/Services/TrashNothing/Ingestion/TNPayloadToRfc822.php` +- `iznik-batch/app/Services/TrashNothing/Dto/TNPostPayload.php` +- `iznik-batch/app/Services/TrashNothing/Dto/TNChatMessagePayload.php` +- `iznik-batch/app/Services/TrashNothing/Dto/SyncResult.php` + +## Key design decisions + +### Parallel-run mode = `--dry-run` +The existing `--dry-run` flag is the comparison mode. With it set, the new API services emit `TRACE [WRITE]` log lines for every intended DB write but execute none. Comparison diffs those trace logs against the rows the email path actually wrote, joining on `tnpostid`. The email path remains source of truth during comparison. Going live = run without `--dry-run` and disable the email path at the same time. + +Implications: +- Every new service takes `bool $dryRun` and gates every `save()`, `DB::insert/update/delete`, side-effect call (`notifyGroupMods`, `addToSpatialIndex`, `recordFailure`, image attachments, log inserts). +- No shadow tables, no source-tagging. +- Trace payload must capture every column the email path writes so the diff isn't blind to e.g. a missing `replyto`. + +### Raw message → synthesized RFC822 blob +Centralized in `TNPayloadToRfc822::synthesize($payload): string`. Minimal headers: `From`, `To`, `Subject`, `Date`, `Message-ID`, `X-Trashnothing-Post-Id`, `X-Trashnothing-Coordinates`, `Content-Type: text/plain` — mirrors what the email path relied on so any downstream code that re-parses `messages.message` still works. Unit test: round-trip through `ParsedEmail` parsing to confirm we recover the same fields. + +### Checkpointing → all-or-nothing +Keep the single sync-date file. Each syncer runs in try/catch; if any throws, the sync-date file is not written. The orchestrator aggregates `maxChangeDate` across all syncers only after they all succeed. A flaky endpoint blocks progress on the others — accepted for simplicity. Document on `storeSyncDate()`. + +## Angles to cover + +### A. Side-by-side / comparison +- Correlation key: `messages.tnpostid` (populated by both paths). +- Time alignment: TN API may not deliver a post the same minute the email arrives; comparison tooling needs a tolerance window. +- Comparison tooling: TBD — new artisan command `tn:sync-compare` vs offline scripting. + +### B. Idempotency / dedup +- During parallel run, even though API path is dry-run, trace emitter should detect "row with this `tnpostid` already exists" and tag the trace line `would_be_duplicate: true`. +- Once live: `firstOrCreate` on `(tnpostid, groupid)`. + +### C. Field-level parity — `createGroupPostMessage` writes these and each needs an API mapping +- `message` — synthesized RFC822 (see above) +- `messageid` — synthesized; format `{tnpostid}@tn.trashnothing.com-{groupid}` or similar +- `envelopefrom`, `envelopeto`, `replyto`, `fromip`, `sourceheader` — synthesized or null; decide per field +- `fromname`, `fromaddr` — from TN user data +- `subject`, `textbody` — direct from API +- `lat`/`lng`/`locationid` — from API coordinates (replacing `X-Trashnothing-Coordinates` header parsing) +- `tnpostid` — direct +- `type` — still via `Message::determineType($subject)` +- Images — from API image URLs (replacing `scrapeTnImageUrls` on textbody); confirm URLs match the email path's final URLs + +### D. Behavioral parity — slices of `handleGroupPost` to replicate +- Group lookup (by name? id? — depends on API shape) +- User lookup (API gives `fd_user_id` directly — simpler than email-based lookup, but verify parity for unmapped/banned/deleted users) +- Membership check (`collection = Approved`) +- TAKEN/RECEIVED subject swallow +- Spam check decision (see open items) +- Posting-status decision tree: `ourPostingStatus`, Big Switch (`overridemoderation`), mod-post-to-pending, group `moderated` setting, unmapped user, worry words +- Side-effects: `messages_postings`, `messages_history`, `messages_groups`, `messages_spatial`, `logs (Message/Received)`, `notifyGroupMods`, `addToSpatialIndex`, `pruneSubject`, `recordFailure` + +### E. Chat messages +- API equivalent of `handleChatNotificationReply` / `handleReplyToAddress` / `createChatMessageFromEmail`. +- Map: chat id, sender user id, `refmsgid`, message type (`TYPE_INTERESTED` vs `TYPE_DEFAULT`), body, attachments. +- Stale-chat / unfamiliar-sender drop logic — still applicable? +- `addEmailToUser` (email forwarding scenario) — N/A. +- `trackEmailReply` (AMP comparison stats) — N/A or replaced with TN-source tracking. +- Read-receipts from TN — separate concern; map only if the API exposes them. + +### F. Ordering between syncers +Order: ratings → user-changes → posts → chats → duplicate merge. +Risk: a post references an `fd_user_id` not yet created locally (race with `UserChangesSyncer`). Behavior on missing user is an open item. + +### G. Failure semantics +Covered by all-or-nothing checkpoint decision above. Each syncer surfaces its own `maxChangeDate`; orchestrator aggregates only on full success. + +### H. Throughput / rate limits +Existing syncers page 100 at a time. Posts/chats volume unknown — confirm pagination + rate-limit headers, plan for backoff. If posts add minutes of work, may exceed scheduler interval (lock prevents overlap but starves other resources). + +### I. Loki / observability parity +Email path emits structured logs at every routing decision (`routing_reason`, `user_id`, `message_id`, `chat_id`). New path needs equivalent `loki->logEvent` calls. Define event names up front on the `tn-sync` channel: `post-create`, `post-skip-duplicate`, `chat-create`, etc. + +### J. Dry-run / fixture-test parity +- Every DB-write call in new services must respect `dryRun`. +- Convention: services receive `bool $dryRun` in the constructor. +- Fixture files at `tests/fixtures/tn_sync/posts_page_*.json` and `chat_messages_page_*.json` — schema decided before generation. +- Trace log format: machine-parseable JSON (`TRACE [WRITE] {"table":...,"op":...,"set":{...}}`). Possibly emit both JSON (for diff tool) and existing `key=value` style (for humans) — open item. + +### K. Feature flag / rollout +- `config('freegle.trashnothing.ingest_posts_via_api')` (default false). When false, `PostsSyncer` and `ChatMessagesSyncer` skipped entirely. +- Separate flag to disable email path once parity proven — flipped much later. Both flags on = double-write (needs idempotency from B). + +### L. Test strategy +- Unit-test each new service with fixture payloads; snapshot the rows that would be written. +- Parity test: feed a representative TN email through `IncomingMailService` and a matching TN API payload through `PostsSyncer`; assert resulting `messages` / `messages_groups` / `logs` rows match (modulo source field and synthetic message-id). +- Existing `IncomingMailServiceTest` suite stays green untouched. + +### M. NOT in scope +- Modifying `IncomingMailService` in any way. +- Extracting/sharing helpers between email + API paths during parallel running. +- Removing SMTP receivers or any TN-aware code paths in the mail pipeline. + +## Open items still to resolve + +1. **Trace log format** — JSON only, key=value only, or both? +2. **Comparison tooling** — new `tn:sync-compare` artisan command vs offline scripting? +3. **Spam check on API path** — skip entirely (TN trusted), or run it and log when it would have flagged? +4. **Worry-words on API path** — apply, or skip because TN moderates on their end? +5. **Missing user handling** — when `PostsSyncer` sees an `fd_user_id` that doesn't exist locally yet (race with `UserChangesSyncer`), what's the desired behavior? Note: all-or-nothing checkpointing means failing the sync blocks ratings progress too. +6. **Group lookup** — does the TN API give `nameshort`, `groupid`, or something else? +7. **Duplicate detection in dry-run** — confirm trace lines should carry `would_be_duplicate: true` when a row with the same `tnpostid` already exists. From f0bf173b42d825e42f66e620aa255be8b5041faf Mon Sep 17 00:00:00 2001 From: fnnbrr Date: Thu, 21 May 2026 12:15:50 -0400 Subject: [PATCH 2/8] First pass generating PHP client from Trash Nothing public OpenAPI spec --- .../TrashNothing/PublicApi/.gitignore | 15 + .../PublicApi/.openapi-generator-ignore | 23 + .../PublicApi/.openapi-generator/FILES | 83 + .../PublicApi/.openapi-generator/VERSION | 1 + .../PublicApi/.php-cs-fixer.dist.php | 29 + .../TrashNothing/PublicApi/.travis.yml | 8 + .../Services/TrashNothing/PublicApi/README.md | 152 + .../TrashNothing/PublicApi/composer.json | 38 + .../PublicApi/docs/Api/GroupsApi.md | 212 ++ .../PublicApi/docs/Api/PostsApi.md | 516 ++++ .../PublicApi/docs/Api/UsersApi.md | 191 ++ .../PublicApi/docs/Model/Feedback.md | 14 + .../docs/Model/GetAllPosts200Response.md | 9 + .../Model/GetAllPostsChanges200Response.md | 9 + ...tAllPostsChanges200ResponseChangesInner.md | 12 + .../Model/GetPostAndRelatedData200Response.md | 19 + .../docs/Model/GetPostsByIds200Response.md | 11 + .../docs/Model/GetUserPosts200Response.md | 17 + .../PublicApi/docs/Model/Group.md | 22 + .../PublicApi/docs/Model/GroupCountry.md | 10 + .../PublicApi/docs/Model/GroupMembership.md | 11 + .../Model/GroupMembershipQuestionnaire.md | 10 + .../PublicApi/docs/Model/GroupRegion.md | 10 + .../PublicApi/docs/Model/Photo.md | 14 + .../PublicApi/docs/Model/PhotoImagesInner.md | 11 + .../TrashNothing/PublicApi/docs/Model/Post.md | 25 + .../PublicApi/docs/Model/PostSearchResult.md | 27 + .../docs/Model/SearchGroups200Response.md | 15 + .../docs/Model/SearchUserPosts200Response.md | 16 + .../TrashNothing/PublicApi/docs/Model/User.md | 18 + .../PublicApi/docs/Model/UserFeedback.md | 11 + .../TrashNothing/PublicApi/git_push.sh | 57 + .../PublicApi/lib/Api/GroupsApi.php | 1183 +++++++ .../PublicApi/lib/Api/PostsApi.php | 2752 +++++++++++++++++ .../PublicApi/lib/Api/UsersApi.php | 1253 ++++++++ .../PublicApi/lib/ApiException.php | 119 + .../PublicApi/lib/Configuration.php | 588 ++++ .../PublicApi/lib/FormDataProcessor.php | 246 ++ .../PublicApi/lib/HeaderSelector.php | 273 ++ .../PublicApi/lib/Model/Feedback.php | 579 ++++ .../lib/Model/GetAllPosts200Response.php | 409 +++ .../Model/GetAllPostsChanges200Response.php | 409 +++ ...AllPostsChanges200ResponseChangesInner.php | 511 +++ .../GetPostAndRelatedData200Response.php | 749 +++++ .../lib/Model/GetPostsByIds200Response.php | 477 +++ .../lib/Model/GetUserPosts200Response.php | 681 ++++ .../PublicApi/lib/Model/Group.php | 852 +++++ .../PublicApi/lib/Model/GroupCountry.php | 444 +++ .../PublicApi/lib/Model/GroupMembership.php | 478 +++ .../Model/GroupMembershipQuestionnaire.php | 444 +++ .../PublicApi/lib/Model/GroupRegion.php | 444 +++ .../PublicApi/lib/Model/ModelInterface.php | 111 + .../PublicApi/lib/Model/Photo.php | 579 ++++ .../PublicApi/lib/Model/PhotoImagesInner.php | 477 +++ .../TrashNothing/PublicApi/lib/Model/Post.php | 954 ++++++ .../PublicApi/lib/Model/PostSearchResult.php | 1021 ++++++ .../lib/Model/SearchGroups200Response.php | 613 ++++ .../lib/Model/SearchUserPosts200Response.php | 647 ++++ .../TrashNothing/PublicApi/lib/Model/User.php | 715 +++++ .../PublicApi/lib/Model/UserFeedback.php | 493 +++ .../PublicApi/lib/ObjectSerializer.php | 603 ++++ .../TrashNothing/PublicApi/phpunit.xml.dist | 18 + .../PublicApi/test/Api/GroupsApiTest.php | 109 + .../PublicApi/test/Api/PostsApiTest.php | 157 + .../PublicApi/test/Api/UsersApiTest.php | 97 + .../PublicApi/test/Model/FeedbackTest.php | 135 + .../test/Model/GetAllPosts200ResponseTest.php | 90 + ...ostsChanges200ResponseChangesInnerTest.php | 117 + .../GetAllPostsChanges200ResponseTest.php | 90 + .../GetPostAndRelatedData200ResponseTest.php | 180 ++ .../Model/GetPostsByIds200ResponseTest.php | 108 + .../Model/GetUserPosts200ResponseTest.php | 162 + .../PublicApi/test/Model/GroupCountryTest.php | 99 + .../GroupMembershipQuestionnaireTest.php | 99 + .../test/Model/GroupMembershipTest.php | 108 + .../PublicApi/test/Model/GroupRegionTest.php | 99 + .../PublicApi/test/Model/GroupTest.php | 207 ++ .../test/Model/PhotoImagesInnerTest.php | 108 + .../PublicApi/test/Model/PhotoTest.php | 135 + .../test/Model/PostSearchResultTest.php | 252 ++ .../PublicApi/test/Model/PostTest.php | 234 ++ .../Model/SearchGroups200ResponseTest.php | 144 + .../Model/SearchUserPosts200ResponseTest.php | 153 + .../PublicApi/test/Model/UserFeedbackTest.php | 108 + .../PublicApi/test/Model/UserTest.php | 171 + 85 files changed, 23900 insertions(+) create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/.gitignore create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/.openapi-generator-ignore create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/.openapi-generator/FILES create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/.openapi-generator/VERSION create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/.php-cs-fixer.dist.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/.travis.yml create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/README.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/composer.json create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Api/GroupsApi.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Api/PostsApi.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Api/UsersApi.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Feedback.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetAllPosts200Response.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetAllPostsChanges200Response.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetAllPostsChanges200ResponseChangesInner.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetPostAndRelatedData200Response.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetPostsByIds200Response.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetUserPosts200Response.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Group.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupCountry.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupMembership.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupMembershipQuestionnaire.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupRegion.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Photo.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/PhotoImagesInner.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Post.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/PostSearchResult.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/SearchGroups200Response.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/SearchUserPosts200Response.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/User.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/UserFeedback.md create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/git_push.sh create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Api/GroupsApi.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Api/PostsApi.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Api/UsersApi.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/ApiException.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Configuration.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/FormDataProcessor.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/HeaderSelector.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/Feedback.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetAllPosts200Response.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetAllPostsChanges200Response.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetAllPostsChanges200ResponseChangesInner.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetPostAndRelatedData200Response.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetPostsByIds200Response.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetUserPosts200Response.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/Group.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupCountry.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupMembership.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupMembershipQuestionnaire.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupRegion.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/ModelInterface.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/Photo.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/PhotoImagesInner.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/Post.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/PostSearchResult.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/SearchGroups200Response.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/SearchUserPosts200Response.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/User.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/UserFeedback.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/lib/ObjectSerializer.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/phpunit.xml.dist create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Api/GroupsApiTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Api/PostsApiTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Api/UsersApiTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/FeedbackTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/GetAllPosts200ResponseTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/GetAllPostsChanges200ResponseChangesInnerTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/GetAllPostsChanges200ResponseTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/GetPostAndRelatedData200ResponseTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/GetPostsByIds200ResponseTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/GetUserPosts200ResponseTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/GroupCountryTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/GroupMembershipQuestionnaireTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/GroupMembershipTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/GroupRegionTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/GroupTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/PhotoImagesInnerTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/PhotoTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/PostSearchResultTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/PostTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/SearchGroups200ResponseTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/SearchUserPosts200ResponseTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/UserFeedbackTest.php create mode 100644 iznik-batch/app/Services/TrashNothing/PublicApi/test/Model/UserTest.php diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/.gitignore b/iznik-batch/app/Services/TrashNothing/PublicApi/.gitignore new file mode 100644 index 0000000000..9f1681c2be --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/.gitignore @@ -0,0 +1,15 @@ +# ref: https://github.com/github/gitignore/blob/master/Composer.gitignore + +composer.phar +/vendor/ + +# Commit your application's lock file https://getcomposer.org/doc/01-basic-usage.md#commit-your-composer-lock-file-to-version-control +# You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file +# composer.lock + +# php-cs-fixer cache +.php_cs.cache +.php-cs-fixer.cache + +# PHPUnit cache +.phpunit.result.cache diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/.openapi-generator-ignore b/iznik-batch/app/Services/TrashNothing/PublicApi/.openapi-generator-ignore new file mode 100644 index 0000000000..7484ee590a --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/.openapi-generator/FILES b/iznik-batch/app/Services/TrashNothing/PublicApi/.openapi-generator/FILES new file mode 100644 index 0000000000..847fb185f3 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/.openapi-generator/FILES @@ -0,0 +1,83 @@ +.gitignore +.openapi-generator-ignore +.php-cs-fixer.dist.php +.travis.yml +README.md +composer.json +docs/Api/GroupsApi.md +docs/Api/PostsApi.md +docs/Api/UsersApi.md +docs/Model/Feedback.md +docs/Model/GetAllPosts200Response.md +docs/Model/GetAllPostsChanges200Response.md +docs/Model/GetAllPostsChanges200ResponseChangesInner.md +docs/Model/GetPostAndRelatedData200Response.md +docs/Model/GetPostsByIds200Response.md +docs/Model/GetUserPosts200Response.md +docs/Model/Group.md +docs/Model/GroupCountry.md +docs/Model/GroupMembership.md +docs/Model/GroupMembershipQuestionnaire.md +docs/Model/GroupRegion.md +docs/Model/Photo.md +docs/Model/PhotoImagesInner.md +docs/Model/Post.md +docs/Model/PostSearchResult.md +docs/Model/SearchGroups200Response.md +docs/Model/SearchUserPosts200Response.md +docs/Model/User.md +docs/Model/UserFeedback.md +git_push.sh +lib/Api/GroupsApi.php +lib/Api/PostsApi.php +lib/Api/UsersApi.php +lib/ApiException.php +lib/Configuration.php +lib/FormDataProcessor.php +lib/HeaderSelector.php +lib/Model/Feedback.php +lib/Model/GetAllPosts200Response.php +lib/Model/GetAllPostsChanges200Response.php +lib/Model/GetAllPostsChanges200ResponseChangesInner.php +lib/Model/GetPostAndRelatedData200Response.php +lib/Model/GetPostsByIds200Response.php +lib/Model/GetUserPosts200Response.php +lib/Model/Group.php +lib/Model/GroupCountry.php +lib/Model/GroupMembership.php +lib/Model/GroupMembershipQuestionnaire.php +lib/Model/GroupRegion.php +lib/Model/ModelInterface.php +lib/Model/Photo.php +lib/Model/PhotoImagesInner.php +lib/Model/Post.php +lib/Model/PostSearchResult.php +lib/Model/SearchGroups200Response.php +lib/Model/SearchUserPosts200Response.php +lib/Model/User.php +lib/Model/UserFeedback.php +lib/ObjectSerializer.php +phpunit.xml.dist +test/Api/GroupsApiTest.php +test/Api/PostsApiTest.php +test/Api/UsersApiTest.php +test/Model/FeedbackTest.php +test/Model/GetAllPosts200ResponseTest.php +test/Model/GetAllPostsChanges200ResponseChangesInnerTest.php +test/Model/GetAllPostsChanges200ResponseTest.php +test/Model/GetPostAndRelatedData200ResponseTest.php +test/Model/GetPostsByIds200ResponseTest.php +test/Model/GetUserPosts200ResponseTest.php +test/Model/GroupCountryTest.php +test/Model/GroupMembershipQuestionnaireTest.php +test/Model/GroupMembershipTest.php +test/Model/GroupRegionTest.php +test/Model/GroupTest.php +test/Model/PhotoImagesInnerTest.php +test/Model/PhotoTest.php +test/Model/PostSearchResultTest.php +test/Model/PostTest.php +test/Model/SearchGroups200ResponseTest.php +test/Model/SearchUserPosts200ResponseTest.php +test/Model/UserFeedbackTest.php +test/Model/UserTest.php diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/.openapi-generator/VERSION b/iznik-batch/app/Services/TrashNothing/PublicApi/.openapi-generator/VERSION new file mode 100644 index 0000000000..ca7bf6e468 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.23.0-SNAPSHOT diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/.php-cs-fixer.dist.php b/iznik-batch/app/Services/TrashNothing/PublicApi/.php-cs-fixer.dist.php new file mode 100644 index 0000000000..af9cf39fdd --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/.php-cs-fixer.dist.php @@ -0,0 +1,29 @@ +in(__DIR__) + ->exclude('vendor') + ->exclude('test') + ->exclude('tests') +; + +$config = new PhpCsFixer\Config(); +return $config->setRules([ + '@PSR12' => true, + 'phpdoc_order' => true, + 'array_syntax' => [ 'syntax' => 'short' ], + 'strict_comparison' => true, + 'strict_param' => true, + 'no_trailing_whitespace' => false, + 'no_trailing_whitespace_in_comment' => false, + 'braces' => false, + 'single_blank_line_at_eof' => false, + 'blank_line_after_namespace' => false, + 'no_leading_import_slash' => false, + ]) + ->setFinder($finder) +; diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/.travis.yml b/iznik-batch/app/Services/TrashNothing/PublicApi/.travis.yml new file mode 100644 index 0000000000..667b815653 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/.travis.yml @@ -0,0 +1,8 @@ +language: php +# Bionic environment has preinstalled PHP from 7.1 to 7.4 +# https://docs.travis-ci.com/user/reference/bionic/#php-support +dist: bionic +php: + - 7.4 +before_install: "composer install" +script: "vendor/bin/phpunit" diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/README.md b/iznik-batch/app/Services/TrashNothing/PublicApi/README.md new file mode 100644 index 0000000000..665278b9d8 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/README.md @@ -0,0 +1,152 @@ +# OpenAPIClient-php + +This is the REST API for [trashnothing.com](https://trashnothing.com). + +To learn more about the API or to register your app for use with the API +visit the [Trash Nothing Developer page](https://trashnothing.com/app/developer). + +NOTE: All date-time values are [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) +and are in [ISO 8601 format](https://en.wikipedia.org/wiki/ISO_8601) (eg. 2019-02-03T01:23:53). + + + +## Installation & Usage + +### Requirements + +PHP 8.1 and later. + +### Composer + +To install the bindings via [Composer](https://getcomposer.org/), add the following to `composer.json`: + +```json +{ + "repositories": [ + { + "type": "vcs", + "url": "https://github.com/GIT_USER_ID/GIT_REPO_ID.git" + } + ], + "require": { + "GIT_USER_ID/GIT_REPO_ID": "*@dev" + } +} +``` + +Then run `composer install` + +### Manual Installation + +Download the files and include `autoload.php`: + +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + + +$apiInstance = new OpenAPI\Client\Api\GroupsApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$group_id = 'group_id_example'; // string | The ID of the group to retrieve. + +try { + $result = $apiInstance->getGroup($group_id); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling GroupsApi->getGroup: ', $e->getMessage(), PHP_EOL; +} + +``` + +## API Endpoints + +All URIs are relative to *https://trashnothing.com/api/v1.4* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*GroupsApi* | [**getGroup**](docs/Api/GroupsApi.md#getgroup) | **GET** /groups/{group_id} | Retrieve a group +*GroupsApi* | [**getGroupsByIds**](docs/Api/GroupsApi.md#getgroupsbyids) | **GET** /groups/multiple | Retrieve multiple groups +*GroupsApi* | [**searchGroups**](docs/Api/GroupsApi.md#searchgroups) | **GET** /groups | Search groups +*PostsApi* | [**getAllPosts**](docs/Api/PostsApi.md#getallposts) | **GET** /posts/all | List all posts +*PostsApi* | [**getAllPostsChanges**](docs/Api/PostsApi.md#getallpostschanges) | **GET** /posts/all/changes | List all post changes +*PostsApi* | [**getPost**](docs/Api/PostsApi.md#getpost) | **GET** /posts/{post_id} | Retrieve a post +*PostsApi* | [**getPostAndRelatedData**](docs/Api/PostsApi.md#getpostandrelateddata) | **GET** /posts/{post_id}/display | Retrieve post display data +*PostsApi* | [**getPosts**](docs/Api/PostsApi.md#getposts) | **GET** /posts | List posts +*PostsApi* | [**getPostsByIds**](docs/Api/PostsApi.md#getpostsbyids) | **GET** /posts/multiple | Retrieve multiple posts +*PostsApi* | [**searchPosts**](docs/Api/PostsApi.md#searchposts) | **GET** /posts/search | Search posts +*UsersApi* | [**getUserPosts**](docs/Api/UsersApi.md#getuserposts) | **GET** /users/{user_id}/posts | List posts by a user +*UsersApi* | [**searchUserPosts**](docs/Api/UsersApi.md#searchuserposts) | **GET** /users/{user_id}/posts/search | Search posts by a user + +## Models + +- [Feedback](docs/Model/Feedback.md) +- [GetAllPosts200Response](docs/Model/GetAllPosts200Response.md) +- [GetAllPostsChanges200Response](docs/Model/GetAllPostsChanges200Response.md) +- [GetAllPostsChanges200ResponseChangesInner](docs/Model/GetAllPostsChanges200ResponseChangesInner.md) +- [GetPostAndRelatedData200Response](docs/Model/GetPostAndRelatedData200Response.md) +- [GetPostsByIds200Response](docs/Model/GetPostsByIds200Response.md) +- [GetUserPosts200Response](docs/Model/GetUserPosts200Response.md) +- [Group](docs/Model/Group.md) +- [GroupCountry](docs/Model/GroupCountry.md) +- [GroupMembership](docs/Model/GroupMembership.md) +- [GroupMembershipQuestionnaire](docs/Model/GroupMembershipQuestionnaire.md) +- [GroupRegion](docs/Model/GroupRegion.md) +- [Photo](docs/Model/Photo.md) +- [PhotoImagesInner](docs/Model/PhotoImagesInner.md) +- [Post](docs/Model/Post.md) +- [PostSearchResult](docs/Model/PostSearchResult.md) +- [SearchGroups200Response](docs/Model/SearchGroups200Response.md) +- [SearchUserPosts200Response](docs/Model/SearchUserPosts200Response.md) +- [User](docs/Model/User.md) +- [UserFeedback](docs/Model/UserFeedback.md) + +## Authorization + +Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: URL query string + + +## Tests + +To run the tests, use: + +```bash +composer install +vendor/bin/phpunit +``` + +## Author + + + +## About this package + +This PHP package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: `1.4` + - Generator version: `7.23.0-SNAPSHOT` +- Build package: `org.openapitools.codegen.languages.PhpClientCodegen` diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/composer.json b/iznik-batch/app/Services/TrashNothing/PublicApi/composer.json new file mode 100644 index 0000000000..a3bc7e3cb3 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/composer.json @@ -0,0 +1,38 @@ +{ + "description": "This is the REST API for [trashnothing.com](https://trashnothing.com). To learn more about the API or to register your app for use with the API visit the [Trash Nothing Developer page](https://trashnothing.com/app/developer). NOTE: All date-time values are [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) and are in [ISO 8601 format](https://en.wikipedia.org/wiki/ISO_8601) (eg. 2019-02-03T01:23:53).", + "keywords": [ + "openapitools", + "openapi-generator", + "openapi", + "php", + "sdk", + "rest", + "api" + ], + "homepage": "https://openapi-generator.tech", + "license": "unlicense", + "authors": [ + { + "name": "OpenAPI", + "homepage": "https://openapi-generator.tech" + } + ], + "require": { + "php": "^8.1", + "ext-curl": "*", + "ext-json": "*", + "ext-mbstring": "*", + "guzzlehttp/guzzle": "^7.3", + "guzzlehttp/psr7": "^1.7 || ^2.0" + }, + "require-dev": { + "phpunit/phpunit": "^8.0 || ^9.0", + "friendsofphp/php-cs-fixer": "^3.5" + }, + "autoload": { + "psr-4": { "OpenAPI\\Client\\" : "lib/" } + }, + "autoload-dev": { + "psr-4": { "OpenAPI\\Client\\Test\\" : "test/" } + } +} diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Api/GroupsApi.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Api/GroupsApi.md new file mode 100644 index 0000000000..49e43da77c --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Api/GroupsApi.md @@ -0,0 +1,212 @@ +# OpenAPI\Client\GroupsApi + +Search, subscribe and unsubscribe to groups. + +All URIs are relative to https://trashnothing.com/api/v1.4, except if the operation defines another base path. + +| Method | HTTP request | Description | +| ------------- | ------------- | ------------- | +| [**getGroup()**](GroupsApi.md#getGroup) | **GET** /groups/{group_id} | Retrieve a group | +| [**getGroupsByIds()**](GroupsApi.md#getGroupsByIds) | **GET** /groups/multiple | Retrieve multiple groups | +| [**searchGroups()**](GroupsApi.md#searchGroups) | **GET** /groups | Search groups | + + +## `getGroup()` + +```php +getGroup($group_id): \OpenAPI\Client\Model\Group +``` + +Retrieve a group + +### Example + +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + + +$apiInstance = new OpenAPI\Client\Api\GroupsApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$group_id = 'group_id_example'; // string | The ID of the group to retrieve. + +try { + $result = $apiInstance->getGroup($group_id); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling GroupsApi->getGroup: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **group_id** | **string**| The ID of the group to retrieve. | | + +### Return type + +[**\OpenAPI\Client\Model\Group**](../Model/Group.md) + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `getGroupsByIds()` + +```php +getGroupsByIds($group_ids, $latitude, $longitude): \OpenAPI\Client\Model\Group[] +``` + +Retrieve multiple groups + +### Example + +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + + +$apiInstance = new OpenAPI\Client\Api\GroupsApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$group_ids = 'group_ids_example'; // string | The IDs of the groups to retrieve. If more than 20 group IDs are passed, only the first 20 groups will be returned. +$latitude = 3.4; // float | If latitude and longitude are passed, each group returned will have a supported_point boolean property indicating whether the group supports the point. +$longitude = 3.4; // float | If latitude and longitude are passed, each group returned will have a supported_point boolean property indicating whether the group supports the point. + +try { + $result = $apiInstance->getGroupsByIds($group_ids, $latitude, $longitude); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling GroupsApi->getGroupsByIds: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **group_ids** | **string**| The IDs of the groups to retrieve. If more than 20 group IDs are passed, only the first 20 groups will be returned. | | +| **latitude** | **float**| If latitude and longitude are passed, each group returned will have a supported_point boolean property indicating whether the group supports the point. | [optional] | +| **longitude** | **float**| If latitude and longitude are passed, each group returned will have a supported_point boolean property indicating whether the group supports the point. | [optional] | + +### Return type + +[**\OpenAPI\Client\Model\Group[]**](../Model/Group.md) + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `searchGroups()` + +```php +searchGroups($name, $latitude, $longitude, $distance, $country, $region, $postal_code, $page, $per_page): \OpenAPI\Client\Model\SearchGroups200Response +``` + +Search groups + +### Example + +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + + +$apiInstance = new OpenAPI\Client\Api\GroupsApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$name = 'name_example'; // string | Find groups that have the given text somewhere in their name (case insensitive). +$latitude = 3.4; // float | Find groups near the given latitude and longitude. +$longitude = 3.4; // float | Find groups near the given latitude and longitude. +$distance = 100.0; // float | When latitude and longitude are passed, distance can optionally be passed to only return groups within a certain distance (in kilometers) from the point specified by the latitude and longitude. The distance must be > 0 and <= 150 and will default to 100. +$country = 'country_example'; // string | Find groups in the given country where country is a 2 letter country code for the country (see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ). +$region = 'region_example'; // string | For countries with regions (AU, CA, GB, US), search groups in a specific region as specified by the region abbreviation. The supported regions and their abbreviations are listed below.

NOTE: The region and postal_code parameters cannot be used at the same time and if both are passed then the postal_code will take priority.

---

**AU**
- QLD: Queensland
- SA: South Australia
- TAS: Tasmania
- VIC: Victoria
- WA: Western Australia
- NT: Northern Territory
- NSW: New South Wales - ACT

**CA**
- AB: Alberta
- BC: British Columbia
- MB: Manitoba
- NB: New Brunswick
- NL: Newfoundland and Labrador
- NS: Nova Scotia
- ON: Ontario
- QC: Quebec
- SK: Saskatchewan
- PE: Prince Edward Island

**GB**
- E: East
- EM: East Midlands
- LDN: London
- NE: North East
- NW: North West
- NI: Northern Ireland
- SC: Scotland
- SE: South East
- SW: South West
- WA: Wales
- WM: West Midlands
- YH: Yorkshire and the Humber

**US**
All 50 states and the District of Columbia are supported. For the abbreviations, see: https://github.com/jasonong/List-of-US-States/blob/master/states.csv +$postal_code = 'postal_code_example'; // string | Find groups in the given postal code. Only a few countries support postal code searches (US, CA, AU, GB). The country parameter must be passed when the postal_code parameter is set.

NOTE: The region and postal_code parameters cannot be used at the same time and if both are passed then the postal_code will take priority. +$page = 1; // int | The page of groups to return. +$per_page = 20; // int | The number of groups to return per page (must be >= 1 and <= 100). + +try { + $result = $apiInstance->searchGroups($name, $latitude, $longitude, $distance, $country, $region, $postal_code, $page, $per_page); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling GroupsApi->searchGroups: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **name** | **string**| Find groups that have the given text somewhere in their name (case insensitive). | [optional] | +| **latitude** | **float**| Find groups near the given latitude and longitude. | [optional] | +| **longitude** | **float**| Find groups near the given latitude and longitude. | [optional] | +| **distance** | **float**| When latitude and longitude are passed, distance can optionally be passed to only return groups within a certain distance (in kilometers) from the point specified by the latitude and longitude. The distance must be > 0 and <= 150 and will default to 100. | [optional] [default to 100.0] | +| **country** | **string**| Find groups in the given country where country is a 2 letter country code for the country (see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ). | [optional] | +| **region** | **string**| For countries with regions (AU, CA, GB, US), search groups in a specific region as specified by the region abbreviation. The supported regions and their abbreviations are listed below. <br /><br /> NOTE: The region and postal_code parameters cannot be used at the same time and if both are passed then the postal_code will take priority. <br /><br /> --- <br /><br /> **AU**<br /> - QLD: Queensland<br /> - SA: South Australia<br /> - TAS: Tasmania<br /> - VIC: Victoria<br /> - WA: Western Australia<br /> - NT: Northern Territory<br /> - NSW: New South Wales - ACT<br /> <br /> **CA**<br /> - AB: Alberta<br /> - BC: British Columbia<br /> - MB: Manitoba<br /> - NB: New Brunswick<br /> - NL: Newfoundland and Labrador<br /> - NS: Nova Scotia<br /> - ON: Ontario<br /> - QC: Quebec<br /> - SK: Saskatchewan<br /> - PE: Prince Edward Island<br /> <br /> **GB**<br /> - E: East<br /> - EM: East Midlands<br /> - LDN: London<br /> - NE: North East<br /> - NW: North West<br /> - NI: Northern Ireland<br /> - SC: Scotland<br /> - SE: South East<br /> - SW: South West<br /> - WA: Wales<br /> - WM: West Midlands<br /> - YH: Yorkshire and the Humber<br /> <br /> **US**<br /> All 50 states and the District of Columbia are supported. For the abbreviations, see: https://github.com/jasonong/List-of-US-States/blob/master/states.csv | [optional] | +| **postal_code** | **string**| Find groups in the given postal code. Only a few countries support postal code searches (US, CA, AU, GB). The country parameter must be passed when the postal_code parameter is set. <br /><br /> NOTE: The region and postal_code parameters cannot be used at the same time and if both are passed then the postal_code will take priority. | [optional] | +| **page** | **int**| The page of groups to return. | [optional] [default to 1] | +| **per_page** | **int**| The number of groups to return per page (must be >= 1 and <= 100). | [optional] [default to 20] | + +### Return type + +[**\OpenAPI\Client\Model\SearchGroups200Response**](../Model/SearchGroups200Response.md) + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Api/PostsApi.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Api/PostsApi.md new file mode 100644 index 0000000000..ba06f073cb --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Api/PostsApi.md @@ -0,0 +1,516 @@ +# OpenAPI\Client\PostsApi + +Retrieve and update posts. + +All URIs are relative to https://trashnothing.com/api/v1.4, except if the operation defines another base path. + +| Method | HTTP request | Description | +| ------------- | ------------- | ------------- | +| [**getAllPosts()**](PostsApi.md#getAllPosts) | **GET** /posts/all | List all posts | +| [**getAllPostsChanges()**](PostsApi.md#getAllPostsChanges) | **GET** /posts/all/changes | List all post changes | +| [**getPost()**](PostsApi.md#getPost) | **GET** /posts/{post_id} | Retrieve a post | +| [**getPostAndRelatedData()**](PostsApi.md#getPostAndRelatedData) | **GET** /posts/{post_id}/display | Retrieve post display data | +| [**getPosts()**](PostsApi.md#getPosts) | **GET** /posts | List posts | +| [**getPostsByIds()**](PostsApi.md#getPostsByIds) | **GET** /posts/multiple | Retrieve multiple posts | +| [**searchPosts()**](PostsApi.md#searchPosts) | **GET** /posts/search | Search posts | + + +## `getAllPosts()` + +```php +getAllPosts($types, $date_min, $date_max, $per_page, $page, $device_pixel_ratio): \OpenAPI\Client\Model\GetAllPosts200Response +``` + +List all posts + +This endpoint provides an easy way to get a feed of all the publicly published posts on Trash Nothing. It provides access to all publicly published offer and wanted posts from the last 30 days. The posts are sorted by date (newest first).

There are fewer options for filtering, sorting and searching posts with this endpoint but there is no 1,000 post limit and posts that are crossposted to multiple groups are not merged together in the response. In most cases, crossposted posts are easy to detect because they have the same user_id, title and content. + +### Example + +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + + +$apiInstance = new OpenAPI\Client\Api\PostsApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$types = 'types_example'; // string | A comma separated list of the post types to return. The available post types are: offer, wanted +$date_min = new \DateTime('2013-10-20T19:20:30+01:00'); // \DateTime | Only posts newer than or equal to this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_max. And the date and time must be within the last 30 days. And the date and time must be rounded to the nearest second. +$date_max = new \DateTime('2013-10-20T19:20:30+01:00'); // \DateTime | Only posts older than this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_min. And the date and time must be rounded to the nearest second. +$per_page = 20; // int | The number of posts to return per page (must be >= 1 and <= 50). +$page = 1; // int | The page of posts to return. +$device_pixel_ratio = 1.0; // float | Client device pixel ratio used to determine thumbnail size (default 1.0). + +try { + $result = $apiInstance->getAllPosts($types, $date_min, $date_max, $per_page, $page, $device_pixel_ratio); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PostsApi->getAllPosts: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **types** | **string**| A comma separated list of the post types to return. The available post types are: offer, wanted | | +| **date_min** | **\DateTime**| Only posts newer than or equal to this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_max. And the date and time must be within the last 30 days. And the date and time must be rounded to the nearest second. | | +| **date_max** | **\DateTime**| Only posts older than this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_min. And the date and time must be rounded to the nearest second. | | +| **per_page** | **int**| The number of posts to return per page (must be >= 1 and <= 50). | [optional] [default to 20] | +| **page** | **int**| The page of posts to return. | [optional] [default to 1] | +| **device_pixel_ratio** | **float**| Client device pixel ratio used to determine thumbnail size (default 1.0). | [optional] [default to 1.0] | + +### Return type + +[**\OpenAPI\Client\Model\GetAllPosts200Response**](../Model/GetAllPosts200Response.md) + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `getAllPostsChanges()` + +```php +getAllPostsChanges($date_min, $date_max, $per_page, $page): \OpenAPI\Client\Model\GetAllPostsChanges200Response +``` + +List all post changes + +This endpoint provides an easy way to get a feed of all the changes that have been made to publicly published posts on Trash Nothing. Similar to the /posts/all endpoint, only data from the last 30 days is available and the changes are sorted by date (newest first). Every change includes the date of the change, the post_id of the post that was changed and the type of change.

The different types of changes that are returned are listed below.

- published
- deleted
- undeleted
- satisfied
- promised
- unpromised
- withdrawn
- edited

For published and edited changes, clients can use the retrieve post API endpoint to get the edits that have been made to the post. + +### Example + +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + + +$apiInstance = new OpenAPI\Client\Api\PostsApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$date_min = new \DateTime('2013-10-20T19:20:30+01:00'); // \DateTime | Only changes newer than or equal to this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_max. And the date and time must be within the last 30 days. And the date and time must be rounded to the nearest second. +$date_max = new \DateTime('2013-10-20T19:20:30+01:00'); // \DateTime | Only changes older than this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_min. And the date and time must be rounded to the nearest second. +$per_page = 20; // int | The number of changes to return per page (must be >= 1 and <= 50). +$page = 1; // int | The page of changes to return. + +try { + $result = $apiInstance->getAllPostsChanges($date_min, $date_max, $per_page, $page); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PostsApi->getAllPostsChanges: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **date_min** | **\DateTime**| Only changes newer than or equal to this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_max. And the date and time must be within the last 30 days. And the date and time must be rounded to the nearest second. | | +| **date_max** | **\DateTime**| Only changes older than this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_min. And the date and time must be rounded to the nearest second. | | +| **per_page** | **int**| The number of changes to return per page (must be >= 1 and <= 50). | [optional] [default to 20] | +| **page** | **int**| The page of changes to return. | [optional] [default to 1] | + +### Return type + +[**\OpenAPI\Client\Model\GetAllPostsChanges200Response**](../Model/GetAllPostsChanges200Response.md) + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `getPost()` + +```php +getPost($post_id): \OpenAPI\Client\Model\Post +``` + +Retrieve a post + +### Example + +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + + +$apiInstance = new OpenAPI\Client\Api\PostsApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$post_id = 'post_id_example'; // string | The ID of the post to retrieve. + +try { + $result = $apiInstance->getPost($post_id); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PostsApi->getPost: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **post_id** | **string**| The ID of the post to retrieve. | | + +### Return type + +[**\OpenAPI\Client\Model\Post**](../Model/Post.md) + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `getPostAndRelatedData()` + +```php +getPostAndRelatedData($post_id): \OpenAPI\Client\Model\GetPostAndRelatedData200Response +``` + +Retrieve post display data + +Retrieve a post and other data related to the post that is useful for displaying the post such as data about the user who posted the post and the groups the post was posted on. + +### Example + +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + + +$apiInstance = new OpenAPI\Client\Api\PostsApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$post_id = 'post_id_example'; // string | The ID of the post to retrieve. + +try { + $result = $apiInstance->getPostAndRelatedData($post_id); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PostsApi->getPostAndRelatedData: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **post_id** | **string**| The ID of the post to retrieve. | | + +### Return type + +[**\OpenAPI\Client\Model\GetPostAndRelatedData200Response**](../Model/GetPostAndRelatedData200Response.md) + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `getPosts()` + +```php +getPosts($types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts): \OpenAPI\Client\Model\GetUserPosts200Response +``` + +List posts + +NOTE: When paging through the posts returned by this endpoint, there will be at most 1,000 posts that can be returned (eg. 50 pages worth of posts with the default per_page value of 20). In areas where there are more than 1,000 posts, clients can use more specific query parameters to adjust which posts are returned. NOTE: Passing the latitude, longitude and radius parameters filters all posts by their location and so these parameters will temporarily override the current users' location preferences. When latitude, longitude and radius are not specified, public posts will be filtered by the current users' location preferences. + +### Example + +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + + +$apiInstance = new OpenAPI\Client\Api\PostsApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$types = 'types_example'; // string | A comma separated list of the post types to return. The available post types are: offer, wanted, admin +$sources = 'sources_example'; // string | A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or the current users' location if latitude, longitude and radius aren't passed).

NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. +$sort_by = 'date'; // string | How to sort the posts that are returned. One of: date, active, distance

Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. +$group_ids = 'The group IDs of every group the current user is a member of.'; // string | A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*).

NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*).

*To determine which group IDs were used and which were discarded, use the group_ids field in the response. +$per_page = 20; // int | The number of posts to return per page (must be >= 1 and <= 100). +$page = 1; // int | The page of posts to return. +$device_pixel_ratio = 1.0; // float | Client device pixel ratio used to determine thumbnail size (default 1.0). +$latitude = 3.4; // float | The latitude of a point around which to return posts. +$longitude = 3.4; // float | The longitude of a point around which to return posts. +$radius = 3.4; // float | The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. +$date_min = new \DateTime('2013-10-20T19:20:30+01:00'); // \DateTime | Only posts newer than or equal to this UTC date and time will be returned. If unset, defaults to the current date and time minus 90 days. +$date_max = new \DateTime('2013-10-20T19:20:30+01:00'); // \DateTime | Only posts older than this UTC date and time will be returned. If unset, defaults to the current date and time. +$outcomes = 'outcomes_example'; // string | A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn

There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. +$include_reposts = 1; // int | If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. + +try { + $result = $apiInstance->getPosts($types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PostsApi->getPosts: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **types** | **string**| A comma separated list of the post types to return. The available post types are: offer, wanted, admin | | +| **sources** | **string**| A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or the current users' location if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. | | +| **sort_by** | **string**| How to sort the posts that are returned. One of: date, active, distance <br /><br /> Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. | [optional] [default to 'date'] | +| **group_ids** | **string**| A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. | [optional] [default to 'The group IDs of every group the current user is a member of.'] | +| **per_page** | **int**| The number of posts to return per page (must be >= 1 and <= 100). | [optional] [default to 20] | +| **page** | **int**| The page of posts to return. | [optional] [default to 1] | +| **device_pixel_ratio** | **float**| Client device pixel ratio used to determine thumbnail size (default 1.0). | [optional] [default to 1.0] | +| **latitude** | **float**| The latitude of a point around which to return posts. | [optional] | +| **longitude** | **float**| The longitude of a point around which to return posts. | [optional] | +| **radius** | **float**| The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. | [optional] | +| **date_min** | **\DateTime**| Only posts newer than or equal to this UTC date and time will be returned. If unset, defaults to the current date and time minus 90 days. | [optional] | +| **date_max** | **\DateTime**| Only posts older than this UTC date and time will be returned. If unset, defaults to the current date and time. | [optional] | +| **outcomes** | **string**| A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. | [optional] | +| **include_reposts** | **int**| If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. | [optional] [default to 1] | + +### Return type + +[**\OpenAPI\Client\Model\GetUserPosts200Response**](../Model/GetUserPosts200Response.md) + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `getPostsByIds()` + +```php +getPostsByIds($post_ids): \OpenAPI\Client\Model\GetPostsByIds200Response +``` + +Retrieve multiple posts + +### Example + +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + + +$apiInstance = new OpenAPI\Client\Api\PostsApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$post_ids = 'post_ids_example'; // string | A comma separated list of the post IDs. If more than 10 post IDs are passed, only the first 10 posts will be returned. + +try { + $result = $apiInstance->getPostsByIds($post_ids); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PostsApi->getPostsByIds: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **post_ids** | **string**| A comma separated list of the post IDs. If more than 10 post IDs are passed, only the first 10 posts will be returned. | | + +### Return type + +[**\OpenAPI\Client\Model\GetPostsByIds200Response**](../Model/GetPostsByIds200Response.md) + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `searchPosts()` + +```php +searchPosts($search, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts): \OpenAPI\Client\Model\SearchUserPosts200Response +``` + +Search posts + +Searching posts takes the same arguments as listing posts except for the addition of the search and sort_by parameters. NOTE: When paging through the posts returned by this endpoint, there will be at most 1,000 posts that can be returned (eg. 50 pages worth of posts with the default per_page value of 20). In areas where there are more than 1,000 posts, clients can use more specific query parameters to adjust which posts are returned. + +### Example + +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + + +$apiInstance = new OpenAPI\Client\Api\PostsApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$search = 'search_example'; // string | The search query used to find posts. +$types = 'types_example'; // string | A comma separated list of the post types to return. The available post types are: offer, wanted, admin +$sources = 'sources_example'; // string | A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or the current users' location if latitude, longitude and radius aren't passed).

NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. +$sort_by = 'relevance'; // string | How to sort the posts that are returned. One of: relevance, date, active, distance

Relevance sorting will sort the posts that best match the search query first. Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. +$group_ids = 'The group IDs of every group the current user is a member of.'; // string | A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*).

NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*).

*To determine which group IDs were used and which were discarded, use the group_ids field in the response. +$per_page = 20; // int | The number of posts to return per page (must be >= 1 and <= 100). +$page = 1; // int | The page of posts to return. +$device_pixel_ratio = 1.0; // float | Client device pixel ratio used to determine thumbnail size (default 1.0). +$latitude = 3.4; // float | The latitude of a point around which to return posts. +$longitude = 3.4; // float | The longitude of a point around which to return posts. +$radius = 3.4; // float | The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. +$date_min = new \DateTime('2013-10-20T19:20:30+01:00'); // \DateTime | Only posts newer than or equal to this UTC date and time will be returned. If unset, defaults to the current date and time minus 90 days. +$date_max = new \DateTime('2013-10-20T19:20:30+01:00'); // \DateTime | Only posts older than this UTC date and time will be returned. If unset, defaults to the current date and time. +$outcomes = 'outcomes_example'; // string | A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn

There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. +$include_reposts = 1; // int | If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. + +try { + $result = $apiInstance->searchPosts($search, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling PostsApi->searchPosts: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **search** | **string**| The search query used to find posts. | | +| **types** | **string**| A comma separated list of the post types to return. The available post types are: offer, wanted, admin | | +| **sources** | **string**| A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or the current users' location if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. | | +| **sort_by** | **string**| How to sort the posts that are returned. One of: relevance, date, active, distance <br /><br /> Relevance sorting will sort the posts that best match the search query first. Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. | [optional] [default to 'relevance'] | +| **group_ids** | **string**| A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. | [optional] [default to 'The group IDs of every group the current user is a member of.'] | +| **per_page** | **int**| The number of posts to return per page (must be >= 1 and <= 100). | [optional] [default to 20] | +| **page** | **int**| The page of posts to return. | [optional] [default to 1] | +| **device_pixel_ratio** | **float**| Client device pixel ratio used to determine thumbnail size (default 1.0). | [optional] [default to 1.0] | +| **latitude** | **float**| The latitude of a point around which to return posts. | [optional] | +| **longitude** | **float**| The longitude of a point around which to return posts. | [optional] | +| **radius** | **float**| The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. | [optional] | +| **date_min** | **\DateTime**| Only posts newer than or equal to this UTC date and time will be returned. If unset, defaults to the current date and time minus 90 days. | [optional] | +| **date_max** | **\DateTime**| Only posts older than this UTC date and time will be returned. If unset, defaults to the current date and time. | [optional] | +| **outcomes** | **string**| A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. | [optional] | +| **include_reposts** | **int**| If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. | [optional] [default to 1] | + +### Return type + +[**\OpenAPI\Client\Model\SearchUserPosts200Response**](../Model/SearchUserPosts200Response.md) + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Api/UsersApi.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Api/UsersApi.md new file mode 100644 index 0000000000..f470b9e1ca --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Api/UsersApi.md @@ -0,0 +1,191 @@ +# OpenAPI\Client\UsersApi + +Retrieve and update user data. + +All URIs are relative to https://trashnothing.com/api/v1.4, except if the operation defines another base path. + +| Method | HTTP request | Description | +| ------------- | ------------- | ------------- | +| [**getUserPosts()**](UsersApi.md#getUserPosts) | **GET** /users/{user_id}/posts | List posts by a user | +| [**searchUserPosts()**](UsersApi.md#searchUserPosts) | **GET** /users/{user_id}/posts/search | Search posts by a user | + + +## `getUserPosts()` + +```php +getUserPosts($user_id, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts): \OpenAPI\Client\Model\GetUserPosts200Response +``` + +List posts by a user + +### Example + +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + + +$apiInstance = new OpenAPI\Client\Api\UsersApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$user_id = 'user_id_example'; // string | The user ID of the user whose posts will be retrieved. Using 'me' as the user_id will return the posts for the current user. +$types = 'types_example'; // string | A comma separated list of the post types to return. The available post types are: offer, wanted, admin +$sources = 'sources_example'; // string | A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or all the open archive groups the requested user has posted to if latitude, longitude and radius aren't passed).

NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. +$sort_by = 'date'; // string | How to sort the posts that are returned. One of: date, active, distance

Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. +$group_ids = 'The group IDs of every group the current user is a member of.'; // string | A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*).

NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*).

*To determine which group IDs were used and which were discarded, use the group_ids field in the response. +$per_page = 20; // int | The number of posts to return per page (must be >= 1 and <= 100). +$page = 1; // int | The page of posts to return. +$device_pixel_ratio = 1.0; // float | Client device pixel ratio used to determine thumbnail size (default 1.0). +$latitude = 3.4; // float | The latitude of a point around which to return posts. +$longitude = 3.4; // float | The longitude of a point around which to return posts. +$radius = 3.4; // float | The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. +$date_min = new \DateTime('2013-10-20T19:20:30+01:00'); // \DateTime | Only posts newer than or equal to this UTC date and time will be returned. +$date_max = new \DateTime('2013-10-20T19:20:30+01:00'); // \DateTime | Only posts older than this UTC date and time will be returned. +$outcomes = 'outcomes_example'; // string | A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn

There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. +$include_reposts = 1; // int | If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. + +try { + $result = $apiInstance->getUserPosts($user_id, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling UsersApi->getUserPosts: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **user_id** | **string**| The user ID of the user whose posts will be retrieved. Using 'me' as the user_id will return the posts for the current user. | | +| **types** | **string**| A comma separated list of the post types to return. The available post types are: offer, wanted, admin | | +| **sources** | **string**| A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or all the open archive groups the requested user has posted to if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. | | +| **sort_by** | **string**| How to sort the posts that are returned. One of: date, active, distance <br /><br /> Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. | [optional] [default to 'date'] | +| **group_ids** | **string**| A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. | [optional] [default to 'The group IDs of every group the current user is a member of.'] | +| **per_page** | **int**| The number of posts to return per page (must be >= 1 and <= 100). | [optional] [default to 20] | +| **page** | **int**| The page of posts to return. | [optional] [default to 1] | +| **device_pixel_ratio** | **float**| Client device pixel ratio used to determine thumbnail size (default 1.0). | [optional] [default to 1.0] | +| **latitude** | **float**| The latitude of a point around which to return posts. | [optional] | +| **longitude** | **float**| The longitude of a point around which to return posts. | [optional] | +| **radius** | **float**| The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. | [optional] | +| **date_min** | **\DateTime**| Only posts newer than or equal to this UTC date and time will be returned. | [optional] | +| **date_max** | **\DateTime**| Only posts older than this UTC date and time will be returned. | [optional] | +| **outcomes** | **string**| A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. | [optional] | +| **include_reposts** | **int**| If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. | [optional] [default to 1] | + +### Return type + +[**\OpenAPI\Client\Model\GetUserPosts200Response**](../Model/GetUserPosts200Response.md) + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `searchUserPosts()` + +```php +searchUserPosts($user_id, $search, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts): \OpenAPI\Client\Model\SearchUserPosts200Response +``` + +Search posts by a user + +Searching posts takes the same arguments as listing posts except for the addition of the search and sort_by parameters. + +### Example + +```php +setApiKey('api_key', 'YOUR_API_KEY'); +// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +// $config = OpenAPI\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); + + +$apiInstance = new OpenAPI\Client\Api\UsersApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); +$user_id = 'user_id_example'; // string | The user ID of the user whose posts will be retrieved. Using 'me' as the user_id will return the posts for the current user. +$search = 'search_example'; // string | The search query used to find posts. +$types = 'types_example'; // string | A comma separated list of the post types to return. The available post types are: offer, wanted, admin +$sources = 'sources_example'; // string | A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or all the open archive groups the requested user has posted to if latitude, longitude and radius aren't passed).

NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. +$sort_by = 'relevance'; // string | How to sort the posts that are returned. One of: relevance, date, active, distance

Relevance sorting will sort the posts that best match the search query first. Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. +$group_ids = 'The group IDs of every group the current user is a member of.'; // string | A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*).

NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*).

*To determine which group IDs were used and which were discarded, use the group_ids field in the response. +$per_page = 20; // int | The number of posts to return per page (must be >= 1 and <= 100). +$page = 1; // int | The page of posts to return. +$device_pixel_ratio = 1.0; // float | Client device pixel ratio used to determine thumbnail size (default 1.0). +$latitude = 3.4; // float | The latitude of a point around which to return posts. +$longitude = 3.4; // float | The longitude of a point around which to return posts. +$radius = 3.4; // float | The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. +$date_min = new \DateTime('2013-10-20T19:20:30+01:00'); // \DateTime | Only posts newer than or equal to this UTC date and time will be returned. +$date_max = new \DateTime('2013-10-20T19:20:30+01:00'); // \DateTime | Only posts older than this UTC date and time will be returned. +$outcomes = 'outcomes_example'; // string | A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn

There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. +$include_reposts = 1; // int | If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. + +try { + $result = $apiInstance->searchUserPosts($user_id, $search, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling UsersApi->searchUserPosts: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **user_id** | **string**| The user ID of the user whose posts will be retrieved. Using 'me' as the user_id will return the posts for the current user. | | +| **search** | **string**| The search query used to find posts. | | +| **types** | **string**| A comma separated list of the post types to return. The available post types are: offer, wanted, admin | | +| **sources** | **string**| A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or all the open archive groups the requested user has posted to if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. | | +| **sort_by** | **string**| How to sort the posts that are returned. One of: relevance, date, active, distance <br /><br /> Relevance sorting will sort the posts that best match the search query first. Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. | [optional] [default to 'relevance'] | +| **group_ids** | **string**| A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. | [optional] [default to 'The group IDs of every group the current user is a member of.'] | +| **per_page** | **int**| The number of posts to return per page (must be >= 1 and <= 100). | [optional] [default to 20] | +| **page** | **int**| The page of posts to return. | [optional] [default to 1] | +| **device_pixel_ratio** | **float**| Client device pixel ratio used to determine thumbnail size (default 1.0). | [optional] [default to 1.0] | +| **latitude** | **float**| The latitude of a point around which to return posts. | [optional] | +| **longitude** | **float**| The longitude of a point around which to return posts. | [optional] | +| **radius** | **float**| The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. | [optional] | +| **date_min** | **\DateTime**| Only posts newer than or equal to this UTC date and time will be returned. | [optional] | +| **date_max** | **\DateTime**| Only posts older than this UTC date and time will be returned. | [optional] | +| **outcomes** | **string**| A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. | [optional] | +| **include_reposts** | **int**| If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. | [optional] [default to 1] | + +### Return type + +[**\OpenAPI\Client\Model\SearchUserPosts200Response**](../Model/SearchUserPosts200Response.md) + +### Authorization + +[api_key](../../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Feedback.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Feedback.md new file mode 100644 index 0000000000..b73793a88a --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Feedback.md @@ -0,0 +1,14 @@ +# Feedback + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**feedback_id** | **string** | | [optional] +**user_id** | **string** | The user ID of the user that the feedback is about. | [optional] +**reviewer_user_id** | **string** | The user ID of the user that submitted the feedback. | [optional] +**content** | **string** | A comment written by the reviewer about the user (may be null). | [optional] +**positive** | **bool** | Set to true for positive feedback and false for negative feedback. | [optional] +**date** | **\DateTime** | Date when the feedback was submitted. | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetAllPosts200Response.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetAllPosts200Response.md new file mode 100644 index 0000000000..c1136e4e37 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetAllPosts200Response.md @@ -0,0 +1,9 @@ +# GetAllPosts200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**posts** | [**\OpenAPI\Client\Model\Post[]**](Post.md) | | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetAllPostsChanges200Response.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetAllPostsChanges200Response.md new file mode 100644 index 0000000000..96286c0731 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetAllPostsChanges200Response.md @@ -0,0 +1,9 @@ +# GetAllPostsChanges200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**changes** | [**\OpenAPI\Client\Model\GetAllPostsChanges200ResponseChangesInner[]**](GetAllPostsChanges200ResponseChangesInner.md) | | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetAllPostsChanges200ResponseChangesInner.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetAllPostsChanges200ResponseChangesInner.md new file mode 100644 index 0000000000..97c8a2fb87 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetAllPostsChanges200ResponseChangesInner.md @@ -0,0 +1,12 @@ +# GetAllPostsChanges200ResponseChangesInner + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**change_id** | **int** | The unique ID for this change. This is an auto-incrementing ID that can be used by clients to make sure they have received every change. If a client detects a gap in the change ID (eg. 1, 3, 4 instead of 1,2,3,4) then the client should repoll older changes to get the missing change. | [optional] +**post_id** | **string** | | [optional] +**date** | **\DateTime** | The UTC date and time when the post was changed. | [optional] +**type** | **string** | The type of change. One of: published, deleted, undeleted, satisfied, promised, unpromised, withdrawn, edited, expired | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetPostAndRelatedData200Response.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetPostAndRelatedData200Response.md new file mode 100644 index 0000000000..28150def88 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetPostAndRelatedData200Response.md @@ -0,0 +1,19 @@ +# GetPostAndRelatedData200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**post** | [**\OpenAPI\Client\Model\Post**](Post.md) | | [optional] +**author** | [**\OpenAPI\Client\Model\User**](User.md) | | [optional] +**author_posts** | [**\OpenAPI\Client\Model\Post[]**](Post.md) | Other active posts from the post author in the last 90 days. A maximum of 30 posts will be returned. | [optional] +**author_offer_count** | **int** | Count of offer posts made by the post author in the last 90 days. | [optional] +**author_wanted_count** | **int** | Count of wanted posts made by the post author in the last 90 days. | [optional] +**groups** | [**\OpenAPI\Client\Model\Group[]**](Group.md) | The groups the post is published on. | [optional] +**user_can_reply** | **bool** | Whether or not the current user (if any) can reply to this post. Unverified users cannot reply to posts until they verify their account. | [optional] +**viewed** | **bool** | Whether or not the current user has previously viewed this post. Will be null for api key requests and for the current users' posts. | [optional] +**replied** | **bool** | Whether or not the current user has replied to this post. Will be null for api key requests and for the current users' posts. | [optional] +**bookmarked** | **bool** | Whether or not the current user has bookmarked this post. Will be null for api key requests and for the current users' posts. | [optional] +**hidden** | **bool** | Whether the current user has hidden the post author. | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetPostsByIds200Response.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetPostsByIds200Response.md new file mode 100644 index 0000000000..f430077582 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetPostsByIds200Response.md @@ -0,0 +1,11 @@ +# GetPostsByIds200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**posts** | [**\OpenAPI\Client\Model\Post[]**](Post.md) | | [optional] +**not_found** | **string[]** | The IDs of posts that weren't found (may have been deleted or never existed). | [optional] +**forbidden** | **string[]** | The IDs of posts that are forbidden for the current user. | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetUserPosts200Response.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetUserPosts200Response.md new file mode 100644 index 0000000000..e449eaca8b --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GetUserPosts200Response.md @@ -0,0 +1,17 @@ +# GetUserPosts200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**posts** | [**\OpenAPI\Client\Model\Post[]**](Post.md) | | [optional] +**num_posts** | **int** | The total number of posts available. | [optional] +**page** | **int** | The page number of the posts being returned. | [optional] +**per_page** | **int** | The number of posts being returned per page. | [optional] +**num_pages** | **int** | The total number of pages available. | [optional] +**start_index** | **int** | The index of the first post being returned (an integer between 1 and num_posts). | [optional] +**end_index** | **int** | The index of the last post being returned (an integer between start_index and num_posts). | [optional] +**group_ids** | **string[]** | The IDs of the groups that the posts were retrieved from (will be null when no group IDs were used). These IDs may be a subset of the requested group IDs when a request includes group IDs for groups that are not open archives and that the current user is not a member of. If the open_archive_groups source is used, these IDs may include the IDs of open archive groups that weren't present in the group_ids parameter of the request. | [optional] +**last_listings_view** | **\DateTime** | The UTC date and time when the current user last viewed the newest posts on the All Posts page (may be null). <br /><br /> NOTE: For this to be accurate, clients must update the last_listings_view property of the current user every time the user is shown the newest posts on the All Posts page. <br /><br /> NOTE: For requests using an api key instead of oauth, this field is always null. | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Group.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Group.md new file mode 100644 index 0000000000..03410c5595 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Group.md @@ -0,0 +1,22 @@ +# Group + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**group_id** | **string** | | [optional] +**name** | **string** | The name of the group (not guaranteed to be unique). | [optional] +**identifier** | **string** | A unique identifier for the group that is used in URLs. | [optional] +**homepage** | **string** | A URL to the group homepage. | [optional] +**member_count** | **int** | The number of members who belong to the group. | [optional] +**latitude** | **float** | | [optional] +**longitude** | **float** | | [optional] +**timezone** | **string** | The timezone that the group is in (eg. America/New_York). | [optional] +**open_membership** | **bool** | When true, the group allows anyone to join. When false, the group moderators review and approve applicants. | [optional] +**open_archives** | **bool** | When true, the group posts are viewable by anyone. When false, the group posts can only be viewed by members of the group. | [optional] +**has_questions** | **bool** | When true, anyone requesting membership to this group will be required to answer a new membership questionnaire. | [optional] +**country** | [**\OpenAPI\Client\Model\GroupCountry**](GroupCountry.md) | | [optional] +**region** | [**\OpenAPI\Client\Model\GroupRegion**](GroupRegion.md) | | [optional] +**membership** | [**\OpenAPI\Client\Model\GroupMembership**](GroupMembership.md) | | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupCountry.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupCountry.md new file mode 100644 index 0000000000..6f347fd659 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupCountry.md @@ -0,0 +1,10 @@ +# GroupCountry + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **string** | The name of the country. | [optional] +**abbreviation** | **string** | A 2 letter country code for the country (see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ). | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupMembership.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupMembership.md new file mode 100644 index 0000000000..ad201d9ebb --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupMembership.md @@ -0,0 +1,11 @@ +# GroupMembership + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**status** | **string** | One of: subscribed, pending, pending-questions | [optional] +**date** | **\DateTime** | The UTC date and time when the membership was last updated. | [optional] +**questionnaire** | [**\OpenAPI\Client\Model\GroupMembershipQuestionnaire**](GroupMembershipQuestionnaire.md) | | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupMembershipQuestionnaire.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupMembershipQuestionnaire.md new file mode 100644 index 0000000000..20c8db7215 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupMembershipQuestionnaire.md @@ -0,0 +1,10 @@ +# GroupMembershipQuestionnaire + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**message** | **string** | A message from the group moderators to be displayed above the questions (may be null). | [optional] +**questions** | **string[]** | The list of questions. | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupRegion.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupRegion.md new file mode 100644 index 0000000000..b5533883f4 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/GroupRegion.md @@ -0,0 +1,10 @@ +# GroupRegion + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **string** | The name of the region. | [optional] +**abbreviation** | **string** | A 2 letter abbreviation for the region (is not guaranteed to be globally unique but is unique among all the regions in the country). | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Photo.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Photo.md new file mode 100644 index 0000000000..656a744e71 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Photo.md @@ -0,0 +1,14 @@ +# Photo + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**photo_id** | **string** | | [optional] +**thumbnail** | **string** | A URL to a thumbnail of this photo. The size of the thumbnail depends on the device_pixel_ratio parameter and it is not guaranteed to be square. | [optional] +**url** | **string** | A URL to a large version of this photo (but not necessarily the largest size available). | [optional] +**blurhash** | **string** | A blurhash of the photo that can be used as a placeholder while the photo is loading (see: https://github.com/woltapp/blurhash). May be null if no blurhash is available and the length of the blurhash can vary based on the photo. | [optional] +**avif** | **bool** | Whether avif versions of the image are available. If they are, the avif image can be loaded by changing the extension on any of the image URLs to 'avif'. | [optional] +**images** | [**\OpenAPI\Client\Model\PhotoImagesInner[]**](PhotoImagesInner.md) | All the versions of this photo ordered from smallest to largest. This list is guaranteed to include the photos specified by the above thumbnail and url properties. | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/PhotoImagesInner.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/PhotoImagesInner.md new file mode 100644 index 0000000000..3275d1d7bd --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/PhotoImagesInner.md @@ -0,0 +1,11 @@ +# PhotoImagesInner + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**url** | **string** | | [optional] +**width** | **int** | | [optional] +**height** | **int** | | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Post.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Post.md new file mode 100644 index 0000000000..9465ee65d5 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/Post.md @@ -0,0 +1,25 @@ +# Post + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**post_id** | **string** | | [optional] +**source** | **string** | The source of the post. One of: groups, trashnothing, open_archive_groups. A value of groups or open_archive_groups indicates the post is from a group and the group_id field will contain the ID of the group. A value of trashnothing indicates the post is a public post not associated with any group. | [optional] +**group_id** | **string** | The group ID of the post. For public posts, this is always null. | [optional] +**user_id** | **string** | | [optional] +**title** | **string** | | [optional] +**content** | **string** | | [optional] +**date** | **\DateTime** | The UTC date and time when the post was published. | [optional] +**type** | **string** | The type of post. One of: offer, wanted, admin | [optional] +**outcome** | **string** | For offer and wanted posts, this indicates the outcome of the post which is null if no outcome has been set yet. <br /><br /> Offer post outcomes will be one of: satisfied, withdrawn, promised, expired <br /><br /> Wanted post outcomes will be one of: satisfied, withdrawn, expired <br /><br /> For all other posts, outcome is always null. | [optional] +**latitude** | **float** | May be null if a post hasn't been mapped. | [optional] +**longitude** | **float** | May be null if a post hasn't been mapped. | [optional] +**footer** | **string** | Some groups add footers to posts that are separate and sometimes unrelated to the post itself - such as reminders about group rules or features (may be null). | [optional] +**photos** | [**\OpenAPI\Client\Model\Photo[]**](Photo.md) | Details about the photos associated with this post (may be null if there are no photos). | [optional] +**expiration** | **\DateTime** | The UTC date and time when the post will expire. Currently only offer and wanted posts expire. For all other posts, expiration is always null. | [optional] +**reselling** | **bool** | For wanted posts, whether the item is being requested in order to resell it or not. Will be null for all posts that are not wanted posts and for wanted posts where the poster hasn't indicated whether or not they intend to resell the item they are requesting. | [optional] +**url** | **string** | The link to use to view the post on the Trash Nothing site. | [optional] +**repost_count** | **int** | The count of how many times this post has been reposted in the last 90 days. A value of zero is used to indicate that the post is not a repost. The count is specific to the source of the post (eg. the specific group the post is on). If a post is crossposted to multiple groups, the repost_count of the post on each group may be different for each group depending on how many times the post has been posted on that group in the last 90 days. | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/PostSearchResult.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/PostSearchResult.md new file mode 100644 index 0000000000..c7c138fce2 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/PostSearchResult.md @@ -0,0 +1,27 @@ +# PostSearchResult + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**post_id** | **string** | | [optional] +**source** | **string** | The source of the post. One of: groups, trashnothing, open_archive_groups. A value of groups or open_archive_groups indicates the post is from a group and the group_id field will contain the ID of the group. A value of trashnothing indicates the post is a public post not associated with any group. | [optional] +**group_id** | **string** | The group ID of the post. For public posts, this is always null. | [optional] +**user_id** | **string** | | [optional] +**title** | **string** | | [optional] +**content** | **string** | | [optional] +**date** | **\DateTime** | The UTC date and time when the post was published. | [optional] +**type** | **string** | The type of post. One of: offer, wanted, admin | [optional] +**outcome** | **string** | For offer and wanted posts, this indicates the outcome of the post which is null if no outcome has been set yet. <br /><br /> Offer post outcomes will be one of: satisfied, withdrawn, promised, expired <br /><br /> Wanted post outcomes will be one of: satisfied, withdrawn, expired <br /><br /> For all other posts, outcome is always null. | [optional] +**latitude** | **float** | May be null if a post hasn't been mapped. | [optional] +**longitude** | **float** | May be null if a post hasn't been mapped. | [optional] +**footer** | **string** | Some groups add footers to posts that are separate and sometimes unrelated to the post itself - such as reminders about group rules or features (may be null). | [optional] +**photos** | [**\OpenAPI\Client\Model\Photo[]**](Photo.md) | Details about the photos associated with this post (may be null if there are no photos). | [optional] +**expiration** | **\DateTime** | The UTC date and time when the post will expire. Currently only offer and wanted posts expire. For all other posts, expiration is always null. | [optional] +**reselling** | **bool** | For wanted posts, whether the item is being requested in order to resell it or not. Will be null for all posts that are not wanted posts and for wanted posts where the poster hasn't indicated whether or not they intend to resell the item they are requesting. | [optional] +**url** | **string** | The link to use to view the post on the Trash Nothing site. | [optional] +**repost_count** | **int** | The count of how many times this post has been reposted in the last 90 days. A value of zero is used to indicate that the post is not a repost. The count is specific to the source of the post (eg. the specific group the post is on). If a post is crossposted to multiple groups, the repost_count of the post on each group may be different for each group depending on how many times the post has been posted on that group in the last 90 days. | [optional] +**search_title** | **string** | The post subject as HTML with the parts of the subject that matched the search query (if any) wrapped in HTML span tags with the class 'highlight'. (eg. &lt;span class=\"highlight\"&gt;matched words&lt;/span&gt;). May be null if none of the words in the subject matched the search query. | [optional] +**search_content** | **string** | A snippet of the post content as HTML with the parts of the content that matched the search query (if any) wrapped in an HTML span tags with the class 'highlight' (eg. &lt;span class=\"highlight\"&gt;matched words&lt;/span&gt;). May be null if none of the words in the post content matched the search query. <br /><br /> NOTE: This is not the full content of the post It is just a snippet of around 200 characters that can be used to display the parts of the post content relevant to the search query. | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/SearchGroups200Response.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/SearchGroups200Response.md new file mode 100644 index 0000000000..6feb0ac8be --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/SearchGroups200Response.md @@ -0,0 +1,15 @@ +# SearchGroups200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**groups** | [**\OpenAPI\Client\Model\Group[]**](Group.md) | | [optional] +**num_groups** | **int** | The total number of groups available. | [optional] +**page** | **int** | The page number of the groups being returned. | [optional] +**per_page** | **int** | The number of groups being returned per page. | [optional] +**num_pages** | **int** | The total number of pages available. | [optional] +**start_index** | **int** | The index of the first group being returned (an integer between 1 and num_groups). | [optional] +**end_index** | **int** | The index of the last group being returned (an integer between start_index and num_groups). | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/SearchUserPosts200Response.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/SearchUserPosts200Response.md new file mode 100644 index 0000000000..55e8f458fa --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/SearchUserPosts200Response.md @@ -0,0 +1,16 @@ +# SearchUserPosts200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**posts** | [**\OpenAPI\Client\Model\PostSearchResult[]**](PostSearchResult.md) | | [optional] +**num_posts** | **int** | The total number of posts available. | [optional] +**page** | **int** | The page number of the posts being returned. | [optional] +**per_page** | **int** | The number of posts being returned per page. | [optional] +**num_pages** | **int** | The total number of pages available. | [optional] +**start_index** | **int** | The index of the first post being returned (an integer between 1 and num_posts). | [optional] +**end_index** | **int** | The index of the last post being returned (an integer between start_index and num_posts). | [optional] +**group_ids** | **string[]** | The IDs of the groups that the posts were retrieved from (will be null when no group IDs were used). These IDs may be a subset of the requested group IDs when a request includes group IDs for groups that are not open archives and that the current user is not a member of. If the open_archive_groups source is used, these IDs may include the IDs of open archive groups that weren't present in the group_ids parameter of the request. | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/User.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/User.md new file mode 100644 index 0000000000..410229b670 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/User.md @@ -0,0 +1,18 @@ +# User + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**user_id** | **string** | | [optional] +**username** | **string** | A username that can be displayed for the user (the username is NOT guaranteed to be unique). Will be null for api key requests and requests where the oauth user doesn't belong to any of the same groups as this user. | [optional] +**country** | **string** | A 2 letter country code for the country that has been automatically detected for the user (see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ). May be null if no country has been set. | [optional] +**profile_image** | **string** | A URL to a profile image for the user. Profile images sizes vary based on the source (Google, Facebook, Gravatar, etc) and some can be as small as 64px by 64px. Will be null for api key requests and requests where the oauth user doesn't belong to any of the same groups as this user. | [optional] +**member_since** | **string** | The date and time when the user first became publicly active on a group (the date may be older than when the user signed up). | [optional] +**firstname** | **string** | The first name of the user (may be null). | [optional] +**lastname** | **string** | The last name of the user (may be null). | [optional] +**reply_time** | **int** | An estimate of how many seconds it takes this user to reply to messages. May be null when there is not enough data to calculate an estimate. | [optional] +**feedback** | [**\OpenAPI\Client\Model\UserFeedback**](UserFeedback.md) | | [optional] +**about_me** | **string** | A short bio a user has written about themselves to help other members get to know them better. May be null if the user has not written anything about themselves. | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/UserFeedback.md b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/UserFeedback.md new file mode 100644 index 0000000000..ce145658c6 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/docs/Model/UserFeedback.md @@ -0,0 +1,11 @@ +# UserFeedback + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**restriction** | **string** | If the current user can leave positive or negative feedback on this user then restriction is null. <br /><br /> Otherwise, restriction is set to a string that explains why feedback is currently restricted and what type of feedback is restricted. The string will be one of the following: no-recent-messages, negative-score, moderator, [days]-day-wait-for-negative <br /><br /> - **no-recent-messages**: The current user has not received any messages from this user in the last 30 days. <br /> - **negative-score**: The current user has a negative feedback and will not be able to leave feedback until their score is >= 0. <br /> - **moderator**: The user is a moderator and leaving feedback on moderators is not currently supported. <br /> - **[days]-day-wait-for-negative**: Positive feedback is not restricted but the current user must wait some number of days before they will be able to leave negative feedback on this user. This string can change depending on the number of days. For example, when the current user must wait one day, the string will be '1-day-wait-for-negative'. A wait is necessary because a lot of negative feedback results from communication issues that are resolved with more time. | [optional] +**score** | **int** | The feedback score of this user. Higher scores are better. Scores are calculated by substracting the total number of negative feedback from the total number of positive feedback that a user has received. May be null if a user has not received enough feedback to calculate a score. | [optional] +**percent_positive** | **float** | The percent of feedback that this user has received in the last year that was positive. May be null if a user has not received enough feedback to calculate a percentage. | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/git_push.sh b/iznik-batch/app/Services/TrashNothing/PublicApi/git_push.sh new file mode 100644 index 0000000000..f53a75d4fa --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Api/GroupsApi.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Api/GroupsApi.php new file mode 100644 index 0000000000..738004c9d1 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Api/GroupsApi.php @@ -0,0 +1,1183 @@ + [ + 'application/json', + ], + 'getGroupsByIds' => [ + 'application/json', + ], + 'searchGroups' => [ + 'application/json', + ], + ]; + + /** + * @param ClientInterface $client + * @param Configuration $config + * @param HeaderSelector $selector + * @param int $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec + */ + public function __construct( + ?ClientInterface $client = null, + ?Configuration $config = null, + ?HeaderSelector $selector = null, + int $hostIndex = 0 + ) { + $this->client = $client ?: new Client(); + $this->config = $config ?: Configuration::getDefaultConfiguration(); + $this->headerSelector = $selector ?: new HeaderSelector(); + $this->hostIndex = $hostIndex; + } + + /** + * Set the host index + * + * @param int $hostIndex Host index (required) + */ + public function setHostIndex($hostIndex): void + { + $this->hostIndex = $hostIndex; + } + + /** + * Get the host index + * + * @return int Host index + */ + public function getHostIndex() + { + return $this->hostIndex; + } + + /** + * @return Configuration + */ + public function getConfig() + { + return $this->config; + } + + /** + * Operation getGroup + * + * Retrieve a group + * + * @param string $group_id The ID of the group to retrieve. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getGroup'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\Group + */ + public function getGroup($group_id, string $contentType = self::contentTypes['getGroup'][0]) + { + list($response) = $this->getGroupWithHttpInfo($group_id, $contentType); + return $response; + } + + /** + * Operation getGroupWithHttpInfo + * + * Retrieve a group + * + * @param string $group_id The ID of the group to retrieve. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getGroup'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\Group, HTTP status code, HTTP response headers (array of strings) + */ + public function getGroupWithHttpInfo($group_id, string $contentType = self::contentTypes['getGroup'][0]) + { + $request = $this->getGroupRequest($group_id, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + + switch($statusCode) { + case 200: + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\Group', + $request, + $response, + ); + } + + + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\Group', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\Group', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation getGroupAsync + * + * Retrieve a group + * + * @param string $group_id The ID of the group to retrieve. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getGroup'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getGroupAsync($group_id, string $contentType = self::contentTypes['getGroup'][0]) + { + return $this->getGroupAsyncWithHttpInfo($group_id, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getGroupAsyncWithHttpInfo + * + * Retrieve a group + * + * @param string $group_id The ID of the group to retrieve. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getGroup'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getGroupAsyncWithHttpInfo($group_id, string $contentType = self::contentTypes['getGroup'][0]) + { + $returnType = '\OpenAPI\Client\Model\Group'; + $request = $this->getGroupRequest($group_id, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'getGroup' + * + * @param string $group_id The ID of the group to retrieve. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getGroup'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function getGroupRequest($group_id, string $contentType = self::contentTypes['getGroup'][0]) + { + + // verify the required parameter 'group_id' is set + if ($group_id === null || (is_array($group_id) && count($group_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $group_id when calling getGroup' + ); + } + + + $resourcePath = '/groups/{group_id}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // path params + if ($group_id !== null) { + $resourcePath = str_replace( + '{group_id}', + ObjectSerializer::toPathValue($group_id), + $resourcePath + ); + } + + + $headers = $this->headerSelector->selectHeaders( + ['application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $queryParams['api_key'] = $apiKey; + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'GET', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation getGroupsByIds + * + * Retrieve multiple groups + * + * @param string $group_ids The IDs of the groups to retrieve. If more than 20 group IDs are passed, only the first 20 groups will be returned. (required) + * @param float|null $latitude If latitude and longitude are passed, each group returned will have a supported_point boolean property indicating whether the group supports the point. (optional) + * @param float|null $longitude If latitude and longitude are passed, each group returned will have a supported_point boolean property indicating whether the group supports the point. (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getGroupsByIds'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\Group[] + */ + public function getGroupsByIds($group_ids, $latitude = null, $longitude = null, string $contentType = self::contentTypes['getGroupsByIds'][0]) + { + list($response) = $this->getGroupsByIdsWithHttpInfo($group_ids, $latitude, $longitude, $contentType); + return $response; + } + + /** + * Operation getGroupsByIdsWithHttpInfo + * + * Retrieve multiple groups + * + * @param string $group_ids The IDs of the groups to retrieve. If more than 20 group IDs are passed, only the first 20 groups will be returned. (required) + * @param float|null $latitude If latitude and longitude are passed, each group returned will have a supported_point boolean property indicating whether the group supports the point. (optional) + * @param float|null $longitude If latitude and longitude are passed, each group returned will have a supported_point boolean property indicating whether the group supports the point. (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getGroupsByIds'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\Group[], HTTP status code, HTTP response headers (array of strings) + */ + public function getGroupsByIdsWithHttpInfo($group_ids, $latitude = null, $longitude = null, string $contentType = self::contentTypes['getGroupsByIds'][0]) + { + $request = $this->getGroupsByIdsRequest($group_ids, $latitude, $longitude, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + + switch($statusCode) { + case 200: + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\Group[]', + $request, + $response, + ); + } + + + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\Group[]', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\Group[]', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation getGroupsByIdsAsync + * + * Retrieve multiple groups + * + * @param string $group_ids The IDs of the groups to retrieve. If more than 20 group IDs are passed, only the first 20 groups will be returned. (required) + * @param float|null $latitude If latitude and longitude are passed, each group returned will have a supported_point boolean property indicating whether the group supports the point. (optional) + * @param float|null $longitude If latitude and longitude are passed, each group returned will have a supported_point boolean property indicating whether the group supports the point. (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getGroupsByIds'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getGroupsByIdsAsync($group_ids, $latitude = null, $longitude = null, string $contentType = self::contentTypes['getGroupsByIds'][0]) + { + return $this->getGroupsByIdsAsyncWithHttpInfo($group_ids, $latitude, $longitude, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getGroupsByIdsAsyncWithHttpInfo + * + * Retrieve multiple groups + * + * @param string $group_ids The IDs of the groups to retrieve. If more than 20 group IDs are passed, only the first 20 groups will be returned. (required) + * @param float|null $latitude If latitude and longitude are passed, each group returned will have a supported_point boolean property indicating whether the group supports the point. (optional) + * @param float|null $longitude If latitude and longitude are passed, each group returned will have a supported_point boolean property indicating whether the group supports the point. (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getGroupsByIds'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getGroupsByIdsAsyncWithHttpInfo($group_ids, $latitude = null, $longitude = null, string $contentType = self::contentTypes['getGroupsByIds'][0]) + { + $returnType = '\OpenAPI\Client\Model\Group[]'; + $request = $this->getGroupsByIdsRequest($group_ids, $latitude, $longitude, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'getGroupsByIds' + * + * @param string $group_ids The IDs of the groups to retrieve. If more than 20 group IDs are passed, only the first 20 groups will be returned. (required) + * @param float|null $latitude If latitude and longitude are passed, each group returned will have a supported_point boolean property indicating whether the group supports the point. (optional) + * @param float|null $longitude If latitude and longitude are passed, each group returned will have a supported_point boolean property indicating whether the group supports the point. (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getGroupsByIds'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function getGroupsByIdsRequest($group_ids, $latitude = null, $longitude = null, string $contentType = self::contentTypes['getGroupsByIds'][0]) + { + + // verify the required parameter 'group_ids' is set + if ($group_ids === null || (is_array($group_ids) && count($group_ids) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $group_ids when calling getGroupsByIds' + ); + } + + + + + $resourcePath = '/groups/multiple'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $group_ids, + 'group_ids', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $latitude, + 'latitude', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $longitude, + 'longitude', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + + + + + $headers = $this->headerSelector->selectHeaders( + ['application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $queryParams['api_key'] = $apiKey; + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'GET', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation searchGroups + * + * Search groups + * + * @param string|null $name Find groups that have the given text somewhere in their name (case insensitive). (optional) + * @param float|null $latitude Find groups near the given latitude and longitude. (optional) + * @param float|null $longitude Find groups near the given latitude and longitude. (optional) + * @param float|null $distance When latitude and longitude are passed, distance can optionally be passed to only return groups within a certain distance (in kilometers) from the point specified by the latitude and longitude. The distance must be > 0 and <= 150 and will default to 100. (optional, default to 100.0) + * @param string|null $country Find groups in the given country where country is a 2 letter country code for the country (see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ). (optional) + * @param string|null $region For countries with regions (AU, CA, GB, US), search groups in a specific region as specified by the region abbreviation. The supported regions and their abbreviations are listed below. <br /><br /> NOTE: The region and postal_code parameters cannot be used at the same time and if both are passed then the postal_code will take priority. <br /><br /> --- <br /><br /> **AU**<br /> - QLD: Queensland<br /> - SA: South Australia<br /> - TAS: Tasmania<br /> - VIC: Victoria<br /> - WA: Western Australia<br /> - NT: Northern Territory<br /> - NSW: New South Wales - ACT<br /> <br /> **CA**<br /> - AB: Alberta<br /> - BC: British Columbia<br /> - MB: Manitoba<br /> - NB: New Brunswick<br /> - NL: Newfoundland and Labrador<br /> - NS: Nova Scotia<br /> - ON: Ontario<br /> - QC: Quebec<br /> - SK: Saskatchewan<br /> - PE: Prince Edward Island<br /> <br /> **GB**<br /> - E: East<br /> - EM: East Midlands<br /> - LDN: London<br /> - NE: North East<br /> - NW: North West<br /> - NI: Northern Ireland<br /> - SC: Scotland<br /> - SE: South East<br /> - SW: South West<br /> - WA: Wales<br /> - WM: West Midlands<br /> - YH: Yorkshire and the Humber<br /> <br /> **US**<br /> All 50 states and the District of Columbia are supported. For the abbreviations, see: https://github.com/jasonong/List-of-US-States/blob/master/states.csv (optional) + * @param string|null $postal_code Find groups in the given postal code. Only a few countries support postal code searches (US, CA, AU, GB). The country parameter must be passed when the postal_code parameter is set. <br /><br /> NOTE: The region and postal_code parameters cannot be used at the same time and if both are passed then the postal_code will take priority. (optional) + * @param int|null $page The page of groups to return. (optional, default to 1) + * @param int|null $per_page The number of groups to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['searchGroups'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\SearchGroups200Response + */ + public function searchGroups($name = null, $latitude = null, $longitude = null, $distance = 100.0, $country = null, $region = null, $postal_code = null, $page = 1, $per_page = 20, string $contentType = self::contentTypes['searchGroups'][0]) + { + list($response) = $this->searchGroupsWithHttpInfo($name, $latitude, $longitude, $distance, $country, $region, $postal_code, $page, $per_page, $contentType); + return $response; + } + + /** + * Operation searchGroupsWithHttpInfo + * + * Search groups + * + * @param string|null $name Find groups that have the given text somewhere in their name (case insensitive). (optional) + * @param float|null $latitude Find groups near the given latitude and longitude. (optional) + * @param float|null $longitude Find groups near the given latitude and longitude. (optional) + * @param float|null $distance When latitude and longitude are passed, distance can optionally be passed to only return groups within a certain distance (in kilometers) from the point specified by the latitude and longitude. The distance must be > 0 and <= 150 and will default to 100. (optional, default to 100.0) + * @param string|null $country Find groups in the given country where country is a 2 letter country code for the country (see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ). (optional) + * @param string|null $region For countries with regions (AU, CA, GB, US), search groups in a specific region as specified by the region abbreviation. The supported regions and their abbreviations are listed below. <br /><br /> NOTE: The region and postal_code parameters cannot be used at the same time and if both are passed then the postal_code will take priority. <br /><br /> --- <br /><br /> **AU**<br /> - QLD: Queensland<br /> - SA: South Australia<br /> - TAS: Tasmania<br /> - VIC: Victoria<br /> - WA: Western Australia<br /> - NT: Northern Territory<br /> - NSW: New South Wales - ACT<br /> <br /> **CA**<br /> - AB: Alberta<br /> - BC: British Columbia<br /> - MB: Manitoba<br /> - NB: New Brunswick<br /> - NL: Newfoundland and Labrador<br /> - NS: Nova Scotia<br /> - ON: Ontario<br /> - QC: Quebec<br /> - SK: Saskatchewan<br /> - PE: Prince Edward Island<br /> <br /> **GB**<br /> - E: East<br /> - EM: East Midlands<br /> - LDN: London<br /> - NE: North East<br /> - NW: North West<br /> - NI: Northern Ireland<br /> - SC: Scotland<br /> - SE: South East<br /> - SW: South West<br /> - WA: Wales<br /> - WM: West Midlands<br /> - YH: Yorkshire and the Humber<br /> <br /> **US**<br /> All 50 states and the District of Columbia are supported. For the abbreviations, see: https://github.com/jasonong/List-of-US-States/blob/master/states.csv (optional) + * @param string|null $postal_code Find groups in the given postal code. Only a few countries support postal code searches (US, CA, AU, GB). The country parameter must be passed when the postal_code parameter is set. <br /><br /> NOTE: The region and postal_code parameters cannot be used at the same time and if both are passed then the postal_code will take priority. (optional) + * @param int|null $page The page of groups to return. (optional, default to 1) + * @param int|null $per_page The number of groups to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['searchGroups'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\SearchGroups200Response, HTTP status code, HTTP response headers (array of strings) + */ + public function searchGroupsWithHttpInfo($name = null, $latitude = null, $longitude = null, $distance = 100.0, $country = null, $region = null, $postal_code = null, $page = 1, $per_page = 20, string $contentType = self::contentTypes['searchGroups'][0]) + { + $request = $this->searchGroupsRequest($name, $latitude, $longitude, $distance, $country, $region, $postal_code, $page, $per_page, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + + switch($statusCode) { + case 200: + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\SearchGroups200Response', + $request, + $response, + ); + } + + + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\SearchGroups200Response', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\SearchGroups200Response', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation searchGroupsAsync + * + * Search groups + * + * @param string|null $name Find groups that have the given text somewhere in their name (case insensitive). (optional) + * @param float|null $latitude Find groups near the given latitude and longitude. (optional) + * @param float|null $longitude Find groups near the given latitude and longitude. (optional) + * @param float|null $distance When latitude and longitude are passed, distance can optionally be passed to only return groups within a certain distance (in kilometers) from the point specified by the latitude and longitude. The distance must be > 0 and <= 150 and will default to 100. (optional, default to 100.0) + * @param string|null $country Find groups in the given country where country is a 2 letter country code for the country (see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ). (optional) + * @param string|null $region For countries with regions (AU, CA, GB, US), search groups in a specific region as specified by the region abbreviation. The supported regions and their abbreviations are listed below. <br /><br /> NOTE: The region and postal_code parameters cannot be used at the same time and if both are passed then the postal_code will take priority. <br /><br /> --- <br /><br /> **AU**<br /> - QLD: Queensland<br /> - SA: South Australia<br /> - TAS: Tasmania<br /> - VIC: Victoria<br /> - WA: Western Australia<br /> - NT: Northern Territory<br /> - NSW: New South Wales - ACT<br /> <br /> **CA**<br /> - AB: Alberta<br /> - BC: British Columbia<br /> - MB: Manitoba<br /> - NB: New Brunswick<br /> - NL: Newfoundland and Labrador<br /> - NS: Nova Scotia<br /> - ON: Ontario<br /> - QC: Quebec<br /> - SK: Saskatchewan<br /> - PE: Prince Edward Island<br /> <br /> **GB**<br /> - E: East<br /> - EM: East Midlands<br /> - LDN: London<br /> - NE: North East<br /> - NW: North West<br /> - NI: Northern Ireland<br /> - SC: Scotland<br /> - SE: South East<br /> - SW: South West<br /> - WA: Wales<br /> - WM: West Midlands<br /> - YH: Yorkshire and the Humber<br /> <br /> **US**<br /> All 50 states and the District of Columbia are supported. For the abbreviations, see: https://github.com/jasonong/List-of-US-States/blob/master/states.csv (optional) + * @param string|null $postal_code Find groups in the given postal code. Only a few countries support postal code searches (US, CA, AU, GB). The country parameter must be passed when the postal_code parameter is set. <br /><br /> NOTE: The region and postal_code parameters cannot be used at the same time and if both are passed then the postal_code will take priority. (optional) + * @param int|null $page The page of groups to return. (optional, default to 1) + * @param int|null $per_page The number of groups to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['searchGroups'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function searchGroupsAsync($name = null, $latitude = null, $longitude = null, $distance = 100.0, $country = null, $region = null, $postal_code = null, $page = 1, $per_page = 20, string $contentType = self::contentTypes['searchGroups'][0]) + { + return $this->searchGroupsAsyncWithHttpInfo($name, $latitude, $longitude, $distance, $country, $region, $postal_code, $page, $per_page, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation searchGroupsAsyncWithHttpInfo + * + * Search groups + * + * @param string|null $name Find groups that have the given text somewhere in their name (case insensitive). (optional) + * @param float|null $latitude Find groups near the given latitude and longitude. (optional) + * @param float|null $longitude Find groups near the given latitude and longitude. (optional) + * @param float|null $distance When latitude and longitude are passed, distance can optionally be passed to only return groups within a certain distance (in kilometers) from the point specified by the latitude and longitude. The distance must be > 0 and <= 150 and will default to 100. (optional, default to 100.0) + * @param string|null $country Find groups in the given country where country is a 2 letter country code for the country (see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ). (optional) + * @param string|null $region For countries with regions (AU, CA, GB, US), search groups in a specific region as specified by the region abbreviation. The supported regions and their abbreviations are listed below. <br /><br /> NOTE: The region and postal_code parameters cannot be used at the same time and if both are passed then the postal_code will take priority. <br /><br /> --- <br /><br /> **AU**<br /> - QLD: Queensland<br /> - SA: South Australia<br /> - TAS: Tasmania<br /> - VIC: Victoria<br /> - WA: Western Australia<br /> - NT: Northern Territory<br /> - NSW: New South Wales - ACT<br /> <br /> **CA**<br /> - AB: Alberta<br /> - BC: British Columbia<br /> - MB: Manitoba<br /> - NB: New Brunswick<br /> - NL: Newfoundland and Labrador<br /> - NS: Nova Scotia<br /> - ON: Ontario<br /> - QC: Quebec<br /> - SK: Saskatchewan<br /> - PE: Prince Edward Island<br /> <br /> **GB**<br /> - E: East<br /> - EM: East Midlands<br /> - LDN: London<br /> - NE: North East<br /> - NW: North West<br /> - NI: Northern Ireland<br /> - SC: Scotland<br /> - SE: South East<br /> - SW: South West<br /> - WA: Wales<br /> - WM: West Midlands<br /> - YH: Yorkshire and the Humber<br /> <br /> **US**<br /> All 50 states and the District of Columbia are supported. For the abbreviations, see: https://github.com/jasonong/List-of-US-States/blob/master/states.csv (optional) + * @param string|null $postal_code Find groups in the given postal code. Only a few countries support postal code searches (US, CA, AU, GB). The country parameter must be passed when the postal_code parameter is set. <br /><br /> NOTE: The region and postal_code parameters cannot be used at the same time and if both are passed then the postal_code will take priority. (optional) + * @param int|null $page The page of groups to return. (optional, default to 1) + * @param int|null $per_page The number of groups to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['searchGroups'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function searchGroupsAsyncWithHttpInfo($name = null, $latitude = null, $longitude = null, $distance = 100.0, $country = null, $region = null, $postal_code = null, $page = 1, $per_page = 20, string $contentType = self::contentTypes['searchGroups'][0]) + { + $returnType = '\OpenAPI\Client\Model\SearchGroups200Response'; + $request = $this->searchGroupsRequest($name, $latitude, $longitude, $distance, $country, $region, $postal_code, $page, $per_page, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'searchGroups' + * + * @param string|null $name Find groups that have the given text somewhere in their name (case insensitive). (optional) + * @param float|null $latitude Find groups near the given latitude and longitude. (optional) + * @param float|null $longitude Find groups near the given latitude and longitude. (optional) + * @param float|null $distance When latitude and longitude are passed, distance can optionally be passed to only return groups within a certain distance (in kilometers) from the point specified by the latitude and longitude. The distance must be > 0 and <= 150 and will default to 100. (optional, default to 100.0) + * @param string|null $country Find groups in the given country where country is a 2 letter country code for the country (see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ). (optional) + * @param string|null $region For countries with regions (AU, CA, GB, US), search groups in a specific region as specified by the region abbreviation. The supported regions and their abbreviations are listed below. <br /><br /> NOTE: The region and postal_code parameters cannot be used at the same time and if both are passed then the postal_code will take priority. <br /><br /> --- <br /><br /> **AU**<br /> - QLD: Queensland<br /> - SA: South Australia<br /> - TAS: Tasmania<br /> - VIC: Victoria<br /> - WA: Western Australia<br /> - NT: Northern Territory<br /> - NSW: New South Wales - ACT<br /> <br /> **CA**<br /> - AB: Alberta<br /> - BC: British Columbia<br /> - MB: Manitoba<br /> - NB: New Brunswick<br /> - NL: Newfoundland and Labrador<br /> - NS: Nova Scotia<br /> - ON: Ontario<br /> - QC: Quebec<br /> - SK: Saskatchewan<br /> - PE: Prince Edward Island<br /> <br /> **GB**<br /> - E: East<br /> - EM: East Midlands<br /> - LDN: London<br /> - NE: North East<br /> - NW: North West<br /> - NI: Northern Ireland<br /> - SC: Scotland<br /> - SE: South East<br /> - SW: South West<br /> - WA: Wales<br /> - WM: West Midlands<br /> - YH: Yorkshire and the Humber<br /> <br /> **US**<br /> All 50 states and the District of Columbia are supported. For the abbreviations, see: https://github.com/jasonong/List-of-US-States/blob/master/states.csv (optional) + * @param string|null $postal_code Find groups in the given postal code. Only a few countries support postal code searches (US, CA, AU, GB). The country parameter must be passed when the postal_code parameter is set. <br /><br /> NOTE: The region and postal_code parameters cannot be used at the same time and if both are passed then the postal_code will take priority. (optional) + * @param int|null $page The page of groups to return. (optional, default to 1) + * @param int|null $per_page The number of groups to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['searchGroups'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function searchGroupsRequest($name = null, $latitude = null, $longitude = null, $distance = 100.0, $country = null, $region = null, $postal_code = null, $page = 1, $per_page = 20, string $contentType = self::contentTypes['searchGroups'][0]) + { + + + + + if ($distance !== null && $distance > 150) { + throw new \InvalidArgumentException('invalid value for "$distance" when calling GroupsApi.searchGroups, must be smaller than or equal to 150.'); + } + if ($distance !== null && $distance < 0) { + throw new \InvalidArgumentException('invalid value for "$distance" when calling GroupsApi.searchGroups, must be bigger than or equal to 0.'); + } + + + + + if ($page !== null && $page < 1) { + throw new \InvalidArgumentException('invalid value for "$page" when calling GroupsApi.searchGroups, must be bigger than or equal to 1.'); + } + + if ($per_page !== null && $per_page > 100) { + throw new \InvalidArgumentException('invalid value for "$per_page" when calling GroupsApi.searchGroups, must be smaller than or equal to 100.'); + } + if ($per_page !== null && $per_page < 1) { + throw new \InvalidArgumentException('invalid value for "$per_page" when calling GroupsApi.searchGroups, must be bigger than or equal to 1.'); + } + + + $resourcePath = '/groups'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $name, + 'name', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $latitude, + 'latitude', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $longitude, + 'longitude', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $distance, + 'distance', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $country, + 'country', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $region, + 'region', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $postal_code, + 'postal_code', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $page, + 'page', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $per_page, + 'per_page', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + + + + + $headers = $this->headerSelector->selectHeaders( + ['application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $queryParams['api_key'] = $apiKey; + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'GET', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + if ($this->config->getCertFile()) { + $options[RequestOptions::CERT] = $this->config->getCertFile(); + } + + if ($this->config->getKeyFile()) { + $options[RequestOptions::SSL_KEY] = $this->config->getKeyFile(); + } + + return $options; + } + + private function handleResponseWithDataType( + string $dataType, + RequestInterface $request, + ResponseInterface $response + ): array { + if ($dataType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($dataType !== 'string') { + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $response->getStatusCode(), + $response->getHeaders(), + $content + ); + } + } + } + + return [ + ObjectSerializer::deserialize($content, $dataType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + private function responseWithinRangeCode( + string $rangeCode, + int $statusCode + ): bool { + $left = (int) ($rangeCode[0].'00'); + $right = (int) ($rangeCode[0].'99'); + + return $statusCode >= $left && $statusCode <= $right; + } +} diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Api/PostsApi.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Api/PostsApi.php new file mode 100644 index 0000000000..889616629a --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Api/PostsApi.php @@ -0,0 +1,2752 @@ + [ + 'application/json', + ], + 'getAllPostsChanges' => [ + 'application/json', + ], + 'getPost' => [ + 'application/json', + ], + 'getPostAndRelatedData' => [ + 'application/json', + ], + 'getPosts' => [ + 'application/json', + ], + 'getPostsByIds' => [ + 'application/json', + ], + 'searchPosts' => [ + 'application/json', + ], + ]; + + /** + * @param ClientInterface $client + * @param Configuration $config + * @param HeaderSelector $selector + * @param int $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec + */ + public function __construct( + ?ClientInterface $client = null, + ?Configuration $config = null, + ?HeaderSelector $selector = null, + int $hostIndex = 0 + ) { + $this->client = $client ?: new Client(); + $this->config = $config ?: Configuration::getDefaultConfiguration(); + $this->headerSelector = $selector ?: new HeaderSelector(); + $this->hostIndex = $hostIndex; + } + + /** + * Set the host index + * + * @param int $hostIndex Host index (required) + */ + public function setHostIndex($hostIndex): void + { + $this->hostIndex = $hostIndex; + } + + /** + * Get the host index + * + * @return int Host index + */ + public function getHostIndex() + { + return $this->hostIndex; + } + + /** + * @return Configuration + */ + public function getConfig() + { + return $this->config; + } + + /** + * Operation getAllPosts + * + * List all posts + * + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted (required) + * @param \DateTime $date_min Only posts newer than or equal to this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_max. And the date and time must be within the last 30 days. And the date and time must be rounded to the nearest second. (required) + * @param \DateTime $date_max Only posts older than this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_min. And the date and time must be rounded to the nearest second. (required) + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 50). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getAllPosts'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\GetAllPosts200Response + */ + public function getAllPosts($types, $date_min, $date_max, $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, string $contentType = self::contentTypes['getAllPosts'][0]) + { + list($response) = $this->getAllPostsWithHttpInfo($types, $date_min, $date_max, $per_page, $page, $device_pixel_ratio, $contentType); + return $response; + } + + /** + * Operation getAllPostsWithHttpInfo + * + * List all posts + * + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted (required) + * @param \DateTime $date_min Only posts newer than or equal to this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_max. And the date and time must be within the last 30 days. And the date and time must be rounded to the nearest second. (required) + * @param \DateTime $date_max Only posts older than this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_min. And the date and time must be rounded to the nearest second. (required) + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 50). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getAllPosts'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\GetAllPosts200Response, HTTP status code, HTTP response headers (array of strings) + */ + public function getAllPostsWithHttpInfo($types, $date_min, $date_max, $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, string $contentType = self::contentTypes['getAllPosts'][0]) + { + $request = $this->getAllPostsRequest($types, $date_min, $date_max, $per_page, $page, $device_pixel_ratio, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + + switch($statusCode) { + case 200: + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\GetAllPosts200Response', + $request, + $response, + ); + } + + + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\GetAllPosts200Response', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\GetAllPosts200Response', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation getAllPostsAsync + * + * List all posts + * + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted (required) + * @param \DateTime $date_min Only posts newer than or equal to this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_max. And the date and time must be within the last 30 days. And the date and time must be rounded to the nearest second. (required) + * @param \DateTime $date_max Only posts older than this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_min. And the date and time must be rounded to the nearest second. (required) + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 50). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getAllPosts'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getAllPostsAsync($types, $date_min, $date_max, $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, string $contentType = self::contentTypes['getAllPosts'][0]) + { + return $this->getAllPostsAsyncWithHttpInfo($types, $date_min, $date_max, $per_page, $page, $device_pixel_ratio, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getAllPostsAsyncWithHttpInfo + * + * List all posts + * + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted (required) + * @param \DateTime $date_min Only posts newer than or equal to this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_max. And the date and time must be within the last 30 days. And the date and time must be rounded to the nearest second. (required) + * @param \DateTime $date_max Only posts older than this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_min. And the date and time must be rounded to the nearest second. (required) + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 50). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getAllPosts'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getAllPostsAsyncWithHttpInfo($types, $date_min, $date_max, $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, string $contentType = self::contentTypes['getAllPosts'][0]) + { + $returnType = '\OpenAPI\Client\Model\GetAllPosts200Response'; + $request = $this->getAllPostsRequest($types, $date_min, $date_max, $per_page, $page, $device_pixel_ratio, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'getAllPosts' + * + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted (required) + * @param \DateTime $date_min Only posts newer than or equal to this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_max. And the date and time must be within the last 30 days. And the date and time must be rounded to the nearest second. (required) + * @param \DateTime $date_max Only posts older than this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_min. And the date and time must be rounded to the nearest second. (required) + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 50). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getAllPosts'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function getAllPostsRequest($types, $date_min, $date_max, $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, string $contentType = self::contentTypes['getAllPosts'][0]) + { + + // verify the required parameter 'types' is set + if ($types === null || (is_array($types) && count($types) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $types when calling getAllPosts' + ); + } + + // verify the required parameter 'date_min' is set + if ($date_min === null || (is_array($date_min) && count($date_min) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $date_min when calling getAllPosts' + ); + } + + // verify the required parameter 'date_max' is set + if ($date_max === null || (is_array($date_max) && count($date_max) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $date_max when calling getAllPosts' + ); + } + + if ($per_page !== null && $per_page > 50) { + throw new \InvalidArgumentException('invalid value for "$per_page" when calling PostsApi.getAllPosts, must be smaller than or equal to 50.'); + } + if ($per_page !== null && $per_page < 1) { + throw new \InvalidArgumentException('invalid value for "$per_page" when calling PostsApi.getAllPosts, must be bigger than or equal to 1.'); + } + + if ($page !== null && $page < 1) { + throw new \InvalidArgumentException('invalid value for "$page" when calling PostsApi.getAllPosts, must be bigger than or equal to 1.'); + } + + + + $resourcePath = '/posts/all'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $types, + 'types', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $date_min, + 'date_min', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $date_max, + 'date_max', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $per_page, + 'per_page', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $page, + 'page', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $device_pixel_ratio, + 'device_pixel_ratio', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + + + + + $headers = $this->headerSelector->selectHeaders( + ['application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $queryParams['api_key'] = $apiKey; + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'GET', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation getAllPostsChanges + * + * List all post changes + * + * @param \DateTime $date_min Only changes newer than or equal to this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_max. And the date and time must be within the last 30 days. And the date and time must be rounded to the nearest second. (required) + * @param \DateTime $date_max Only changes older than this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_min. And the date and time must be rounded to the nearest second. (required) + * @param int|null $per_page The number of changes to return per page (must be >= 1 and <= 50). (optional, default to 20) + * @param int|null $page The page of changes to return. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getAllPostsChanges'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\GetAllPostsChanges200Response + */ + public function getAllPostsChanges($date_min, $date_max, $per_page = 20, $page = 1, string $contentType = self::contentTypes['getAllPostsChanges'][0]) + { + list($response) = $this->getAllPostsChangesWithHttpInfo($date_min, $date_max, $per_page, $page, $contentType); + return $response; + } + + /** + * Operation getAllPostsChangesWithHttpInfo + * + * List all post changes + * + * @param \DateTime $date_min Only changes newer than or equal to this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_max. And the date and time must be within the last 30 days. And the date and time must be rounded to the nearest second. (required) + * @param \DateTime $date_max Only changes older than this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_min. And the date and time must be rounded to the nearest second. (required) + * @param int|null $per_page The number of changes to return per page (must be >= 1 and <= 50). (optional, default to 20) + * @param int|null $page The page of changes to return. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getAllPostsChanges'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\GetAllPostsChanges200Response, HTTP status code, HTTP response headers (array of strings) + */ + public function getAllPostsChangesWithHttpInfo($date_min, $date_max, $per_page = 20, $page = 1, string $contentType = self::contentTypes['getAllPostsChanges'][0]) + { + $request = $this->getAllPostsChangesRequest($date_min, $date_max, $per_page, $page, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + + switch($statusCode) { + case 200: + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\GetAllPostsChanges200Response', + $request, + $response, + ); + } + + + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\GetAllPostsChanges200Response', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\GetAllPostsChanges200Response', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation getAllPostsChangesAsync + * + * List all post changes + * + * @param \DateTime $date_min Only changes newer than or equal to this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_max. And the date and time must be within the last 30 days. And the date and time must be rounded to the nearest second. (required) + * @param \DateTime $date_max Only changes older than this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_min. And the date and time must be rounded to the nearest second. (required) + * @param int|null $per_page The number of changes to return per page (must be >= 1 and <= 50). (optional, default to 20) + * @param int|null $page The page of changes to return. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getAllPostsChanges'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getAllPostsChangesAsync($date_min, $date_max, $per_page = 20, $page = 1, string $contentType = self::contentTypes['getAllPostsChanges'][0]) + { + return $this->getAllPostsChangesAsyncWithHttpInfo($date_min, $date_max, $per_page, $page, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getAllPostsChangesAsyncWithHttpInfo + * + * List all post changes + * + * @param \DateTime $date_min Only changes newer than or equal to this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_max. And the date and time must be within the last 30 days. And the date and time must be rounded to the nearest second. (required) + * @param \DateTime $date_max Only changes older than this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_min. And the date and time must be rounded to the nearest second. (required) + * @param int|null $per_page The number of changes to return per page (must be >= 1 and <= 50). (optional, default to 20) + * @param int|null $page The page of changes to return. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getAllPostsChanges'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getAllPostsChangesAsyncWithHttpInfo($date_min, $date_max, $per_page = 20, $page = 1, string $contentType = self::contentTypes['getAllPostsChanges'][0]) + { + $returnType = '\OpenAPI\Client\Model\GetAllPostsChanges200Response'; + $request = $this->getAllPostsChangesRequest($date_min, $date_max, $per_page, $page, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'getAllPostsChanges' + * + * @param \DateTime $date_min Only changes newer than or equal to this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_max. And the date and time must be within the last 30 days. And the date and time must be rounded to the nearest second. (required) + * @param \DateTime $date_max Only changes older than this UTC date and time will be returned. The UTC date and time used must be within a day or less of date_min. And the date and time must be rounded to the nearest second. (required) + * @param int|null $per_page The number of changes to return per page (must be >= 1 and <= 50). (optional, default to 20) + * @param int|null $page The page of changes to return. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getAllPostsChanges'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function getAllPostsChangesRequest($date_min, $date_max, $per_page = 20, $page = 1, string $contentType = self::contentTypes['getAllPostsChanges'][0]) + { + + // verify the required parameter 'date_min' is set + if ($date_min === null || (is_array($date_min) && count($date_min) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $date_min when calling getAllPostsChanges' + ); + } + + // verify the required parameter 'date_max' is set + if ($date_max === null || (is_array($date_max) && count($date_max) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $date_max when calling getAllPostsChanges' + ); + } + + if ($per_page !== null && $per_page > 50) { + throw new \InvalidArgumentException('invalid value for "$per_page" when calling PostsApi.getAllPostsChanges, must be smaller than or equal to 50.'); + } + if ($per_page !== null && $per_page < 1) { + throw new \InvalidArgumentException('invalid value for "$per_page" when calling PostsApi.getAllPostsChanges, must be bigger than or equal to 1.'); + } + + if ($page !== null && $page < 1) { + throw new \InvalidArgumentException('invalid value for "$page" when calling PostsApi.getAllPostsChanges, must be bigger than or equal to 1.'); + } + + + $resourcePath = '/posts/all/changes'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $date_min, + 'date_min', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $date_max, + 'date_max', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $per_page, + 'per_page', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $page, + 'page', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + + + + + $headers = $this->headerSelector->selectHeaders( + ['application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $queryParams['api_key'] = $apiKey; + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'GET', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation getPost + * + * Retrieve a post + * + * @param string $post_id The ID of the post to retrieve. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPost'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\Post + */ + public function getPost($post_id, string $contentType = self::contentTypes['getPost'][0]) + { + list($response) = $this->getPostWithHttpInfo($post_id, $contentType); + return $response; + } + + /** + * Operation getPostWithHttpInfo + * + * Retrieve a post + * + * @param string $post_id The ID of the post to retrieve. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPost'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\Post, HTTP status code, HTTP response headers (array of strings) + */ + public function getPostWithHttpInfo($post_id, string $contentType = self::contentTypes['getPost'][0]) + { + $request = $this->getPostRequest($post_id, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + + switch($statusCode) { + case 200: + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\Post', + $request, + $response, + ); + } + + + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\Post', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\Post', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation getPostAsync + * + * Retrieve a post + * + * @param string $post_id The ID of the post to retrieve. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPost'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getPostAsync($post_id, string $contentType = self::contentTypes['getPost'][0]) + { + return $this->getPostAsyncWithHttpInfo($post_id, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getPostAsyncWithHttpInfo + * + * Retrieve a post + * + * @param string $post_id The ID of the post to retrieve. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPost'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getPostAsyncWithHttpInfo($post_id, string $contentType = self::contentTypes['getPost'][0]) + { + $returnType = '\OpenAPI\Client\Model\Post'; + $request = $this->getPostRequest($post_id, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'getPost' + * + * @param string $post_id The ID of the post to retrieve. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPost'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function getPostRequest($post_id, string $contentType = self::contentTypes['getPost'][0]) + { + + // verify the required parameter 'post_id' is set + if ($post_id === null || (is_array($post_id) && count($post_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $post_id when calling getPost' + ); + } + + + $resourcePath = '/posts/{post_id}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // path params + if ($post_id !== null) { + $resourcePath = str_replace( + '{post_id}', + ObjectSerializer::toPathValue($post_id), + $resourcePath + ); + } + + + $headers = $this->headerSelector->selectHeaders( + ['application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $queryParams['api_key'] = $apiKey; + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'GET', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation getPostAndRelatedData + * + * Retrieve post display data + * + * @param string $post_id The ID of the post to retrieve. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPostAndRelatedData'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\GetPostAndRelatedData200Response + */ + public function getPostAndRelatedData($post_id, string $contentType = self::contentTypes['getPostAndRelatedData'][0]) + { + list($response) = $this->getPostAndRelatedDataWithHttpInfo($post_id, $contentType); + return $response; + } + + /** + * Operation getPostAndRelatedDataWithHttpInfo + * + * Retrieve post display data + * + * @param string $post_id The ID of the post to retrieve. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPostAndRelatedData'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\GetPostAndRelatedData200Response, HTTP status code, HTTP response headers (array of strings) + */ + public function getPostAndRelatedDataWithHttpInfo($post_id, string $contentType = self::contentTypes['getPostAndRelatedData'][0]) + { + $request = $this->getPostAndRelatedDataRequest($post_id, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + + switch($statusCode) { + case 200: + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\GetPostAndRelatedData200Response', + $request, + $response, + ); + } + + + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\GetPostAndRelatedData200Response', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\GetPostAndRelatedData200Response', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation getPostAndRelatedDataAsync + * + * Retrieve post display data + * + * @param string $post_id The ID of the post to retrieve. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPostAndRelatedData'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getPostAndRelatedDataAsync($post_id, string $contentType = self::contentTypes['getPostAndRelatedData'][0]) + { + return $this->getPostAndRelatedDataAsyncWithHttpInfo($post_id, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getPostAndRelatedDataAsyncWithHttpInfo + * + * Retrieve post display data + * + * @param string $post_id The ID of the post to retrieve. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPostAndRelatedData'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getPostAndRelatedDataAsyncWithHttpInfo($post_id, string $contentType = self::contentTypes['getPostAndRelatedData'][0]) + { + $returnType = '\OpenAPI\Client\Model\GetPostAndRelatedData200Response'; + $request = $this->getPostAndRelatedDataRequest($post_id, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'getPostAndRelatedData' + * + * @param string $post_id The ID of the post to retrieve. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPostAndRelatedData'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function getPostAndRelatedDataRequest($post_id, string $contentType = self::contentTypes['getPostAndRelatedData'][0]) + { + + // verify the required parameter 'post_id' is set + if ($post_id === null || (is_array($post_id) && count($post_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $post_id when calling getPostAndRelatedData' + ); + } + + + $resourcePath = '/posts/{post_id}/display'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // path params + if ($post_id !== null) { + $resourcePath = str_replace( + '{post_id}', + ObjectSerializer::toPathValue($post_id), + $resourcePath + ); + } + + + $headers = $this->headerSelector->selectHeaders( + ['application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $queryParams['api_key'] = $apiKey; + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'GET', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation getPosts + * + * List posts + * + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or the current users' location if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: date, active, distance <br /><br /> Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'date') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. If unset, defaults to the current date and time minus 90 days. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. If unset, defaults to the current date and time. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPosts'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\GetUserPosts200Response + */ + public function getPosts($types, $sources, $sort_by = 'date', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['getPosts'][0]) + { + list($response) = $this->getPostsWithHttpInfo($types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType); + return $response; + } + + /** + * Operation getPostsWithHttpInfo + * + * List posts + * + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or the current users' location if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: date, active, distance <br /><br /> Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'date') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. If unset, defaults to the current date and time minus 90 days. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. If unset, defaults to the current date and time. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPosts'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\GetUserPosts200Response, HTTP status code, HTTP response headers (array of strings) + */ + public function getPostsWithHttpInfo($types, $sources, $sort_by = 'date', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['getPosts'][0]) + { + $request = $this->getPostsRequest($types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + + switch($statusCode) { + case 200: + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\GetUserPosts200Response', + $request, + $response, + ); + } + + + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\GetUserPosts200Response', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\GetUserPosts200Response', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation getPostsAsync + * + * List posts + * + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or the current users' location if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: date, active, distance <br /><br /> Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'date') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. If unset, defaults to the current date and time minus 90 days. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. If unset, defaults to the current date and time. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPosts'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getPostsAsync($types, $sources, $sort_by = 'date', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['getPosts'][0]) + { + return $this->getPostsAsyncWithHttpInfo($types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getPostsAsyncWithHttpInfo + * + * List posts + * + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or the current users' location if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: date, active, distance <br /><br /> Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'date') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. If unset, defaults to the current date and time minus 90 days. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. If unset, defaults to the current date and time. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPosts'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getPostsAsyncWithHttpInfo($types, $sources, $sort_by = 'date', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['getPosts'][0]) + { + $returnType = '\OpenAPI\Client\Model\GetUserPosts200Response'; + $request = $this->getPostsRequest($types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'getPosts' + * + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or the current users' location if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: date, active, distance <br /><br /> Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'date') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. If unset, defaults to the current date and time minus 90 days. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. If unset, defaults to the current date and time. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPosts'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function getPostsRequest($types, $sources, $sort_by = 'date', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['getPosts'][0]) + { + + // verify the required parameter 'types' is set + if ($types === null || (is_array($types) && count($types) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $types when calling getPosts' + ); + } + + // verify the required parameter 'sources' is set + if ($sources === null || (is_array($sources) && count($sources) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $sources when calling getPosts' + ); + } + + + + if ($per_page !== null && $per_page > 100) { + throw new \InvalidArgumentException('invalid value for "$per_page" when calling PostsApi.getPosts, must be smaller than or equal to 100.'); + } + if ($per_page !== null && $per_page < 1) { + throw new \InvalidArgumentException('invalid value for "$per_page" when calling PostsApi.getPosts, must be bigger than or equal to 1.'); + } + + if ($page !== null && $page < 1) { + throw new \InvalidArgumentException('invalid value for "$page" when calling PostsApi.getPosts, must be bigger than or equal to 1.'); + } + + + + + if ($radius !== null && $radius > 80500) { + throw new \InvalidArgumentException('invalid value for "$radius" when calling PostsApi.getPosts, must be smaller than or equal to 80500.'); + } + if ($radius !== null && $radius < 0) { + throw new \InvalidArgumentException('invalid value for "$radius" when calling PostsApi.getPosts, must be bigger than or equal to 0.'); + } + + + + + if ($include_reposts !== null && $include_reposts > 1) { + throw new \InvalidArgumentException('invalid value for "$include_reposts" when calling PostsApi.getPosts, must be smaller than or equal to 1.'); + } + if ($include_reposts !== null && $include_reposts < 0) { + throw new \InvalidArgumentException('invalid value for "$include_reposts" when calling PostsApi.getPosts, must be bigger than or equal to 0.'); + } + + + $resourcePath = '/posts'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $sort_by, + 'sort_by', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $types, + 'types', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $sources, + 'sources', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $group_ids, + 'group_ids', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $per_page, + 'per_page', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $page, + 'page', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $device_pixel_ratio, + 'device_pixel_ratio', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $latitude, + 'latitude', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $longitude, + 'longitude', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $radius, + 'radius', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $date_min, + 'date_min', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $date_max, + 'date_max', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $outcomes, + 'outcomes', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $include_reposts, + 'include_reposts', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + + + + + $headers = $this->headerSelector->selectHeaders( + ['application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $queryParams['api_key'] = $apiKey; + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'GET', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation getPostsByIds + * + * Retrieve multiple posts + * + * @param string $post_ids A comma separated list of the post IDs. If more than 10 post IDs are passed, only the first 10 posts will be returned. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPostsByIds'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\GetPostsByIds200Response + */ + public function getPostsByIds($post_ids, string $contentType = self::contentTypes['getPostsByIds'][0]) + { + list($response) = $this->getPostsByIdsWithHttpInfo($post_ids, $contentType); + return $response; + } + + /** + * Operation getPostsByIdsWithHttpInfo + * + * Retrieve multiple posts + * + * @param string $post_ids A comma separated list of the post IDs. If more than 10 post IDs are passed, only the first 10 posts will be returned. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPostsByIds'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\GetPostsByIds200Response, HTTP status code, HTTP response headers (array of strings) + */ + public function getPostsByIdsWithHttpInfo($post_ids, string $contentType = self::contentTypes['getPostsByIds'][0]) + { + $request = $this->getPostsByIdsRequest($post_ids, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + + switch($statusCode) { + case 200: + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\GetPostsByIds200Response', + $request, + $response, + ); + } + + + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\GetPostsByIds200Response', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\GetPostsByIds200Response', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation getPostsByIdsAsync + * + * Retrieve multiple posts + * + * @param string $post_ids A comma separated list of the post IDs. If more than 10 post IDs are passed, only the first 10 posts will be returned. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPostsByIds'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getPostsByIdsAsync($post_ids, string $contentType = self::contentTypes['getPostsByIds'][0]) + { + return $this->getPostsByIdsAsyncWithHttpInfo($post_ids, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getPostsByIdsAsyncWithHttpInfo + * + * Retrieve multiple posts + * + * @param string $post_ids A comma separated list of the post IDs. If more than 10 post IDs are passed, only the first 10 posts will be returned. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPostsByIds'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getPostsByIdsAsyncWithHttpInfo($post_ids, string $contentType = self::contentTypes['getPostsByIds'][0]) + { + $returnType = '\OpenAPI\Client\Model\GetPostsByIds200Response'; + $request = $this->getPostsByIdsRequest($post_ids, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'getPostsByIds' + * + * @param string $post_ids A comma separated list of the post IDs. If more than 10 post IDs are passed, only the first 10 posts will be returned. (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPostsByIds'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function getPostsByIdsRequest($post_ids, string $contentType = self::contentTypes['getPostsByIds'][0]) + { + + // verify the required parameter 'post_ids' is set + if ($post_ids === null || (is_array($post_ids) && count($post_ids) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $post_ids when calling getPostsByIds' + ); + } + + + $resourcePath = '/posts/multiple'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $post_ids, + 'post_ids', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + + + + + $headers = $this->headerSelector->selectHeaders( + ['application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $queryParams['api_key'] = $apiKey; + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'GET', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation searchPosts + * + * Search posts + * + * @param string $search The search query used to find posts. (required) + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or the current users' location if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: relevance, date, active, distance <br /><br /> Relevance sorting will sort the posts that best match the search query first. Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'relevance') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. If unset, defaults to the current date and time minus 90 days. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. If unset, defaults to the current date and time. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['searchPosts'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\SearchUserPosts200Response + */ + public function searchPosts($search, $types, $sources, $sort_by = 'relevance', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['searchPosts'][0]) + { + list($response) = $this->searchPostsWithHttpInfo($search, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType); + return $response; + } + + /** + * Operation searchPostsWithHttpInfo + * + * Search posts + * + * @param string $search The search query used to find posts. (required) + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or the current users' location if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: relevance, date, active, distance <br /><br /> Relevance sorting will sort the posts that best match the search query first. Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'relevance') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. If unset, defaults to the current date and time minus 90 days. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. If unset, defaults to the current date and time. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['searchPosts'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\SearchUserPosts200Response, HTTP status code, HTTP response headers (array of strings) + */ + public function searchPostsWithHttpInfo($search, $types, $sources, $sort_by = 'relevance', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['searchPosts'][0]) + { + $request = $this->searchPostsRequest($search, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + + switch($statusCode) { + case 200: + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\SearchUserPosts200Response', + $request, + $response, + ); + } + + + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\SearchUserPosts200Response', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\SearchUserPosts200Response', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation searchPostsAsync + * + * Search posts + * + * @param string $search The search query used to find posts. (required) + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or the current users' location if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: relevance, date, active, distance <br /><br /> Relevance sorting will sort the posts that best match the search query first. Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'relevance') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. If unset, defaults to the current date and time minus 90 days. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. If unset, defaults to the current date and time. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['searchPosts'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function searchPostsAsync($search, $types, $sources, $sort_by = 'relevance', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['searchPosts'][0]) + { + return $this->searchPostsAsyncWithHttpInfo($search, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation searchPostsAsyncWithHttpInfo + * + * Search posts + * + * @param string $search The search query used to find posts. (required) + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or the current users' location if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: relevance, date, active, distance <br /><br /> Relevance sorting will sort the posts that best match the search query first. Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'relevance') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. If unset, defaults to the current date and time minus 90 days. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. If unset, defaults to the current date and time. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['searchPosts'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function searchPostsAsyncWithHttpInfo($search, $types, $sources, $sort_by = 'relevance', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['searchPosts'][0]) + { + $returnType = '\OpenAPI\Client\Model\SearchUserPosts200Response'; + $request = $this->searchPostsRequest($search, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'searchPosts' + * + * @param string $search The search query used to find posts. (required) + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or the current users' location if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: relevance, date, active, distance <br /><br /> Relevance sorting will sort the posts that best match the search query first. Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'relevance') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. If unset, defaults to the current date and time minus 90 days. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. If unset, defaults to the current date and time. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['searchPosts'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function searchPostsRequest($search, $types, $sources, $sort_by = 'relevance', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['searchPosts'][0]) + { + + // verify the required parameter 'search' is set + if ($search === null || (is_array($search) && count($search) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $search when calling searchPosts' + ); + } + + // verify the required parameter 'types' is set + if ($types === null || (is_array($types) && count($types) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $types when calling searchPosts' + ); + } + + // verify the required parameter 'sources' is set + if ($sources === null || (is_array($sources) && count($sources) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $sources when calling searchPosts' + ); + } + + + + if ($per_page !== null && $per_page > 100) { + throw new \InvalidArgumentException('invalid value for "$per_page" when calling PostsApi.searchPosts, must be smaller than or equal to 100.'); + } + if ($per_page !== null && $per_page < 1) { + throw new \InvalidArgumentException('invalid value for "$per_page" when calling PostsApi.searchPosts, must be bigger than or equal to 1.'); + } + + if ($page !== null && $page < 1) { + throw new \InvalidArgumentException('invalid value for "$page" when calling PostsApi.searchPosts, must be bigger than or equal to 1.'); + } + + + + + if ($radius !== null && $radius > 80500) { + throw new \InvalidArgumentException('invalid value for "$radius" when calling PostsApi.searchPosts, must be smaller than or equal to 80500.'); + } + if ($radius !== null && $radius < 0) { + throw new \InvalidArgumentException('invalid value for "$radius" when calling PostsApi.searchPosts, must be bigger than or equal to 0.'); + } + + + + + if ($include_reposts !== null && $include_reposts > 1) { + throw new \InvalidArgumentException('invalid value for "$include_reposts" when calling PostsApi.searchPosts, must be smaller than or equal to 1.'); + } + if ($include_reposts !== null && $include_reposts < 0) { + throw new \InvalidArgumentException('invalid value for "$include_reposts" when calling PostsApi.searchPosts, must be bigger than or equal to 0.'); + } + + + $resourcePath = '/posts/search'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $search, + 'search', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $sort_by, + 'sort_by', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $types, + 'types', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $sources, + 'sources', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $group_ids, + 'group_ids', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $per_page, + 'per_page', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $page, + 'page', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $device_pixel_ratio, + 'device_pixel_ratio', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $latitude, + 'latitude', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $longitude, + 'longitude', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $radius, + 'radius', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $date_min, + 'date_min', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $date_max, + 'date_max', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $outcomes, + 'outcomes', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $include_reposts, + 'include_reposts', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + + + + + $headers = $this->headerSelector->selectHeaders( + ['application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $queryParams['api_key'] = $apiKey; + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'GET', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + if ($this->config->getCertFile()) { + $options[RequestOptions::CERT] = $this->config->getCertFile(); + } + + if ($this->config->getKeyFile()) { + $options[RequestOptions::SSL_KEY] = $this->config->getKeyFile(); + } + + return $options; + } + + private function handleResponseWithDataType( + string $dataType, + RequestInterface $request, + ResponseInterface $response + ): array { + if ($dataType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($dataType !== 'string') { + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $response->getStatusCode(), + $response->getHeaders(), + $content + ); + } + } + } + + return [ + ObjectSerializer::deserialize($content, $dataType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + private function responseWithinRangeCode( + string $rangeCode, + int $statusCode + ): bool { + $left = (int) ($rangeCode[0].'00'); + $right = (int) ($rangeCode[0].'99'); + + return $statusCode >= $left && $statusCode <= $right; + } +} diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Api/UsersApi.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Api/UsersApi.php new file mode 100644 index 0000000000..a2b3732a4d --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Api/UsersApi.php @@ -0,0 +1,1253 @@ + [ + 'application/json', + ], + 'searchUserPosts' => [ + 'application/json', + ], + ]; + + /** + * @param ClientInterface $client + * @param Configuration $config + * @param HeaderSelector $selector + * @param int $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec + */ + public function __construct( + ?ClientInterface $client = null, + ?Configuration $config = null, + ?HeaderSelector $selector = null, + int $hostIndex = 0 + ) { + $this->client = $client ?: new Client(); + $this->config = $config ?: Configuration::getDefaultConfiguration(); + $this->headerSelector = $selector ?: new HeaderSelector(); + $this->hostIndex = $hostIndex; + } + + /** + * Set the host index + * + * @param int $hostIndex Host index (required) + */ + public function setHostIndex($hostIndex): void + { + $this->hostIndex = $hostIndex; + } + + /** + * Get the host index + * + * @return int Host index + */ + public function getHostIndex() + { + return $this->hostIndex; + } + + /** + * @return Configuration + */ + public function getConfig() + { + return $this->config; + } + + /** + * Operation getUserPosts + * + * List posts by a user + * + * @param string $user_id The user ID of the user whose posts will be retrieved. Using 'me' as the user_id will return the posts for the current user. (required) + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or all the open archive groups the requested user has posted to if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: date, active, distance <br /><br /> Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'date') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserPosts'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\GetUserPosts200Response + */ + public function getUserPosts($user_id, $types, $sources, $sort_by = 'date', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['getUserPosts'][0]) + { + list($response) = $this->getUserPostsWithHttpInfo($user_id, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType); + return $response; + } + + /** + * Operation getUserPostsWithHttpInfo + * + * List posts by a user + * + * @param string $user_id The user ID of the user whose posts will be retrieved. Using 'me' as the user_id will return the posts for the current user. (required) + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or all the open archive groups the requested user has posted to if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: date, active, distance <br /><br /> Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'date') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserPosts'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\GetUserPosts200Response, HTTP status code, HTTP response headers (array of strings) + */ + public function getUserPostsWithHttpInfo($user_id, $types, $sources, $sort_by = 'date', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['getUserPosts'][0]) + { + $request = $this->getUserPostsRequest($user_id, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + + switch($statusCode) { + case 200: + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\GetUserPosts200Response', + $request, + $response, + ); + } + + + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\GetUserPosts200Response', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\GetUserPosts200Response', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation getUserPostsAsync + * + * List posts by a user + * + * @param string $user_id The user ID of the user whose posts will be retrieved. Using 'me' as the user_id will return the posts for the current user. (required) + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or all the open archive groups the requested user has posted to if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: date, active, distance <br /><br /> Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'date') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserPosts'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getUserPostsAsync($user_id, $types, $sources, $sort_by = 'date', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['getUserPosts'][0]) + { + return $this->getUserPostsAsyncWithHttpInfo($user_id, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getUserPostsAsyncWithHttpInfo + * + * List posts by a user + * + * @param string $user_id The user ID of the user whose posts will be retrieved. Using 'me' as the user_id will return the posts for the current user. (required) + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or all the open archive groups the requested user has posted to if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: date, active, distance <br /><br /> Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'date') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserPosts'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getUserPostsAsyncWithHttpInfo($user_id, $types, $sources, $sort_by = 'date', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['getUserPosts'][0]) + { + $returnType = '\OpenAPI\Client\Model\GetUserPosts200Response'; + $request = $this->getUserPostsRequest($user_id, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'getUserPosts' + * + * @param string $user_id The user ID of the user whose posts will be retrieved. Using 'me' as the user_id will return the posts for the current user. (required) + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or all the open archive groups the requested user has posted to if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: date, active, distance <br /><br /> Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'date') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserPosts'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function getUserPostsRequest($user_id, $types, $sources, $sort_by = 'date', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['getUserPosts'][0]) + { + + // verify the required parameter 'user_id' is set + if ($user_id === null || (is_array($user_id) && count($user_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $user_id when calling getUserPosts' + ); + } + + // verify the required parameter 'types' is set + if ($types === null || (is_array($types) && count($types) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $types when calling getUserPosts' + ); + } + + // verify the required parameter 'sources' is set + if ($sources === null || (is_array($sources) && count($sources) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $sources when calling getUserPosts' + ); + } + + + + if ($per_page !== null && $per_page > 100) { + throw new \InvalidArgumentException('invalid value for "$per_page" when calling UsersApi.getUserPosts, must be smaller than or equal to 100.'); + } + if ($per_page !== null && $per_page < 1) { + throw new \InvalidArgumentException('invalid value for "$per_page" when calling UsersApi.getUserPosts, must be bigger than or equal to 1.'); + } + + if ($page !== null && $page < 1) { + throw new \InvalidArgumentException('invalid value for "$page" when calling UsersApi.getUserPosts, must be bigger than or equal to 1.'); + } + + + + + if ($radius !== null && $radius > 80500) { + throw new \InvalidArgumentException('invalid value for "$radius" when calling UsersApi.getUserPosts, must be smaller than or equal to 80500.'); + } + if ($radius !== null && $radius < 0) { + throw new \InvalidArgumentException('invalid value for "$radius" when calling UsersApi.getUserPosts, must be bigger than or equal to 0.'); + } + + + + + if ($include_reposts !== null && $include_reposts > 1) { + throw new \InvalidArgumentException('invalid value for "$include_reposts" when calling UsersApi.getUserPosts, must be smaller than or equal to 1.'); + } + if ($include_reposts !== null && $include_reposts < 0) { + throw new \InvalidArgumentException('invalid value for "$include_reposts" when calling UsersApi.getUserPosts, must be bigger than or equal to 0.'); + } + + + $resourcePath = '/users/{user_id}/posts'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $sort_by, + 'sort_by', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $types, + 'types', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $sources, + 'sources', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $group_ids, + 'group_ids', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $per_page, + 'per_page', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $page, + 'page', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $device_pixel_ratio, + 'device_pixel_ratio', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $latitude, + 'latitude', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $longitude, + 'longitude', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $radius, + 'radius', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $date_min, + 'date_min', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $date_max, + 'date_max', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $outcomes, + 'outcomes', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $include_reposts, + 'include_reposts', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + + + // path params + if ($user_id !== null) { + $resourcePath = str_replace( + '{user_id}', + ObjectSerializer::toPathValue($user_id), + $resourcePath + ); + } + + + $headers = $this->headerSelector->selectHeaders( + ['application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $queryParams['api_key'] = $apiKey; + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'GET', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation searchUserPosts + * + * Search posts by a user + * + * @param string $user_id The user ID of the user whose posts will be retrieved. Using 'me' as the user_id will return the posts for the current user. (required) + * @param string $search The search query used to find posts. (required) + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or all the open archive groups the requested user has posted to if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: relevance, date, active, distance <br /><br /> Relevance sorting will sort the posts that best match the search query first. Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'relevance') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['searchUserPosts'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return \OpenAPI\Client\Model\SearchUserPosts200Response + */ + public function searchUserPosts($user_id, $search, $types, $sources, $sort_by = 'relevance', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['searchUserPosts'][0]) + { + list($response) = $this->searchUserPostsWithHttpInfo($user_id, $search, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType); + return $response; + } + + /** + * Operation searchUserPostsWithHttpInfo + * + * Search posts by a user + * + * @param string $user_id The user ID of the user whose posts will be retrieved. Using 'me' as the user_id will return the posts for the current user. (required) + * @param string $search The search query used to find posts. (required) + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or all the open archive groups the requested user has posted to if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: relevance, date, active, distance <br /><br /> Relevance sorting will sort the posts that best match the search query first. Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'relevance') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['searchUserPosts'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of \OpenAPI\Client\Model\SearchUserPosts200Response, HTTP status code, HTTP response headers (array of strings) + */ + public function searchUserPostsWithHttpInfo($user_id, $search, $types, $sources, $sort_by = 'relevance', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['searchUserPosts'][0]) + { + $request = $this->searchUserPostsRequest($user_id, $search, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + + switch($statusCode) { + case 200: + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\SearchUserPosts200Response', + $request, + $response, + ); + } + + + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + return $this->handleResponseWithDataType( + '\OpenAPI\Client\Model\SearchUserPosts200Response', + $request, + $response, + ); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\SearchUserPosts200Response', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + throw $e; + } + + + throw $e; + } + } + + /** + * Operation searchUserPostsAsync + * + * Search posts by a user + * + * @param string $user_id The user ID of the user whose posts will be retrieved. Using 'me' as the user_id will return the posts for the current user. (required) + * @param string $search The search query used to find posts. (required) + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or all the open archive groups the requested user has posted to if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: relevance, date, active, distance <br /><br /> Relevance sorting will sort the posts that best match the search query first. Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'relevance') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['searchUserPosts'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function searchUserPostsAsync($user_id, $search, $types, $sources, $sort_by = 'relevance', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['searchUserPosts'][0]) + { + return $this->searchUserPostsAsyncWithHttpInfo($user_id, $search, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation searchUserPostsAsyncWithHttpInfo + * + * Search posts by a user + * + * @param string $user_id The user ID of the user whose posts will be retrieved. Using 'me' as the user_id will return the posts for the current user. (required) + * @param string $search The search query used to find posts. (required) + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or all the open archive groups the requested user has posted to if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: relevance, date, active, distance <br /><br /> Relevance sorting will sort the posts that best match the search query first. Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'relevance') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['searchUserPosts'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function searchUserPostsAsyncWithHttpInfo($user_id, $search, $types, $sources, $sort_by = 'relevance', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['searchUserPosts'][0]) + { + $returnType = '\OpenAPI\Client\Model\SearchUserPosts200Response'; + $request = $this->searchUserPostsRequest($user_id, $search, $types, $sources, $sort_by, $group_ids, $per_page, $page, $device_pixel_ratio, $latitude, $longitude, $radius, $date_min, $date_max, $outcomes, $include_reposts, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'searchUserPosts' + * + * @param string $user_id The user ID of the user whose posts will be retrieved. Using 'me' as the user_id will return the posts for the current user. (required) + * @param string $search The search query used to find posts. (required) + * @param string $types A comma separated list of the post types to return. The available post types are: offer, wanted, admin (required) + * @param string $sources A comma separated list of the post sources to retrieve posts from. The available sources are: groups, trashnothing, open_archive_groups. The trashnothing source is for public posts that are posted on Trash Nothing but are not associated with any group. The open_archive_groups source provides a way to easily request posts from groups that have open_archives set to true without having to pass a group_ids parameter. When passed, it will automatically return posts from open archive groups that are within the area specified by the latitude, longitude and radius parameters (or all the open archive groups the requested user has posted to if latitude, longitude and radius aren't passed). <br /><br /> NOTE: For requests using an api key instead of oauth, passing the trashnothing source or the open_archive_groups source makes the latitude, longitude and radius parameters required. (required) + * @param string|null $sort_by How to sort the posts that are returned. One of: relevance, date, active, distance <br /><br /> Relevance sorting will sort the posts that best match the search query first. Date sorting will sort posts from newest to oldest. Active sorting will sort active posts before satisfied, withdrawn and expired posts and then sort by date. Distance sorting will sort the closest posts first. (optional, default to 'relevance') + * @param string|null $group_ids A comma separated list of the group IDs to retrieve posts from. This parameter is only used if the 'groups' source is passed in the sources parameter and only groups that the current user is a member of or that are open archives groups will be used (the group IDs of other groups will be silently discarded*). <br /><br /> NOTE: For requests using an api key instead of oauth, this field is required if the 'groups' source is passed. In addition, only posts from groups that have open_archives set to true will be used (the group IDs of other groups will be silently discarded*). <br /><br/> *To determine which group IDs were used and which were discarded, use the group_ids field in the response. (optional, default to 'The group IDs of every group the current user is a member of.') + * @param int|null $per_page The number of posts to return per page (must be >= 1 and <= 100). (optional, default to 20) + * @param int|null $page The page of posts to return. (optional, default to 1) + * @param float|null $device_pixel_ratio Client device pixel ratio used to determine thumbnail size (default 1.0). (optional, default to 1.0) + * @param float|null $latitude The latitude of a point around which to return posts. (optional) + * @param float|null $longitude The longitude of a point around which to return posts. (optional) + * @param float|null $radius The radius in meters of a circle centered at the point defined by the latitude and longitude parameters. When latitude, longitude and radius are passed, only posts within the circle defined by these parameters will be returned. (optional) + * @param \DateTime|null $date_min Only posts newer than or equal to this UTC date and time will be returned. (optional) + * @param \DateTime|null $date_max Only posts older than this UTC date and time will be returned. (optional) + * @param string|null $outcomes A comma separated list of the post outcomes to return. The available post outcomes are: satisfied, withdrawn <br /><br /> There are also a couple special values that can be passed. If set to an empty string (the default), only posts that are not satisfied and not withdrawn and not expired are returned. If set to 'all', all posts will be returned no matter what outcome the posts have. If set to 'not-promised', only posts that are not satisfied ant not withdrawn and not expired and not promised are returned. (optional) + * @param int|null $include_reposts If set to 1 (the default), posts that are reposts will be included. If set to 0, reposts will be excluded. See the repost_count field of post objects for details about how reposts are identified. (optional, default to 1) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['searchUserPosts'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function searchUserPostsRequest($user_id, $search, $types, $sources, $sort_by = 'relevance', $group_ids = 'The group IDs of every group the current user is a member of.', $per_page = 20, $page = 1, $device_pixel_ratio = 1.0, $latitude = null, $longitude = null, $radius = null, $date_min = null, $date_max = null, $outcomes = null, $include_reposts = 1, string $contentType = self::contentTypes['searchUserPosts'][0]) + { + + // verify the required parameter 'user_id' is set + if ($user_id === null || (is_array($user_id) && count($user_id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $user_id when calling searchUserPosts' + ); + } + + // verify the required parameter 'search' is set + if ($search === null || (is_array($search) && count($search) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $search when calling searchUserPosts' + ); + } + + // verify the required parameter 'types' is set + if ($types === null || (is_array($types) && count($types) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $types when calling searchUserPosts' + ); + } + + // verify the required parameter 'sources' is set + if ($sources === null || (is_array($sources) && count($sources) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $sources when calling searchUserPosts' + ); + } + + + + if ($per_page !== null && $per_page > 100) { + throw new \InvalidArgumentException('invalid value for "$per_page" when calling UsersApi.searchUserPosts, must be smaller than or equal to 100.'); + } + if ($per_page !== null && $per_page < 1) { + throw new \InvalidArgumentException('invalid value for "$per_page" when calling UsersApi.searchUserPosts, must be bigger than or equal to 1.'); + } + + if ($page !== null && $page < 1) { + throw new \InvalidArgumentException('invalid value for "$page" when calling UsersApi.searchUserPosts, must be bigger than or equal to 1.'); + } + + + + + if ($radius !== null && $radius > 80500) { + throw new \InvalidArgumentException('invalid value for "$radius" when calling UsersApi.searchUserPosts, must be smaller than or equal to 80500.'); + } + if ($radius !== null && $radius < 0) { + throw new \InvalidArgumentException('invalid value for "$radius" when calling UsersApi.searchUserPosts, must be bigger than or equal to 0.'); + } + + + + + if ($include_reposts !== null && $include_reposts > 1) { + throw new \InvalidArgumentException('invalid value for "$include_reposts" when calling UsersApi.searchUserPosts, must be smaller than or equal to 1.'); + } + if ($include_reposts !== null && $include_reposts < 0) { + throw new \InvalidArgumentException('invalid value for "$include_reposts" when calling UsersApi.searchUserPosts, must be bigger than or equal to 0.'); + } + + + $resourcePath = '/users/{user_id}/posts/search'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $search, + 'search', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $sort_by, + 'sort_by', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $types, + 'types', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $sources, + 'sources', // param base name + 'string', // openApiType + '', // style + false, // explode + true // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $group_ids, + 'group_ids', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $per_page, + 'per_page', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $page, + 'page', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $device_pixel_ratio, + 'device_pixel_ratio', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $latitude, + 'latitude', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $longitude, + 'longitude', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $radius, + 'radius', // param base name + 'number', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $date_min, + 'date_min', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $date_max, + 'date_max', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $outcomes, + 'outcomes', // param base name + 'string', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + // query params + $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( + $include_reposts, + 'include_reposts', // param base name + 'integer', // openApiType + '', // style + false, // explode + false // required + ) ?? []); + + + // path params + if ($user_id !== null) { + $resourcePath = str_replace( + '{user_id}', + ObjectSerializer::toPathValue($user_id), + $resourcePath + ); + } + + + $headers = $this->headerSelector->selectHeaders( + ['application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $queryParams['api_key'] = $apiKey; + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'GET', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + if ($this->config->getCertFile()) { + $options[RequestOptions::CERT] = $this->config->getCertFile(); + } + + if ($this->config->getKeyFile()) { + $options[RequestOptions::SSL_KEY] = $this->config->getKeyFile(); + } + + return $options; + } + + private function handleResponseWithDataType( + string $dataType, + RequestInterface $request, + ResponseInterface $response + ): array { + if ($dataType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($dataType !== 'string') { + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $response->getStatusCode(), + $response->getHeaders(), + $content + ); + } + } + } + + return [ + ObjectSerializer::deserialize($content, $dataType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + private function responseWithinRangeCode( + string $rangeCode, + int $statusCode + ): bool { + $left = (int) ($rangeCode[0].'00'); + $right = (int) ($rangeCode[0].'99'); + + return $statusCode >= $left && $statusCode <= $right; + } +} diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/ApiException.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/ApiException.php new file mode 100644 index 0000000000..bf59c2506b --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/ApiException.php @@ -0,0 +1,119 @@ +responseHeaders = $responseHeaders; + $this->responseBody = $responseBody; + } + + /** + * Gets the HTTP response header + * + * @return string[][]|null HTTP response header + */ + public function getResponseHeaders() + { + return $this->responseHeaders; + } + + /** + * Gets the HTTP body of the server response either as Json or string + * + * @return \stdClass|string|null HTTP body of the server response either as \stdClass or string + */ + public function getResponseBody() + { + return $this->responseBody; + } + + /** + * Sets the deserialized response object (during deserialization) + * + * @param mixed $obj Deserialized response object + * + * @return void + */ + public function setResponseObject($obj) + { + $this->responseObject = $obj; + } + + /** + * Gets the deserialized response object (during deserialization) + * + * @return mixed the deserialized response object + */ + public function getResponseObject() + { + return $this->responseObject; + } +} diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Configuration.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Configuration.php new file mode 100644 index 0000000000..8b5d1b5650 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Configuration.php @@ -0,0 +1,588 @@ +tempFolderPath = sys_get_temp_dir(); + } + + /** + * Sets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $key API key or token + * + * @return $this + */ + public function setApiKey($apiKeyIdentifier, $key) + { + $this->apiKeys[$apiKeyIdentifier] = $key; + return $this; + } + + /** + * Gets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return null|string API key or token + */ + public function getApiKey($apiKeyIdentifier) + { + return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; + } + + /** + * Sets the prefix for API key (e.g. Bearer) + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $prefix API key prefix, e.g. Bearer + * + * @return $this + */ + public function setApiKeyPrefix($apiKeyIdentifier, $prefix) + { + $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; + return $this; + } + + /** + * Gets API key prefix + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return null|string + */ + public function getApiKeyPrefix($apiKeyIdentifier) + { + return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; + } + + /** + * Sets the access token for OAuth + * + * @param string $accessToken Token for OAuth + * + * @return $this + */ + public function setAccessToken($accessToken) + { + $this->accessToken = $accessToken; + return $this; + } + + /** + * Gets the access token for OAuth + * + * @return string Access token for OAuth + */ + public function getAccessToken() + { + return $this->accessToken; + } + + /** + * Sets boolean format for query string. + * + * @param string $booleanFormat Boolean format for query string + * + * @return $this + */ + public function setBooleanFormatForQueryString(string $booleanFormat) + { + $this->booleanFormatForQueryString = $booleanFormat; + + return $this; + } + + /** + * Gets boolean format for query string. + * + * @return string Boolean format for query string + */ + public function getBooleanFormatForQueryString(): string + { + return $this->booleanFormatForQueryString; + } + + /** + * Sets the username for HTTP basic authentication + * + * @param string $username Username for HTTP basic authentication + * + * @return $this + */ + public function setUsername($username) + { + $this->username = $username; + return $this; + } + + /** + * Gets the username for HTTP basic authentication + * + * @return string Username for HTTP basic authentication + */ + public function getUsername() + { + return $this->username; + } + + /** + * Sets the password for HTTP basic authentication + * + * @param string $password Password for HTTP basic authentication + * + * @return $this + */ + public function setPassword($password) + { + $this->password = $password; + return $this; + } + + /** + * Gets the password for HTTP basic authentication + * + * @return string Password for HTTP basic authentication + */ + public function getPassword() + { + return $this->password; + } + + /** + * Sets the host + * + * @param string $host Host + * + * @return $this + */ + public function setHost($host) + { + $this->host = $host; + return $this; + } + + /** + * Gets the host + * + * @return string Host + */ + public function getHost() + { + return $this->host; + } + + /** + * Sets the user agent of the api client + * + * @param string $userAgent the user agent of the api client + * + * @throws \InvalidArgumentException + * @return $this + */ + public function setUserAgent($userAgent) + { + if (!is_string($userAgent)) { + throw new \InvalidArgumentException('User-agent must be a string.'); + } + + $this->userAgent = $userAgent; + return $this; + } + + /** + * Gets the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent() + { + return $this->userAgent; + } + + /** + * Sets debug flag + * + * @param bool $debug Debug flag + * + * @return $this + */ + public function setDebug($debug) + { + $this->debug = $debug; + return $this; + } + + /** + * Gets the debug flag + * + * @return bool + */ + public function getDebug() + { + return $this->debug; + } + + /** + * Sets the debug file + * + * @param string $debugFile Debug file + * + * @return $this + */ + public function setDebugFile($debugFile) + { + $this->debugFile = $debugFile; + return $this; + } + + /** + * Gets the debug file + * + * @return string + */ + public function getDebugFile() + { + return $this->debugFile; + } + + /** + * Sets the temp folder path + * + * @param string $tempFolderPath Temp folder path + * + * @return $this + */ + public function setTempFolderPath($tempFolderPath) + { + $this->tempFolderPath = $tempFolderPath; + return $this; + } + + /** + * Gets the temp folder path + * + * @return string Temp folder path + */ + public function getTempFolderPath() + { + return $this->tempFolderPath; + } + + /** + * Sets the certificate file path, for mTLS + * + * @return $this + */ + public function setCertFile($certFile) + { + $this->certFile = $certFile; + return $this; + } + + /** + * Gets the certificate file path, for mTLS + * + * @return string Certificate file path + */ + public function getCertFile() + { + return $this->certFile; + } + + /** + * Sets the certificate key path, for mTLS + * + * @return $this + */ + public function setKeyFile($keyFile) + { + $this->keyFile = $keyFile; + return $this; + } + + /** + * Gets the certificate key path, for mTLS + * + * @return string Certificate key path + */ + public function getKeyFile() + { + return $this->keyFile; + } + + + /** + * Gets the default configuration instance + * + * @return Configuration + */ + public static function getDefaultConfiguration() + { + if (self::$defaultConfiguration === null) { + self::$defaultConfiguration = new Configuration(); + } + + return self::$defaultConfiguration; + } + + /** + * Sets the default configuration instance + * + * @param Configuration $config An instance of the Configuration Object + * + * @return void + */ + public static function setDefaultConfiguration(Configuration $config) + { + self::$defaultConfiguration = $config; + } + + /** + * Gets the essential information for debugging + * + * @return string The report for debugging + */ + public static function toDebugReport() + { + $report = 'PHP SDK (OpenAPI\Client) Debug Report:' . PHP_EOL; + $report .= ' OS: ' . php_uname() . PHP_EOL; + $report .= ' PHP Version: ' . PHP_VERSION . PHP_EOL; + $report .= ' The version of the OpenAPI document: 1.4' . PHP_EOL; + $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; + + return $report; + } + + /** + * Get API key (with prefix if set) + * + * @param string $apiKeyIdentifier name of apikey + * + * @return null|string API key with the prefix + */ + public function getApiKeyWithPrefix($apiKeyIdentifier) + { + $prefix = $this->getApiKeyPrefix($apiKeyIdentifier); + $apiKey = $this->getApiKey($apiKeyIdentifier); + + if ($apiKey === null) { + return null; + } + + if ($prefix === null) { + $keyWithPrefix = $apiKey; + } else { + $keyWithPrefix = $prefix . ' ' . $apiKey; + } + + return $keyWithPrefix; + } + + /** + * Returns an array of host settings + * + * @return array an array of host settings + */ + public function getHostSettings() + { + return [ + [ + "url" => "https://trashnothing.com/api/v1.4", + "description" => "No description provided", + ] + ]; + } + + /** + * Returns URL based on host settings, index and variables + * + * @param array $hostSettings array of host settings, generated from getHostSettings() or equivalent from the API clients + * @param int $hostIndex index of the host settings + * @param array|null $variables hash of variable and the corresponding value (optional) + * @return string URL based on host settings + */ + public static function getHostString(array $hostSettings, $hostIndex, ?array $variables = null) + { + if (null === $variables) { + $variables = []; + } + + // check array index out of bound + if ($hostIndex < 0 || $hostIndex >= count($hostSettings)) { + throw new \InvalidArgumentException("Invalid index $hostIndex when selecting the host. Must be less than ".count($hostSettings)); + } + + $host = $hostSettings[$hostIndex]; + $url = $host["url"]; + + // go through variable and assign a value + foreach ($host["variables"] ?? [] as $name => $variable) { + if (array_key_exists($name, $variables)) { // check to see if it's in the variables provided by the user + if (!isset($variable['enum_values']) || in_array($variables[$name], $variable["enum_values"], true)) { // check to see if the value is in the enum + $url = str_replace("{".$name."}", $variables[$name], $url); + } else { + throw new \InvalidArgumentException("The variable `$name` in the host URL has invalid value ".$variables[$name].". Must be ".join(',', $variable["enum_values"])."."); + } + } else { + // use default value + $url = str_replace("{".$name."}", $variable["default_value"], $url); + } + } + + return $url; + } + + /** + * Returns URL based on the index and variables + * + * @param int $index index of the host settings + * @param array|null $variables hash of variable and the corresponding value (optional) + * @return string URL based on host settings + */ + public function getHostFromSettings($index, $variables = null) + { + return self::getHostString($this->getHostSettings(), $index, $variables); + } +} diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/FormDataProcessor.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/FormDataProcessor.php new file mode 100644 index 0000000000..3de049b977 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/FormDataProcessor.php @@ -0,0 +1,246 @@ + $values the value of the form parameter + * + * @return array [key => value] of formdata + */ + public function prepare(array $values): array + { + $this->has_file = false; + $result = []; + + foreach ($values as $k => $v) { + if ($v === null) { + continue; + } + + $result[$k] = $this->makeFormSafe($v); + } + + return $result; + } + + /** + * Flattens a multi-level array of data and generates a single-level array + * compatible with formdata - a single-level array where the keys use bracket + * notation to signify nested data. + * + * credit: https://github.com/FranBar1966/FlatPHP + */ + public static function flatten(array $source, string $start = ''): array + { + $opt = [ + 'prefix' => '[', + 'suffix' => ']', + 'suffix-end' => true, + 'prefix-list' => '[', + 'suffix-list' => ']', + 'suffix-list-end' => true, + ]; + + if ($start === '') { + $currentPrefix = ''; + $currentSuffix = ''; + $currentSuffixEnd = false; + } elseif (array_is_list($source)) { + $currentPrefix = $opt['prefix-list']; + $currentSuffix = $opt['suffix-list']; + $currentSuffixEnd = $opt['suffix-list-end']; + } else { + $currentPrefix = $opt['prefix']; + $currentSuffix = $opt['suffix']; + $currentSuffixEnd = $opt['suffix-end']; + } + + $currentName = $start; + $result = []; + + foreach ($source as $key => $val) { + $currentName .= $currentPrefix.$key; + + if (is_array($val) && !empty($val)) { + $currentName .= $currentSuffix; + $result += self::flatten($val, $currentName); + } else { + if ($currentSuffixEnd) { + $currentName .= $currentSuffix; + } + + if (is_resource($val)) { + $result[$currentName] = $val; + } else { + $result[$currentName] = ObjectSerializer::toString($val); + } + } + + $currentName = $start; + } + + return $result; + } + + /** + * formdata must be limited to scalars or arrays of scalar values, + * or a resource for a file upload. Here we iterate through all available + * data and identify how to handle each scenario + */ + protected function makeFormSafe($value) + { + if ($value instanceof SplFileObject) { + return $this->processFiles([$value])[0]; + } + + if (is_resource($value)) { + $this->has_file = true; + + return $value; + } + + if ($value instanceof ModelInterface) { + return $this->processModel($value); + } + + if (is_array($value) || (is_object($value) && !$value instanceof \DateTimeInterface)) { + $data = []; + + foreach ($value as $k => $v) { + $data[$k] = $this->makeFormSafe($v); + } + + return $data; + } + + return ObjectSerializer::toString($value); + } + + /** + * We are able to handle nested ModelInterface. We do not simply call + * json_decode(json_encode()) because any given model may have binary data + * or other data that cannot be serialized to a JSON string + */ + protected function processModel(ModelInterface $model): array + { + $result = []; + + foreach ($model::openAPITypes() as $name => $type) { + $value = $model->offsetGet($name); + + if ($value === null) { + continue; + } + + if (strpos($type, '\SplFileObject') !== false) { + $file = is_array($value) ? $value : [$value]; + $result[$name] = $this->processFiles($file); + + continue; + } + + if ($value instanceof ModelInterface) { + $result[$name] = $this->processModel($value); + + continue; + } + + if (is_array($value) || is_object($value)) { + $result[$name] = $this->makeFormSafe($value); + + continue; + } + + $result[$name] = ObjectSerializer::toString($value); + } + + return $result; + } + + /** + * Handle file data + */ + protected function processFiles(array $files): array + { + $this->has_file = true; + + $result = []; + + foreach ($files as $i => $file) { + if (is_array($file)) { + $result[$i] = $this->processFiles($file); + + continue; + } + + if ($file instanceof StreamInterface) { + $result[$i] = $file; + + continue; + } + + if ($file instanceof SplFileObject) { + $result[$i] = $this->tryFopen($file); + } + } + + return $result; + } + + private function tryFopen(SplFileObject $file) + { + return Utils::tryFopen($file->getRealPath(), 'rb'); + } +} diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/HeaderSelector.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/HeaderSelector.php new file mode 100644 index 0000000000..75baa3d5ec --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/HeaderSelector.php @@ -0,0 +1,273 @@ +selectAcceptHeader($accept); + if ($accept !== null) { + $headers['Accept'] = $accept; + } + + if (!$isMultipart) { + if($contentType === '') { + $contentType = 'application/json'; + } + + $headers['Content-Type'] = $contentType; + } + + return $headers; + } + + /** + * Return the header 'Accept' based on an array of Accept provided. + * + * @param string[] $accept Array of header + * + * @return null|string Accept (e.g. application/json) + */ + private function selectAcceptHeader(array $accept): ?string + { + # filter out empty entries + $accept = array_filter($accept); + + if (count($accept) === 0) { + return null; + } + + # If there's only one Accept header, just use it + if (count($accept) === 1) { + return reset($accept); + } + + # If none of the available Accept headers is of type "json", then just use all them + $headersWithJson = $this->selectJsonMimeList($accept); + if (count($headersWithJson) === 0) { + return implode(',', $accept); + } + + # If we got here, then we need add quality values (weight), as described in IETF RFC 9110, Items 12.4.2/12.5.1, + # to give the highest priority to json-like headers - recalculating the existing ones, if needed + return $this->getAcceptHeaderWithAdjustedWeight($accept, $headersWithJson); + } + + /** + * Detects whether a string contains a valid JSON mime type + * + * @param string $searchString + * @return bool + */ + public function isJsonMime(string $searchString): bool + { + return preg_match('~^application/(json|[\w!#$&.+-^_]+\+json)\s*(;|$)~', $searchString) === 1; + } + + /** + * Select all items from a list containing a JSON mime type + * + * @param array $mimeList + * @return array + */ + private function selectJsonMimeList(array $mimeList): array { + $jsonMimeList = []; + foreach ($mimeList as $mime) { + if($this->isJsonMime($mime)) { + $jsonMimeList[] = $mime; + } + } + return $jsonMimeList; + } + + + /** + * Create an Accept header string from the given "Accept" headers array, recalculating all weights + * + * @param string[] $accept Array of Accept Headers + * @param string[] $headersWithJson Array of Accept Headers of type "json" + * + * @return string "Accept" Header (e.g. "application/json, text/html; q=0.9") + */ + private function getAcceptHeaderWithAdjustedWeight(array $accept, array $headersWithJson): string + { + $processedHeaders = [ + 'withApplicationJson' => [], + 'withJson' => [], + 'withoutJson' => [], + ]; + + foreach ($accept as $header) { + + $headerData = $this->getHeaderAndWeight($header); + + if (stripos($headerData['header'], 'application/json') === 0) { + $processedHeaders['withApplicationJson'][] = $headerData; + } elseif (in_array($header, $headersWithJson, true)) { + $processedHeaders['withJson'][] = $headerData; + } else { + $processedHeaders['withoutJson'][] = $headerData; + } + } + + $acceptHeaders = []; + $currentWeight = 1000; + + $hasMoreThan28Headers = count($accept) > 28; + + foreach($processedHeaders as $headers) { + if (count($headers) > 0) { + $acceptHeaders[] = $this->adjustWeight($headers, $currentWeight, $hasMoreThan28Headers); + } + } + + $acceptHeaders = array_merge(...$acceptHeaders); + + return implode(',', $acceptHeaders); + } + + /** + * Given an Accept header, returns an associative array splitting the header and its weight + * + * @param string $header "Accept" Header + * + * @return array with the header and its weight + */ + private function getHeaderAndWeight(string $header): array + { + # matches headers with weight, splitting the header and the weight in $outputArray + if (preg_match('/(.*);\s*q=(1(?:\.0+)?|0\.\d+)$/', $header, $outputArray) === 1) { + $headerData = [ + 'header' => $outputArray[1], + 'weight' => (int)($outputArray[2] * 1000), + ]; + } else { + $headerData = [ + 'header' => trim($header), + 'weight' => 1000, + ]; + } + + return $headerData; + } + + /** + * @param array[] $headers + * @param float $currentWeight + * @param bool $hasMoreThan28Headers + * @return string[] array of adjusted "Accept" headers + */ + private function adjustWeight(array $headers, float &$currentWeight, bool $hasMoreThan28Headers): array + { + usort($headers, function (array $a, array $b) { + return $b['weight'] - $a['weight']; + }); + + $acceptHeaders = []; + foreach ($headers as $index => $header) { + if($index > 0 && $headers[$index - 1]['weight'] > $header['weight']) + { + $currentWeight = $this->getNextWeight($currentWeight, $hasMoreThan28Headers); + } + + $weight = $currentWeight; + + $acceptHeaders[] = $this->buildAcceptHeader($header['header'], $weight); + } + + $currentWeight = $this->getNextWeight($currentWeight, $hasMoreThan28Headers); + + return $acceptHeaders; + } + + /** + * @param string $header + * @param int $weight + * @return string + */ + private function buildAcceptHeader(string $header, int $weight): string + { + if($weight === 1000) { + return $header; + } + + return trim($header, '; ') . ';q=' . rtrim(sprintf('%0.3f', $weight / 1000), '0'); + } + + /** + * Calculate the next weight, based on the current one. + * + * If there are less than 28 "Accept" headers, the weights will be decreased by 1 on its highest significant digit, using the + * following formula: + * + * next weight = current weight - 10 ^ (floor(log(current weight - 1))) + * + * ( current weight minus ( 10 raised to the power of ( floor of (log to the base 10 of ( current weight minus 1 ) ) ) ) ) + * + * Starting from 1000, this generates the following series: + * + * 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 + * + * The resulting quality codes are closer to the average "normal" usage of them (like "q=0.9", "q=0.8" and so on), but it only works + * if there is a maximum of 28 "Accept" headers. If we have more than that (which is extremely unlikely), then we fall back to a 1-by-1 + * decrement rule, which will result in quality codes like "q=0.999", "q=0.998" etc. + * + * @param int $currentWeight varying from 1 to 1000 (will be divided by 1000 to build the quality value) + * @param bool $hasMoreThan28Headers + * @return int + */ + public function getNextWeight(int $currentWeight, bool $hasMoreThan28Headers): int + { + if ($currentWeight <= 1) { + return 1; + } + + if ($hasMoreThan28Headers) { + return $currentWeight - 1; + } + + return $currentWeight - 10 ** floor( log10($currentWeight - 1) ); + } +} diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/Feedback.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/Feedback.php new file mode 100644 index 0000000000..7ac933df11 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/Feedback.php @@ -0,0 +1,579 @@ + + */ +class Feedback implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'Feedback'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'feedback_id' => 'string', + 'user_id' => 'string', + 'reviewer_user_id' => 'string', + 'content' => 'string', + 'positive' => 'bool', + 'date' => '\DateTime' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'feedback_id' => null, + 'user_id' => null, + 'reviewer_user_id' => null, + 'content' => null, + 'positive' => null, + 'date' => 'date-time' + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'feedback_id' => false, + 'user_id' => false, + 'reviewer_user_id' => false, + 'content' => false, + 'positive' => false, + 'date' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'feedback_id' => 'feedback_id', + 'user_id' => 'user_id', + 'reviewer_user_id' => 'reviewer_user_id', + 'content' => 'content', + 'positive' => 'positive', + 'date' => 'date' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'feedback_id' => 'setFeedbackId', + 'user_id' => 'setUserId', + 'reviewer_user_id' => 'setReviewerUserId', + 'content' => 'setContent', + 'positive' => 'setPositive', + 'date' => 'setDate' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'feedback_id' => 'getFeedbackId', + 'user_id' => 'getUserId', + 'reviewer_user_id' => 'getReviewerUserId', + 'content' => 'getContent', + 'positive' => 'getPositive', + 'date' => 'getDate' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('feedback_id', $data ?? [], null); + $this->setIfExists('user_id', $data ?? [], null); + $this->setIfExists('reviewer_user_id', $data ?? [], null); + $this->setIfExists('content', $data ?? [], null); + $this->setIfExists('positive', $data ?? [], null); + $this->setIfExists('date', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets feedback_id + * + * @return string|null + */ + public function getFeedbackId() + { + return $this->container['feedback_id']; + } + + /** + * Sets feedback_id + * + * @param string|null $feedback_id feedback_id + * + * @return self + */ + public function setFeedbackId($feedback_id) + { + if (is_null($feedback_id)) { + throw new \InvalidArgumentException('non-nullable feedback_id cannot be null'); + } + $this->container['feedback_id'] = $feedback_id; + + return $this; + } + + /** + * Gets user_id + * + * @return string|null + */ + public function getUserId() + { + return $this->container['user_id']; + } + + /** + * Sets user_id + * + * @param string|null $user_id The user ID of the user that the feedback is about. + * + * @return self + */ + public function setUserId($user_id) + { + if (is_null($user_id)) { + throw new \InvalidArgumentException('non-nullable user_id cannot be null'); + } + $this->container['user_id'] = $user_id; + + return $this; + } + + /** + * Gets reviewer_user_id + * + * @return string|null + */ + public function getReviewerUserId() + { + return $this->container['reviewer_user_id']; + } + + /** + * Sets reviewer_user_id + * + * @param string|null $reviewer_user_id The user ID of the user that submitted the feedback. + * + * @return self + */ + public function setReviewerUserId($reviewer_user_id) + { + if (is_null($reviewer_user_id)) { + throw new \InvalidArgumentException('non-nullable reviewer_user_id cannot be null'); + } + $this->container['reviewer_user_id'] = $reviewer_user_id; + + return $this; + } + + /** + * Gets content + * + * @return string|null + */ + public function getContent() + { + return $this->container['content']; + } + + /** + * Sets content + * + * @param string|null $content A comment written by the reviewer about the user (may be null). + * + * @return self + */ + public function setContent($content) + { + if (is_null($content)) { + throw new \InvalidArgumentException('non-nullable content cannot be null'); + } + $this->container['content'] = $content; + + return $this; + } + + /** + * Gets positive + * + * @return bool|null + */ + public function getPositive() + { + return $this->container['positive']; + } + + /** + * Sets positive + * + * @param bool|null $positive Set to true for positive feedback and false for negative feedback. + * + * @return self + */ + public function setPositive($positive) + { + if (is_null($positive)) { + throw new \InvalidArgumentException('non-nullable positive cannot be null'); + } + $this->container['positive'] = $positive; + + return $this; + } + + /** + * Gets date + * + * @return \DateTime|null + */ + public function getDate() + { + return $this->container['date']; + } + + /** + * Sets date + * + * @param \DateTime|null $date Date when the feedback was submitted. + * + * @return self + */ + public function setDate($date) + { + if (is_null($date)) { + throw new \InvalidArgumentException('non-nullable date cannot be null'); + } + $this->container['date'] = $date; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetAllPosts200Response.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetAllPosts200Response.php new file mode 100644 index 0000000000..f1bcbb08a7 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetAllPosts200Response.php @@ -0,0 +1,409 @@ + + */ +class GetAllPosts200Response implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'get_all_posts_200_response'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'posts' => '\OpenAPI\Client\Model\Post[]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'posts' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'posts' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'posts' => 'posts' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'posts' => 'setPosts' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'posts' => 'getPosts' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('posts', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets posts + * + * @return \OpenAPI\Client\Model\Post[]|null + */ + public function getPosts() + { + return $this->container['posts']; + } + + /** + * Sets posts + * + * @param \OpenAPI\Client\Model\Post[]|null $posts posts + * + * @return self + */ + public function setPosts($posts) + { + if (is_null($posts)) { + throw new \InvalidArgumentException('non-nullable posts cannot be null'); + } + $this->container['posts'] = $posts; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetAllPostsChanges200Response.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetAllPostsChanges200Response.php new file mode 100644 index 0000000000..6dd3ea97c8 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetAllPostsChanges200Response.php @@ -0,0 +1,409 @@ + + */ +class GetAllPostsChanges200Response implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'get_all_posts_changes_200_response'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'changes' => '\OpenAPI\Client\Model\GetAllPostsChanges200ResponseChangesInner[]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'changes' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'changes' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'changes' => 'changes' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'changes' => 'setChanges' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'changes' => 'getChanges' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('changes', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets changes + * + * @return \OpenAPI\Client\Model\GetAllPostsChanges200ResponseChangesInner[]|null + */ + public function getChanges() + { + return $this->container['changes']; + } + + /** + * Sets changes + * + * @param \OpenAPI\Client\Model\GetAllPostsChanges200ResponseChangesInner[]|null $changes changes + * + * @return self + */ + public function setChanges($changes) + { + if (is_null($changes)) { + throw new \InvalidArgumentException('non-nullable changes cannot be null'); + } + $this->container['changes'] = $changes; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetAllPostsChanges200ResponseChangesInner.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetAllPostsChanges200ResponseChangesInner.php new file mode 100644 index 0000000000..0d41cb34d0 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetAllPostsChanges200ResponseChangesInner.php @@ -0,0 +1,511 @@ + + */ +class GetAllPostsChanges200ResponseChangesInner implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'get_all_posts_changes_200_response_changes_inner'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'change_id' => 'int', + 'post_id' => 'string', + 'date' => '\DateTime', + 'type' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'change_id' => null, + 'post_id' => null, + 'date' => 'date-time', + 'type' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'change_id' => false, + 'post_id' => false, + 'date' => false, + 'type' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'change_id' => 'change_id', + 'post_id' => 'post_id', + 'date' => 'date', + 'type' => 'type' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'change_id' => 'setChangeId', + 'post_id' => 'setPostId', + 'date' => 'setDate', + 'type' => 'setType' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'change_id' => 'getChangeId', + 'post_id' => 'getPostId', + 'date' => 'getDate', + 'type' => 'getType' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('change_id', $data ?? [], null); + $this->setIfExists('post_id', $data ?? [], null); + $this->setIfExists('date', $data ?? [], null); + $this->setIfExists('type', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets change_id + * + * @return int|null + */ + public function getChangeId() + { + return $this->container['change_id']; + } + + /** + * Sets change_id + * + * @param int|null $change_id The unique ID for this change. This is an auto-incrementing ID that can be used by clients to make sure they have received every change. If a client detects a gap in the change ID (eg. 1, 3, 4 instead of 1,2,3,4) then the client should repoll older changes to get the missing change. + * + * @return self + */ + public function setChangeId($change_id) + { + if (is_null($change_id)) { + throw new \InvalidArgumentException('non-nullable change_id cannot be null'); + } + $this->container['change_id'] = $change_id; + + return $this; + } + + /** + * Gets post_id + * + * @return string|null + */ + public function getPostId() + { + return $this->container['post_id']; + } + + /** + * Sets post_id + * + * @param string|null $post_id post_id + * + * @return self + */ + public function setPostId($post_id) + { + if (is_null($post_id)) { + throw new \InvalidArgumentException('non-nullable post_id cannot be null'); + } + $this->container['post_id'] = $post_id; + + return $this; + } + + /** + * Gets date + * + * @return \DateTime|null + */ + public function getDate() + { + return $this->container['date']; + } + + /** + * Sets date + * + * @param \DateTime|null $date The UTC date and time when the post was changed. + * + * @return self + */ + public function setDate($date) + { + if (is_null($date)) { + throw new \InvalidArgumentException('non-nullable date cannot be null'); + } + $this->container['date'] = $date; + + return $this; + } + + /** + * Gets type + * + * @return string|null + */ + public function getType() + { + return $this->container['type']; + } + + /** + * Sets type + * + * @param string|null $type The type of change. One of: published, deleted, undeleted, satisfied, promised, unpromised, withdrawn, edited, expired + * + * @return self + */ + public function setType($type) + { + if (is_null($type)) { + throw new \InvalidArgumentException('non-nullable type cannot be null'); + } + $this->container['type'] = $type; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetPostAndRelatedData200Response.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetPostAndRelatedData200Response.php new file mode 100644 index 0000000000..129a15d954 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetPostAndRelatedData200Response.php @@ -0,0 +1,749 @@ + + */ +class GetPostAndRelatedData200Response implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'get_post_and_related_data_200_response'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'post' => '\OpenAPI\Client\Model\Post', + 'author' => '\OpenAPI\Client\Model\User', + 'author_posts' => '\OpenAPI\Client\Model\Post[]', + 'author_offer_count' => 'int', + 'author_wanted_count' => 'int', + 'groups' => '\OpenAPI\Client\Model\Group[]', + 'user_can_reply' => 'bool', + 'viewed' => 'bool', + 'replied' => 'bool', + 'bookmarked' => 'bool', + 'hidden' => 'bool' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'post' => null, + 'author' => null, + 'author_posts' => null, + 'author_offer_count' => null, + 'author_wanted_count' => null, + 'groups' => null, + 'user_can_reply' => null, + 'viewed' => null, + 'replied' => null, + 'bookmarked' => null, + 'hidden' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'post' => false, + 'author' => false, + 'author_posts' => false, + 'author_offer_count' => false, + 'author_wanted_count' => false, + 'groups' => false, + 'user_can_reply' => false, + 'viewed' => false, + 'replied' => false, + 'bookmarked' => false, + 'hidden' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'post' => 'post', + 'author' => 'author', + 'author_posts' => 'author_posts', + 'author_offer_count' => 'author_offer_count', + 'author_wanted_count' => 'author_wanted_count', + 'groups' => 'groups', + 'user_can_reply' => 'user_can_reply', + 'viewed' => 'viewed', + 'replied' => 'replied', + 'bookmarked' => 'bookmarked', + 'hidden' => 'hidden' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'post' => 'setPost', + 'author' => 'setAuthor', + 'author_posts' => 'setAuthorPosts', + 'author_offer_count' => 'setAuthorOfferCount', + 'author_wanted_count' => 'setAuthorWantedCount', + 'groups' => 'setGroups', + 'user_can_reply' => 'setUserCanReply', + 'viewed' => 'setViewed', + 'replied' => 'setReplied', + 'bookmarked' => 'setBookmarked', + 'hidden' => 'setHidden' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'post' => 'getPost', + 'author' => 'getAuthor', + 'author_posts' => 'getAuthorPosts', + 'author_offer_count' => 'getAuthorOfferCount', + 'author_wanted_count' => 'getAuthorWantedCount', + 'groups' => 'getGroups', + 'user_can_reply' => 'getUserCanReply', + 'viewed' => 'getViewed', + 'replied' => 'getReplied', + 'bookmarked' => 'getBookmarked', + 'hidden' => 'getHidden' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('post', $data ?? [], null); + $this->setIfExists('author', $data ?? [], null); + $this->setIfExists('author_posts', $data ?? [], null); + $this->setIfExists('author_offer_count', $data ?? [], null); + $this->setIfExists('author_wanted_count', $data ?? [], null); + $this->setIfExists('groups', $data ?? [], null); + $this->setIfExists('user_can_reply', $data ?? [], null); + $this->setIfExists('viewed', $data ?? [], null); + $this->setIfExists('replied', $data ?? [], null); + $this->setIfExists('bookmarked', $data ?? [], null); + $this->setIfExists('hidden', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets post + * + * @return \OpenAPI\Client\Model\Post|null + */ + public function getPost() + { + return $this->container['post']; + } + + /** + * Sets post + * + * @param \OpenAPI\Client\Model\Post|null $post post + * + * @return self + */ + public function setPost($post) + { + if (is_null($post)) { + throw new \InvalidArgumentException('non-nullable post cannot be null'); + } + $this->container['post'] = $post; + + return $this; + } + + /** + * Gets author + * + * @return \OpenAPI\Client\Model\User|null + */ + public function getAuthor() + { + return $this->container['author']; + } + + /** + * Sets author + * + * @param \OpenAPI\Client\Model\User|null $author author + * + * @return self + */ + public function setAuthor($author) + { + if (is_null($author)) { + throw new \InvalidArgumentException('non-nullable author cannot be null'); + } + $this->container['author'] = $author; + + return $this; + } + + /** + * Gets author_posts + * + * @return \OpenAPI\Client\Model\Post[]|null + */ + public function getAuthorPosts() + { + return $this->container['author_posts']; + } + + /** + * Sets author_posts + * + * @param \OpenAPI\Client\Model\Post[]|null $author_posts Other active posts from the post author in the last 90 days. A maximum of 30 posts will be returned. + * + * @return self + */ + public function setAuthorPosts($author_posts) + { + if (is_null($author_posts)) { + throw new \InvalidArgumentException('non-nullable author_posts cannot be null'); + } + $this->container['author_posts'] = $author_posts; + + return $this; + } + + /** + * Gets author_offer_count + * + * @return int|null + */ + public function getAuthorOfferCount() + { + return $this->container['author_offer_count']; + } + + /** + * Sets author_offer_count + * + * @param int|null $author_offer_count Count of offer posts made by the post author in the last 90 days. + * + * @return self + */ + public function setAuthorOfferCount($author_offer_count) + { + if (is_null($author_offer_count)) { + throw new \InvalidArgumentException('non-nullable author_offer_count cannot be null'); + } + $this->container['author_offer_count'] = $author_offer_count; + + return $this; + } + + /** + * Gets author_wanted_count + * + * @return int|null + */ + public function getAuthorWantedCount() + { + return $this->container['author_wanted_count']; + } + + /** + * Sets author_wanted_count + * + * @param int|null $author_wanted_count Count of wanted posts made by the post author in the last 90 days. + * + * @return self + */ + public function setAuthorWantedCount($author_wanted_count) + { + if (is_null($author_wanted_count)) { + throw new \InvalidArgumentException('non-nullable author_wanted_count cannot be null'); + } + $this->container['author_wanted_count'] = $author_wanted_count; + + return $this; + } + + /** + * Gets groups + * + * @return \OpenAPI\Client\Model\Group[]|null + */ + public function getGroups() + { + return $this->container['groups']; + } + + /** + * Sets groups + * + * @param \OpenAPI\Client\Model\Group[]|null $groups The groups the post is published on. + * + * @return self + */ + public function setGroups($groups) + { + if (is_null($groups)) { + throw new \InvalidArgumentException('non-nullable groups cannot be null'); + } + $this->container['groups'] = $groups; + + return $this; + } + + /** + * Gets user_can_reply + * + * @return bool|null + */ + public function getUserCanReply() + { + return $this->container['user_can_reply']; + } + + /** + * Sets user_can_reply + * + * @param bool|null $user_can_reply Whether or not the current user (if any) can reply to this post. Unverified users cannot reply to posts until they verify their account. + * + * @return self + */ + public function setUserCanReply($user_can_reply) + { + if (is_null($user_can_reply)) { + throw new \InvalidArgumentException('non-nullable user_can_reply cannot be null'); + } + $this->container['user_can_reply'] = $user_can_reply; + + return $this; + } + + /** + * Gets viewed + * + * @return bool|null + */ + public function getViewed() + { + return $this->container['viewed']; + } + + /** + * Sets viewed + * + * @param bool|null $viewed Whether or not the current user has previously viewed this post. Will be null for api key requests and for the current users' posts. + * + * @return self + */ + public function setViewed($viewed) + { + if (is_null($viewed)) { + throw new \InvalidArgumentException('non-nullable viewed cannot be null'); + } + $this->container['viewed'] = $viewed; + + return $this; + } + + /** + * Gets replied + * + * @return bool|null + */ + public function getReplied() + { + return $this->container['replied']; + } + + /** + * Sets replied + * + * @param bool|null $replied Whether or not the current user has replied to this post. Will be null for api key requests and for the current users' posts. + * + * @return self + */ + public function setReplied($replied) + { + if (is_null($replied)) { + throw new \InvalidArgumentException('non-nullable replied cannot be null'); + } + $this->container['replied'] = $replied; + + return $this; + } + + /** + * Gets bookmarked + * + * @return bool|null + */ + public function getBookmarked() + { + return $this->container['bookmarked']; + } + + /** + * Sets bookmarked + * + * @param bool|null $bookmarked Whether or not the current user has bookmarked this post. Will be null for api key requests and for the current users' posts. + * + * @return self + */ + public function setBookmarked($bookmarked) + { + if (is_null($bookmarked)) { + throw new \InvalidArgumentException('non-nullable bookmarked cannot be null'); + } + $this->container['bookmarked'] = $bookmarked; + + return $this; + } + + /** + * Gets hidden + * + * @return bool|null + */ + public function getHidden() + { + return $this->container['hidden']; + } + + /** + * Sets hidden + * + * @param bool|null $hidden Whether the current user has hidden the post author. + * + * @return self + */ + public function setHidden($hidden) + { + if (is_null($hidden)) { + throw new \InvalidArgumentException('non-nullable hidden cannot be null'); + } + $this->container['hidden'] = $hidden; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetPostsByIds200Response.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetPostsByIds200Response.php new file mode 100644 index 0000000000..0e86e8acd6 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetPostsByIds200Response.php @@ -0,0 +1,477 @@ + + */ +class GetPostsByIds200Response implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'get_posts_by_ids_200_response'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'posts' => '\OpenAPI\Client\Model\Post[]', + 'not_found' => 'string[]', + 'forbidden' => 'string[]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'posts' => null, + 'not_found' => null, + 'forbidden' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'posts' => false, + 'not_found' => false, + 'forbidden' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'posts' => 'posts', + 'not_found' => 'not_found', + 'forbidden' => 'forbidden' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'posts' => 'setPosts', + 'not_found' => 'setNotFound', + 'forbidden' => 'setForbidden' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'posts' => 'getPosts', + 'not_found' => 'getNotFound', + 'forbidden' => 'getForbidden' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('posts', $data ?? [], null); + $this->setIfExists('not_found', $data ?? [], null); + $this->setIfExists('forbidden', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets posts + * + * @return \OpenAPI\Client\Model\Post[]|null + */ + public function getPosts() + { + return $this->container['posts']; + } + + /** + * Sets posts + * + * @param \OpenAPI\Client\Model\Post[]|null $posts posts + * + * @return self + */ + public function setPosts($posts) + { + if (is_null($posts)) { + throw new \InvalidArgumentException('non-nullable posts cannot be null'); + } + $this->container['posts'] = $posts; + + return $this; + } + + /** + * Gets not_found + * + * @return string[]|null + */ + public function getNotFound() + { + return $this->container['not_found']; + } + + /** + * Sets not_found + * + * @param string[]|null $not_found The IDs of posts that weren't found (may have been deleted or never existed). + * + * @return self + */ + public function setNotFound($not_found) + { + if (is_null($not_found)) { + throw new \InvalidArgumentException('non-nullable not_found cannot be null'); + } + $this->container['not_found'] = $not_found; + + return $this; + } + + /** + * Gets forbidden + * + * @return string[]|null + */ + public function getForbidden() + { + return $this->container['forbidden']; + } + + /** + * Sets forbidden + * + * @param string[]|null $forbidden The IDs of posts that are forbidden for the current user. + * + * @return self + */ + public function setForbidden($forbidden) + { + if (is_null($forbidden)) { + throw new \InvalidArgumentException('non-nullable forbidden cannot be null'); + } + $this->container['forbidden'] = $forbidden; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetUserPosts200Response.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetUserPosts200Response.php new file mode 100644 index 0000000000..f46e7ce0f0 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GetUserPosts200Response.php @@ -0,0 +1,681 @@ + + */ +class GetUserPosts200Response implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'get_user_posts_200_response'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'posts' => '\OpenAPI\Client\Model\Post[]', + 'num_posts' => 'int', + 'page' => 'int', + 'per_page' => 'int', + 'num_pages' => 'int', + 'start_index' => 'int', + 'end_index' => 'int', + 'group_ids' => 'string[]', + 'last_listings_view' => '\DateTime' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'posts' => null, + 'num_posts' => null, + 'page' => null, + 'per_page' => null, + 'num_pages' => null, + 'start_index' => null, + 'end_index' => null, + 'group_ids' => null, + 'last_listings_view' => 'date-time' + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'posts' => false, + 'num_posts' => false, + 'page' => false, + 'per_page' => false, + 'num_pages' => false, + 'start_index' => false, + 'end_index' => false, + 'group_ids' => false, + 'last_listings_view' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'posts' => 'posts', + 'num_posts' => 'num_posts', + 'page' => 'page', + 'per_page' => 'per_page', + 'num_pages' => 'num_pages', + 'start_index' => 'start_index', + 'end_index' => 'end_index', + 'group_ids' => 'group_ids', + 'last_listings_view' => 'last_listings_view' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'posts' => 'setPosts', + 'num_posts' => 'setNumPosts', + 'page' => 'setPage', + 'per_page' => 'setPerPage', + 'num_pages' => 'setNumPages', + 'start_index' => 'setStartIndex', + 'end_index' => 'setEndIndex', + 'group_ids' => 'setGroupIds', + 'last_listings_view' => 'setLastListingsView' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'posts' => 'getPosts', + 'num_posts' => 'getNumPosts', + 'page' => 'getPage', + 'per_page' => 'getPerPage', + 'num_pages' => 'getNumPages', + 'start_index' => 'getStartIndex', + 'end_index' => 'getEndIndex', + 'group_ids' => 'getGroupIds', + 'last_listings_view' => 'getLastListingsView' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('posts', $data ?? [], null); + $this->setIfExists('num_posts', $data ?? [], null); + $this->setIfExists('page', $data ?? [], null); + $this->setIfExists('per_page', $data ?? [], null); + $this->setIfExists('num_pages', $data ?? [], null); + $this->setIfExists('start_index', $data ?? [], null); + $this->setIfExists('end_index', $data ?? [], null); + $this->setIfExists('group_ids', $data ?? [], null); + $this->setIfExists('last_listings_view', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets posts + * + * @return \OpenAPI\Client\Model\Post[]|null + */ + public function getPosts() + { + return $this->container['posts']; + } + + /** + * Sets posts + * + * @param \OpenAPI\Client\Model\Post[]|null $posts posts + * + * @return self + */ + public function setPosts($posts) + { + if (is_null($posts)) { + throw new \InvalidArgumentException('non-nullable posts cannot be null'); + } + $this->container['posts'] = $posts; + + return $this; + } + + /** + * Gets num_posts + * + * @return int|null + */ + public function getNumPosts() + { + return $this->container['num_posts']; + } + + /** + * Sets num_posts + * + * @param int|null $num_posts The total number of posts available. + * + * @return self + */ + public function setNumPosts($num_posts) + { + if (is_null($num_posts)) { + throw new \InvalidArgumentException('non-nullable num_posts cannot be null'); + } + $this->container['num_posts'] = $num_posts; + + return $this; + } + + /** + * Gets page + * + * @return int|null + */ + public function getPage() + { + return $this->container['page']; + } + + /** + * Sets page + * + * @param int|null $page The page number of the posts being returned. + * + * @return self + */ + public function setPage($page) + { + if (is_null($page)) { + throw new \InvalidArgumentException('non-nullable page cannot be null'); + } + $this->container['page'] = $page; + + return $this; + } + + /** + * Gets per_page + * + * @return int|null + */ + public function getPerPage() + { + return $this->container['per_page']; + } + + /** + * Sets per_page + * + * @param int|null $per_page The number of posts being returned per page. + * + * @return self + */ + public function setPerPage($per_page) + { + if (is_null($per_page)) { + throw new \InvalidArgumentException('non-nullable per_page cannot be null'); + } + $this->container['per_page'] = $per_page; + + return $this; + } + + /** + * Gets num_pages + * + * @return int|null + */ + public function getNumPages() + { + return $this->container['num_pages']; + } + + /** + * Sets num_pages + * + * @param int|null $num_pages The total number of pages available. + * + * @return self + */ + public function setNumPages($num_pages) + { + if (is_null($num_pages)) { + throw new \InvalidArgumentException('non-nullable num_pages cannot be null'); + } + $this->container['num_pages'] = $num_pages; + + return $this; + } + + /** + * Gets start_index + * + * @return int|null + */ + public function getStartIndex() + { + return $this->container['start_index']; + } + + /** + * Sets start_index + * + * @param int|null $start_index The index of the first post being returned (an integer between 1 and num_posts). + * + * @return self + */ + public function setStartIndex($start_index) + { + if (is_null($start_index)) { + throw new \InvalidArgumentException('non-nullable start_index cannot be null'); + } + $this->container['start_index'] = $start_index; + + return $this; + } + + /** + * Gets end_index + * + * @return int|null + */ + public function getEndIndex() + { + return $this->container['end_index']; + } + + /** + * Sets end_index + * + * @param int|null $end_index The index of the last post being returned (an integer between start_index and num_posts). + * + * @return self + */ + public function setEndIndex($end_index) + { + if (is_null($end_index)) { + throw new \InvalidArgumentException('non-nullable end_index cannot be null'); + } + $this->container['end_index'] = $end_index; + + return $this; + } + + /** + * Gets group_ids + * + * @return string[]|null + */ + public function getGroupIds() + { + return $this->container['group_ids']; + } + + /** + * Sets group_ids + * + * @param string[]|null $group_ids The IDs of the groups that the posts were retrieved from (will be null when no group IDs were used). These IDs may be a subset of the requested group IDs when a request includes group IDs for groups that are not open archives and that the current user is not a member of. If the open_archive_groups source is used, these IDs may include the IDs of open archive groups that weren't present in the group_ids parameter of the request. + * + * @return self + */ + public function setGroupIds($group_ids) + { + if (is_null($group_ids)) { + throw new \InvalidArgumentException('non-nullable group_ids cannot be null'); + } + $this->container['group_ids'] = $group_ids; + + return $this; + } + + /** + * Gets last_listings_view + * + * @return \DateTime|null + */ + public function getLastListingsView() + { + return $this->container['last_listings_view']; + } + + /** + * Sets last_listings_view + * + * @param \DateTime|null $last_listings_view The UTC date and time when the current user last viewed the newest posts on the All Posts page (may be null).

NOTE: For this to be accurate, clients must update the last_listings_view property of the current user every time the user is shown the newest posts on the All Posts page.

NOTE: For requests using an api key instead of oauth, this field is always null. + * + * @return self + */ + public function setLastListingsView($last_listings_view) + { + if (is_null($last_listings_view)) { + throw new \InvalidArgumentException('non-nullable last_listings_view cannot be null'); + } + $this->container['last_listings_view'] = $last_listings_view; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/Group.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/Group.php new file mode 100644 index 0000000000..948c1c2f2c --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/Group.php @@ -0,0 +1,852 @@ + + */ +class Group implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'Group'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'group_id' => 'string', + 'name' => 'string', + 'identifier' => 'string', + 'homepage' => 'string', + 'member_count' => 'int', + 'latitude' => 'float', + 'longitude' => 'float', + 'timezone' => 'string', + 'open_membership' => 'bool', + 'open_archives' => 'bool', + 'has_questions' => 'bool', + 'country' => '\OpenAPI\Client\Model\GroupCountry', + 'region' => '\OpenAPI\Client\Model\GroupRegion', + 'membership' => '\OpenAPI\Client\Model\GroupMembership' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'group_id' => null, + 'name' => null, + 'identifier' => null, + 'homepage' => null, + 'member_count' => null, + 'latitude' => null, + 'longitude' => null, + 'timezone' => null, + 'open_membership' => null, + 'open_archives' => null, + 'has_questions' => null, + 'country' => null, + 'region' => null, + 'membership' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'group_id' => false, + 'name' => false, + 'identifier' => false, + 'homepage' => false, + 'member_count' => false, + 'latitude' => false, + 'longitude' => false, + 'timezone' => false, + 'open_membership' => false, + 'open_archives' => false, + 'has_questions' => false, + 'country' => false, + 'region' => false, + 'membership' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'group_id' => 'group_id', + 'name' => 'name', + 'identifier' => 'identifier', + 'homepage' => 'homepage', + 'member_count' => 'member_count', + 'latitude' => 'latitude', + 'longitude' => 'longitude', + 'timezone' => 'timezone', + 'open_membership' => 'open_membership', + 'open_archives' => 'open_archives', + 'has_questions' => 'has_questions', + 'country' => 'country', + 'region' => 'region', + 'membership' => 'membership' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'group_id' => 'setGroupId', + 'name' => 'setName', + 'identifier' => 'setIdentifier', + 'homepage' => 'setHomepage', + 'member_count' => 'setMemberCount', + 'latitude' => 'setLatitude', + 'longitude' => 'setLongitude', + 'timezone' => 'setTimezone', + 'open_membership' => 'setOpenMembership', + 'open_archives' => 'setOpenArchives', + 'has_questions' => 'setHasQuestions', + 'country' => 'setCountry', + 'region' => 'setRegion', + 'membership' => 'setMembership' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'group_id' => 'getGroupId', + 'name' => 'getName', + 'identifier' => 'getIdentifier', + 'homepage' => 'getHomepage', + 'member_count' => 'getMemberCount', + 'latitude' => 'getLatitude', + 'longitude' => 'getLongitude', + 'timezone' => 'getTimezone', + 'open_membership' => 'getOpenMembership', + 'open_archives' => 'getOpenArchives', + 'has_questions' => 'getHasQuestions', + 'country' => 'getCountry', + 'region' => 'getRegion', + 'membership' => 'getMembership' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('group_id', $data ?? [], null); + $this->setIfExists('name', $data ?? [], null); + $this->setIfExists('identifier', $data ?? [], null); + $this->setIfExists('homepage', $data ?? [], null); + $this->setIfExists('member_count', $data ?? [], null); + $this->setIfExists('latitude', $data ?? [], null); + $this->setIfExists('longitude', $data ?? [], null); + $this->setIfExists('timezone', $data ?? [], null); + $this->setIfExists('open_membership', $data ?? [], null); + $this->setIfExists('open_archives', $data ?? [], null); + $this->setIfExists('has_questions', $data ?? [], null); + $this->setIfExists('country', $data ?? [], null); + $this->setIfExists('region', $data ?? [], null); + $this->setIfExists('membership', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets group_id + * + * @return string|null + */ + public function getGroupId() + { + return $this->container['group_id']; + } + + /** + * Sets group_id + * + * @param string|null $group_id group_id + * + * @return self + */ + public function setGroupId($group_id) + { + if (is_null($group_id)) { + throw new \InvalidArgumentException('non-nullable group_id cannot be null'); + } + $this->container['group_id'] = $group_id; + + return $this; + } + + /** + * Gets name + * + * @return string|null + */ + public function getName() + { + return $this->container['name']; + } + + /** + * Sets name + * + * @param string|null $name The name of the group (not guaranteed to be unique). + * + * @return self + */ + public function setName($name) + { + if (is_null($name)) { + throw new \InvalidArgumentException('non-nullable name cannot be null'); + } + $this->container['name'] = $name; + + return $this; + } + + /** + * Gets identifier + * + * @return string|null + */ + public function getIdentifier() + { + return $this->container['identifier']; + } + + /** + * Sets identifier + * + * @param string|null $identifier A unique identifier for the group that is used in URLs. + * + * @return self + */ + public function setIdentifier($identifier) + { + if (is_null($identifier)) { + throw new \InvalidArgumentException('non-nullable identifier cannot be null'); + } + $this->container['identifier'] = $identifier; + + return $this; + } + + /** + * Gets homepage + * + * @return string|null + */ + public function getHomepage() + { + return $this->container['homepage']; + } + + /** + * Sets homepage + * + * @param string|null $homepage A URL to the group homepage. + * + * @return self + */ + public function setHomepage($homepage) + { + if (is_null($homepage)) { + throw new \InvalidArgumentException('non-nullable homepage cannot be null'); + } + $this->container['homepage'] = $homepage; + + return $this; + } + + /** + * Gets member_count + * + * @return int|null + */ + public function getMemberCount() + { + return $this->container['member_count']; + } + + /** + * Sets member_count + * + * @param int|null $member_count The number of members who belong to the group. + * + * @return self + */ + public function setMemberCount($member_count) + { + if (is_null($member_count)) { + throw new \InvalidArgumentException('non-nullable member_count cannot be null'); + } + $this->container['member_count'] = $member_count; + + return $this; + } + + /** + * Gets latitude + * + * @return float|null + */ + public function getLatitude() + { + return $this->container['latitude']; + } + + /** + * Sets latitude + * + * @param float|null $latitude latitude + * + * @return self + */ + public function setLatitude($latitude) + { + if (is_null($latitude)) { + throw new \InvalidArgumentException('non-nullable latitude cannot be null'); + } + $this->container['latitude'] = $latitude; + + return $this; + } + + /** + * Gets longitude + * + * @return float|null + */ + public function getLongitude() + { + return $this->container['longitude']; + } + + /** + * Sets longitude + * + * @param float|null $longitude longitude + * + * @return self + */ + public function setLongitude($longitude) + { + if (is_null($longitude)) { + throw new \InvalidArgumentException('non-nullable longitude cannot be null'); + } + $this->container['longitude'] = $longitude; + + return $this; + } + + /** + * Gets timezone + * + * @return string|null + */ + public function getTimezone() + { + return $this->container['timezone']; + } + + /** + * Sets timezone + * + * @param string|null $timezone The timezone that the group is in (eg. America/New_York). + * + * @return self + */ + public function setTimezone($timezone) + { + if (is_null($timezone)) { + throw new \InvalidArgumentException('non-nullable timezone cannot be null'); + } + $this->container['timezone'] = $timezone; + + return $this; + } + + /** + * Gets open_membership + * + * @return bool|null + */ + public function getOpenMembership() + { + return $this->container['open_membership']; + } + + /** + * Sets open_membership + * + * @param bool|null $open_membership When true, the group allows anyone to join. When false, the group moderators review and approve applicants. + * + * @return self + */ + public function setOpenMembership($open_membership) + { + if (is_null($open_membership)) { + throw new \InvalidArgumentException('non-nullable open_membership cannot be null'); + } + $this->container['open_membership'] = $open_membership; + + return $this; + } + + /** + * Gets open_archives + * + * @return bool|null + */ + public function getOpenArchives() + { + return $this->container['open_archives']; + } + + /** + * Sets open_archives + * + * @param bool|null $open_archives When true, the group posts are viewable by anyone. When false, the group posts can only be viewed by members of the group. + * + * @return self + */ + public function setOpenArchives($open_archives) + { + if (is_null($open_archives)) { + throw new \InvalidArgumentException('non-nullable open_archives cannot be null'); + } + $this->container['open_archives'] = $open_archives; + + return $this; + } + + /** + * Gets has_questions + * + * @return bool|null + */ + public function getHasQuestions() + { + return $this->container['has_questions']; + } + + /** + * Sets has_questions + * + * @param bool|null $has_questions When true, anyone requesting membership to this group will be required to answer a new membership questionnaire. + * + * @return self + */ + public function setHasQuestions($has_questions) + { + if (is_null($has_questions)) { + throw new \InvalidArgumentException('non-nullable has_questions cannot be null'); + } + $this->container['has_questions'] = $has_questions; + + return $this; + } + + /** + * Gets country + * + * @return \OpenAPI\Client\Model\GroupCountry|null + */ + public function getCountry() + { + return $this->container['country']; + } + + /** + * Sets country + * + * @param \OpenAPI\Client\Model\GroupCountry|null $country country + * + * @return self + */ + public function setCountry($country) + { + if (is_null($country)) { + throw new \InvalidArgumentException('non-nullable country cannot be null'); + } + $this->container['country'] = $country; + + return $this; + } + + /** + * Gets region + * + * @return \OpenAPI\Client\Model\GroupRegion|null + */ + public function getRegion() + { + return $this->container['region']; + } + + /** + * Sets region + * + * @param \OpenAPI\Client\Model\GroupRegion|null $region region + * + * @return self + */ + public function setRegion($region) + { + if (is_null($region)) { + throw new \InvalidArgumentException('non-nullable region cannot be null'); + } + $this->container['region'] = $region; + + return $this; + } + + /** + * Gets membership + * + * @return \OpenAPI\Client\Model\GroupMembership|null + */ + public function getMembership() + { + return $this->container['membership']; + } + + /** + * Sets membership + * + * @param \OpenAPI\Client\Model\GroupMembership|null $membership membership + * + * @return self + */ + public function setMembership($membership) + { + if (is_null($membership)) { + throw new \InvalidArgumentException('non-nullable membership cannot be null'); + } + $this->container['membership'] = $membership; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupCountry.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupCountry.php new file mode 100644 index 0000000000..30ad2a1bf6 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupCountry.php @@ -0,0 +1,444 @@ + + */ +class GroupCountry implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'Group_country'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'name' => 'string', + 'abbreviation' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'name' => null, + 'abbreviation' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'name' => false, + 'abbreviation' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'name' => 'name', + 'abbreviation' => 'abbreviation' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'name' => 'setName', + 'abbreviation' => 'setAbbreviation' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'name' => 'getName', + 'abbreviation' => 'getAbbreviation' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('name', $data ?? [], null); + $this->setIfExists('abbreviation', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets name + * + * @return string|null + */ + public function getName() + { + return $this->container['name']; + } + + /** + * Sets name + * + * @param string|null $name The name of the country. + * + * @return self + */ + public function setName($name) + { + if (is_null($name)) { + throw new \InvalidArgumentException('non-nullable name cannot be null'); + } + $this->container['name'] = $name; + + return $this; + } + + /** + * Gets abbreviation + * + * @return string|null + */ + public function getAbbreviation() + { + return $this->container['abbreviation']; + } + + /** + * Sets abbreviation + * + * @param string|null $abbreviation A 2 letter country code for the country (see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ). + * + * @return self + */ + public function setAbbreviation($abbreviation) + { + if (is_null($abbreviation)) { + throw new \InvalidArgumentException('non-nullable abbreviation cannot be null'); + } + $this->container['abbreviation'] = $abbreviation; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupMembership.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupMembership.php new file mode 100644 index 0000000000..062dcde539 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupMembership.php @@ -0,0 +1,478 @@ + + */ +class GroupMembership implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'Group_membership'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'status' => 'string', + 'date' => '\DateTime', + 'questionnaire' => '\OpenAPI\Client\Model\GroupMembershipQuestionnaire' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'status' => null, + 'date' => 'date-time', + 'questionnaire' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'status' => false, + 'date' => false, + 'questionnaire' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'status' => 'status', + 'date' => 'date', + 'questionnaire' => 'questionnaire' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'status' => 'setStatus', + 'date' => 'setDate', + 'questionnaire' => 'setQuestionnaire' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'status' => 'getStatus', + 'date' => 'getDate', + 'questionnaire' => 'getQuestionnaire' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('status', $data ?? [], null); + $this->setIfExists('date', $data ?? [], null); + $this->setIfExists('questionnaire', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets status + * + * @return string|null + */ + public function getStatus() + { + return $this->container['status']; + } + + /** + * Sets status + * + * @param string|null $status One of: subscribed, pending, pending-questions + * + * @return self + */ + public function setStatus($status) + { + if (is_null($status)) { + throw new \InvalidArgumentException('non-nullable status cannot be null'); + } + $this->container['status'] = $status; + + return $this; + } + + /** + * Gets date + * + * @return \DateTime|null + */ + public function getDate() + { + return $this->container['date']; + } + + /** + * Sets date + * + * @param \DateTime|null $date The UTC date and time when the membership was last updated. + * + * @return self + */ + public function setDate($date) + { + if (is_null($date)) { + throw new \InvalidArgumentException('non-nullable date cannot be null'); + } + $this->container['date'] = $date; + + return $this; + } + + /** + * Gets questionnaire + * + * @return \OpenAPI\Client\Model\GroupMembershipQuestionnaire|null + */ + public function getQuestionnaire() + { + return $this->container['questionnaire']; + } + + /** + * Sets questionnaire + * + * @param \OpenAPI\Client\Model\GroupMembershipQuestionnaire|null $questionnaire questionnaire + * + * @return self + */ + public function setQuestionnaire($questionnaire) + { + if (is_null($questionnaire)) { + throw new \InvalidArgumentException('non-nullable questionnaire cannot be null'); + } + $this->container['questionnaire'] = $questionnaire; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupMembershipQuestionnaire.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupMembershipQuestionnaire.php new file mode 100644 index 0000000000..30b2e38090 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupMembershipQuestionnaire.php @@ -0,0 +1,444 @@ + + */ +class GroupMembershipQuestionnaire implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'Group_membership_questionnaire'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'message' => 'string', + 'questions' => 'string[]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'message' => null, + 'questions' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'message' => false, + 'questions' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'message' => 'message', + 'questions' => 'questions' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'message' => 'setMessage', + 'questions' => 'setQuestions' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'message' => 'getMessage', + 'questions' => 'getQuestions' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('message', $data ?? [], null); + $this->setIfExists('questions', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets message + * + * @return string|null + */ + public function getMessage() + { + return $this->container['message']; + } + + /** + * Sets message + * + * @param string|null $message A message from the group moderators to be displayed above the questions (may be null). + * + * @return self + */ + public function setMessage($message) + { + if (is_null($message)) { + throw new \InvalidArgumentException('non-nullable message cannot be null'); + } + $this->container['message'] = $message; + + return $this; + } + + /** + * Gets questions + * + * @return string[]|null + */ + public function getQuestions() + { + return $this->container['questions']; + } + + /** + * Sets questions + * + * @param string[]|null $questions The list of questions. + * + * @return self + */ + public function setQuestions($questions) + { + if (is_null($questions)) { + throw new \InvalidArgumentException('non-nullable questions cannot be null'); + } + $this->container['questions'] = $questions; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupRegion.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupRegion.php new file mode 100644 index 0000000000..30d427b364 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/GroupRegion.php @@ -0,0 +1,444 @@ + + */ +class GroupRegion implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'Group_region'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'name' => 'string', + 'abbreviation' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'name' => null, + 'abbreviation' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'name' => false, + 'abbreviation' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'name' => 'name', + 'abbreviation' => 'abbreviation' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'name' => 'setName', + 'abbreviation' => 'setAbbreviation' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'name' => 'getName', + 'abbreviation' => 'getAbbreviation' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('name', $data ?? [], null); + $this->setIfExists('abbreviation', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets name + * + * @return string|null + */ + public function getName() + { + return $this->container['name']; + } + + /** + * Sets name + * + * @param string|null $name The name of the region. + * + * @return self + */ + public function setName($name) + { + if (is_null($name)) { + throw new \InvalidArgumentException('non-nullable name cannot be null'); + } + $this->container['name'] = $name; + + return $this; + } + + /** + * Gets abbreviation + * + * @return string|null + */ + public function getAbbreviation() + { + return $this->container['abbreviation']; + } + + /** + * Sets abbreviation + * + * @param string|null $abbreviation A 2 letter abbreviation for the region (is not guaranteed to be globally unique but is unique among all the regions in the country). + * + * @return self + */ + public function setAbbreviation($abbreviation) + { + if (is_null($abbreviation)) { + throw new \InvalidArgumentException('non-nullable abbreviation cannot be null'); + } + $this->container['abbreviation'] = $abbreviation; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/ModelInterface.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/ModelInterface.php new file mode 100644 index 0000000000..3c49a265a6 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/ModelInterface.php @@ -0,0 +1,111 @@ + + */ +class Photo implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'Photo'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'photo_id' => 'string', + 'thumbnail' => 'string', + 'url' => 'string', + 'blurhash' => 'string', + 'avif' => 'bool', + 'images' => '\OpenAPI\Client\Model\PhotoImagesInner[]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'photo_id' => null, + 'thumbnail' => null, + 'url' => null, + 'blurhash' => null, + 'avif' => null, + 'images' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'photo_id' => false, + 'thumbnail' => false, + 'url' => false, + 'blurhash' => false, + 'avif' => false, + 'images' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'photo_id' => 'photo_id', + 'thumbnail' => 'thumbnail', + 'url' => 'url', + 'blurhash' => 'blurhash', + 'avif' => 'avif', + 'images' => 'images' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'photo_id' => 'setPhotoId', + 'thumbnail' => 'setThumbnail', + 'url' => 'setUrl', + 'blurhash' => 'setBlurhash', + 'avif' => 'setAvif', + 'images' => 'setImages' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'photo_id' => 'getPhotoId', + 'thumbnail' => 'getThumbnail', + 'url' => 'getUrl', + 'blurhash' => 'getBlurhash', + 'avif' => 'getAvif', + 'images' => 'getImages' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('photo_id', $data ?? [], null); + $this->setIfExists('thumbnail', $data ?? [], null); + $this->setIfExists('url', $data ?? [], null); + $this->setIfExists('blurhash', $data ?? [], null); + $this->setIfExists('avif', $data ?? [], null); + $this->setIfExists('images', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets photo_id + * + * @return string|null + */ + public function getPhotoId() + { + return $this->container['photo_id']; + } + + /** + * Sets photo_id + * + * @param string|null $photo_id photo_id + * + * @return self + */ + public function setPhotoId($photo_id) + { + if (is_null($photo_id)) { + throw new \InvalidArgumentException('non-nullable photo_id cannot be null'); + } + $this->container['photo_id'] = $photo_id; + + return $this; + } + + /** + * Gets thumbnail + * + * @return string|null + */ + public function getThumbnail() + { + return $this->container['thumbnail']; + } + + /** + * Sets thumbnail + * + * @param string|null $thumbnail A URL to a thumbnail of this photo. The size of the thumbnail depends on the device_pixel_ratio parameter and it is not guaranteed to be square. + * + * @return self + */ + public function setThumbnail($thumbnail) + { + if (is_null($thumbnail)) { + throw new \InvalidArgumentException('non-nullable thumbnail cannot be null'); + } + $this->container['thumbnail'] = $thumbnail; + + return $this; + } + + /** + * Gets url + * + * @return string|null + */ + public function getUrl() + { + return $this->container['url']; + } + + /** + * Sets url + * + * @param string|null $url A URL to a large version of this photo (but not necessarily the largest size available). + * + * @return self + */ + public function setUrl($url) + { + if (is_null($url)) { + throw new \InvalidArgumentException('non-nullable url cannot be null'); + } + $this->container['url'] = $url; + + return $this; + } + + /** + * Gets blurhash + * + * @return string|null + */ + public function getBlurhash() + { + return $this->container['blurhash']; + } + + /** + * Sets blurhash + * + * @param string|null $blurhash A blurhash of the photo that can be used as a placeholder while the photo is loading (see: https://github.com/woltapp/blurhash). May be null if no blurhash is available and the length of the blurhash can vary based on the photo. + * + * @return self + */ + public function setBlurhash($blurhash) + { + if (is_null($blurhash)) { + throw new \InvalidArgumentException('non-nullable blurhash cannot be null'); + } + $this->container['blurhash'] = $blurhash; + + return $this; + } + + /** + * Gets avif + * + * @return bool|null + */ + public function getAvif() + { + return $this->container['avif']; + } + + /** + * Sets avif + * + * @param bool|null $avif Whether avif versions of the image are available. If they are, the avif image can be loaded by changing the extension on any of the image URLs to 'avif'. + * + * @return self + */ + public function setAvif($avif) + { + if (is_null($avif)) { + throw new \InvalidArgumentException('non-nullable avif cannot be null'); + } + $this->container['avif'] = $avif; + + return $this; + } + + /** + * Gets images + * + * @return \OpenAPI\Client\Model\PhotoImagesInner[]|null + */ + public function getImages() + { + return $this->container['images']; + } + + /** + * Sets images + * + * @param \OpenAPI\Client\Model\PhotoImagesInner[]|null $images All the versions of this photo ordered from smallest to largest. This list is guaranteed to include the photos specified by the above thumbnail and url properties. + * + * @return self + */ + public function setImages($images) + { + if (is_null($images)) { + throw new \InvalidArgumentException('non-nullable images cannot be null'); + } + $this->container['images'] = $images; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/PhotoImagesInner.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/PhotoImagesInner.php new file mode 100644 index 0000000000..7eb7f852df --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/PhotoImagesInner.php @@ -0,0 +1,477 @@ + + */ +class PhotoImagesInner implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'Photo_images_inner'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'url' => 'string', + 'width' => 'int', + 'height' => 'int' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'url' => null, + 'width' => null, + 'height' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'url' => false, + 'width' => false, + 'height' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'url' => 'url', + 'width' => 'width', + 'height' => 'height' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'url' => 'setUrl', + 'width' => 'setWidth', + 'height' => 'setHeight' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'url' => 'getUrl', + 'width' => 'getWidth', + 'height' => 'getHeight' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('url', $data ?? [], null); + $this->setIfExists('width', $data ?? [], null); + $this->setIfExists('height', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets url + * + * @return string|null + */ + public function getUrl() + { + return $this->container['url']; + } + + /** + * Sets url + * + * @param string|null $url url + * + * @return self + */ + public function setUrl($url) + { + if (is_null($url)) { + throw new \InvalidArgumentException('non-nullable url cannot be null'); + } + $this->container['url'] = $url; + + return $this; + } + + /** + * Gets width + * + * @return int|null + */ + public function getWidth() + { + return $this->container['width']; + } + + /** + * Sets width + * + * @param int|null $width width + * + * @return self + */ + public function setWidth($width) + { + if (is_null($width)) { + throw new \InvalidArgumentException('non-nullable width cannot be null'); + } + $this->container['width'] = $width; + + return $this; + } + + /** + * Gets height + * + * @return int|null + */ + public function getHeight() + { + return $this->container['height']; + } + + /** + * Sets height + * + * @param int|null $height height + * + * @return self + */ + public function setHeight($height) + { + if (is_null($height)) { + throw new \InvalidArgumentException('non-nullable height cannot be null'); + } + $this->container['height'] = $height; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/Post.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/Post.php new file mode 100644 index 0000000000..15b19d7fc1 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/Post.php @@ -0,0 +1,954 @@ + + */ +class Post implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'Post'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'post_id' => 'string', + 'source' => 'string', + 'group_id' => 'string', + 'user_id' => 'string', + 'title' => 'string', + 'content' => 'string', + 'date' => '\DateTime', + 'type' => 'string', + 'outcome' => 'string', + 'latitude' => 'float', + 'longitude' => 'float', + 'footer' => 'string', + 'photos' => '\OpenAPI\Client\Model\Photo[]', + 'expiration' => '\DateTime', + 'reselling' => 'bool', + 'url' => 'string', + 'repost_count' => 'int' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'post_id' => null, + 'source' => null, + 'group_id' => null, + 'user_id' => null, + 'title' => null, + 'content' => null, + 'date' => 'date-time', + 'type' => null, + 'outcome' => null, + 'latitude' => null, + 'longitude' => null, + 'footer' => null, + 'photos' => null, + 'expiration' => 'date-time', + 'reselling' => null, + 'url' => null, + 'repost_count' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'post_id' => false, + 'source' => false, + 'group_id' => false, + 'user_id' => false, + 'title' => false, + 'content' => false, + 'date' => false, + 'type' => false, + 'outcome' => false, + 'latitude' => false, + 'longitude' => false, + 'footer' => false, + 'photos' => false, + 'expiration' => false, + 'reselling' => false, + 'url' => false, + 'repost_count' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'post_id' => 'post_id', + 'source' => 'source', + 'group_id' => 'group_id', + 'user_id' => 'user_id', + 'title' => 'title', + 'content' => 'content', + 'date' => 'date', + 'type' => 'type', + 'outcome' => 'outcome', + 'latitude' => 'latitude', + 'longitude' => 'longitude', + 'footer' => 'footer', + 'photos' => 'photos', + 'expiration' => 'expiration', + 'reselling' => 'reselling', + 'url' => 'url', + 'repost_count' => 'repost_count' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'post_id' => 'setPostId', + 'source' => 'setSource', + 'group_id' => 'setGroupId', + 'user_id' => 'setUserId', + 'title' => 'setTitle', + 'content' => 'setContent', + 'date' => 'setDate', + 'type' => 'setType', + 'outcome' => 'setOutcome', + 'latitude' => 'setLatitude', + 'longitude' => 'setLongitude', + 'footer' => 'setFooter', + 'photos' => 'setPhotos', + 'expiration' => 'setExpiration', + 'reselling' => 'setReselling', + 'url' => 'setUrl', + 'repost_count' => 'setRepostCount' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'post_id' => 'getPostId', + 'source' => 'getSource', + 'group_id' => 'getGroupId', + 'user_id' => 'getUserId', + 'title' => 'getTitle', + 'content' => 'getContent', + 'date' => 'getDate', + 'type' => 'getType', + 'outcome' => 'getOutcome', + 'latitude' => 'getLatitude', + 'longitude' => 'getLongitude', + 'footer' => 'getFooter', + 'photos' => 'getPhotos', + 'expiration' => 'getExpiration', + 'reselling' => 'getReselling', + 'url' => 'getUrl', + 'repost_count' => 'getRepostCount' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('post_id', $data ?? [], null); + $this->setIfExists('source', $data ?? [], null); + $this->setIfExists('group_id', $data ?? [], null); + $this->setIfExists('user_id', $data ?? [], null); + $this->setIfExists('title', $data ?? [], null); + $this->setIfExists('content', $data ?? [], null); + $this->setIfExists('date', $data ?? [], null); + $this->setIfExists('type', $data ?? [], null); + $this->setIfExists('outcome', $data ?? [], null); + $this->setIfExists('latitude', $data ?? [], null); + $this->setIfExists('longitude', $data ?? [], null); + $this->setIfExists('footer', $data ?? [], null); + $this->setIfExists('photos', $data ?? [], null); + $this->setIfExists('expiration', $data ?? [], null); + $this->setIfExists('reselling', $data ?? [], null); + $this->setIfExists('url', $data ?? [], null); + $this->setIfExists('repost_count', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets post_id + * + * @return string|null + */ + public function getPostId() + { + return $this->container['post_id']; + } + + /** + * Sets post_id + * + * @param string|null $post_id post_id + * + * @return self + */ + public function setPostId($post_id) + { + if (is_null($post_id)) { + throw new \InvalidArgumentException('non-nullable post_id cannot be null'); + } + $this->container['post_id'] = $post_id; + + return $this; + } + + /** + * Gets source + * + * @return string|null + */ + public function getSource() + { + return $this->container['source']; + } + + /** + * Sets source + * + * @param string|null $source The source of the post. One of: groups, trashnothing, open_archive_groups. A value of groups or open_archive_groups indicates the post is from a group and the group_id field will contain the ID of the group. A value of trashnothing indicates the post is a public post not associated with any group. + * + * @return self + */ + public function setSource($source) + { + if (is_null($source)) { + throw new \InvalidArgumentException('non-nullable source cannot be null'); + } + $this->container['source'] = $source; + + return $this; + } + + /** + * Gets group_id + * + * @return string|null + */ + public function getGroupId() + { + return $this->container['group_id']; + } + + /** + * Sets group_id + * + * @param string|null $group_id The group ID of the post. For public posts, this is always null. + * + * @return self + */ + public function setGroupId($group_id) + { + if (is_null($group_id)) { + throw new \InvalidArgumentException('non-nullable group_id cannot be null'); + } + $this->container['group_id'] = $group_id; + + return $this; + } + + /** + * Gets user_id + * + * @return string|null + */ + public function getUserId() + { + return $this->container['user_id']; + } + + /** + * Sets user_id + * + * @param string|null $user_id user_id + * + * @return self + */ + public function setUserId($user_id) + { + if (is_null($user_id)) { + throw new \InvalidArgumentException('non-nullable user_id cannot be null'); + } + $this->container['user_id'] = $user_id; + + return $this; + } + + /** + * Gets title + * + * @return string|null + */ + public function getTitle() + { + return $this->container['title']; + } + + /** + * Sets title + * + * @param string|null $title title + * + * @return self + */ + public function setTitle($title) + { + if (is_null($title)) { + throw new \InvalidArgumentException('non-nullable title cannot be null'); + } + $this->container['title'] = $title; + + return $this; + } + + /** + * Gets content + * + * @return string|null + */ + public function getContent() + { + return $this->container['content']; + } + + /** + * Sets content + * + * @param string|null $content content + * + * @return self + */ + public function setContent($content) + { + if (is_null($content)) { + throw new \InvalidArgumentException('non-nullable content cannot be null'); + } + $this->container['content'] = $content; + + return $this; + } + + /** + * Gets date + * + * @return \DateTime|null + */ + public function getDate() + { + return $this->container['date']; + } + + /** + * Sets date + * + * @param \DateTime|null $date The UTC date and time when the post was published. + * + * @return self + */ + public function setDate($date) + { + if (is_null($date)) { + throw new \InvalidArgumentException('non-nullable date cannot be null'); + } + $this->container['date'] = $date; + + return $this; + } + + /** + * Gets type + * + * @return string|null + */ + public function getType() + { + return $this->container['type']; + } + + /** + * Sets type + * + * @param string|null $type The type of post. One of: offer, wanted, admin + * + * @return self + */ + public function setType($type) + { + if (is_null($type)) { + throw new \InvalidArgumentException('non-nullable type cannot be null'); + } + $this->container['type'] = $type; + + return $this; + } + + /** + * Gets outcome + * + * @return string|null + */ + public function getOutcome() + { + return $this->container['outcome']; + } + + /** + * Sets outcome + * + * @param string|null $outcome For offer and wanted posts, this indicates the outcome of the post which is null if no outcome has been set yet.

Offer post outcomes will be one of: satisfied, withdrawn, promised, expired

Wanted post outcomes will be one of: satisfied, withdrawn, expired

For all other posts, outcome is always null. + * + * @return self + */ + public function setOutcome($outcome) + { + if (is_null($outcome)) { + throw new \InvalidArgumentException('non-nullable outcome cannot be null'); + } + $this->container['outcome'] = $outcome; + + return $this; + } + + /** + * Gets latitude + * + * @return float|null + */ + public function getLatitude() + { + return $this->container['latitude']; + } + + /** + * Sets latitude + * + * @param float|null $latitude May be null if a post hasn't been mapped. + * + * @return self + */ + public function setLatitude($latitude) + { + if (is_null($latitude)) { + throw new \InvalidArgumentException('non-nullable latitude cannot be null'); + } + $this->container['latitude'] = $latitude; + + return $this; + } + + /** + * Gets longitude + * + * @return float|null + */ + public function getLongitude() + { + return $this->container['longitude']; + } + + /** + * Sets longitude + * + * @param float|null $longitude May be null if a post hasn't been mapped. + * + * @return self + */ + public function setLongitude($longitude) + { + if (is_null($longitude)) { + throw new \InvalidArgumentException('non-nullable longitude cannot be null'); + } + $this->container['longitude'] = $longitude; + + return $this; + } + + /** + * Gets footer + * + * @return string|null + */ + public function getFooter() + { + return $this->container['footer']; + } + + /** + * Sets footer + * + * @param string|null $footer Some groups add footers to posts that are separate and sometimes unrelated to the post itself - such as reminders about group rules or features (may be null). + * + * @return self + */ + public function setFooter($footer) + { + if (is_null($footer)) { + throw new \InvalidArgumentException('non-nullable footer cannot be null'); + } + $this->container['footer'] = $footer; + + return $this; + } + + /** + * Gets photos + * + * @return \OpenAPI\Client\Model\Photo[]|null + */ + public function getPhotos() + { + return $this->container['photos']; + } + + /** + * Sets photos + * + * @param \OpenAPI\Client\Model\Photo[]|null $photos Details about the photos associated with this post (may be null if there are no photos). + * + * @return self + */ + public function setPhotos($photos) + { + if (is_null($photos)) { + throw new \InvalidArgumentException('non-nullable photos cannot be null'); + } + $this->container['photos'] = $photos; + + return $this; + } + + /** + * Gets expiration + * + * @return \DateTime|null + */ + public function getExpiration() + { + return $this->container['expiration']; + } + + /** + * Sets expiration + * + * @param \DateTime|null $expiration The UTC date and time when the post will expire. Currently only offer and wanted posts expire. For all other posts, expiration is always null. + * + * @return self + */ + public function setExpiration($expiration) + { + if (is_null($expiration)) { + throw new \InvalidArgumentException('non-nullable expiration cannot be null'); + } + $this->container['expiration'] = $expiration; + + return $this; + } + + /** + * Gets reselling + * + * @return bool|null + */ + public function getReselling() + { + return $this->container['reselling']; + } + + /** + * Sets reselling + * + * @param bool|null $reselling For wanted posts, whether the item is being requested in order to resell it or not. Will be null for all posts that are not wanted posts and for wanted posts where the poster hasn't indicated whether or not they intend to resell the item they are requesting. + * + * @return self + */ + public function setReselling($reselling) + { + if (is_null($reselling)) { + throw new \InvalidArgumentException('non-nullable reselling cannot be null'); + } + $this->container['reselling'] = $reselling; + + return $this; + } + + /** + * Gets url + * + * @return string|null + */ + public function getUrl() + { + return $this->container['url']; + } + + /** + * Sets url + * + * @param string|null $url The link to use to view the post on the Trash Nothing site. + * + * @return self + */ + public function setUrl($url) + { + if (is_null($url)) { + throw new \InvalidArgumentException('non-nullable url cannot be null'); + } + $this->container['url'] = $url; + + return $this; + } + + /** + * Gets repost_count + * + * @return int|null + */ + public function getRepostCount() + { + return $this->container['repost_count']; + } + + /** + * Sets repost_count + * + * @param int|null $repost_count The count of how many times this post has been reposted in the last 90 days. A value of zero is used to indicate that the post is not a repost. The count is specific to the source of the post (eg. the specific group the post is on). If a post is crossposted to multiple groups, the repost_count of the post on each group may be different for each group depending on how many times the post has been posted on that group in the last 90 days. + * + * @return self + */ + public function setRepostCount($repost_count) + { + if (is_null($repost_count)) { + throw new \InvalidArgumentException('non-nullable repost_count cannot be null'); + } + $this->container['repost_count'] = $repost_count; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/PostSearchResult.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/PostSearchResult.php new file mode 100644 index 0000000000..1888f6f93e --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/PostSearchResult.php @@ -0,0 +1,1021 @@ + + */ +class PostSearchResult implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'PostSearchResult'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'post_id' => 'string', + 'source' => 'string', + 'group_id' => 'string', + 'user_id' => 'string', + 'title' => 'string', + 'content' => 'string', + 'date' => '\DateTime', + 'type' => 'string', + 'outcome' => 'string', + 'latitude' => 'float', + 'longitude' => 'float', + 'footer' => 'string', + 'photos' => '\OpenAPI\Client\Model\Photo[]', + 'expiration' => '\DateTime', + 'reselling' => 'bool', + 'url' => 'string', + 'repost_count' => 'int', + 'search_title' => 'string', + 'search_content' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'post_id' => null, + 'source' => null, + 'group_id' => null, + 'user_id' => null, + 'title' => null, + 'content' => null, + 'date' => 'date-time', + 'type' => null, + 'outcome' => null, + 'latitude' => null, + 'longitude' => null, + 'footer' => null, + 'photos' => null, + 'expiration' => 'date-time', + 'reselling' => null, + 'url' => null, + 'repost_count' => null, + 'search_title' => null, + 'search_content' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'post_id' => false, + 'source' => false, + 'group_id' => false, + 'user_id' => false, + 'title' => false, + 'content' => false, + 'date' => false, + 'type' => false, + 'outcome' => false, + 'latitude' => false, + 'longitude' => false, + 'footer' => false, + 'photos' => false, + 'expiration' => false, + 'reselling' => false, + 'url' => false, + 'repost_count' => false, + 'search_title' => false, + 'search_content' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'post_id' => 'post_id', + 'source' => 'source', + 'group_id' => 'group_id', + 'user_id' => 'user_id', + 'title' => 'title', + 'content' => 'content', + 'date' => 'date', + 'type' => 'type', + 'outcome' => 'outcome', + 'latitude' => 'latitude', + 'longitude' => 'longitude', + 'footer' => 'footer', + 'photos' => 'photos', + 'expiration' => 'expiration', + 'reselling' => 'reselling', + 'url' => 'url', + 'repost_count' => 'repost_count', + 'search_title' => 'search_title', + 'search_content' => 'search_content' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'post_id' => 'setPostId', + 'source' => 'setSource', + 'group_id' => 'setGroupId', + 'user_id' => 'setUserId', + 'title' => 'setTitle', + 'content' => 'setContent', + 'date' => 'setDate', + 'type' => 'setType', + 'outcome' => 'setOutcome', + 'latitude' => 'setLatitude', + 'longitude' => 'setLongitude', + 'footer' => 'setFooter', + 'photos' => 'setPhotos', + 'expiration' => 'setExpiration', + 'reselling' => 'setReselling', + 'url' => 'setUrl', + 'repost_count' => 'setRepostCount', + 'search_title' => 'setSearchTitle', + 'search_content' => 'setSearchContent' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'post_id' => 'getPostId', + 'source' => 'getSource', + 'group_id' => 'getGroupId', + 'user_id' => 'getUserId', + 'title' => 'getTitle', + 'content' => 'getContent', + 'date' => 'getDate', + 'type' => 'getType', + 'outcome' => 'getOutcome', + 'latitude' => 'getLatitude', + 'longitude' => 'getLongitude', + 'footer' => 'getFooter', + 'photos' => 'getPhotos', + 'expiration' => 'getExpiration', + 'reselling' => 'getReselling', + 'url' => 'getUrl', + 'repost_count' => 'getRepostCount', + 'search_title' => 'getSearchTitle', + 'search_content' => 'getSearchContent' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('post_id', $data ?? [], null); + $this->setIfExists('source', $data ?? [], null); + $this->setIfExists('group_id', $data ?? [], null); + $this->setIfExists('user_id', $data ?? [], null); + $this->setIfExists('title', $data ?? [], null); + $this->setIfExists('content', $data ?? [], null); + $this->setIfExists('date', $data ?? [], null); + $this->setIfExists('type', $data ?? [], null); + $this->setIfExists('outcome', $data ?? [], null); + $this->setIfExists('latitude', $data ?? [], null); + $this->setIfExists('longitude', $data ?? [], null); + $this->setIfExists('footer', $data ?? [], null); + $this->setIfExists('photos', $data ?? [], null); + $this->setIfExists('expiration', $data ?? [], null); + $this->setIfExists('reselling', $data ?? [], null); + $this->setIfExists('url', $data ?? [], null); + $this->setIfExists('repost_count', $data ?? [], null); + $this->setIfExists('search_title', $data ?? [], null); + $this->setIfExists('search_content', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets post_id + * + * @return string|null + */ + public function getPostId() + { + return $this->container['post_id']; + } + + /** + * Sets post_id + * + * @param string|null $post_id post_id + * + * @return self + */ + public function setPostId($post_id) + { + if (is_null($post_id)) { + throw new \InvalidArgumentException('non-nullable post_id cannot be null'); + } + $this->container['post_id'] = $post_id; + + return $this; + } + + /** + * Gets source + * + * @return string|null + */ + public function getSource() + { + return $this->container['source']; + } + + /** + * Sets source + * + * @param string|null $source The source of the post. One of: groups, trashnothing, open_archive_groups. A value of groups or open_archive_groups indicates the post is from a group and the group_id field will contain the ID of the group. A value of trashnothing indicates the post is a public post not associated with any group. + * + * @return self + */ + public function setSource($source) + { + if (is_null($source)) { + throw new \InvalidArgumentException('non-nullable source cannot be null'); + } + $this->container['source'] = $source; + + return $this; + } + + /** + * Gets group_id + * + * @return string|null + */ + public function getGroupId() + { + return $this->container['group_id']; + } + + /** + * Sets group_id + * + * @param string|null $group_id The group ID of the post. For public posts, this is always null. + * + * @return self + */ + public function setGroupId($group_id) + { + if (is_null($group_id)) { + throw new \InvalidArgumentException('non-nullable group_id cannot be null'); + } + $this->container['group_id'] = $group_id; + + return $this; + } + + /** + * Gets user_id + * + * @return string|null + */ + public function getUserId() + { + return $this->container['user_id']; + } + + /** + * Sets user_id + * + * @param string|null $user_id user_id + * + * @return self + */ + public function setUserId($user_id) + { + if (is_null($user_id)) { + throw new \InvalidArgumentException('non-nullable user_id cannot be null'); + } + $this->container['user_id'] = $user_id; + + return $this; + } + + /** + * Gets title + * + * @return string|null + */ + public function getTitle() + { + return $this->container['title']; + } + + /** + * Sets title + * + * @param string|null $title title + * + * @return self + */ + public function setTitle($title) + { + if (is_null($title)) { + throw new \InvalidArgumentException('non-nullable title cannot be null'); + } + $this->container['title'] = $title; + + return $this; + } + + /** + * Gets content + * + * @return string|null + */ + public function getContent() + { + return $this->container['content']; + } + + /** + * Sets content + * + * @param string|null $content content + * + * @return self + */ + public function setContent($content) + { + if (is_null($content)) { + throw new \InvalidArgumentException('non-nullable content cannot be null'); + } + $this->container['content'] = $content; + + return $this; + } + + /** + * Gets date + * + * @return \DateTime|null + */ + public function getDate() + { + return $this->container['date']; + } + + /** + * Sets date + * + * @param \DateTime|null $date The UTC date and time when the post was published. + * + * @return self + */ + public function setDate($date) + { + if (is_null($date)) { + throw new \InvalidArgumentException('non-nullable date cannot be null'); + } + $this->container['date'] = $date; + + return $this; + } + + /** + * Gets type + * + * @return string|null + */ + public function getType() + { + return $this->container['type']; + } + + /** + * Sets type + * + * @param string|null $type The type of post. One of: offer, wanted, admin + * + * @return self + */ + public function setType($type) + { + if (is_null($type)) { + throw new \InvalidArgumentException('non-nullable type cannot be null'); + } + $this->container['type'] = $type; + + return $this; + } + + /** + * Gets outcome + * + * @return string|null + */ + public function getOutcome() + { + return $this->container['outcome']; + } + + /** + * Sets outcome + * + * @param string|null $outcome For offer and wanted posts, this indicates the outcome of the post which is null if no outcome has been set yet.

Offer post outcomes will be one of: satisfied, withdrawn, promised, expired

Wanted post outcomes will be one of: satisfied, withdrawn, expired

For all other posts, outcome is always null. + * + * @return self + */ + public function setOutcome($outcome) + { + if (is_null($outcome)) { + throw new \InvalidArgumentException('non-nullable outcome cannot be null'); + } + $this->container['outcome'] = $outcome; + + return $this; + } + + /** + * Gets latitude + * + * @return float|null + */ + public function getLatitude() + { + return $this->container['latitude']; + } + + /** + * Sets latitude + * + * @param float|null $latitude May be null if a post hasn't been mapped. + * + * @return self + */ + public function setLatitude($latitude) + { + if (is_null($latitude)) { + throw new \InvalidArgumentException('non-nullable latitude cannot be null'); + } + $this->container['latitude'] = $latitude; + + return $this; + } + + /** + * Gets longitude + * + * @return float|null + */ + public function getLongitude() + { + return $this->container['longitude']; + } + + /** + * Sets longitude + * + * @param float|null $longitude May be null if a post hasn't been mapped. + * + * @return self + */ + public function setLongitude($longitude) + { + if (is_null($longitude)) { + throw new \InvalidArgumentException('non-nullable longitude cannot be null'); + } + $this->container['longitude'] = $longitude; + + return $this; + } + + /** + * Gets footer + * + * @return string|null + */ + public function getFooter() + { + return $this->container['footer']; + } + + /** + * Sets footer + * + * @param string|null $footer Some groups add footers to posts that are separate and sometimes unrelated to the post itself - such as reminders about group rules or features (may be null). + * + * @return self + */ + public function setFooter($footer) + { + if (is_null($footer)) { + throw new \InvalidArgumentException('non-nullable footer cannot be null'); + } + $this->container['footer'] = $footer; + + return $this; + } + + /** + * Gets photos + * + * @return \OpenAPI\Client\Model\Photo[]|null + */ + public function getPhotos() + { + return $this->container['photos']; + } + + /** + * Sets photos + * + * @param \OpenAPI\Client\Model\Photo[]|null $photos Details about the photos associated with this post (may be null if there are no photos). + * + * @return self + */ + public function setPhotos($photos) + { + if (is_null($photos)) { + throw new \InvalidArgumentException('non-nullable photos cannot be null'); + } + $this->container['photos'] = $photos; + + return $this; + } + + /** + * Gets expiration + * + * @return \DateTime|null + */ + public function getExpiration() + { + return $this->container['expiration']; + } + + /** + * Sets expiration + * + * @param \DateTime|null $expiration The UTC date and time when the post will expire. Currently only offer and wanted posts expire. For all other posts, expiration is always null. + * + * @return self + */ + public function setExpiration($expiration) + { + if (is_null($expiration)) { + throw new \InvalidArgumentException('non-nullable expiration cannot be null'); + } + $this->container['expiration'] = $expiration; + + return $this; + } + + /** + * Gets reselling + * + * @return bool|null + */ + public function getReselling() + { + return $this->container['reselling']; + } + + /** + * Sets reselling + * + * @param bool|null $reselling For wanted posts, whether the item is being requested in order to resell it or not. Will be null for all posts that are not wanted posts and for wanted posts where the poster hasn't indicated whether or not they intend to resell the item they are requesting. + * + * @return self + */ + public function setReselling($reselling) + { + if (is_null($reselling)) { + throw new \InvalidArgumentException('non-nullable reselling cannot be null'); + } + $this->container['reselling'] = $reselling; + + return $this; + } + + /** + * Gets url + * + * @return string|null + */ + public function getUrl() + { + return $this->container['url']; + } + + /** + * Sets url + * + * @param string|null $url The link to use to view the post on the Trash Nothing site. + * + * @return self + */ + public function setUrl($url) + { + if (is_null($url)) { + throw new \InvalidArgumentException('non-nullable url cannot be null'); + } + $this->container['url'] = $url; + + return $this; + } + + /** + * Gets repost_count + * + * @return int|null + */ + public function getRepostCount() + { + return $this->container['repost_count']; + } + + /** + * Sets repost_count + * + * @param int|null $repost_count The count of how many times this post has been reposted in the last 90 days. A value of zero is used to indicate that the post is not a repost. The count is specific to the source of the post (eg. the specific group the post is on). If a post is crossposted to multiple groups, the repost_count of the post on each group may be different for each group depending on how many times the post has been posted on that group in the last 90 days. + * + * @return self + */ + public function setRepostCount($repost_count) + { + if (is_null($repost_count)) { + throw new \InvalidArgumentException('non-nullable repost_count cannot be null'); + } + $this->container['repost_count'] = $repost_count; + + return $this; + } + + /** + * Gets search_title + * + * @return string|null + */ + public function getSearchTitle() + { + return $this->container['search_title']; + } + + /** + * Sets search_title + * + * @param string|null $search_title The post subject as HTML with the parts of the subject that matched the search query (if any) wrapped in HTML span tags with the class 'highlight'. (eg. <span class=\"highlight\">matched words</span>). May be null if none of the words in the subject matched the search query. + * + * @return self + */ + public function setSearchTitle($search_title) + { + if (is_null($search_title)) { + throw new \InvalidArgumentException('non-nullable search_title cannot be null'); + } + $this->container['search_title'] = $search_title; + + return $this; + } + + /** + * Gets search_content + * + * @return string|null + */ + public function getSearchContent() + { + return $this->container['search_content']; + } + + /** + * Sets search_content + * + * @param string|null $search_content A snippet of the post content as HTML with the parts of the content that matched the search query (if any) wrapped in an HTML span tags with the class 'highlight' (eg. <span class=\"highlight\">matched words</span>). May be null if none of the words in the post content matched the search query.

NOTE: This is not the full content of the post It is just a snippet of around 200 characters that can be used to display the parts of the post content relevant to the search query. + * + * @return self + */ + public function setSearchContent($search_content) + { + if (is_null($search_content)) { + throw new \InvalidArgumentException('non-nullable search_content cannot be null'); + } + $this->container['search_content'] = $search_content; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/SearchGroups200Response.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/SearchGroups200Response.php new file mode 100644 index 0000000000..8cc1a7e0d2 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/SearchGroups200Response.php @@ -0,0 +1,613 @@ + + */ +class SearchGroups200Response implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'search_groups_200_response'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'groups' => '\OpenAPI\Client\Model\Group[]', + 'num_groups' => 'int', + 'page' => 'int', + 'per_page' => 'int', + 'num_pages' => 'int', + 'start_index' => 'int', + 'end_index' => 'int' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'groups' => null, + 'num_groups' => null, + 'page' => null, + 'per_page' => null, + 'num_pages' => null, + 'start_index' => null, + 'end_index' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'groups' => false, + 'num_groups' => false, + 'page' => false, + 'per_page' => false, + 'num_pages' => false, + 'start_index' => false, + 'end_index' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'groups' => 'groups', + 'num_groups' => 'num_groups', + 'page' => 'page', + 'per_page' => 'per_page', + 'num_pages' => 'num_pages', + 'start_index' => 'start_index', + 'end_index' => 'end_index' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'groups' => 'setGroups', + 'num_groups' => 'setNumGroups', + 'page' => 'setPage', + 'per_page' => 'setPerPage', + 'num_pages' => 'setNumPages', + 'start_index' => 'setStartIndex', + 'end_index' => 'setEndIndex' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'groups' => 'getGroups', + 'num_groups' => 'getNumGroups', + 'page' => 'getPage', + 'per_page' => 'getPerPage', + 'num_pages' => 'getNumPages', + 'start_index' => 'getStartIndex', + 'end_index' => 'getEndIndex' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('groups', $data ?? [], null); + $this->setIfExists('num_groups', $data ?? [], null); + $this->setIfExists('page', $data ?? [], null); + $this->setIfExists('per_page', $data ?? [], null); + $this->setIfExists('num_pages', $data ?? [], null); + $this->setIfExists('start_index', $data ?? [], null); + $this->setIfExists('end_index', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets groups + * + * @return \OpenAPI\Client\Model\Group[]|null + */ + public function getGroups() + { + return $this->container['groups']; + } + + /** + * Sets groups + * + * @param \OpenAPI\Client\Model\Group[]|null $groups groups + * + * @return self + */ + public function setGroups($groups) + { + if (is_null($groups)) { + throw new \InvalidArgumentException('non-nullable groups cannot be null'); + } + $this->container['groups'] = $groups; + + return $this; + } + + /** + * Gets num_groups + * + * @return int|null + */ + public function getNumGroups() + { + return $this->container['num_groups']; + } + + /** + * Sets num_groups + * + * @param int|null $num_groups The total number of groups available. + * + * @return self + */ + public function setNumGroups($num_groups) + { + if (is_null($num_groups)) { + throw new \InvalidArgumentException('non-nullable num_groups cannot be null'); + } + $this->container['num_groups'] = $num_groups; + + return $this; + } + + /** + * Gets page + * + * @return int|null + */ + public function getPage() + { + return $this->container['page']; + } + + /** + * Sets page + * + * @param int|null $page The page number of the groups being returned. + * + * @return self + */ + public function setPage($page) + { + if (is_null($page)) { + throw new \InvalidArgumentException('non-nullable page cannot be null'); + } + $this->container['page'] = $page; + + return $this; + } + + /** + * Gets per_page + * + * @return int|null + */ + public function getPerPage() + { + return $this->container['per_page']; + } + + /** + * Sets per_page + * + * @param int|null $per_page The number of groups being returned per page. + * + * @return self + */ + public function setPerPage($per_page) + { + if (is_null($per_page)) { + throw new \InvalidArgumentException('non-nullable per_page cannot be null'); + } + $this->container['per_page'] = $per_page; + + return $this; + } + + /** + * Gets num_pages + * + * @return int|null + */ + public function getNumPages() + { + return $this->container['num_pages']; + } + + /** + * Sets num_pages + * + * @param int|null $num_pages The total number of pages available. + * + * @return self + */ + public function setNumPages($num_pages) + { + if (is_null($num_pages)) { + throw new \InvalidArgumentException('non-nullable num_pages cannot be null'); + } + $this->container['num_pages'] = $num_pages; + + return $this; + } + + /** + * Gets start_index + * + * @return int|null + */ + public function getStartIndex() + { + return $this->container['start_index']; + } + + /** + * Sets start_index + * + * @param int|null $start_index The index of the first group being returned (an integer between 1 and num_groups). + * + * @return self + */ + public function setStartIndex($start_index) + { + if (is_null($start_index)) { + throw new \InvalidArgumentException('non-nullable start_index cannot be null'); + } + $this->container['start_index'] = $start_index; + + return $this; + } + + /** + * Gets end_index + * + * @return int|null + */ + public function getEndIndex() + { + return $this->container['end_index']; + } + + /** + * Sets end_index + * + * @param int|null $end_index The index of the last group being returned (an integer between start_index and num_groups). + * + * @return self + */ + public function setEndIndex($end_index) + { + if (is_null($end_index)) { + throw new \InvalidArgumentException('non-nullable end_index cannot be null'); + } + $this->container['end_index'] = $end_index; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/SearchUserPosts200Response.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/SearchUserPosts200Response.php new file mode 100644 index 0000000000..bf6594cea0 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/SearchUserPosts200Response.php @@ -0,0 +1,647 @@ + + */ +class SearchUserPosts200Response implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'search_user_posts_200_response'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'posts' => '\OpenAPI\Client\Model\PostSearchResult[]', + 'num_posts' => 'int', + 'page' => 'int', + 'per_page' => 'int', + 'num_pages' => 'int', + 'start_index' => 'int', + 'end_index' => 'int', + 'group_ids' => 'string[]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'posts' => null, + 'num_posts' => null, + 'page' => null, + 'per_page' => null, + 'num_pages' => null, + 'start_index' => null, + 'end_index' => null, + 'group_ids' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'posts' => false, + 'num_posts' => false, + 'page' => false, + 'per_page' => false, + 'num_pages' => false, + 'start_index' => false, + 'end_index' => false, + 'group_ids' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'posts' => 'posts', + 'num_posts' => 'num_posts', + 'page' => 'page', + 'per_page' => 'per_page', + 'num_pages' => 'num_pages', + 'start_index' => 'start_index', + 'end_index' => 'end_index', + 'group_ids' => 'group_ids' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'posts' => 'setPosts', + 'num_posts' => 'setNumPosts', + 'page' => 'setPage', + 'per_page' => 'setPerPage', + 'num_pages' => 'setNumPages', + 'start_index' => 'setStartIndex', + 'end_index' => 'setEndIndex', + 'group_ids' => 'setGroupIds' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'posts' => 'getPosts', + 'num_posts' => 'getNumPosts', + 'page' => 'getPage', + 'per_page' => 'getPerPage', + 'num_pages' => 'getNumPages', + 'start_index' => 'getStartIndex', + 'end_index' => 'getEndIndex', + 'group_ids' => 'getGroupIds' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('posts', $data ?? [], null); + $this->setIfExists('num_posts', $data ?? [], null); + $this->setIfExists('page', $data ?? [], null); + $this->setIfExists('per_page', $data ?? [], null); + $this->setIfExists('num_pages', $data ?? [], null); + $this->setIfExists('start_index', $data ?? [], null); + $this->setIfExists('end_index', $data ?? [], null); + $this->setIfExists('group_ids', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets posts + * + * @return \OpenAPI\Client\Model\PostSearchResult[]|null + */ + public function getPosts() + { + return $this->container['posts']; + } + + /** + * Sets posts + * + * @param \OpenAPI\Client\Model\PostSearchResult[]|null $posts posts + * + * @return self + */ + public function setPosts($posts) + { + if (is_null($posts)) { + throw new \InvalidArgumentException('non-nullable posts cannot be null'); + } + $this->container['posts'] = $posts; + + return $this; + } + + /** + * Gets num_posts + * + * @return int|null + */ + public function getNumPosts() + { + return $this->container['num_posts']; + } + + /** + * Sets num_posts + * + * @param int|null $num_posts The total number of posts available. + * + * @return self + */ + public function setNumPosts($num_posts) + { + if (is_null($num_posts)) { + throw new \InvalidArgumentException('non-nullable num_posts cannot be null'); + } + $this->container['num_posts'] = $num_posts; + + return $this; + } + + /** + * Gets page + * + * @return int|null + */ + public function getPage() + { + return $this->container['page']; + } + + /** + * Sets page + * + * @param int|null $page The page number of the posts being returned. + * + * @return self + */ + public function setPage($page) + { + if (is_null($page)) { + throw new \InvalidArgumentException('non-nullable page cannot be null'); + } + $this->container['page'] = $page; + + return $this; + } + + /** + * Gets per_page + * + * @return int|null + */ + public function getPerPage() + { + return $this->container['per_page']; + } + + /** + * Sets per_page + * + * @param int|null $per_page The number of posts being returned per page. + * + * @return self + */ + public function setPerPage($per_page) + { + if (is_null($per_page)) { + throw new \InvalidArgumentException('non-nullable per_page cannot be null'); + } + $this->container['per_page'] = $per_page; + + return $this; + } + + /** + * Gets num_pages + * + * @return int|null + */ + public function getNumPages() + { + return $this->container['num_pages']; + } + + /** + * Sets num_pages + * + * @param int|null $num_pages The total number of pages available. + * + * @return self + */ + public function setNumPages($num_pages) + { + if (is_null($num_pages)) { + throw new \InvalidArgumentException('non-nullable num_pages cannot be null'); + } + $this->container['num_pages'] = $num_pages; + + return $this; + } + + /** + * Gets start_index + * + * @return int|null + */ + public function getStartIndex() + { + return $this->container['start_index']; + } + + /** + * Sets start_index + * + * @param int|null $start_index The index of the first post being returned (an integer between 1 and num_posts). + * + * @return self + */ + public function setStartIndex($start_index) + { + if (is_null($start_index)) { + throw new \InvalidArgumentException('non-nullable start_index cannot be null'); + } + $this->container['start_index'] = $start_index; + + return $this; + } + + /** + * Gets end_index + * + * @return int|null + */ + public function getEndIndex() + { + return $this->container['end_index']; + } + + /** + * Sets end_index + * + * @param int|null $end_index The index of the last post being returned (an integer between start_index and num_posts). + * + * @return self + */ + public function setEndIndex($end_index) + { + if (is_null($end_index)) { + throw new \InvalidArgumentException('non-nullable end_index cannot be null'); + } + $this->container['end_index'] = $end_index; + + return $this; + } + + /** + * Gets group_ids + * + * @return string[]|null + */ + public function getGroupIds() + { + return $this->container['group_ids']; + } + + /** + * Sets group_ids + * + * @param string[]|null $group_ids The IDs of the groups that the posts were retrieved from (will be null when no group IDs were used). These IDs may be a subset of the requested group IDs when a request includes group IDs for groups that are not open archives and that the current user is not a member of. If the open_archive_groups source is used, these IDs may include the IDs of open archive groups that weren't present in the group_ids parameter of the request. + * + * @return self + */ + public function setGroupIds($group_ids) + { + if (is_null($group_ids)) { + throw new \InvalidArgumentException('non-nullable group_ids cannot be null'); + } + $this->container['group_ids'] = $group_ids; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/User.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/User.php new file mode 100644 index 0000000000..84275db6d1 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/User.php @@ -0,0 +1,715 @@ + + */ +class User implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'User'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'user_id' => 'string', + 'username' => 'string', + 'country' => 'string', + 'profile_image' => 'string', + 'member_since' => 'string', + 'firstname' => 'string', + 'lastname' => 'string', + 'reply_time' => 'int', + 'feedback' => '\OpenAPI\Client\Model\UserFeedback', + 'about_me' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'user_id' => null, + 'username' => null, + 'country' => null, + 'profile_image' => null, + 'member_since' => null, + 'firstname' => null, + 'lastname' => null, + 'reply_time' => null, + 'feedback' => null, + 'about_me' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'user_id' => false, + 'username' => false, + 'country' => false, + 'profile_image' => false, + 'member_since' => false, + 'firstname' => false, + 'lastname' => false, + 'reply_time' => false, + 'feedback' => false, + 'about_me' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'user_id' => 'user_id', + 'username' => 'username', + 'country' => 'country', + 'profile_image' => 'profile_image', + 'member_since' => 'member_since', + 'firstname' => 'firstname', + 'lastname' => 'lastname', + 'reply_time' => 'reply_time', + 'feedback' => 'feedback', + 'about_me' => 'about_me' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'user_id' => 'setUserId', + 'username' => 'setUsername', + 'country' => 'setCountry', + 'profile_image' => 'setProfileImage', + 'member_since' => 'setMemberSince', + 'firstname' => 'setFirstname', + 'lastname' => 'setLastname', + 'reply_time' => 'setReplyTime', + 'feedback' => 'setFeedback', + 'about_me' => 'setAboutMe' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'user_id' => 'getUserId', + 'username' => 'getUsername', + 'country' => 'getCountry', + 'profile_image' => 'getProfileImage', + 'member_since' => 'getMemberSince', + 'firstname' => 'getFirstname', + 'lastname' => 'getLastname', + 'reply_time' => 'getReplyTime', + 'feedback' => 'getFeedback', + 'about_me' => 'getAboutMe' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('user_id', $data ?? [], null); + $this->setIfExists('username', $data ?? [], null); + $this->setIfExists('country', $data ?? [], null); + $this->setIfExists('profile_image', $data ?? [], null); + $this->setIfExists('member_since', $data ?? [], null); + $this->setIfExists('firstname', $data ?? [], null); + $this->setIfExists('lastname', $data ?? [], null); + $this->setIfExists('reply_time', $data ?? [], null); + $this->setIfExists('feedback', $data ?? [], null); + $this->setIfExists('about_me', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets user_id + * + * @return string|null + */ + public function getUserId() + { + return $this->container['user_id']; + } + + /** + * Sets user_id + * + * @param string|null $user_id user_id + * + * @return self + */ + public function setUserId($user_id) + { + if (is_null($user_id)) { + throw new \InvalidArgumentException('non-nullable user_id cannot be null'); + } + $this->container['user_id'] = $user_id; + + return $this; + } + + /** + * Gets username + * + * @return string|null + */ + public function getUsername() + { + return $this->container['username']; + } + + /** + * Sets username + * + * @param string|null $username A username that can be displayed for the user (the username is NOT guaranteed to be unique). Will be null for api key requests and requests where the oauth user doesn't belong to any of the same groups as this user. + * + * @return self + */ + public function setUsername($username) + { + if (is_null($username)) { + throw new \InvalidArgumentException('non-nullable username cannot be null'); + } + $this->container['username'] = $username; + + return $this; + } + + /** + * Gets country + * + * @return string|null + */ + public function getCountry() + { + return $this->container['country']; + } + + /** + * Sets country + * + * @param string|null $country A 2 letter country code for the country that has been automatically detected for the user (see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ). May be null if no country has been set. + * + * @return self + */ + public function setCountry($country) + { + if (is_null($country)) { + throw new \InvalidArgumentException('non-nullable country cannot be null'); + } + $this->container['country'] = $country; + + return $this; + } + + /** + * Gets profile_image + * + * @return string|null + */ + public function getProfileImage() + { + return $this->container['profile_image']; + } + + /** + * Sets profile_image + * + * @param string|null $profile_image A URL to a profile image for the user. Profile images sizes vary based on the source (Google, Facebook, Gravatar, etc) and some can be as small as 64px by 64px. Will be null for api key requests and requests where the oauth user doesn't belong to any of the same groups as this user. + * + * @return self + */ + public function setProfileImage($profile_image) + { + if (is_null($profile_image)) { + throw new \InvalidArgumentException('non-nullable profile_image cannot be null'); + } + $this->container['profile_image'] = $profile_image; + + return $this; + } + + /** + * Gets member_since + * + * @return string|null + */ + public function getMemberSince() + { + return $this->container['member_since']; + } + + /** + * Sets member_since + * + * @param string|null $member_since The date and time when the user first became publicly active on a group (the date may be older than when the user signed up). + * + * @return self + */ + public function setMemberSince($member_since) + { + if (is_null($member_since)) { + throw new \InvalidArgumentException('non-nullable member_since cannot be null'); + } + $this->container['member_since'] = $member_since; + + return $this; + } + + /** + * Gets firstname + * + * @return string|null + */ + public function getFirstname() + { + return $this->container['firstname']; + } + + /** + * Sets firstname + * + * @param string|null $firstname The first name of the user (may be null). + * + * @return self + */ + public function setFirstname($firstname) + { + if (is_null($firstname)) { + throw new \InvalidArgumentException('non-nullable firstname cannot be null'); + } + $this->container['firstname'] = $firstname; + + return $this; + } + + /** + * Gets lastname + * + * @return string|null + */ + public function getLastname() + { + return $this->container['lastname']; + } + + /** + * Sets lastname + * + * @param string|null $lastname The last name of the user (may be null). + * + * @return self + */ + public function setLastname($lastname) + { + if (is_null($lastname)) { + throw new \InvalidArgumentException('non-nullable lastname cannot be null'); + } + $this->container['lastname'] = $lastname; + + return $this; + } + + /** + * Gets reply_time + * + * @return int|null + */ + public function getReplyTime() + { + return $this->container['reply_time']; + } + + /** + * Sets reply_time + * + * @param int|null $reply_time An estimate of how many seconds it takes this user to reply to messages. May be null when there is not enough data to calculate an estimate. + * + * @return self + */ + public function setReplyTime($reply_time) + { + if (is_null($reply_time)) { + throw new \InvalidArgumentException('non-nullable reply_time cannot be null'); + } + $this->container['reply_time'] = $reply_time; + + return $this; + } + + /** + * Gets feedback + * + * @return \OpenAPI\Client\Model\UserFeedback|null + */ + public function getFeedback() + { + return $this->container['feedback']; + } + + /** + * Sets feedback + * + * @param \OpenAPI\Client\Model\UserFeedback|null $feedback feedback + * + * @return self + */ + public function setFeedback($feedback) + { + if (is_null($feedback)) { + throw new \InvalidArgumentException('non-nullable feedback cannot be null'); + } + $this->container['feedback'] = $feedback; + + return $this; + } + + /** + * Gets about_me + * + * @return string|null + */ + public function getAboutMe() + { + return $this->container['about_me']; + } + + /** + * Sets about_me + * + * @param string|null $about_me A short bio a user has written about themselves to help other members get to know them better. May be null if the user has not written anything about themselves. + * + * @return self + */ + public function setAboutMe($about_me) + { + if (is_null($about_me)) { + throw new \InvalidArgumentException('non-nullable about_me cannot be null'); + } + $this->container['about_me'] = $about_me; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/UserFeedback.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/UserFeedback.php new file mode 100644 index 0000000000..53acc53140 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/Model/UserFeedback.php @@ -0,0 +1,493 @@ + + */ +class UserFeedback implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'User_feedback'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'restriction' => 'string', + 'score' => 'int', + 'percent_positive' => 'float' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'restriction' => null, + 'score' => null, + 'percent_positive' => null + ]; + + /** + * Array of nullable properties. Used for (de)serialization + * + * @var boolean[] + */ + protected static array $openAPINullables = [ + 'restriction' => false, + 'score' => false, + 'percent_positive' => false + ]; + + /** + * If a nullable field gets set to null, insert it here + * + * @var boolean[] + */ + protected array $openAPINullablesSetToNull = []; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of nullable properties + * + * @return array + */ + protected static function openAPINullables(): array + { + return self::$openAPINullables; + } + + /** + * Array of nullable field names deliberately set to null + * + * @return boolean[] + */ + private function getOpenAPINullablesSetToNull(): array + { + return $this->openAPINullablesSetToNull; + } + + /** + * Setter - Array of nullable field names deliberately set to null + * + * @param boolean[] $openAPINullablesSetToNull + */ + private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void + { + $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; + } + + /** + * Checks if a property is nullable + * + * @param string $property + * @return bool + */ + public static function isNullable(string $property): bool + { + return self::openAPINullables()[$property] ?? false; + } + + /** + * Checks if a nullable property is set to null. + * + * @param string $property + * @return bool + */ + public function isNullableSetToNull(string $property): bool + { + return in_array($property, $this->getOpenAPINullablesSetToNull(), true); + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'restriction' => 'restriction', + 'score' => 'score', + 'percent_positive' => 'percent_positive' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'restriction' => 'setRestriction', + 'score' => 'setScore', + 'percent_positive' => 'setPercentPositive' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'restriction' => 'getRestriction', + 'score' => 'getScore', + 'percent_positive' => 'getPercentPositive' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[]|null $data Associated array of property values + * initializing the model + */ + public function __construct(?array $data = null) + { + $this->setIfExists('restriction', $data ?? [], null); + $this->setIfExists('score', $data ?? [], null); + $this->setIfExists('percent_positive', $data ?? [], null); + } + + /** + * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName + * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the + * $this->openAPINullablesSetToNull array + * + * @param string $variableName + * @param array $fields + * @param mixed $defaultValue + */ + private function setIfExists(string $variableName, array $fields, $defaultValue): void + { + if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { + $this->openAPINullablesSetToNull[] = $variableName; + } + + $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + if (!is_null($this->container['percent_positive']) && ($this->container['percent_positive'] > 1E+2)) { + $invalidProperties[] = "invalid value for 'percent_positive', must be smaller than or equal to 1E+2."; + } + + if (!is_null($this->container['percent_positive']) && ($this->container['percent_positive'] < 0)) { + $invalidProperties[] = "invalid value for 'percent_positive', must be bigger than or equal to 0."; + } + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets restriction + * + * @return string|null + */ + public function getRestriction() + { + return $this->container['restriction']; + } + + /** + * Sets restriction + * + * @param string|null $restriction If the current user can leave positive or negative feedback on this user then restriction is null.

Otherwise, restriction is set to a string that explains why feedback is currently restricted and what type of feedback is restricted. The string will be one of the following: no-recent-messages, negative-score, moderator, [days]-day-wait-for-negative

- **no-recent-messages**: The current user has not received any messages from this user in the last 30 days.
- **negative-score**: The current user has a negative feedback and will not be able to leave feedback until their score is >= 0.
- **moderator**: The user is a moderator and leaving feedback on moderators is not currently supported.
- **[days]-day-wait-for-negative**: Positive feedback is not restricted but the current user must wait some number of days before they will be able to leave negative feedback on this user. This string can change depending on the number of days. For example, when the current user must wait one day, the string will be '1-day-wait-for-negative'. A wait is necessary because a lot of negative feedback results from communication issues that are resolved with more time. + * + * @return self + */ + public function setRestriction($restriction) + { + if (is_null($restriction)) { + throw new \InvalidArgumentException('non-nullable restriction cannot be null'); + } + $this->container['restriction'] = $restriction; + + return $this; + } + + /** + * Gets score + * + * @return int|null + */ + public function getScore() + { + return $this->container['score']; + } + + /** + * Sets score + * + * @param int|null $score The feedback score of this user. Higher scores are better. Scores are calculated by substracting the total number of negative feedback from the total number of positive feedback that a user has received. May be null if a user has not received enough feedback to calculate a score. + * + * @return self + */ + public function setScore($score) + { + if (is_null($score)) { + throw new \InvalidArgumentException('non-nullable score cannot be null'); + } + $this->container['score'] = $score; + + return $this; + } + + /** + * Gets percent_positive + * + * @return float|null + */ + public function getPercentPositive() + { + return $this->container['percent_positive']; + } + + /** + * Sets percent_positive + * + * @param float|null $percent_positive The percent of feedback that this user has received in the last year that was positive. May be null if a user has not received enough feedback to calculate a percentage. + * + * @return self + */ + public function setPercentPositive($percent_positive) + { + if (is_null($percent_positive)) { + throw new \InvalidArgumentException('non-nullable percent_positive cannot be null'); + } + + if (($percent_positive > 1E+2)) { + throw new \InvalidArgumentException('invalid value for $percent_positive when calling UserFeedback., must be smaller than or equal to 1E+2.'); + } + if (($percent_positive < 0)) { + throw new \InvalidArgumentException('invalid value for $percent_positive when calling UserFeedback., must be bigger than or equal to 0.'); + } + + $this->container['percent_positive'] = $percent_positive; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer|string $offset Offset + * + * @return boolean + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer|string $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet(mixed $offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer|string $offset Offset + * + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/lib/ObjectSerializer.php b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/ObjectSerializer.php new file mode 100644 index 0000000000..6afcfaeb4d --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/lib/ObjectSerializer.php @@ -0,0 +1,603 @@ +format('Y-m-d') : $data->format(self::$dateTimeFormat); + } + + if (is_array($data)) { + foreach ($data as $property => $value) { + $data[$property] = self::sanitizeForSerialization($value); + } + return $data; + } + + if (is_object($data)) { + $values = []; + if ($data instanceof ModelInterface) { + $formats = $data::openAPIFormats(); + foreach ($data::openAPITypes() as $property => $openAPIType) { + $getter = $data::getters()[$property]; + $value = $data->$getter(); + if ($value !== null && !in_array($openAPIType, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { + $callable = [$openAPIType, 'getAllowableEnumValues']; + if (is_callable($callable)) { + /** array $callable */ + $allowedEnumTypes = $callable(); + if (!in_array($value, $allowedEnumTypes, true)) { + $imploded = implode("', '", $allowedEnumTypes); + throw new \InvalidArgumentException("Invalid value for enum '$openAPIType', must be one of: '$imploded'"); + } + } + } + if (($data::isNullable($property) && $data->isNullableSetToNull($property)) || $value !== null) { + $values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($value, $openAPIType, $formats[$property]); + } + } + } else { + foreach ($data as $property => $value) { + $values[$property] = self::sanitizeForSerialization($value); + } + } + return (object) $values; + } else { + return (string)$data; + } + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param string $filename filename to be sanitized + * + * @return string the sanitized filename + */ + public static function sanitizeFilename($filename) + { + if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { + return $match[1]; + } else { + return $filename; + } + } + + /** + * Shorter timestamp microseconds to 6 digits length. + * + * @param string $timestamp Original timestamp + * + * @return string the shorten timestamp + */ + public static function sanitizeTimestamp($timestamp) + { + if (!is_string($timestamp)) { + return $timestamp; + } + + return preg_replace('/(:\d{2}.\d{6})\d*/', '$1', $timestamp); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the path, by url-encoding. + * + * @param string $value a string which will be part of the path + * + * @return string the serialized object + */ + public static function toPathValue($value) + { + return rawurlencode(self::toString($value)); + } + + /** + * Checks if a value is empty, based on its OpenAPI type. + * + * @param mixed $value + * @param string $openApiType + * + * @return bool true if $value is empty + */ + private static function isEmptyValue($value, string $openApiType): bool + { + // If empty() returns false, it is not empty regardless of its type. + if (!empty($value)) { + return false; + } + + // Null is always empty, as we cannot send a real "null" value in a query parameter. + if ($value === null) { + return true; + } + + switch ($openApiType) { + // For numeric values, false and '' are considered empty. + // This comparison is safe for floating point values, since the previous call to empty() will + // filter out values that don't match 0. + case 'int': + case 'integer': + return $value !== 0; + + case 'number': + case 'float': + return $value !== 0 && $value !== 0.0; + + // For boolean values, '' is considered empty + case 'bool': + case 'boolean': + return !in_array($value, [false, 0], true); + + // For string values, '' is considered empty. + case 'string': + return $value === ''; + + // For all the other types, any value at this point can be considered empty. + default: + return true; + } + } + + /** + * Take query parameter properties and turn it into an array suitable for + * native http_build_query or GuzzleHttp\Psr7\Query::build. + * + * @param mixed $value Parameter value + * @param string $paramName Parameter name + * @param string $openApiType OpenAPIType eg. array or object + * @param string $style Parameter serialization style + * @param bool $explode Parameter explode option + * @param bool $required Whether query param is required or not + * + * @return array + */ + public static function toQueryValue( + $value, + string $paramName, + string $openApiType = 'string', + string $style = 'form', + bool $explode = true, + bool $required = true + ): array { + + // Check if we should omit this parameter from the query. This should only happen when: + // - Parameter is NOT required; AND + // - its value is set to a value that is equivalent to "empty", depending on its OpenAPI type. For + // example, 0 as "int" or "boolean" is NOT an empty value. + if (self::isEmptyValue($value, $openApiType)) { + if ($required) { + return ["{$paramName}" => '']; + } else { + return []; + } + } + + // Handle DateTime objects in query + if ($openApiType === "\\DateTime" && $value instanceof \DateTime) { + return ["{$paramName}" => $value->format(self::$dateTimeFormat)]; + } + + $query = []; + $value = (in_array($openApiType, ['object', 'array'], true)) ? (array)$value : $value; + + // since \GuzzleHttp\Psr7\Query::build fails with nested arrays + // need to flatten array first + $flattenArray = function ($arr, $name, &$result = []) use (&$flattenArray, $style, $explode) { + if (!is_array($arr)) { + return $arr; + } + + foreach ($arr as $k => $v) { + $prop = ($style === 'deepObject') ? "{$name}[{$k}]" : $k; + + if (is_array($v)) { + $flattenArray($v, $prop, $result); + } else { + if ($style !== 'deepObject' && !$explode) { + // push key itself + $result[] = $prop; + } + $result[$prop] = $v; + } + } + return $result; + }; + + $value = $flattenArray($value, $paramName); + + // https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values + if ($openApiType === 'array' && $style === 'deepObject' && $explode) { + return $value; + } + + if ($openApiType === 'object' && ($style === 'deepObject' || $explode)) { + return $value; + } + + if ('boolean' === $openApiType && is_bool($value)) { + $value = self::convertBoolToQueryStringFormat($value); + } + + // handle style in serializeCollection + $query[$paramName] = ($explode) ? $value : self::serializeCollection((array)$value, $style); + + return $query; + } + + /** + * Convert boolean value to format for query string. + * + * @param bool $value Boolean value + * + * @return int|string Boolean value in format + */ + public static function convertBoolToQueryStringFormat(bool $value) + { + if (Configuration::BOOLEAN_FORMAT_STRING == Configuration::getDefaultConfiguration()->getBooleanFormatForQueryString()) { + return $value ? 'true' : 'false'; + } + + return (int) $value; + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the header. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * + * @param string $value a string which will be part of the header + * + * @return string the header string + */ + public static function toHeaderValue($value) + { + $callable = [$value, 'toHeaderValue']; + if (is_callable($callable)) { + return $callable(); + } + + return self::toString($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the parameter. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * If it's a boolean, convert it to "true" or "false". + * + * @param float|int|bool|\DateTime $value the value of the parameter + * + * @return string the header string + */ + public static function toString($value) + { + if ($value instanceof \DateTime) { // datetime in ISO8601 format + return $value->format(self::$dateTimeFormat); + } elseif (is_bool($value)) { + return $value ? 'true' : 'false'; + } else { + return (string) $value; + } + } + + /** + * Serialize an array to a string. + * + * @param array $collection collection to serialize to a string + * @param string $style the format use for serialization (csv, + * ssv, tsv, pipes, multi) + * @param bool $allowCollectionFormatMulti allow collection format to be a multidimensional array + * + * @return string + */ + public static function serializeCollection(array $collection, $style, $allowCollectionFormatMulti = false) + { + if ($allowCollectionFormatMulti && ('multi' === $style)) { + // http_build_query() almost does the job for us. We just + // need to fix the result of multidimensional arrays. + return preg_replace('/%5B[0-9]+%5D=/', '=', http_build_query($collection, '', '&')); + } + switch ($style) { + case 'pipeDelimited': + case 'pipes': + return implode('|', $collection); + + case 'tsv': + return implode("\t", $collection); + + case 'spaceDelimited': + case 'ssv': + return implode(' ', $collection); + + case 'simple': + case 'csv': + // Deliberate fall through. CSV is default format. + default: + return implode(',', $collection); + } + } + + /** + * Deserialize a JSON string into an object + * + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @param string[]|null $httpHeaders HTTP headers + * + * @return object|array|null a single or an array of $class instances + */ + public static function deserialize($data, $class, $httpHeaders = null) + { + if (null === $data) { + return null; + } + + if (strcasecmp(substr($class, -2), '[]') === 0) { + $data = is_string($data) ? json_decode($data) : $data; + + if (!is_array($data)) { + throw new \InvalidArgumentException("Invalid array '$class'"); + } + + $subClass = substr($class, 0, -2); + $values = []; + foreach ($data as $key => $value) { + $values[] = self::deserialize($value, $subClass, null); + } + return $values; + } + + if (preg_match('/^(array<|map\[)/', $class)) { // for associative array e.g. array + $data = is_string($data) ? json_decode($data) : $data; + settype($data, 'array'); + $inner = substr($class, 4, -1); + $deserialized = []; + if (strrpos($inner, ",") !== false) { + $subClass_array = explode(',', $inner, 2); + $subClass = $subClass_array[1]; + foreach ($data as $key => $value) { + $deserialized[$key] = self::deserialize($value, $subClass, null); + } + } + return $deserialized; + } + + if ($class === 'object') { + settype($data, 'array'); + return $data; + } elseif ($class === 'mixed') { + settype($data, gettype($data)); + return $data; + } + + if ($class === '\DateTime') { + // Some APIs return an invalid, empty string as a + // date-time property. DateTime::__construct() will return + // the current time for empty input which is probably not + // what is meant. The invalid empty string is probably to + // be interpreted as a missing field/value. Let's handle + // this graceful. + if (!empty($data)) { + try { + return new \DateTime($data); + } catch (\Exception $exception) { + // Some APIs return a date-time with too high nanosecond + // precision for php's DateTime to handle. + // With provided regexp 6 digits of microseconds saved + return new \DateTime(self::sanitizeTimestamp($data)); + } + } else { + return null; + } + } + + if ($class === '\SplFileObject') { + $data = Utils::streamFor($data); + + /** @var \Psr\Http\Message\StreamInterface $data */ + + // determine file name + if ( + is_array($httpHeaders) + && array_key_exists('Content-Disposition', $httpHeaders) + && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match) + ) { + $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . DIRECTORY_SEPARATOR . self::sanitizeFilename($match[1]); + } else { + $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); + } + + $file = fopen($filename, 'w'); + while ($chunk = $data->read(200)) { + fwrite($file, $chunk); + } + fclose($file); + + return new \SplFileObject($filename, 'r'); + } + + /** @psalm-suppress ParadoxicalCondition */ + if (in_array($class, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { + settype($data, $class); + return $data; + } + + + if (method_exists($class, 'getAllowableEnumValues')) { + if (!in_array($data, $class::getAllowableEnumValues(), true)) { + $imploded = implode("', '", $class::getAllowableEnumValues()); + throw new \InvalidArgumentException("Invalid value for enum '$class', must be one of: '$imploded'"); + } + return $data; + } else { + $data = is_string($data) ? json_decode($data) : $data; + + if (is_array($data)) { + $data = (object) $data; + } + + // If a discriminator is defined and points to a valid subclass, use it. + $discriminator = $class::DISCRIMINATOR; + if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { + $subclass = '\OpenAPI\Client\Model\\' . $data->{$discriminator}; + if (is_subclass_of($subclass, $class)) { + $class = $subclass; + } + } + + /** @var ModelInterface $instance */ + $instance = new $class(); + foreach ($instance::openAPITypes() as $property => $type) { + $propertySetter = $instance::setters()[$property]; + + if (!isset($propertySetter)) { + continue; + } + + if (!isset($data->{$instance::attributeMap()[$property]})) { + if ($instance::isNullable($property)) { + $instance->$propertySetter(null); + } + + continue; + } + + if (isset($data->{$instance::attributeMap()[$property]})) { + $propertyValue = $data->{$instance::attributeMap()[$property]}; + $instance->$propertySetter(self::deserialize($propertyValue, $type, null)); + } + } + return $instance; + } + } + + /** + * Build a query string from an array of key value pairs. + * + * This function can use the return value of `parse()` to build a query + * string. This function does not modify the provided keys when an array is + * encountered (like `http_build_query()` would). + * + * The function is copied from https://github.com/guzzle/psr7/blob/a243f80a1ca7fe8ceed4deee17f12c1930efe662/src/Query.php#L59-L112 + * with a modification which is described in https://github.com/guzzle/psr7/pull/603 + * + * @param array $params Query string parameters. + * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 + * to encode using RFC3986, or PHP_QUERY_RFC1738 + * to encode using RFC1738. + */ + public static function buildQuery(array $params, $encoding = PHP_QUERY_RFC3986): string + { + if (!$params) { + return ''; + } + + if ($encoding === false) { + $encoder = function (string $str): string { + return $str; + }; + } elseif ($encoding === PHP_QUERY_RFC3986) { + $encoder = 'rawurlencode'; + } elseif ($encoding === PHP_QUERY_RFC1738) { + $encoder = 'urlencode'; + } else { + throw new \InvalidArgumentException('Invalid type'); + } + + $castBool = Configuration::BOOLEAN_FORMAT_INT == Configuration::getDefaultConfiguration()->getBooleanFormatForQueryString() + ? function ($v) { return (int) $v; } + : function ($v) { return $v ? 'true' : 'false'; }; + + $qs = ''; + foreach ($params as $k => $v) { + $k = $encoder((string) $k); + if (!is_array($v)) { + $qs .= $k; + $v = is_bool($v) ? $castBool($v) : $v; + if ($v !== null) { + $qs .= '='.$encoder((string) $v); + } + $qs .= '&'; + } else { + foreach ($v as $vv) { + $qs .= $k; + $vv = is_bool($vv) ? $castBool($vv) : $vv; + if ($vv !== null) { + $qs .= '='.$encoder((string) $vv); + } + $qs .= '&'; + } + } + } + + return $qs ? substr($qs, 0, -1) : ''; + } +} diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/phpunit.xml.dist b/iznik-batch/app/Services/TrashNothing/PublicApi/phpunit.xml.dist new file mode 100644 index 0000000000..485899aaf2 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/phpunit.xml.dist @@ -0,0 +1,18 @@ + + + + + ./lib/Api + ./lib/Model + + + + + ./test/Api + ./test/Model + + + + + + diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/test/Api/GroupsApiTest.php b/iznik-batch/app/Services/TrashNothing/PublicApi/test/Api/GroupsApiTest.php new file mode 100644 index 0000000000..36223d544f --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/test/Api/GroupsApiTest.php @@ -0,0 +1,109 @@ + Date: Thu, 21 May 2026 14:08:30 -0400 Subject: [PATCH 3/8] Require TN public API package in root composer.json --- .../Services/TrashNothing/PublicApi/composer.json | 1 + iznik-batch/composer.json | 14 ++++++++++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/composer.json b/iznik-batch/app/Services/TrashNothing/PublicApi/composer.json index a3bc7e3cb3..501c8dd1c0 100644 --- a/iznik-batch/app/Services/TrashNothing/PublicApi/composer.json +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/composer.json @@ -1,4 +1,5 @@ { + "name": "trashnothing/public-api", "description": "This is the REST API for [trashnothing.com](https://trashnothing.com). To learn more about the API or to register your app for use with the API visit the [Trash Nothing Developer page](https://trashnothing.com/app/developer). NOTE: All date-time values are [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) and are in [ISO 8601 format](https://en.wikipedia.org/wiki/ISO_8601) (eg. 2019-02-03T01:23:53).", "keywords": [ "openapitools", diff --git a/iznik-batch/composer.json b/iznik-batch/composer.json index 6f76426388..1dc07e71d8 100644 --- a/iznik-batch/composer.json +++ b/iznik-batch/composer.json @@ -17,7 +17,8 @@ "sentry/sentry-laravel": "^4.20", "simple-as-fuck/laravel-lock": "^0.4.0", "spatie/mjml-php": "^1.2", - "zbateson/mail-mime-parser": "^3.0" + "zbateson/mail-mime-parser": "^3.0", + "trashnothing/public-api": "*" }, "require-dev": { "barryvdh/laravel-ide-helper": "*", @@ -94,5 +95,14 @@ } }, "minimum-stability": "stable", - "prefer-stable": true + "prefer-stable": true, + "repositories": [ + { + "type": "path", + "url": "./app/Services/TrashNothing/PublicApi", + "options": { + "symlink": true + } + } + ] } From 5286f13e8a131c9e038146cacab76bc84b0f4e3e Mon Sep 17 00:00:00 2001 From: fnnbrr Date: Thu, 21 May 2026 14:34:38 -0400 Subject: [PATCH 4/8] Skeleton code for PostSyncer to pull TN posts in TNSyncCommand --- .../Commands/TrashNothing/TNSyncCommand.php | 17 ++++++++--- .../Services/TrashNothing/Sync/PostSyncer.php | 29 +++++++++++++++++++ 2 files changed, 42 insertions(+), 4 deletions(-) create mode 100644 iznik-batch/app/Services/TrashNothing/Sync/PostSyncer.php diff --git a/iznik-batch/app/Console/Commands/TrashNothing/TNSyncCommand.php b/iznik-batch/app/Console/Commands/TrashNothing/TNSyncCommand.php index 34b4bc48d6..21cde77202 100644 --- a/iznik-batch/app/Console/Commands/TrashNothing/TNSyncCommand.php +++ b/iznik-batch/app/Console/Commands/TrashNothing/TNSyncCommand.php @@ -10,6 +10,7 @@ use App\Models\UserEmail; use App\Models\UserReplyTime; use App\Services\LokiService; +use App\Services\TrashNothing\Sync\PostSyncer; use App\Traits\GracefulShutdown; use App\Traits\LogsBatchJob; use Illuminate\Console\Command; @@ -21,7 +22,7 @@ class TNSyncCommand extends Command { use GracefulShutdown; use LogsBatchJob; - + // TODO Finnbarr: remove this after testing is complete. The Laravel scheduler's withoutOverlapping will handle locking. use PreventsOverlapping; @@ -103,6 +104,13 @@ public function handle(): int // Merge duplicate TN users. $duplicatesMerged = $this->mergeDuplicateTNUsers(); + // Sync posts. + $postSyncer = new PostSyncer($this->dryRun, $this->localTesting, $this->apiKey, $this->apiBaseUrl, $this->loki); + [$postsProcessed, $postsMaxDate] = $postSyncer->sync($from, $to); + if ($postsMaxDate && (!$maxChangeDate || $postsMaxDate > $maxChangeDate)) { + $maxChangeDate = $postsMaxDate; + } + // Store the max change date for next sync. if ($maxChangeDate) { $this->storeSyncDate($maxChangeDate); @@ -110,21 +118,22 @@ public function handle(): int Log::info('No change date to store - no data processed'); } - if ($ratingsProcessed === 0 && $changesProcessed === 0 && $duplicatesMerged === 0) { + if ($ratingsProcessed === 0 && $changesProcessed === 0 && $duplicatesMerged === 0 && $postsProcessed === 0) { Log::warning('TN sync did nothing'); if (function_exists('\Sentry\captureMessage')) { \Sentry\captureMessage('TN sync did nothing'); } } - $this->info("TN sync complete: {$ratingsProcessed} ratings, {$changesProcessed} user changes, {$duplicatesMerged} duplicates merged."); + $this->info("TN sync complete: {$ratingsProcessed} ratings, {$changesProcessed} user changes, {$duplicatesMerged} duplicates merged, {$postsProcessed} posts."); Log::info('TN sync complete', [ 'ratings_processed' => $ratingsProcessed, 'changes_processed' => $changesProcessed, 'duplicates_merged' => $duplicatesMerged, + 'posts_processed' => $postsProcessed, ]); - Log::info("TN-SYNC-TRACE [END] ratings={$ratingsProcessed} changes={$changesProcessed} merges={$duplicatesMerged} max_date=" . ($maxChangeDate ?? 'null')); + Log::info("TN-SYNC-TRACE [END] ratings={$ratingsProcessed} changes={$changesProcessed} merges={$duplicatesMerged} posts={$postsProcessed} max_date=" . ($maxChangeDate ?? 'null')); return Command::SUCCESS; }); diff --git a/iznik-batch/app/Services/TrashNothing/Sync/PostSyncer.php b/iznik-batch/app/Services/TrashNothing/Sync/PostSyncer.php new file mode 100644 index 0000000000..55ec7e70d4 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/Sync/PostSyncer.php @@ -0,0 +1,29 @@ + Date: Thu, 21 May 2026 14:58:12 -0400 Subject: [PATCH 5/8] First pass using generated TN API client for fetching posts --- .../Services/TrashNothing/Sync/PostSyncer.php | 112 +++++++++++++++++- 1 file changed, 109 insertions(+), 3 deletions(-) diff --git a/iznik-batch/app/Services/TrashNothing/Sync/PostSyncer.php b/iznik-batch/app/Services/TrashNothing/Sync/PostSyncer.php index 55ec7e70d4..b948bd3501 100644 --- a/iznik-batch/app/Services/TrashNothing/Sync/PostSyncer.php +++ b/iznik-batch/app/Services/TrashNothing/Sync/PostSyncer.php @@ -4,11 +4,17 @@ use App\Services\LokiService; use Illuminate\Support\Facades\Log; +use OpenAPI\Client\Api\PostsApi; +use OpenAPI\Client\ApiException; +use OpenAPI\Client\Configuration; class PostSyncer { private const PAGE_SIZE = 100; + // TODO: temporarily just requesting posts for the FreeglePlayground group. + private const GROUP_IDS = '8444'; + public function __construct( private bool $dryRun, private bool $localTesting, @@ -22,8 +28,108 @@ public function __construct( */ public function sync(string $from, string $to): array { - // TODO: implement post sync - Log::info('TN-SYNC-TRACE [POSTS] not yet implemented'); - return [0, null]; + $page = 1; + $count = 0; + $maxDate = null; + $api = $this->buildApiClient(); + + do { + [$posts, $numPages] = $this->fetchPage($api, $page, $from, $to); + if ($posts === null) { + break; + } + + Log::info("TN-SYNC-TRACE [POSTS-PAGE] page={$page} count=" . count($posts)); + + foreach ($posts as $post) { + $count++; + $maxDate = $this->processPost($post, $maxDate); + } + + $page++; + } while ($posts && $page <= $numPages); + + Log::info("TN-SYNC-TRACE [POSTS-DONE] total={$count} max_date=" . ($maxDate ?? 'null')); + + return [$count, $maxDate]; + } + + /** + * @return array{array|null, int} [posts, numPages] — posts is null on API error + */ + private function fetchPage(PostsApi $api, int $page, string $from, string $to): array + { + if ($this->localTesting) { + return $this->fetchPageFromFixture($page); + } + + try { + $response = $api->getPosts( + types: 'offer,wanted', + sources: 'groups', + sort_by: 'date', + group_ids: self::GROUP_IDS, + per_page: self::PAGE_SIZE, + page: $page, + date_min: new \DateTime($from), + date_max: new \DateTime($to), + outcomes: 'all', + ); + } catch (ApiException $e) { + Log::error("TN sync: posts API failed on page {$page}", [ + 'status' => $e->getCode(), + 'error' => $e->getMessage(), + ]); + return [null, 0]; + } + + return [$response->getPosts() ?? [], $response->getNumPages() ?? 1]; + } + + /** + * @return array{array, int} [posts, numPages] + */ + private function fetchPageFromFixture(int $page): array + { + $fixtureFile = base_path("tests/fixtures/tn_sync/posts_page_{$page}.json"); + + if (!file_exists($fixtureFile)) { + Log::info("TN-SYNC-TRACE [POSTS-PAGE] missing fixture file={$fixtureFile}"); + return [[], 0]; + } + + $payload = json_decode(file_get_contents($fixtureFile), true); + + return [ + is_array($payload) ? ($payload['posts'] ?? []) : [], + is_array($payload) ? (int) ($payload['num_pages'] ?? 1) : 1, + ]; + } + + private function processPost(mixed $post, ?string $maxDate): ?string + { + $date = is_array($post) ? ($post['date'] ?? null) : $post->getDate()?->format('Y-m-d\TH:i:s\Z'); + $postId = is_array($post) ? ($post['post_id'] ?? '') : $post->getPostId(); + $type = is_array($post) ? ($post['type'] ?? '') : $post->getType(); + $groupId = is_array($post) ? ($post['group_id'] ?? '') : $post->getGroupId(); + $title = is_array($post) ? ($post['title'] ?? '') : $post->getTitle(); + + if ($date && (!$maxDate || $date > $maxDate)) { + $maxDate = $date; + } + + // TODO: ingest post into the database. + Log::info("TN-SYNC-TRACE [POST] post_id={$postId} type={$type} group_id={$groupId} date={$date} title=" . substr((string) $title, 0, 60)); + + return $maxDate; + } + + private function buildApiClient(): PostsApi + { + $config = Configuration::getDefaultConfiguration() + ->setApiKey('api_key', $this->apiKey) + ->setHost($this->apiBaseUrl); + + return new PostsApi(config: $config); } } From c580eebbfb802ff61c57183532cbcde7753c74f0 Mon Sep 17 00:00:00 2001 From: fnnbrr Date: Wed, 8 Jul 2026 14:06:26 -0400 Subject: [PATCH 6/8] Fixes for docker compose build with Trash Nothing API composer package --- .../TrashNothing/PublicApi/composer.json | 1 + iznik-batch/composer.lock | 58 ++++++++++++++++++- status-nuxt/Dockerfile | 2 +- 3 files changed, 59 insertions(+), 2 deletions(-) diff --git a/iznik-batch/app/Services/TrashNothing/PublicApi/composer.json b/iznik-batch/app/Services/TrashNothing/PublicApi/composer.json index 501c8dd1c0..002533565d 100644 --- a/iznik-batch/app/Services/TrashNothing/PublicApi/composer.json +++ b/iznik-batch/app/Services/TrashNothing/PublicApi/composer.json @@ -11,6 +11,7 @@ "api" ], "homepage": "https://openapi-generator.tech", + "version": "1.4.0", "license": "unlicense", "authors": [ { diff --git a/iznik-batch/composer.lock b/iznik-batch/composer.lock index cc8caa9ec4..6a6fdae09d 100644 --- a/iznik-batch/composer.lock +++ b/iznik-batch/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "2367e1e318ad0eefc81635b5d5beecc7", + "content-hash": "63d9bcc43d4781171c37e0d829e4ae39", "packages": [ { "name": "beste/clock", @@ -8914,6 +8914,62 @@ }, "time": "2024-12-21T16:25:41+00:00" }, + { + "name": "trashnothing/public-api", + "version": "1.4.0", + "dist": { + "type": "path", + "url": "./app/Services/TrashNothing/PublicApi", + "reference": "3c3f0d354d77da981280a8a2a2db086c1abd2b05" + }, + "require": { + "ext-curl": "*", + "ext-json": "*", + "ext-mbstring": "*", + "guzzlehttp/guzzle": "^7.3", + "guzzlehttp/psr7": "^1.7 || ^2.0", + "php": "^8.1" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.5", + "phpunit/phpunit": "^8.0 || ^9.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "OpenAPI\\Client\\": "lib/" + } + }, + "autoload-dev": { + "psr-4": { + "OpenAPI\\Client\\Test\\": "test/" + } + }, + "license": [ + "unlicense" + ], + "authors": [ + { + "name": "OpenAPI", + "homepage": "https://openapi-generator.tech" + } + ], + "description": "This is the REST API for [trashnothing.com](https://trashnothing.com). To learn more about the API or to register your app for use with the API visit the [Trash Nothing Developer page](https://trashnothing.com/app/developer). NOTE: All date-time values are [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) and are in [ISO 8601 format](https://en.wikipedia.org/wiki/ISO_8601) (eg. 2019-02-03T01:23:53).", + "homepage": "https://openapi-generator.tech", + "keywords": [ + "api", + "openapi", + "openapi-generator", + "openapitools", + "php", + "rest", + "sdk" + ], + "transport-options": { + "symlink": true, + "relative": true + } + }, { "name": "vlucas/phpdotenv", "version": "v5.6.2", diff --git a/status-nuxt/Dockerfile b/status-nuxt/Dockerfile index 3241314b0a..3afa1eccc3 100644 --- a/status-nuxt/Dockerfile +++ b/status-nuxt/Dockerfile @@ -1,4 +1,4 @@ -FROM node:20-slim +FROM node:22-slim WORKDIR /app From a5b00c9ba3f45ee2c6f90d98bf907afa4c6792fa Mon Sep 17 00:00:00 2001 From: fnnbrr Date: Wed, 8 Jul 2026 15:33:04 -0400 Subject: [PATCH 7/8] Ported TN message ingestion logic from IncomingMailService::handleGroupPost + ::createGroupPostMessage to GroupPostIngestionService --- .../Ingestion/GroupPostIngestionService.php | 627 ++++++++++++++++++ .../Services/TrashNothing/Sync/PostSyncer.php | 73 +- .../tests/fixtures/tn_sync/posts_page_1.json | 46 ++ plans/tn-api-post-ingestion.md | 10 +- 4 files changed, 736 insertions(+), 20 deletions(-) create mode 100644 iznik-batch/app/Services/TrashNothing/Ingestion/GroupPostIngestionService.php create mode 100644 iznik-batch/tests/fixtures/tn_sync/posts_page_1.json diff --git a/iznik-batch/app/Services/TrashNothing/Ingestion/GroupPostIngestionService.php b/iznik-batch/app/Services/TrashNothing/Ingestion/GroupPostIngestionService.php new file mode 100644 index 0000000000..54544a99e7 --- /dev/null +++ b/iznik-batch/app/Services/TrashNothing/Ingestion/GroupPostIngestionService.php @@ -0,0 +1,627 @@ +getField($post, 'post_id', 'getPostId'); + $fdUserId = $this->getField($post, 'user_id', 'getUserId'); + $title = $this->getField($post, 'title', 'getTitle') ?? ''; + $content = $this->getField($post, 'content', 'getContent') ?? ''; + $date = $this->getField($post, 'date', 'getDate'); + $lat = $this->getField($post, 'latitude', 'getLatitude'); + $lng = $this->getField($post, 'longitude', 'getLongitude'); + $tnType = strtolower((string) $this->getField($post, 'type', 'getType')); + $photos = $this->getField($post, 'photos', 'getPhotos') ?? []; + + $dateStr = $date instanceof \DateTime ? $date->format('Y-m-d\TH:i:s\Z') : (string) $date; + $subject = strtoupper($tnType) . ': ' . $title; + + // Idempotency: skip if this post was already ingested for this group. + $isDuplicate = $this->postAlreadyExists((string) $postId, $group->id); + if ($isDuplicate) { + Log::info('TN-SYNC-TRACE [POST-SKIP] reason=duplicate tnpostid=' . $postId . ' groupid=' . $group->id . ($this->dryRun ? ' would_be_duplicate=true' : '')); + $this->loki->logEvent('tn-sync', 'post-skip-duplicate', ['tn_post_id' => $postId, 'group_id' => $group->id]); + return 'duplicate'; + } + + // Resolve Freegle user from TN fd_user_id. + $user = $fdUserId ? User::find($fdUserId) : null; + if ($user === null) { + Log::info('TN-SYNC-TRACE [POST-SKIP] reason=unknown-user tnpostid=' . $postId . ' fd_user_id=' . $fdUserId); + $this->loki->logEvent('tn-sync', 'post-skip-unknown-user', ['tn_post_id' => $postId, 'fd_user_id' => $fdUserId]); + return 'skipped'; + } + + // Update user's last access. + Log::info('TN-SYNC-TRACE [WRITE] table=users op=update where=id=' . $user->id . ' set=lastaccess=now()'); + if (!$this->dryRun) { + DB::table('users')->where('id', $user->id)->update(['lastaccess' => now()]); + } + + // Membership check: user must be an approved member. + $membership = Membership::where('userid', $user->id) + ->where('groupid', $group->id) + ->where('collection', 'Approved') + ->first(); + + if ($membership === null) { + Log::info('TN-SYNC-TRACE [POST-SKIP] reason=non-member tnpostid=' . $postId . ' user_id=' . $user->id . ' group_id=' . $group->id); + $this->loki->logEvent('tn-sync', 'post-skip-non-member', ['tn_post_id' => $postId, 'user_id' => $user->id]); + return 'skipped'; + } + + // Determine posting status, applying the same override hierarchy as the email path. + $postingStatus = $membership->ourPostingStatus; + + $overrideModeration = $group->overridemoderation ?? 'None'; + if ($overrideModeration === 'ModerateAll') { + $postingStatus = 'MODERATED'; + } + + if ($user->isModeratorOf($group->id)) { + $postingStatus = 'MODERATED'; + } + + $groupSettings = is_array($group->settings) ? $group->settings : (json_decode($group->settings ?? '{}', true) ?: []); + if (!empty($groupSettings['moderated'])) { + $postingStatus = 'MODERATED'; + } + + // Determine routing result. + $routingResult = 'pending'; + $pendingReason = null; + + if ($user->lastlocation === null) { + $pendingReason = 'unmapped user'; + } elseif ($this->subjectContainsWorryWords($subject, $content)) { + $pendingReason = 'worry words'; + } else { + $routingResult = match ($postingStatus) { + 'DEFAULT', 'UNMODERATED' => 'approved', + 'PROHIBITED' => 'dropped', + default => 'pending', + }; + } + + if ($routingResult === 'dropped') { + Log::info('TN-SYNC-TRACE [POST-SKIP] reason=prohibited tnpostid=' . $postId . ' user_id=' . $user->id); + return 'dropped'; + } + + // Create the message record. + $messageId = $this->createMessage($post, $user, $group, $subject, $content, $lat, $lng, $date, $postId, $photos); + + if ($messageId === null) { + return 'skipped'; + } + + // Record in messages_postings (matches email path #12). + Log::info('TN-SYNC-TRACE [WRITE] table=messages_postings op=insert set=msgid=' . $messageId . ',groupid=' . $group->id . ',repost=0,autorepost=0'); + if (!$this->dryRun) { + DB::table('messages_postings')->insert([ + 'msgid' => $messageId, + 'groupid' => $group->id, + 'repost' => 0, + 'autorepost' => 0, + 'date' => now(), + ]); + } + + if ($routingResult === 'approved') { + Log::info('TN-SYNC-TRACE [WRITE] table=messages_groups op=update where=msgid=' . $messageId . ' set=collection=Approved,approvedat=now()'); + if (!$this->dryRun) { + MessageGroup::where('msgid', $messageId)->update([ + 'collection' => MessageGroup::COLLECTION_APPROVED, + 'approvedat' => now(), + ]); + $this->addToSpatialIndex($messageId, $group->id); + } + $this->loki->logEvent('tn-sync', 'post-create', ['tn_post_id' => $postId, 'msg_id' => $messageId, 'collection' => 'Approved']); + } else { + Log::info('TN-SYNC-TRACE [WRITE] table=messages_groups op=update where=msgid=' . $messageId . ' set=collection=Pending reason=' . ($pendingReason ?? 'posting-status')); + if (!$this->dryRun) { + MessageGroup::where('msgid', $messageId)->update(['collection' => MessageGroup::COLLECTION_PENDING]); + $this->notifyGroupMods($group->id); + } + $this->loki->logEvent('tn-sync', 'post-create', ['tn_post_id' => $postId, 'msg_id' => $messageId, 'collection' => 'Pending', 'reason' => $pendingReason]); + } + + return $routingResult; + } + + private function createMessage( + mixed $post, + User $user, + Group $group, + string $subject, + string $content, + mixed $lat, + mixed $lng, + mixed $date, + string $postId, + array $photos, + ): ?int { + try { + $type = Message::determineType($subject); + + // Synthesized message-ID: unique per post+group, stable across retries. + $messageid = $postId . '@tn.trashnothing.com-' . $group->id; + + // Resolve location: use API coordinates directly (replaces header parsing). + $locationId = null; + if ($lat !== null && $lng !== null) { + $locationId = $this->findClosestPostcodeId((float) $lat, (float) $lng); + } else { + [$lat, $lng] = $user->getLatLng(); + if ($user->lastlocation) { + $locationId = $user->lastlocation; + } + } + + if ($lat !== null && $lng !== null && $locationId === null) { + $locationId = $this->findClosestPostcodeId((float) $lat, (float) $lng); + } + + if ($locationId && $user->id) { + Log::info('TN-SYNC-TRACE [WRITE] table=users op=update where=id=' . $user->id . ' set=lastlocation=' . $locationId); + if (!$this->dryRun) { + DB::table('users')->where('id', $user->id)->update(['lastlocation' => $locationId]); + } + } + + $fromName = $user->fullname ?? $user->firstname ?? null; + + // Synthesize minimal RFC822 message blob so downstream code that + // re-parses messages.message still recovers the key fields. + $dateStr = $date instanceof \DateTime + ? $date->format('D, d M Y H:i:s +0000') + : now()->format('D, d M Y H:i:s +0000'); + $groupEmail = $group->nameshort . '@' . config('freegle.mail.group_domain', 'groups.ilovefreegle.org'); + $rfc822 = $this->synthesizeRfc822($fromName, $groupEmail, $subject, $dateStr, $messageid, $postId, $lat, $lng, $content); + + $msgData = [ + 'date' => $date instanceof \DateTime ? $date->format('Y-m-d H:i:s') : now(), + 'source' => 'TN-API', + 'sourceheader' => 'TN-API', + 'message' => $rfc822, + 'fromuser' => $user->id, + 'envelopefrom' => null, + 'envelopeto' => $groupEmail, + 'fromname' => $fromName, + 'fromaddr' => null, + 'replyto' => null, + 'fromip' => null, + 'fromcountry' => null, + 'subject' => $subject, + 'suggestedsubject' => $subject, + 'messageid' => $messageid, + 'tnpostid' => $postId, + 'textbody' => $content, + 'type' => $type, + 'lat' => $lat !== null ? (float) $lat : null, + 'lng' => $lng !== null ? (float) $lng : null, + 'locationid' => $locationId, + 'spamtype' => null, + 'spamreason' => null, + ]; + + Log::info('TN-SYNC-TRACE [WRITE] table=messages op=insert set=' . json_encode([ + 'messageid' => $messageid, + 'tnpostid' => $postId, + 'groupid' => $group->id, + 'fromuser' => $user->id, + 'type' => $type, + 'subject' => $subject, + 'lat' => $lat, + 'lng' => $lng, + 'locationid' => $locationId, + ])); + + $message = null; + if (!$this->dryRun) { + $message = Message::create($msgData); + if (!$message || !$message->id) { + Log::error('TN post ingestion: failed to create message record'); + return null; + } + } + + $messageId = $message?->id ?? 0; + + // messages_groups entry — starts as Incoming; collection updated after routing. + Log::info('TN-SYNC-TRACE [WRITE] table=messages_groups op=insert set=msgid=' . $messageId . ',groupid=' . $group->id . ',msgtype=' . $type . ',collection=Incoming'); + if (!$this->dryRun) { + MessageGroup::create([ + 'msgid' => $messageId, + 'groupid' => $group->id, + 'msgtype' => $type, + 'collection' => MessageGroup::COLLECTION_INCOMING, + 'arrival' => now(), + ]); + } + + // messages_items link (weight statistics, same as email path). + if (!$this->dryRun) { + $this->itemService->recordFromSubject($messageId, $subject); + } + + // messages_history. + $prunedSubject = $this->pruneSubject($subject); + Log::info('TN-SYNC-TRACE [WRITE] table=messages_history op=insert set=msgid=' . $messageId . ',groupid=' . $group->id . ',fromuser=' . $user->id); + if (!$this->dryRun) { + DB::table('messages_history')->insert([ + 'groupid' => $group->id, + 'source' => 'TN-API', + 'fromuser' => $user->id, + 'envelopefrom' => null, + 'envelopeto' => $groupEmail, + 'fromname' => $fromName, + 'fromaddr' => null, + 'fromip' => null, + 'subject' => $subject, + 'prunedsubject' => $prunedSubject, + 'messageid' => $messageid, + 'msgid' => $messageId, + ]); + } + + // Log receipt. + Log::info('TN-SYNC-TRACE [WRITE] table=logs op=insert set=type=Message,subtype=Received,msgid=' . $messageId . ',groupid=' . $group->id); + if (!$this->dryRun) { + DB::table('logs')->insert([ + 'timestamp' => now(), + 'type' => 'Message', + 'subtype' => 'Received', + 'groupid' => $group->id, + 'user' => $user->id, + 'msgid' => $messageId, + 'text' => $messageid, + ]); + } + + // Process TN photos from API (replaces scraping trashnothing.com/pics/ links). + if (!empty($photos)) { + $this->createImageAttachments($messageId, $photos); + } + + return $this->dryRun ? -1 : $messageId; + + } catch (\Exception $e) { + if (str_contains($e->getMessage(), 'Duplicate entry')) { + Log::info('TN post ingestion: duplicate messageid, skipping', ['tnpostid' => $postId]); + return null; + } + + Log::error('TN post ingestion: failed to create message', [ + 'tnpostid' => $postId, + 'error' => $e->getMessage(), + ]); + + return null; + } + } + + private function postAlreadyExists(string $tnPostId, int $groupId): bool + { + return DB::table('messages') + ->join('messages_groups', 'messages_groups.msgid', '=', 'messages.id') + ->where('messages.tnpostid', $tnPostId) + ->where('messages_groups.groupid', $groupId) + ->exists(); + } + + /** + * Duplicate of IncomingMailService::containsWorryWords (subject + body). + * Kept separate per plan: no extraction until email path parity is proven. + */ + private function subjectContainsWorryWords(string $subject, string $body): bool + { + if (str_contains($subject, '£') || str_contains($body, '£')) { + return true; + } + + $worryWords = DB::table('worrywords')->get(); + + foreach ($worryWords as $ww) { + if ($ww->type === 'Allowed') { + $pattern = '/\b' . preg_quote($ww->keyword, '/') . '\b/i'; + $subject = preg_replace($pattern, '', $subject) ?? $subject; + $body = preg_replace($pattern, '', $body) ?? $body; + } + } + + foreach ($worryWords as $ww) { + if ($ww->type !== 'Allowed' && str_contains($ww->keyword, ' ')) { + if (stripos($subject, $ww->keyword) !== false || stripos($body, $ww->keyword) !== false) { + return true; + } + } + } + + $allWords = preg_split('/\b/', $subject . ' ' . $body); + foreach ($allWords as $word) { + $word = trim($word); + if (empty($word)) { + continue; + } + foreach ($worryWords as $ww) { + if ($ww->type !== 'Allowed' && !empty($ww->keyword)) { + $ratio = strlen($word) / strlen($ww->keyword); + if ($ratio >= 0.75 && $ratio <= 1.25 && levenshtein(strtolower($ww->keyword), strtolower($word)) < 1) { + return true; + } + } + } + } + + return false; + } + + /** + * Duplicate of IncomingMailService::pruneSubject. + */ + private function pruneSubject(?string $subject): ?string + { + if ($subject === null) { + return null; + } + $pruned = preg_replace('/\s*\([^)]+\)\s*$/', '', $subject); + $pruned = preg_replace('/^(OFFER|WANTED|TAKEN|RECEIVED)\s*:\s*/i', '', $pruned); + return trim($pruned); + } + + /** + * Duplicate of IncomingMailService::findClosestPostcodeId. + */ + private function findClosestPostcodeId(float $lat, float $lng): ?int + { + $ids = (new SpatialQueryService())->nearestIds('postcodes', $lat, $lng, 1); + return $ids[0] ?? null; + } + + /** + * Duplicate of IncomingMailService::addToSpatialIndex. + */ + private function addToSpatialIndex(int $messageId, int $groupId): void + { + $message = Message::query()->useWritePdo()->find($messageId); + if (!$message || (!$message->lat && !$message->lng)) { + return; + } + + $srid = config('freegle.srid', 3857); + $mg = DB::table('messages_groups')->useWritePdo() + ->where('msgid', $messageId) + ->where('groupid', $groupId) + ->first(); + + $arrival = $mg->arrival ?? now(); + $msgType = $message->type; + + try { + DB::statement( + "INSERT INTO messages_spatial (msgid, point, groupid, msgtype, arrival) + VALUES (?, ST_GeomFromText('POINT({$message->lng} {$message->lat})', ?), ?, ?, ?) + ON DUPLICATE KEY UPDATE + point = ST_GeomFromText('POINT({$message->lng} {$message->lat})', ?), + groupid = ?, msgtype = ?, arrival = ?", + [$messageId, $srid, $groupId, $msgType, $arrival, $srid, $groupId, $msgType, $arrival] + ); + } catch (\Exception $e) { + Log::warning('TN post ingestion: failed to add to spatial index', [ + 'message_id' => $messageId, + 'error' => $e->getMessage(), + ]); + } + } + + /** + * Duplicate of IncomingMailService::notifyGroupMods. + */ + private function notifyGroupMods(int $groupId): void + { + try { + $count = app(\App\Services\PushNotificationService::class)->notifyGroupMods($groupId); + Log::info('TN post ingestion: notified group mods', ['group_id' => $groupId, 'count' => $count]); + } catch (\Throwable $e) { + Log::warning('TN post ingestion: failed to notify group mods', ['group_id' => $groupId, 'error' => $e->getMessage()]); + } + } + + /** + * Download TN API photo URLs and create MessageAttachment records. + * Replaces scrapeTnImageUrls + createTnImageAttachments from email path — + * photos are delivered directly by the API, no HTML scraping needed. + */ + private function createImageAttachments(int $messageId, array $photos): int + { + if ($this->dryRun) { + $count = count($photos); + Log::info('TN-SYNC-TRACE [WRITE] table=message_attachments op=insert set=msgid=' . $messageId . ' count=' . $count . ' (dry-run, not fetching)'); + return $count; + } + + $tusService = app(TusService::class); + $created = 0; + $isFirst = true; + + foreach ($photos as $photo) { + $url = $this->bestPhotoUrl($photo); + if (!$url) { + continue; + } + + try { + $response = Http::timeout(120)->get($url); + if (!$response->successful()) { + Log::warning('TN post ingestion: failed to download photo', ['url' => $url, 'status' => $response->status()]); + continue; + } + + $imageData = $response->body(); + $contentType = $response->header('Content-Type') ?? 'image/jpeg'; + $hash = $this->computeImageHash($imageData); + + if ($hash && MessageAttachment::where('msgid', $messageId)->where('hash', $hash)->exists()) { + continue; + } + + $tusUrl = $tusService->upload($imageData, $contentType); + if (!$tusUrl) { + Log::warning('TN post ingestion: failed to upload photo to tusd', ['url' => $url]); + continue; + } + + $externalUid = TusService::urlToExternalUid($tusUrl); + + MessageAttachment::create([ + 'msgid' => $messageId, + 'externaluid' => $externalUid, + 'hash' => $hash, + 'primary' => $isFirst, + ]); + + $created++; + $isFirst = false; + + } catch (\Exception $e) { + Log::warning('TN post ingestion: exception processing photo', ['url' => $url, 'error' => $e->getMessage()]); + } + } + + return $created; + } + + /** + * Return the best available URL from a TN Photo object or array. + * Prefers the highest-resolution image in the images array, falls back to photo url. + */ + private function bestPhotoUrl(mixed $photo): ?string + { + if (is_array($photo)) { + $images = $photo['images'] ?? []; + if (!empty($images)) { + return $images[0]['url'] ?? null; + } + return $photo['url'] ?? null; + } + + // OpenAPI Photo object + $images = $photo->getImages() ?? []; + if (!empty($images)) { + return $images[0]->getUrl(); + } + return $photo->getUrl(); + } + + /** + * Compute perceptual hash for image deduplication. + * Duplicate of IncomingMailService::computeImageHash. + */ + private function computeImageHash(string $imageData): ?string + { + try { + $img = @\imagecreatefromstring($imageData); + if (!$img) { + return substr(md5($imageData), 0, 16); + } + if (class_exists(\Jenssegers\ImageHash\ImageHash::class)) { + $hasher = new \Jenssegers\ImageHash\ImageHash; + $hash = $hasher->hash($img)->toHex(); + \imagedestroy($img); + return substr($hash, 0, 16); + } + \imagedestroy($img); + return substr(md5($imageData), 0, 16); + } catch (\Exception $e) { + return substr(md5($imageData), 0, 16); + } + } + + /** + * Synthesize a minimal RFC822 message blob so any code that re-parses + * messages.message can still recover the key fields. + */ + private function synthesizeRfc822( + ?string $fromName, + string $groupEmail, + string $subject, + string $date, + string $messageId, + string $tnPostId, + mixed $lat, + mixed $lng, + string $body, + ): string { + $from = $fromName ? "{$fromName} " : 'noreply@trashnothing.com'; + $coords = ($lat !== null && $lng !== null) ? "{$lat},{$lng}" : ''; + + return implode("\r\n", [ + "From: {$from}", + "To: {$groupEmail}", + "Subject: {$subject}", + "Date: {$date}", + "Message-ID: <{$messageId}>", + "X-Trashnothing-Post-Id: {$tnPostId}", + $coords ? "X-Trashnothing-Coordinates: {$coords}" : '', + 'Content-Type: text/plain; charset=utf-8', + '', + $body, + ]); + } + + /** + * Unified field accessor for both OpenAPI objects and fixture arrays. + * + * @param mixed $post OpenAPI Post object or array + * @param string $arrayKey Key name for array (fixture) access + * @param string $method Getter method name for object access + */ + private function getField(mixed $post, string $arrayKey, string $method): mixed + { + if (is_array($post)) { + return $post[$arrayKey] ?? null; + } + return method_exists($post, $method) ? $post->$method() : null; + } +} diff --git a/iznik-batch/app/Services/TrashNothing/Sync/PostSyncer.php b/iznik-batch/app/Services/TrashNothing/Sync/PostSyncer.php index b948bd3501..1c70e27d39 100644 --- a/iznik-batch/app/Services/TrashNothing/Sync/PostSyncer.php +++ b/iznik-batch/app/Services/TrashNothing/Sync/PostSyncer.php @@ -2,7 +2,10 @@ namespace App\Services\TrashNothing\Sync; +use App\Models\Group; +use App\Services\ItemService; use App\Services\LokiService; +use App\Services\TrashNothing\Ingestion\GroupPostIngestionService; use Illuminate\Support\Facades\Log; use OpenAPI\Client\Api\PostsApi; use OpenAPI\Client\ApiException; @@ -15,23 +18,31 @@ class PostSyncer // TODO: temporarily just requesting posts for the FreeglePlayground group. private const GROUP_IDS = '8444'; + private GroupPostIngestionService $ingestionService; + public function __construct( private bool $dryRun, private bool $localTesting, private string $apiKey, private string $apiBaseUrl, private LokiService $loki, - ) {} + ) { + $this->ingestionService = new GroupPostIngestionService( + dryRun: $this->dryRun, + loki: $this->loki, + itemService: app(ItemService::class), + ); + } /** * @return array{int, string|null} [count, maxDate] */ public function sync(string $from, string $to): array { - $page = 1; - $count = 0; + $page = 1; + $count = 0; $maxDate = null; - $api = $this->buildApiClient(); + $api = $this->buildApiClient(); do { [$posts, $numPages] = $this->fetchPage($api, $page, $from, $to); @@ -39,7 +50,7 @@ public function sync(string $from, string $to): array break; } - Log::info("TN-SYNC-TRACE [POSTS-PAGE] page={$page} count=" . count($posts)); + Log::info('TN-SYNC-TRACE [POSTS-PAGE] page=' . $page . ' count=' . count($posts)); foreach ($posts as $post) { $count++; @@ -49,7 +60,7 @@ public function sync(string $from, string $to): array $page++; } while ($posts && $page <= $numPages); - Log::info("TN-SYNC-TRACE [POSTS-DONE] total={$count} max_date=" . ($maxDate ?? 'null')); + Log::info('TN-SYNC-TRACE [POSTS-DONE] total=' . $count . ' max_date=' . ($maxDate ?? 'null')); return [$count, $maxDate]; } @@ -76,9 +87,9 @@ private function fetchPage(PostsApi $api, int $page, string $from, string $to): outcomes: 'all', ); } catch (ApiException $e) { - Log::error("TN sync: posts API failed on page {$page}", [ + Log::error('TN sync: posts API failed on page ' . $page, [ 'status' => $e->getCode(), - 'error' => $e->getMessage(), + 'error' => $e->getMessage(), ]); return [null, 0]; } @@ -94,7 +105,7 @@ private function fetchPageFromFixture(int $page): array $fixtureFile = base_path("tests/fixtures/tn_sync/posts_page_{$page}.json"); if (!file_exists($fixtureFile)) { - Log::info("TN-SYNC-TRACE [POSTS-PAGE] missing fixture file={$fixtureFile}"); + Log::info('TN-SYNC-TRACE [POSTS-PAGE] missing fixture file=' . $fixtureFile); return [[], 0]; } @@ -108,22 +119,52 @@ private function fetchPageFromFixture(int $page): array private function processPost(mixed $post, ?string $maxDate): ?string { - $date = is_array($post) ? ($post['date'] ?? null) : $post->getDate()?->format('Y-m-d\TH:i:s\Z'); - $postId = is_array($post) ? ($post['post_id'] ?? '') : $post->getPostId(); - $type = is_array($post) ? ($post['type'] ?? '') : $post->getType(); - $groupId = is_array($post) ? ($post['group_id'] ?? '') : $post->getGroupId(); - $title = is_array($post) ? ($post['title'] ?? '') : $post->getTitle(); + $date = is_array($post) ? ($post['date'] ?? null) : $post->getDate()?->format('Y-m-d\TH:i:s\Z'); + $postId = is_array($post) ? ($post['post_id'] ?? '') : $post->getPostId(); + $type = is_array($post) ? ($post['type'] ?? '') : $post->getType(); + $groupId = is_array($post) ? ($post['group_id'] ?? '') : $post->getGroupId(); + $title = is_array($post) ? ($post['title'] ?? '') : $post->getTitle(); if ($date && (!$maxDate || $date > $maxDate)) { $maxDate = $date; } - // TODO: ingest post into the database. - Log::info("TN-SYNC-TRACE [POST] post_id={$postId} type={$type} group_id={$groupId} date={$date} title=" . substr((string) $title, 0, 60)); + Log::info('TN-SYNC-TRACE [POST] post_id=' . $postId . ' type=' . $type . ' group_id=' . $groupId . ' date=' . $date . ' title=' . substr((string) $title, 0, 60)); + + // Resolve the Freegle group by nameshort — TN uses the Freegle group nameshort + // as the group_id in its API responses, matching how the email path resolves + // groups via IncomingMailService::findGroup($email->targetGroupName). + $group = $this->findGroup((string) $groupId); + if ($group === null) { + Log::info('TN-SYNC-TRACE [POST-SKIP] reason=unknown-group group_id=' . $groupId . ' post_id=' . $postId); + return $maxDate; + } + + try { + $result = $this->ingestionService->ingest($post, $group); + Log::info('TN-SYNC-TRACE [POST-RESULT] post_id=' . $postId . ' result=' . $result); + } catch (\Throwable $e) { + Log::error('TN sync: post ingestion failed', [ + 'post_id' => $postId, + 'error' => $e->getMessage(), + ]); + } return $maxDate; } + /** + * Mirrors IncomingMailService::findGroup() + */ + private function findGroup(string $nameshort): ?Group + { + if (empty($nameshort)) { + return null; + } + + return Group::where('nameshort', $nameshort)->first(); + } + private function buildApiClient(): PostsApi { $config = Configuration::getDefaultConfiguration() diff --git a/iznik-batch/tests/fixtures/tn_sync/posts_page_1.json b/iznik-batch/tests/fixtures/tn_sync/posts_page_1.json new file mode 100644 index 0000000000..8e2ddf15bd --- /dev/null +++ b/iznik-batch/tests/fixtures/tn_sync/posts_page_1.json @@ -0,0 +1,46 @@ +{ + "num_pages": 1, + "posts": [ + { + "post_id": "tn-test-001", + "group_id": "8444", + "user_id": null, + "title": "Old wooden bookshelf (Edinburgh)", + "content": "Good condition wooden bookshelf, 180cm tall, free to a good home. Must be collected.", + "date": "2026-07-07T12:00:00Z", + "type": "offer", + "outcome": null, + "latitude": 55.9533, + "longitude": -3.1883, + "footer": null, + "photos": [ + { + "url": "https://img.trashnothing.com/photos/test-001-large.jpg", + "images": [ + { "url": "https://img.trashnothing.com/photos/test-001-large.jpg" } + ] + } + ], + "expiration": null, + "reselling": false, + "url": "https://trashnothing.com/post/tn-test-001" + }, + { + "post_id": "tn-test-002", + "group_id": "8444", + "user_id": null, + "title": "Dining chairs x4 (Edinburgh)", + "content": "Four solid wood dining chairs, slight scratches on two. Free, collect from Leith.", + "date": "2026-07-07T14:30:00Z", + "type": "offer", + "outcome": null, + "latitude": 55.9743, + "longitude": -3.1736, + "footer": null, + "photos": [], + "expiration": null, + "reselling": false, + "url": "https://trashnothing.com/post/tn-test-002" + } + ] +} diff --git a/plans/tn-api-post-ingestion.md b/plans/tn-api-post-ingestion.md index cccd1dca2c..9bbb1c03cc 100644 --- a/plans/tn-api-post-ingestion.md +++ b/plans/tn-api-post-ingestion.md @@ -22,19 +22,21 @@ TNSyncCommand (orchestrator) ## File layout -- `iznik-batch/app/Console/Commands/TrashNothing/TNSyncCommand.php` — slim orchestrator (~150 lines) +- `iznik-batch/app/Console/Commands/TrashNothing/TNSyncCommand.php` — slim orchestrator (~150 lines) ✅ - `iznik-batch/app/Services/TrashNothing/TNApiClient.php` - `iznik-batch/app/Services/TrashNothing/Syncers/RatingsSyncer.php` - `iznik-batch/app/Services/TrashNothing/Syncers/UserChangesSyncer.php` -- `iznik-batch/app/Services/TrashNothing/Syncers/PostsSyncer.php` +- `iznik-batch/app/Services/TrashNothing/Sync/PostSyncer.php` — paging + group map resolution ✅ - `iznik-batch/app/Services/TrashNothing/Syncers/ChatMessagesSyncer.php` - `iznik-batch/app/Services/TrashNothing/Syncers/DuplicateUserMerger.php` -- `iznik-batch/app/Services/TrashNothing/Ingestion/GroupPostIngestionService.php` +- `iznik-batch/app/Services/TrashNothing/Ingestion/GroupPostIngestionService.php` ✅ - `iznik-batch/app/Services/TrashNothing/Ingestion/ChatMessageIngestionService.php` -- `iznik-batch/app/Services/TrashNothing/Ingestion/TNPayloadToRfc822.php` +- `iznik-batch/app/Services/TrashNothing/Ingestion/TNPayloadToRfc822.php` — RFC822 synthesis inlined into GroupPostIngestionService for now - `iznik-batch/app/Services/TrashNothing/Dto/TNPostPayload.php` - `iznik-batch/app/Services/TrashNothing/Dto/TNChatMessagePayload.php` - `iznik-batch/app/Services/TrashNothing/Dto/SyncResult.php` +- `iznik-batch/tests/fixtures/tn_sync/posts_page_1.json` — local-testing fixture ✅ +- `iznik-batch/config/freegle.php` — `trashnothing.group_map` (TN group_id → nameshort) ✅ ## Key design decisions From e5f6e01ac80e43df758062ada390e77d63be016f Mon Sep 17 00:00:00 2001 From: fnnbrr Date: Wed, 8 Jul 2026 16:39:18 -0400 Subject: [PATCH 8/8] Added feature flag for TN API message ingestion + test for GroupPostIngestionService --- .../Commands/TrashNothing/TNSyncCommand.php | 15 +- .../Ingestion/GroupPostIngestionService.php | 10 +- iznik-batch/config/freegle.php | 3 + .../GroupPostIngestionServiceTest.php | 272 ++++++++++++++++++ plans/tn-api-post-ingestion.md | 26 +- 5 files changed, 305 insertions(+), 21 deletions(-) create mode 100644 iznik-batch/tests/Unit/Services/TrashNothing/GroupPostIngestionServiceTest.php diff --git a/iznik-batch/app/Console/Commands/TrashNothing/TNSyncCommand.php b/iznik-batch/app/Console/Commands/TrashNothing/TNSyncCommand.php index dc597fb891..0cc7ec9154 100644 --- a/iznik-batch/app/Console/Commands/TrashNothing/TNSyncCommand.php +++ b/iznik-batch/app/Console/Commands/TrashNothing/TNSyncCommand.php @@ -105,11 +105,16 @@ public function handle(): int // Merge duplicate TN users. $duplicatesMerged = $this->mergeDuplicateTNUsers(); - // Sync posts. - $postSyncer = new PostSyncer($this->dryRun, $this->localTesting, $this->apiKey, $this->apiBaseUrl, $this->loki); - [$postsProcessed, $postsMaxDate] = $postSyncer->sync($from, $to); - if ($postsMaxDate && (!$maxChangeDate || $postsMaxDate > $maxChangeDate)) { - $maxChangeDate = $postsMaxDate; + // Sync posts (API-based path, off by default — flip FREEGLE_TN_INGEST_POSTS_VIA_API=true to enable). + $postsProcessed = 0; + if (config('freegle.trashnothing.ingest_posts_via_api') || $this->localTesting) { + $postSyncer = new PostSyncer($this->dryRun, $this->localTesting, $this->apiKey, $this->apiBaseUrl, $this->loki); + [$postsProcessed, $postsMaxDate] = $postSyncer->sync($from, $to); + if ($postsMaxDate && (!$maxChangeDate || $postsMaxDate > $maxChangeDate)) { + $maxChangeDate = $postsMaxDate; + } + } else { + Log::info('TN-SYNC-TRACE [POSTS-SKIP] reason=feature-flag-off'); } // Store the max change date for next sync. diff --git a/iznik-batch/app/Services/TrashNothing/Ingestion/GroupPostIngestionService.php b/iznik-batch/app/Services/TrashNothing/Ingestion/GroupPostIngestionService.php index 54544a99e7..3ded6127ab 100644 --- a/iznik-batch/app/Services/TrashNothing/Ingestion/GroupPostIngestionService.php +++ b/iznik-batch/app/Services/TrashNothing/Ingestion/GroupPostIngestionService.php @@ -53,7 +53,6 @@ public function ingest(mixed $post, Group $group): string $tnType = strtolower((string) $this->getField($post, 'type', 'getType')); $photos = $this->getField($post, 'photos', 'getPhotos') ?? []; - $dateStr = $date instanceof \DateTime ? $date->format('Y-m-d\TH:i:s\Z') : (string) $date; $subject = strtoupper($tnType) . ': ' . $title; // Idempotency: skip if this post was already ingested for this group. @@ -129,7 +128,7 @@ public function ingest(mixed $post, Group $group): string } // Create the message record. - $messageId = $this->createMessage($post, $user, $group, $subject, $content, $lat, $lng, $date, $postId, $photos); + $messageId = $this->createMessage($user, $group, $subject, $content, $lat, $lng, $date, $postId, $photos); if ($messageId === null) { return 'skipped'; @@ -170,7 +169,6 @@ public function ingest(mixed $post, Group $group): string } private function createMessage( - mixed $post, User $user, Group $group, string $subject, @@ -221,8 +219,8 @@ private function createMessage( $msgData = [ 'date' => $date instanceof \DateTime ? $date->format('Y-m-d H:i:s') : now(), - 'source' => 'TN-API', - 'sourceheader' => 'TN-API', + 'source' => Message::SOURCE_EMAIL, + 'sourceheader' => Message::SOURCE_EMAIL, 'message' => $rfc822, 'fromuser' => $user->id, 'envelopefrom' => null, @@ -291,7 +289,7 @@ private function createMessage( if (!$this->dryRun) { DB::table('messages_history')->insert([ 'groupid' => $group->id, - 'source' => 'TN-API', + 'source' => Message::SOURCE_EMAIL, 'fromuser' => $user->id, 'envelopefrom' => null, 'envelopeto' => $groupEmail, diff --git a/iznik-batch/config/freegle.php b/iznik-batch/config/freegle.php index 0d9b006daa..d4889d5854 100644 --- a/iznik-batch/config/freegle.php +++ b/iznik-batch/config/freegle.php @@ -119,6 +119,9 @@ 'api_key' => env('FREEGLE_TN_API_KEY', ''), 'api_base_url' => env('FREEGLE_TN_API_BASE_URL', 'https://trashnothing.com/fd/api'), 'sync_date_file' => env('FREEGLE_TN_SYNC_DATE_FILE', '/etc/tn_sync_last_date.txt'), + // Enable the API-based post ingestion path. Default false (disabled) so the email + // path stays authoritative until parity is confirmed. Flip to true to activate. + 'ingest_posts_via_api' => env('FREEGLE_TN_INGEST_POSTS_VIA_API', false), ], // Discourse forum REST API (V1 discourse_not_signed_up.php). diff --git a/iznik-batch/tests/Unit/Services/TrashNothing/GroupPostIngestionServiceTest.php b/iznik-batch/tests/Unit/Services/TrashNothing/GroupPostIngestionServiceTest.php new file mode 100644 index 0000000000..3003eff6d7 --- /dev/null +++ b/iznik-batch/tests/Unit/Services/TrashNothing/GroupPostIngestionServiceTest.php @@ -0,0 +1,272 @@ +loki = app(LokiService::class); + $this->itemService = app(ItemService::class); + } + + private function makeService(bool $dryRun = true): GroupPostIngestionService + { + return new GroupPostIngestionService( + dryRun: $dryRun, + loki: $this->loki, + itemService: $this->itemService, + ); + } + + private function createTestLocation(): int + { + return (int) DB::table('locations')->insertGetId([ + 'name' => 'TestLocation_' . uniqid(), + 'type' => 'Postcode', + 'lat' => 55.9533, + 'lng' => -3.1883, + ]); + } + + private function makePost(array $overrides = []): array + { + return array_merge([ + 'post_id' => 'tn-unit-test-' . uniqid(), + 'group_id' => 'TestGroup', + 'user_id' => null, + 'title' => 'Old wooden bookshelf', + 'content' => 'Good condition, free to collect.', + 'date' => '2026-07-07T12:00:00Z', + 'type' => 'offer', + 'outcome' => null, + 'latitude' => null, + 'longitude' => null, + 'photos' => [], + ], $overrides); + } + + // ------------------------------------------------------------------------- + // Skip cases + // ------------------------------------------------------------------------- + + public function test_skips_when_user_id_is_null(): void + { + $group = $this->createTestGroup(); + $post = $this->makePost(['user_id' => null]); + + $result = $this->makeService()->ingest($post, $group); + + $this->assertSame('skipped', $result); + } + + public function test_skips_when_user_not_found(): void + { + $group = $this->createTestGroup(); + $post = $this->makePost(['user_id' => 999999999]); + + $result = $this->makeService()->ingest($post, $group); + + $this->assertSame('skipped', $result); + } + + public function test_skips_when_user_not_a_member(): void + { + $user = $this->createTestUser(); + $group = $this->createTestGroup(); + // No membership created. + $post = $this->makePost(['user_id' => $user->id]); + + $result = $this->makeService()->ingest($post, $group); + + $this->assertSame('skipped', $result); + } + + public function test_returns_duplicate_when_post_already_ingested(): void + { + $user = $this->createTestUser(); + $group = $this->createTestGroup(); + $this->createMembership($user, $group); + + // Pre-create a message row that looks like a previously-ingested post. + $postId = 'tn-dup-' . uniqid(); + $message = Message::create([ + 'type' => Message::TYPE_OFFER, + 'fromuser' => $user->id, + 'subject' => 'OFFER: Already ingested', + 'textbody' => 'body', + 'source' => 'TN-API', + 'tnpostid' => $postId, + 'date' => now(), + ]); + MessageGroup::create([ + 'msgid' => $message->id, + 'groupid' => $group->id, + 'collection' => MessageGroup::COLLECTION_APPROVED, + 'arrival' => now(), + ]); + + $post = $this->makePost(['post_id' => $postId, 'user_id' => $user->id]); + $result = $this->makeService()->ingest($post, $group); + + $this->assertSame('duplicate', $result); + } + + // ------------------------------------------------------------------------- + // Dry-run: no DB writes, correct log output + // ------------------------------------------------------------------------- + + public function test_dry_run_returns_pending_for_unmapped_user(): void + { + $user = $this->createTestUser(); // lastlocation defaults to null + $group = $this->createTestGroup(); + $this->createMembership($user, $group, ['ourPostingStatus' => 'DEFAULT']); + + $post = $this->makePost(['user_id' => $user->id]); + $result = $this->makeService(dryRun: true)->ingest($post, $group); + + $this->assertSame('pending', $result); + } + + public function test_dry_run_emits_write_trace_log_and_makes_no_db_writes(): void + { + $locationId = $this->createTestLocation(); + $user = $this->createTestUser(['lastlocation' => $locationId]); + $group = $this->createTestGroup(); + $this->createMembership($user, $group, ['ourPostingStatus' => 'DEFAULT']); + + $logLines = []; + Log::listen(function ($message) use (&$logLines) { + if (str_contains((string) $message->message, 'TN-SYNC-TRACE [WRITE]')) { + $logLines[] = (string) $message->message; + } + }); + + $post = $this->makePost(['user_id' => $user->id]); + $result = $this->makeService(dryRun: true)->ingest($post, $group); + + // In dry-run the routing result is still computed correctly. + $this->assertSame('approved', $result); + + // At least one WRITE trace line must have been emitted. + $this->assertNotEmpty($logLines, 'Expected TN-SYNC-TRACE [WRITE] log lines in dry-run'); + + // No messages row should have been created in the DB. + $msgCount = DB::table('messages')->where('fromuser', $user->id)->count(); + $this->assertSame(0, $msgCount, 'Dry-run must not write to messages table'); + } + + // ------------------------------------------------------------------------- + // Live writes (dryRun = false) + // ------------------------------------------------------------------------- + + public function test_live_creates_message_and_messages_groups_rows(): void + { + $locationId = $this->createTestLocation(); + $user = $this->createTestUser(['lastlocation' => $locationId]); + $group = $this->createTestGroup(); + $this->createMembership($user, $group, ['ourPostingStatus' => 'DEFAULT']); + + $postId = 'tn-live-' . uniqid(); + $post = $this->makePost(['post_id' => $postId, 'user_id' => $user->id]); + $result = $this->makeService(dryRun: false)->ingest($post, $group); + + $this->assertSame('approved', $result); + + $message = Message::where('tnpostid', $postId)->first(); + $this->assertNotNull($message, 'Expected a messages row with tnpostid=' . $postId); + $this->assertSame($user->id, $message->fromuser); + $this->assertSame(Message::SOURCE_EMAIL, $message->source); + $this->assertSame(Message::TYPE_OFFER, $message->type); + + $mg = MessageGroup::where('msgid', $message->id)->where('groupid', $group->id)->first(); + $this->assertNotNull($mg, 'Expected a messages_groups row'); + $this->assertSame(MessageGroup::COLLECTION_APPROVED, $mg->collection); + } + + public function test_live_creates_pending_message_when_group_is_moderated(): void + { + $locationId = $this->createTestLocation(); + $user = $this->createTestUser(['lastlocation' => $locationId]); + $group = $this->createTestGroup(['settings' => json_encode(['moderated' => true])]); + $this->createMembership($user, $group, ['ourPostingStatus' => 'DEFAULT']); + + $postId = 'tn-live-mod-' . uniqid(); + $post = $this->makePost(['post_id' => $postId, 'user_id' => $user->id]); + $result = $this->makeService(dryRun: false)->ingest($post, $group); + + $this->assertSame('pending', $result); + + $message = Message::where('tnpostid', $postId)->first(); + $this->assertNotNull($message); + + $mg = MessageGroup::where('msgid', $message->id)->where('groupid', $group->id)->first(); + $this->assertNotNull($mg); + $this->assertSame(MessageGroup::COLLECTION_PENDING, $mg->collection); + } + + public function test_live_is_idempotent_on_second_ingest(): void + { + $locationId = $this->createTestLocation(); + $user = $this->createTestUser(['lastlocation' => $locationId]); + $group = $this->createTestGroup(); + $this->createMembership($user, $group, ['ourPostingStatus' => 'DEFAULT']); + + $postId = 'tn-idem-' . uniqid(); + $post = $this->makePost(['post_id' => $postId, 'user_id' => $user->id]); + $svc = $this->makeService(dryRun: false); + + $first = $svc->ingest($post, $group); + $second = $svc->ingest($post, $group); + + $this->assertSame('approved', $first); + $this->assertSame('duplicate', $second); + + $count = Message::where('tnpostid', $postId)->count(); + $this->assertSame(1, $count, 'Second ingest must not create a second messages row'); + } + + public function test_live_synthesizes_rfc822_blob_in_messages_message(): void + { + $locationId = $this->createTestLocation(); + $user = $this->createTestUser(['lastlocation' => $locationId]); + $group = $this->createTestGroup(); + $this->createMembership($user, $group, ['ourPostingStatus' => 'DEFAULT']); + + $postId = 'tn-rfc-' . uniqid(); + $post = $this->makePost([ + 'post_id' => $postId, + 'user_id' => $user->id, + 'title' => 'Bicycle', + 'content' => 'Blue bike, collect from porch.', + ]); + + $this->makeService(dryRun: false)->ingest($post, $group); + + $message = Message::where('tnpostid', $postId)->first(); + $this->assertNotNull($message); + $this->assertNotEmpty($message->message, 'messages.message (RFC822 blob) must not be empty'); + $this->assertStringContainsString('X-Trashnothing-Post-Id: ' . $postId, $message->message); + $this->assertStringContainsString('OFFER: Bicycle', $message->message); + } +} diff --git a/plans/tn-api-post-ingestion.md b/plans/tn-api-post-ingestion.md index 9bbb1c03cc..7eb087eb7f 100644 --- a/plans/tn-api-post-ingestion.md +++ b/plans/tn-api-post-ingestion.md @@ -22,11 +22,11 @@ TNSyncCommand (orchestrator) ## File layout -- `iznik-batch/app/Console/Commands/TrashNothing/TNSyncCommand.php` — slim orchestrator (~150 lines) ✅ +- `iznik-batch/app/Console/Commands/TrashNothing/TNSyncCommand.php` — slim orchestrator ✅ - `iznik-batch/app/Services/TrashNothing/TNApiClient.php` - `iznik-batch/app/Services/TrashNothing/Syncers/RatingsSyncer.php` - `iznik-batch/app/Services/TrashNothing/Syncers/UserChangesSyncer.php` -- `iznik-batch/app/Services/TrashNothing/Sync/PostSyncer.php` — paging + group map resolution ✅ +- `iznik-batch/app/Services/TrashNothing/Sync/PostSyncer.php` — paging + group lookup ✅ - `iznik-batch/app/Services/TrashNothing/Syncers/ChatMessagesSyncer.php` - `iznik-batch/app/Services/TrashNothing/Syncers/DuplicateUserMerger.php` - `iznik-batch/app/Services/TrashNothing/Ingestion/GroupPostIngestionService.php` ✅ @@ -36,7 +36,8 @@ TNSyncCommand (orchestrator) - `iznik-batch/app/Services/TrashNothing/Dto/TNChatMessagePayload.php` - `iznik-batch/app/Services/TrashNothing/Dto/SyncResult.php` - `iznik-batch/tests/fixtures/tn_sync/posts_page_1.json` — local-testing fixture ✅ -- `iznik-batch/config/freegle.php` — `trashnothing.group_map` (TN group_id → nameshort) ✅ +- `iznik-batch/tests/Unit/Services/TrashNothing/GroupPostIngestionServiceTest.php` ✅ +- `iznik-batch/config/freegle.php` — `trashnothing.ingest_posts_via_api` feature flag ✅ ## Key design decisions @@ -112,13 +113,15 @@ Email path emits structured logs at every routing decision (`routing_reason`, `u - Fixture files at `tests/fixtures/tn_sync/posts_page_*.json` and `chat_messages_page_*.json` — schema decided before generation. - Trace log format: machine-parseable JSON (`TRACE [WRITE] {"table":...,"op":...,"set":{...}}`). Possibly emit both JSON (for diff tool) and existing `key=value` style (for humans) — open item. -### K. Feature flag / rollout -- `config('freegle.trashnothing.ingest_posts_via_api')` (default false). When false, `PostsSyncer` and `ChatMessagesSyncer` skipped entirely. +### K. Feature flag / rollout ✅ +- `config('freegle.trashnothing.ingest_posts_via_api')` (default false) added to `config/freegle.php`. +- `TNSyncCommand` skips `PostSyncer` unless flag is true OR `--local-testing` is set; emits `TN-SYNC-TRACE [POSTS-SKIP] reason=feature-flag-off` when skipped. - Separate flag to disable email path once parity proven — flipped much later. Both flags on = double-write (needs idempotency from B). -### L. Test strategy -- Unit-test each new service with fixture payloads; snapshot the rows that would be written. -- Parity test: feed a representative TN email through `IncomingMailService` and a matching TN API payload through `PostsSyncer`; assert resulting `messages` / `messages_groups` / `logs` rows match (modulo source field and synthetic message-id). +### L. Test strategy ✅ (posts) +- `GroupPostIngestionServiceTest` covers: null user skip, unknown user skip, non-member skip, duplicate detection (idempotency), dry-run trace log + no DB writes, pending routing (unmapped user + moderated group), live approved creation, live pending creation, RFC822 blob content. +- `messages.source` uses `Message::SOURCE_EMAIL` to match the email path (no new enum value or migration needed). +- Parity test (email vs API path producing same rows) — not yet written; deferred until chat path is also done. - Existing `IncomingMailServiceTest` suite stays green untouched. ### M. NOT in scope @@ -133,5 +136,8 @@ Email path emits structured logs at every routing decision (`routing_reason`, `u 3. **Spam check on API path** — skip entirely (TN trusted), or run it and log when it would have flagged? 4. **Worry-words on API path** — apply, or skip because TN moderates on their end? 5. **Missing user handling** — when `PostsSyncer` sees an `fd_user_id` that doesn't exist locally yet (race with `UserChangesSyncer`), what's the desired behavior? Note: all-or-nothing checkpointing means failing the sync blocks ratings progress too. -6. **Group lookup** — does the TN API give `nameshort`, `groupid`, or something else? -7. **Duplicate detection in dry-run** — confirm trace lines should carry `would_be_duplicate: true` when a row with the same `tnpostid` already exists. + +## Resolved decisions + +6. **Group lookup** — TN uses the Freegle group `nameshort` as `group_id` in API responses (confirmed from `iznik-server/http/api/group.php`). `PostSyncer::findGroup()` mirrors `IncomingMailService::findGroup()`: `Group::where('nameshort', $nameshort)->first()`. No config map. +7. **Duplicate detection in dry-run** — trace lines carry `would_be_duplicate=true` when a row with the same `tnpostid` already exists. ✅