4 Commits

Author SHA1 Message Date
Jonathan Martz
b0a0cf6f1f continue on collection create logic 2025-01-27 20:09:15 +01:00
Jonathan Martz
d90cda9613 remove php docs from collection, add methods for token url collection 2025-01-26 22:50:10 +01:00
Jonathan Martz
0d7255d77e start with create collection item test 2025-01-26 22:46:57 +01:00
Jonathan Martz
40db76d3ed refactoring code, add doRequest via httpClient 2025-01-26 21:54:56 +01:00
25 changed files with 1329 additions and 612 deletions

View File

@@ -8,17 +8,23 @@
}
],
"autoload": {
"classmap": [
"src/Client.php",
"src/Settings.php",
"src/Collection.php"
],
"psr-4": {
"PocketBase\\": "src/",
"PocketBase\\ViewModel\\": "src/viewModel"
"Pb\\": "src/",
"Pb\\Exception\\": "src/exception"
}
},
"require": {
"php": "^8.3|^8.4",
"ext-curl": "*"
"php": "^8.1|^8.2",
"ext-curl": "*",
"guzzlehttp/guzzle": "^7.9"
},
"require-dev": {
"tomasvotruba/phpunit-json-result-printer": "^0.2.1",
"phpunit/phpunit": "^11.5"
"phpunit/phpunit": "^11.5",
"tomasvotruba/phpunit-json-result-printer": "^0.2.1"
}
}

617
composer.lock generated
View File

@@ -4,8 +4,605 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "a3032883f5e5af1996fb350351fc84ac",
"packages": [],
"content-hash": "31d1044e8ec00497f8c8aba87b9118b1",
"packages": [
{
"name": "guzzlehttp/guzzle",
"version": "7.9.2",
"source": {
"type": "git",
"url": "https://github.com/guzzle/guzzle.git",
"reference": "d281ed313b989f213357e3be1a179f02196ac99b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/d281ed313b989f213357e3be1a179f02196ac99b",
"reference": "d281ed313b989f213357e3be1a179f02196ac99b",
"shasum": ""
},
"require": {
"ext-json": "*",
"guzzlehttp/promises": "^1.5.3 || ^2.0.3",
"guzzlehttp/psr7": "^2.7.0",
"php": "^7.2.5 || ^8.0",
"psr/http-client": "^1.0",
"symfony/deprecation-contracts": "^2.2 || ^3.0"
},
"provide": {
"psr/http-client-implementation": "1.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"ext-curl": "*",
"guzzle/client-integration-tests": "3.0.2",
"php-http/message-factory": "^1.1",
"phpunit/phpunit": "^8.5.39 || ^9.6.20",
"psr/log": "^1.1 || ^2.0 || ^3.0"
},
"suggest": {
"ext-curl": "Required for CURL handler support",
"ext-intl": "Required for Internationalized Domain Name (IDN) support",
"psr/log": "Required for using the Log middleware"
},
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
}
},
"autoload": {
"files": [
"src/functions_include.php"
],
"psr-4": {
"GuzzleHttp\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
},
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
},
{
"name": "Jeremy Lindblom",
"email": "jeremeamia@gmail.com",
"homepage": "https://github.com/jeremeamia"
},
{
"name": "George Mponos",
"email": "gmponos@gmail.com",
"homepage": "https://github.com/gmponos"
},
{
"name": "Tobias Nyholm",
"email": "tobias.nyholm@gmail.com",
"homepage": "https://github.com/Nyholm"
},
{
"name": "Márk Sági-Kazár",
"email": "mark.sagikazar@gmail.com",
"homepage": "https://github.com/sagikazarmark"
},
{
"name": "Tobias Schultze",
"email": "webmaster@tubo-world.de",
"homepage": "https://github.com/Tobion"
}
],
"description": "Guzzle is a PHP HTTP client library",
"keywords": [
"client",
"curl",
"framework",
"http",
"http client",
"psr-18",
"psr-7",
"rest",
"web service"
],
"support": {
"issues": "https://github.com/guzzle/guzzle/issues",
"source": "https://github.com/guzzle/guzzle/tree/7.9.2"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://github.com/Nyholm",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle",
"type": "tidelift"
}
],
"time": "2024-07-24T11:22:20+00:00"
},
{
"name": "guzzlehttp/promises",
"version": "2.0.4",
"source": {
"type": "git",
"url": "https://github.com/guzzle/promises.git",
"reference": "f9c436286ab2892c7db7be8c8da4ef61ccf7b455"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/promises/zipball/f9c436286ab2892c7db7be8c8da4ef61ccf7b455",
"reference": "f9c436286ab2892c7db7be8c8da4ef61ccf7b455",
"shasum": ""
},
"require": {
"php": "^7.2.5 || ^8.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"phpunit/phpunit": "^8.5.39 || ^9.6.20"
},
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Promise\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
},
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
},
{
"name": "Tobias Nyholm",
"email": "tobias.nyholm@gmail.com",
"homepage": "https://github.com/Nyholm"
},
{
"name": "Tobias Schultze",
"email": "webmaster@tubo-world.de",
"homepage": "https://github.com/Tobion"
}
],
"description": "Guzzle promises library",
"keywords": [
"promise"
],
"support": {
"issues": "https://github.com/guzzle/promises/issues",
"source": "https://github.com/guzzle/promises/tree/2.0.4"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://github.com/Nyholm",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises",
"type": "tidelift"
}
],
"time": "2024-10-17T10:06:22+00:00"
},
{
"name": "guzzlehttp/psr7",
"version": "2.7.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/psr7.git",
"reference": "a70f5c95fb43bc83f07c9c948baa0dc1829bf201"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/psr7/zipball/a70f5c95fb43bc83f07c9c948baa0dc1829bf201",
"reference": "a70f5c95fb43bc83f07c9c948baa0dc1829bf201",
"shasum": ""
},
"require": {
"php": "^7.2.5 || ^8.0",
"psr/http-factory": "^1.0",
"psr/http-message": "^1.1 || ^2.0",
"ralouphie/getallheaders": "^3.0"
},
"provide": {
"psr/http-factory-implementation": "1.0",
"psr/http-message-implementation": "1.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.2",
"http-interop/http-factory-tests": "0.9.0",
"phpunit/phpunit": "^8.5.39 || ^9.6.20"
},
"suggest": {
"laminas/laminas-httphandlerrunner": "Emit PSR-7 responses"
},
"type": "library",
"extra": {
"bamarni-bin": {
"bin-links": true,
"forward-command": false
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Psr7\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Graham Campbell",
"email": "hello@gjcampbell.co.uk",
"homepage": "https://github.com/GrahamCampbell"
},
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
},
{
"name": "George Mponos",
"email": "gmponos@gmail.com",
"homepage": "https://github.com/gmponos"
},
{
"name": "Tobias Nyholm",
"email": "tobias.nyholm@gmail.com",
"homepage": "https://github.com/Nyholm"
},
{
"name": "Márk Sági-Kazár",
"email": "mark.sagikazar@gmail.com",
"homepage": "https://github.com/sagikazarmark"
},
{
"name": "Tobias Schultze",
"email": "webmaster@tubo-world.de",
"homepage": "https://github.com/Tobion"
},
{
"name": "Márk Sági-Kazár",
"email": "mark.sagikazar@gmail.com",
"homepage": "https://sagikazarmark.hu"
}
],
"description": "PSR-7 message implementation that also provides common utility methods",
"keywords": [
"http",
"message",
"psr-7",
"request",
"response",
"stream",
"uri",
"url"
],
"support": {
"issues": "https://github.com/guzzle/psr7/issues",
"source": "https://github.com/guzzle/psr7/tree/2.7.0"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
"type": "github"
},
{
"url": "https://github.com/Nyholm",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7",
"type": "tidelift"
}
],
"time": "2024-07-18T11:15:46+00:00"
},
{
"name": "psr/http-client",
"version": "1.0.3",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-client.git",
"reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90",
"reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90",
"shasum": ""
},
"require": {
"php": "^7.0 || ^8.0",
"psr/http-message": "^1.0 || ^2.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Client\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for HTTP clients",
"homepage": "https://github.com/php-fig/http-client",
"keywords": [
"http",
"http-client",
"psr",
"psr-18"
],
"support": {
"source": "https://github.com/php-fig/http-client"
},
"time": "2023-09-23T14:17:50+00:00"
},
{
"name": "psr/http-factory",
"version": "1.1.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-factory.git",
"reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
"reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a",
"shasum": ""
},
"require": {
"php": ">=7.1",
"psr/http-message": "^1.0 || ^2.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "PSR-17: Common interfaces for PSR-7 HTTP message factories",
"keywords": [
"factory",
"http",
"message",
"psr",
"psr-17",
"psr-7",
"request",
"response"
],
"support": {
"source": "https://github.com/php-fig/http-factory"
},
"time": "2024-04-15T12:06:14+00:00"
},
{
"name": "psr/http-message",
"version": "2.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-message.git",
"reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71",
"reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71",
"shasum": ""
},
"require": {
"php": "^7.2 || ^8.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for HTTP messages",
"homepage": "https://github.com/php-fig/http-message",
"keywords": [
"http",
"http-message",
"psr",
"psr-7",
"request",
"response"
],
"support": {
"source": "https://github.com/php-fig/http-message/tree/2.0"
},
"time": "2023-04-04T09:54:51+00:00"
},
{
"name": "ralouphie/getallheaders",
"version": "3.0.3",
"source": {
"type": "git",
"url": "https://github.com/ralouphie/getallheaders.git",
"reference": "120b605dfeb996808c31b6477290a714d356e822"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822",
"reference": "120b605dfeb996808c31b6477290a714d356e822",
"shasum": ""
},
"require": {
"php": ">=5.6"
},
"require-dev": {
"php-coveralls/php-coveralls": "^2.1",
"phpunit/phpunit": "^5 || ^6.5"
},
"type": "library",
"autoload": {
"files": [
"src/getallheaders.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Ralph Khattar",
"email": "ralph.khattar@gmail.com"
}
],
"description": "A polyfill for getallheaders.",
"support": {
"issues": "https://github.com/ralouphie/getallheaders/issues",
"source": "https://github.com/ralouphie/getallheaders/tree/develop"
},
"time": "2019-03-08T08:55:37+00:00"
},
{
"name": "symfony/deprecation-contracts",
"version": "v3.5.1",
"source": {
"type": "git",
"url": "https://github.com/symfony/deprecation-contracts.git",
"reference": "74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6",
"reference": "74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6",
"shasum": ""
},
"require": {
"php": ">=8.1"
},
"type": "library",
"extra": {
"thanks": {
"url": "https://github.com/symfony/contracts",
"name": "symfony/contracts"
},
"branch-alias": {
"dev-main": "3.5-dev"
}
},
"autoload": {
"files": [
"function.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "A generic function and convention to trigger deprecation notices",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/deprecation-contracts/tree/v3.5.1"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2024-09-25T14:20:29+00:00"
}
],
"packages-dev": [
{
"name": "myclabs/deep-copy",
@@ -568,16 +1165,16 @@
},
{
"name": "phpunit/phpunit",
"version": "11.5.8",
"version": "11.5.2",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "c9bd61aab12f0fc5e82ecfe621ff518a1d1f1049"
"reference": "153d0531b9f7e883c5053160cad6dd5ac28140b3"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/c9bd61aab12f0fc5e82ecfe621ff518a1d1f1049",
"reference": "c9bd61aab12f0fc5e82ecfe621ff518a1d1f1049",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/153d0531b9f7e883c5053160cad6dd5ac28140b3",
"reference": "153d0531b9f7e883c5053160cad6dd5ac28140b3",
"shasum": ""
},
"require": {
@@ -598,7 +1195,7 @@
"phpunit/php-timer": "^7.0.1",
"sebastian/cli-parser": "^3.0.2",
"sebastian/code-unit": "^3.0.2",
"sebastian/comparator": "^6.3.0",
"sebastian/comparator": "^6.2.1",
"sebastian/diff": "^6.0.2",
"sebastian/environment": "^7.2.0",
"sebastian/exporter": "^6.3.0",
@@ -649,7 +1246,7 @@
"support": {
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
"source": "https://github.com/sebastianbergmann/phpunit/tree/11.5.8"
"source": "https://github.com/sebastianbergmann/phpunit/tree/11.5.2"
},
"funding": [
{
@@ -665,7 +1262,7 @@
"type": "tidelift"
}
],
"time": "2025-02-18T06:26:59+00:00"
"time": "2024-12-21T05:51:08+00:00"
},
{
"name": "sebastian/cli-parser",
@@ -1742,7 +2339,7 @@
"prefer-stable": false,
"prefer-lowest": false,
"platform": {
"php": "^8.3|^8.4",
"php": "^8.1|^8.2",
"ext-curl": "*"
},
"platform-dev": [],

View File

@@ -1,12 +0,0 @@
services:
pocketbase_php_sdk:
image: ghcr.io/muchobien/pocketbase:latest
container_name: pocketbase_php_sdk
restart: unless-stopped
ports:
- "7090:8090"
healthcheck: # optional, recommended since v0.10.0
test: wget --no-verbose --tries=1 --spider http://localhost:8090/api/health || exit 1
interval: 5s
timeout: 5s
retries: 5

104
mailer.go Normal file
View File

@@ -0,0 +1,104 @@
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"log"
"net/smtp"
"os/exec"
"time"
)
func main() {
now := time.Now()
// Define flags
smtpPass := flag.String("password", "", "SMTP password")
sender := flag.String("sender", "", "SMTP sender")
smtpUser := flag.String("user", "", "SMTP username")
// Parse the flags
flag.Parse()
// Check if required flags are provided
if *smtpPass == "" {
log.Fatal("Error: Password is required. Use -password flag.")
}
if *smtpUser == "" {
log.Fatal("Error: SMTP username is required. Use -user flag.")
}
if *sender == "" {
log.Fatal("Error: Sender email is required. Use -sender flag.")
}
// Format the date as YYYY-MM-DD
currentDate := now.Format("01.02.2006")
recipient := "support@jonathan-martz.de"
subject := "PHPUnit - PocketBase PHP SDK - " + currentDate
smtpHost := "smtps.udag.de" // Replace with your SMTP host
smtpPort := "587" // Replace with your SMTP port
// Run PHPUnit with combined stdout and stderr
cmd := exec.Command("php", "vendor/bin/phpunit")
var output bytes.Buffer
cmd.Stdout = &output
cmd.Stderr = &output
if err := cmd.Run(); err != nil {
log.Printf("PHPUnit command failed: %v", err)
}
// Check if output is empty
if output.Len() == 0 {
log.Fatal("PHPUnit output is empty. Please check your configuration.")
}
// Parse the JSON output
var result map[string]interface{}
if err := json.Unmarshal(output.Bytes(), &result); err != nil {
log.Fatalf("Failed to parse JSON output: %v", err)
}
// Extract the 'counts' field
counts, ok := result["counts"].(map[string]interface{})
if !ok {
log.Fatal("Counts field not found in PHPUnit output.")
}
// Check if 'fails' is greater than 0
failed, ok := counts["failed"].(float64)
if !ok {
log.Fatal("'fails' field not found in counts.")
}
if failed > 0 {
// Serialize the counts field to JSON for the email body
countsJSON, err := json.MarshalIndent(counts, "", " ")
if err != nil {
log.Fatalf("Failed to serialize counts to JSON: %v", err)
}
// Prepare the email body
emailBody := fmt.Sprintf("Subject: %s\r\n\r\n%s", subject, string(countsJSON))
// Connect to the SMTP server
auth := smtp.PlainAuth("", *smtpUser, *smtpPass, smtpHost)
err = smtp.SendMail(
smtpHost+":"+smtpPort,
auth,
*sender,
[]string{recipient},
[]byte(emailBody),
)
if err != nil {
log.Fatalf("Failed to send email: %v", err)
}
log.Println("Test results sent to", recipient)
} else {
log.Println("No failures detected. No email sent.")
}
}

View File

@@ -5,6 +5,7 @@
cacheDirectory=".phpunit.cache"
executionOrder="depends,defects"
shortenArraysForExportThreshold="10"
requireCoverageMetadata="true"
beStrictAboutCoverageMetadata="true"
beStrictAboutOutputDuringTests="true"
displayDetailsOnPhpunitDeprecations="true"
@@ -16,10 +17,9 @@
<directory>tests</directory>
</testsuite>
</testsuites>
<!-- <extensions>
<extensions>
<bootstrap class="TomasVotruba\PHPUnitJsonResultPrinter\PHPUnitJsonResultPrinterExtension" />
</extensions> -->
</extensions>
<source ignoreIndirectDeprecations="true" restrictNotices="true" restrictWarnings="true">
<include>

View File

@@ -1,52 +1,34 @@
<?php
namespace PocketBase;
namespace Pb;
class Client
{
private string $url;
public string $token = '';
public ?string $baseurl = null;
public ?string $token = null;
public HttpClient $http;
public function __construct($baseurl = null)
public function __construct(string $url)
{
$this->baseurl = $baseurl ?? 'http://localhost:7090';
$this->http = new HttpClient();
$this->token = '';
$this->url = $url;
}
public function collection(string $name): Collection
public function collection(string $collection): Collection
{
return new Collection($this->baseurl, $name);
return new Collection($this->url ,$collection, $this->token);
}
public function setBaseUrl($baseurl){
$this->baseurl = $baseurl;
public function settings(): Settings
{
return new Settings($this->url, $this->token);
}
public function getBaseUrl(){
return $this->baseurl;
public function setAuthToken(string $token): void
{
$this->token = $token;
}
public function getToken(): ?string
public function getAuthToken(): string
{
return $this->token;
}
public function setToken(?string $token): void
{
$this->token = $token;
}
public function getHttp(): HttpClient
{
return $this->http;
}
public function setHttp(HttpClient $http): Client
{
$this->http = $http;
return $this;
}
}

View File

@@ -1,146 +1,196 @@
<?php
namespace PocketBase;
namespace Pb;
use PocketBase\ViewModel\CustomRecordViewModel;
use PocketBase\ViewModel\RecordListViewModel;
use PocketBase\ViewModel\RecordViewModel;
use GuzzleHttp\Exception\GuzzleException;
/**
*
*/
class Collection
{
public HttpClient $http;
private Client $client;
private string $name;
public string $path;
/**
* @var string
*/
private string $collection;
public function getPath(): string
/**
* @var string
*/
private string $url;
/**
* @var string
*/
private static string $token = '';
/**
* @param string $url
* @param string $collection
* @param string $token
*/
public function __construct(string $url,
string $collection,
string $token = ''
)
{
return $this->path;
$this->url = $url;
$this->collection = $collection;
if (!empty($token)) {
self::$token = $token;
}
}
public function setPath(string $path): Collection
public function getList(int $start = 1, int $end = 50, array $queryParams = []): array
{
$this->path = $path;
$queryParams['perPage'] = $end;
$getParams = !empty($queryParams) ? http_build_query($queryParams) : "";
$response = $this->doRequest($this->url . "/api/collections/" . $this->collection . "/records?" . $getParams, 'GET');
return json_decode($response, JSON_FORCE_OBJECT);
}
public function upload(string $recordId, string $field, string $filepath): void
{
$ch = curl_init($this->url . "/api/collections/" . $this->collection . "/records/" . $recordId);
curl_setopt_array($ch, array(
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_POSTFIELDS => array(
$field => new \CURLFile($filepath)
)
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$headers = array('Content-Type: multipart/form-data');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
}
public function authAsUser(string $email, string $password): array
{
$result = $this->doRequest($this->url . "/api/collections/users/auth-with-password", 'POST', ['identity' => $email, 'password' => $password]);
$result = json_decode($result, JSON_FORCE_OBJECT);
if (!empty($result['token'])) {
self::$token = $result['token'];
}
return $result;
}
public function getFullList(array $queryParams, int $batch = 200): array
{
$queryParams = [... $queryParams, 'perPage' => $batch];
$getParams = !empty($queryParams) ? http_build_query($queryParams) : "";
$response = $this->doRequest($this->url . "/api/collections/" . $this->collection . "/records?" . $getParams, 'GET');
return json_decode($response, JSON_FORCE_OBJECT);
}
public function getFirstListItem(string $filter, array $queryParams = []): array
{
// TODO filter
$queryParams['perPage'] = 1;
$queryParams['filter'] = $filter;
$getParams = !empty($queryParams) ? http_build_query($queryParams) : "";
$response = $this->doRequest($this->url . "/api/collections/" . $this->collection . "/records?" . $getParams, 'GET');
$data = json_decode($response, JSON_FORCE_OBJECT);
if (empty($data['items']) || count($data['items']) < 1) {
throw new exception\FirstListItemNotFoundException('First doesnt exists');
}
return $data['items'][0] ?? [];
}
public function create(array $bodyParams = [], array $queryParams = []): string
{
// TODO query params ?
return $this->doRequest($this->url . "/api/collections/" . $this->collection . "/records", 'POST', $bodyParams);
}
public function update(string $recordId, array $bodyParams = [], array $queryParams = []): void
{
// Todo bodyParams equals json, currently workaround
$this->doRequest($this->url . "/api/collections/" . $this->collection . "/records/" . $recordId, 'PATCH', $bodyParams);
}
public function delete(string $recordId, array $queryParams = []): void
{
// TODO params ?
$this->doRequest($this->url . "/api/collections/" . $this->collection . "/records/" . $recordId, 'DELETE');
}
/**
* @throws GuzzleException
*/
public function doRequest(string $url, string $method, $bodyParams = []): string
{
$tmp = $bodyParams;
$bodyParams = [];
$bodyParams['json'] = $tmp;
$bodyParams['headers']['Content-Type'] = 'application/json';
if (self::$token != '') {
$bodyParams['headers']['Authorization'] = 'Bearer ' . self::$token;
}
$client = new \GuzzleHttp\Client();
$response = $client->request($method, $url, $bodyParams);
return $response->getBody()->getContents() ?? '';
}
public function getOne(string $recordId, array $queryParams = []): array
{
// TODO params ?
$output = $this->doRequest($this->url . "/api/collections/" . $this->collection . "/records/" . $recordId, 'GET');
return json_decode($output, JSON_FORCE_OBJECT);
}
public function authAsAdmin(string $email, string $password): string
{
$bodyParams['identity'] = $email;
$bodyParams['password'] = $password;
$output = $this->doRequest($this->url . "/api/collections/_superusers/auth-with-password", 'POST', $bodyParams);
$token = json_decode($output, true)['token'];
if ($token) {
self::$token = $token;
}
return $output;
}
public static function getAuthToken(): string
{
return self::$token;
}
public static function setAuthToken(string $token): void
{
self::$token = $token;
}
public function getUrl(): string
{
return $this->url;
}
public function setUrl(string $url): Collection
{
$this->url = $url;
return $this;
}
public function __construct(string $url = null, string $name = 'users')
public function getCollection(): string
{
$this->name = $name;
$this->http = new HttpClient();
$this->client = new Client();
return $this->collection;
}
public function getFullList(int $batch, $bodyParams = [], array $queryParams = []): RecordListViewModel
public function setCollection(string $collection): Collection
{
$queryParams['limit'] = $batch;
$getParams = !empty($queryParams) ? http_build_query($queryParams) : "";
return new RecordListViewModel(
json_decode(
$this->http->doRequest(
$this->client->getBaseUrl() . $this->path . '?' . $getParams,
'GET',
$bodyParams,
$this->client->token
),
true)
);
}
public function getList(int $page, int $limit, $bodyParams = [], array $queryParams = []): RecordListViewModel
{
$getParams = !empty($queryParams) ? http_build_query($queryParams) : "";
return new RecordListViewModel(json_decode(
$this->http->doRequest(
$this->client->getBaseUrl() . $this->path . '?' . $getParams,
'GET',
$bodyParams,
$this->client->token
), true));
}
public function authAsUser(string $email, string $password): ?string
{
$getParams = !empty($queryParams) ? http_build_query($queryParams) : "";
$data = json_decode(
$this->http->doRequest(
$this->client->getBaseUrl() . '/api/collections/users/auth-with-password' . '?' . $getParams,
'POST',
[
'identity' => $email,
'password' => $password,
]
), true);
return $data['token'];
}
public function authAsAdmin(string $email, string $password): ?string
{
$getParams = !empty($queryParams) ? http_build_query($queryParams) : "";
$data = json_decode($this->http->doRequest(
$this->client->baseurl . "/api/collections/_superusers/auth-with-password" . '?' . $getParams,
'POST',
[
'identity' => $email,
'password' => $password,
]), true);
return $data['token'];
}
public function create(array $bodyParams, array $queryParams = []): CustomRecordViewModel
{
$getParams = !empty($queryParams) ? http_build_query($queryParams) : "";
return new CustomRecordViewModel(json_decode(
$this->http->doRequest(
$this->client->getBaseUrl() . $this->getPath() . '?' . $getParams,
'POST',
$bodyParams,
$this->client->token
), true) ?? []);
}
public function update($id, $bodyParams, $token = '', array $queryParams = []): RecordViewModel
{
$getParams = !empty($queryParams) ? http_build_query($queryParams) : "";
return new RecordViewModel(json_decode($this->http->doRequest(
$this->client->getBaseUrl() . '/api/collections/test/records/' . $id . '?' . $getParams
, 'PATCH', json_encode($bodyParams), $token), true));
}
public function getOne($id, $token = '', array $queryParams = []): CustomRecordViewModel
{
$getParams = !empty($queryParams) ? http_build_query($queryParams) : "";
return new CustomRecordViewModel(json_decode($this->http->doRequest(
$this->client->getBaseUrl() . '/api/collections/test/records/' . $id . '?' . $getParams#
, 'GET', [], $token), true));
}
public function delete($id, $token = '', array $queryParams = []): CustomRecordViewModel
{
$getParams = !empty($queryParams) ? http_build_query($queryParams) : "";
return new CustomRecordViewModel(json_decode($this->http->doRequest(
$this->client->getBaseUrl() . '/api/collections/test/records/' . $id . '?' . $getParams
, 'DELETE', [], $token), true));
}
public function setClient(Client $client): void
{
$this->client = $client;
}
public function getName(): string
{
return $this->name;
}
public function getAuthToken(): ?string
{
return $this->client->token;
}
public function setHttp(HttpClient $httpClient): void
{
$this->http = $httpClient;
$this->collection = $collection;
return $this;
}
}

View File

@@ -1,31 +0,0 @@
<?php
namespace PocketBase;
class HttpClient
{
public function doRequest(string $url, string $method, $bodyParams = [], ?string $token = null): string
{
$ch = curl_init();
if ($token != '') {
$headers = array(
'Content-Type:application/json',
'Authorization: ' . $token
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
if ($bodyParams) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyParams);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}

71
src/Settings.php Normal file
View File

@@ -0,0 +1,71 @@
<?php
namespace Pb;
/**
*
*/
class Settings
{
/**
* @var string
*/
private string $url;
/**
* @var string
*/
private static string $token = '';
/**
* @param string $url
* @param string $token
*/
public function __construct(string $url, string $token = '')
{
$this->url = $url;
self::$token = $token;
}
public function authAsAdmin(string $email, string $password): void
{
$bodyParams['identity'] = $email;
$bodyParams['password'] = $password;
$output = $this->doRequest($this->url . "/api/collections/_superusers/auth-with-password", 'POST', $bodyParams);
self::$token = json_decode($output, true)['token'];
}
public function doRequest(string $url, string $method, $bodyParams = []): string
{
$ch = curl_init();
if (self::$token != '') {
$headers = array(
'Content-Type:application/json',
'Authorization: ' . self::$token
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
if ($bodyParams) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyParams);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
public function getAll():array
{
return json_decode($this->doRequest($this->url . '/api/settings', 'GET', []), true);
}
public function update($bodyParam):array{
return json_decode($this->doRequest($this->url . '/api/settings', 'PATCH', json_encode($bodyParam)), true);
}
}

8
src/SuperUser.php Normal file
View File

@@ -0,0 +1,8 @@
<?php
namespace Pb;
class SuperUser
{
}

18
src/User.php Normal file
View File

@@ -0,0 +1,18 @@
<?php
namespace Pb;
use DateTime;
class User
{
public string $avatar;
public string $collectionName;
public string $collectionId;
public bool $emailVisibility;
public DateTime $created;
public string $id;
public string $name;
public DateTime $updated;
public bool $verified;
}

View File

@@ -0,0 +1,14 @@
<?php
namespace Pb\Exception;
class FirstListItemNotFoundException extends \Exception
{
/**
* @param string $string
*/
public function __construct(string $string)
{
}
}

View File

@@ -1,15 +0,0 @@
<?php
namespace PocketBase\ViewModel;
class CustomRecordViewModel extends RecordViewModel
{
public function __construct(array $data)
{
foreach ($data as $key => $item){
$this->$key = $item;
}
parent::__construct($data);
}
}

View File

@@ -1,88 +0,0 @@
<?php
namespace PocketBase\ViewModel;
class RecordListViewModel extends RecordViewModel
{
private array $items;
private int $page;
private int $perPage;
private int $totalItems;
private int $totalPages;
public function __construct(array $data)
{
if (key_exists('items', $data)) {
$this->setItems($data['items']);
}
if (key_exists('page', $data)) {
$this->setPage($data['page']);
}
if (key_exists('perPage', $data)) {
$this->setPerPage($data['perPage']);
}
if (key_exists('totalItems', $data)) {
$this->setTotalItems($data['totalItems']);
}
if (key_exists('totalPages', $data)) {
$this->setTotalPages($data['totalPages']);
}
parent::__construct($data);
}
public function setTotalItems(int $totalItems): RecordListViewModel
{
$this->totalItems = $totalItems;
return $this;
}
public function getItems(): array
{
return $this->items;
}
public function setItems(array $items): RecordListViewModel
{
$this->items = $items;
return $this;
}
public function getPage(): int
{
return $this->page;
}
public function setPage(int $page): RecordListViewModel
{
$this->page = $page;
return $this;
}
public function getPerPage(): int
{
return $this->perPage;
}
public function setPerPage(int $perPage): RecordListViewModel
{
$this->perPage = $perPage;
return $this;
}
public function getTotalItems(): int
{
return $this->totalItems;
}
public function getTotalPages(): int
{
return $this->totalPages;
}
public function setTotalPages(int $totalPages): void
{
$this->totalPages = $totalPages;
}
}

View File

@@ -1,86 +0,0 @@
<?php
namespace PocketBase\ViewModel;
class RecordViewModel
{
private string $collectionName;
private string $collectionId;
private string $created;
private string $updated;
private string $id;
public function __construct(array $data)
{
if(key_exists('id', $data)){
$this->setId($data['id']);
}
if(key_exists('updated', $data)){
$this->setUpdated($data['updated']);
}
if(key_exists('created', $data)){
$this->setCreated($data['created']);
}
if(key_exists('collectionName', $data)){
$this->setCollectionName($data['collectionName']);
}
if(key_exists('collectionId', $data)){
$this->setCollectionId($data['collectionId']);
}
}
public function getCollectionName(): string
{
return $this->collectionName;
}
public function setCollectionName(string $collectionName): RecordViewModel
{
$this->collectionName = $collectionName;
return $this;
}
public function getCollectionId(): string
{
return $this->collectionId;
}
public function setCollectionId(string $collectionId): RecordViewModel
{
$this->collectionId = $collectionId;
return $this;
}
public function getCreated(): string
{
return $this->created;
}
public function setCreated(string $created): RecordViewModel
{
$this->created = $created;
return $this;
}
public function getUpdated(): string
{
return $this->updated;
}
public function setUpdated(string $updated): RecordViewModel
{
$this->updated = $updated;
return $this;
}
public function getId(): string
{
return $this->id;
}
public function setId(string $id): RecordViewModel
{
$this->id = $id;
return $this;
}
}

View File

@@ -0,0 +1,14 @@
<?php
namespace Pb\viewModels;
use DateTime;
class CollectionItem
{
public string $collectionName;
public string $collectionId;
public DateTime $created;
public string $id;
public DateTime $updated;
}

View File

@@ -0,0 +1,12 @@
<?php
namespace Pb\viewModels;
class CollectionResponse
{
public array $items;
public int $page;
public int $perPage;
public int $totalItems;
public int $totalPages;
}

38
tests/AuthTest.php Normal file
View File

@@ -0,0 +1,38 @@
<?php
use GuzzleHttp\Exception\ClientException;
use Pb\Collection;
use PHPUnit\Framework\TestCase;
final class AuthTest extends TestCase
{
private Collection $collection;
private ?string $url;
protected function setUp(): void
{
$this->url = getenv('POCKETBASE_URL') ?: 'https://admin.pocketbase.dev';
$this->collection = new Collection($this->url, 'users');
}
public function testAuthUser(): void
{
$this->expectException(ClientException::class);
$this->collection->authAsUser('support@jonathan-martz.de', 'rockt');
}
public function testAuthSuperUser(): void
{
$this->collection = new Collection($this->url, '_superusers');
$this->expectException(ClientException::class);
$this->collection->authAsAdmin('admin@jonathan-martz.de', 'rockt');
}
public function testAuthSuperUser2(): void
{
$this->collection = new Collection($this->url, '_superusers');
$this->expectException(ClientException::class);
$this->collection->authAsAdmin('admin@jmartz.de', 'rockt123?!');
}
}

View File

@@ -1,46 +1,48 @@
<?php
use PHPUnit\Framework\MockObject\MockObject;
use Pb\Client;
use Pb\Collection;
use Pb\Settings;
use PHPUnit\Framework\TestCase;
use PocketBase\Client;
use PocketBase\Collection;
use PocketBase\HttpClient;
final class ClientTest extends TestCase
{
private Collection $collection;
private ?Client $client = null;
public ?HttpClient $http = null;
private ?string $url;
protected function setUp(): void
{
$this->url = getenv('POCKETBASE_URL') ?: 'https://admin.pocketbase.dev';
$this->collection = new Collection($this->url, 'users');
}
public function test_collection(): void
{
$this->client = new Client();
$this->collection = $this->client->collection('_superusers');
$this->assertEquals(Collection::class, get_class($this->collection));
$pb = new Client($this->url);
$actual = $pb->collection('users');
$this->assertEquals($actual, $this->collection);
}
public function test_authAsUser(): void
public function test_settings(): void
{
$this->client = new Client();
$this->collection = $this->client->collection('users');
$this->collection->setPath('/api/collections/users/auth-with-password');
$pb = new Client($this->url);
$token = $this->collection->authAsUser('admin@jonathan-martz.de', 'Password123');
$this->assertNotEmpty($token);
$actual = $pb->settings();
$this->assertEquals($actual, new Settings($this->url));
}
/**
* @throws \PHPUnit\Framework\MockObject\Exception
*/
// @sk
public function test_authAsAdmin(): void
{
$this->client = new Client();
$this->collection = $this->client->collection('_superusers');
$this->collection->setPath('/api/collections/' . $this->collection->getName() . '/auth-with-password');
public function test_setToken(){
$token = 'test123';
$token = $this->collection->authAsUser('admin@jonathan-martz.de', 'Password123');
$this->assertNotEmpty($token);
$pb = new Client($this->url);
$pb->setAuthToken($token);
$this->assertEquals($token, $pb->getAuthToken());
$this->assertEquals($token, $pb->token);
$pb->token = 'test456';
$this->assertEquals('test456', $pb->getAuthToken());
}
}

View File

@@ -0,0 +1,35 @@
<?php
use GuzzleHttp\Exception\ClientException;
use Pb\Collection;
use PHPUnit\Framework\TestCase;
class CollectionCreateTest extends TestCase
{
private string $url;
private Collection $collection;
protected function setUp(): void
{
$this->url = getenv('POCKETBASE_URL') ?: 'https://admin.pocketbase.dev';
$this->collection = new Collection($this->url, 'users');
}
public function testCreateCollectionItem(){
$this->expectException(ClientException::class);
$this->expectExceptionCode(403);
$this->collection->create(['name' => 'Hallo Welt']);
}
public function testCreateCollectionItemAuthed(){
$this->collection->authAsUser('admin@jmartz.de', 'rockt123?!');#
self::assertNotEmpty($this->collection->getAuthToken());
}
public function testCreateCollectionItemAuthedAdmin(){
$this->collection->authAsAdmin('admin@jonathan-martz.de', 'rockt123?!');
$response = $this->collection->create(['email' => 'test@jonathan-martz.de','password' => 'rockt123?!','passwordConfirm' => 'rockt123?!']);
var_dump($response);
self::assertNotEmpty($this->collection->getAuthToken());
}
}

View File

@@ -0,0 +1,35 @@
<?php
use Pb\Collection;
use Pb\Exception\FirstListItemNotFoundException;
use PHPUnit\Framework\TestCase;
final class CollectionGetFirstListItemTest extends TestCase
{
private Collection $collection;
protected function setUp(): void
{
$url = getenv('POCKETBASE_URL') ?: 'https://admin.pocketbase.dev';
$this->collection = new Collection($url, 'users');
}
/**
* @throws FirstListItemNotFoundException
*/
public function test_getOne(): void
{
$id = '6588yk36406qqv1';
$actual = $this->collection->getFirstListItem('id="'.$id.'"');
$this->assertEquals($id, $actual['id']);
$this->assertCount(9, $actual);
}
public function test_getOneWrongId(): void
{
$id = '6588yk36406qqvb';
$this->expectException(FirstListItemNotFoundException::class);
$this->collection->getFirstListItem('id="'.$id.'"');
}
}

View File

@@ -0,0 +1,28 @@
<?php
use Pb\Collection;
use PHPUnit\Framework\TestCase;
final class CollectionGetFullListTest extends TestCase
{
private string $url;
private Collection $collection;
protected function setUp(): void
{
$this->url = getenv('POCKETBASE_URL') ?: 'https://admin.pocketbase.dev';
$this->collection = new Collection($this->url, 'users');
}
public function test_getFullList_gettingArrayWithOneUser(): void
{
$actual = $this->collection->getFullList([],100);
$this->assertArrayHasKey('items', $actual, 'Key "items" does not exist in the response.');
$this->assertArrayHasKey('page', $actual, 'Key "page" does not exist in the response.');
$this->assertArrayHasKey('perPage', $actual, 'Key "perPage" does not exist in the response.');
$this->assertArrayHasKey('totalItems', $actual, 'Key "totalItems" does not exist in the response.');
$this->assertArrayHasKey('totalPages', $actual, 'Key "totalPages" does not exist in the response.');
$this->assertCount(1, $actual['items'], 'Expected no items in the response.');
}
}

View File

@@ -0,0 +1,76 @@
<?php declare(strict_types=1);
use Pb\Collection;
use PHPUnit\Framework\TestCase;
final class CollectionGetListTest extends TestCase
{
private string $url;
private Collection $collection;
protected function setUp(): void
{
$this->url = getenv('POCKETBASE_URL') ?: 'https://admin.pocketbase.dev';
$this->collection = new Collection($this->url, 'users');
}
public function test_getList_gettingArrayWithOneItem(): void
{
$actual = $this->collection->getList(1, 10);
$this->assertArrayHasKey('items', $actual, 'Key "items" does not exist in the response.');
$this->assertArrayHasKey('page', $actual, 'Key "page" does not exist in the response.');
$this->assertArrayHasKey('perPage', $actual, 'Key "perPage" does not exist in the response.');
$this->assertArrayHasKey('totalItems', $actual, 'Key "totalItems" does not exist in the response.');
$this->assertArrayHasKey('totalPages', $actual, 'Key "totalPages" does not exist in the response.');
$this->assertCount(1, $actual['items'], 'Expected no items in the response.');
}
public function test_getListWithContainsMartz(): void
{
$actual = $this->collection->getList(1, 10, ['filter'=>'name~"%Martz%"']);
$this->assertArrayHasKey('items', $actual, 'Key "items" does not exist in the response.');
$this->assertArrayHasKey('page', $actual, 'Key "page" does not exist in the response.');
$this->assertArrayHasKey('perPage', $actual, 'Key "perPage" does not exist in the response.');
$this->assertArrayHasKey('totalItems', $actual, 'Key "totalItems" does not exist in the response.');
$this->assertArrayHasKey('totalPages', $actual, 'Key "totalPages" does not exist in the response.');
$this->assertCount(1, $actual['items'], 'Expected no items in the response.');
}
public function test_getListStartsWithMartz(): void
{
$actual = $this->collection->getList(1, 10, ['filter'=>'name~"Martz%"']);
$this->assertArrayHasKey('items', $actual, 'Key "items" does not exist in the response.');
$this->assertArrayHasKey('page', $actual, 'Key "page" does not exist in the response.');
$this->assertArrayHasKey('perPage', $actual, 'Key "perPage" does not exist in the response.');
$this->assertArrayHasKey('totalItems', $actual, 'Key "totalItems" does not exist in the response.');
$this->assertArrayHasKey('totalPages', $actual, 'Key "totalPages" does not exist in the response.');
$this->assertCount(0, $actual['items'], 'Expected no items in the response.');
}
public function test_getListStartWithJonathan(): void
{
$actual = $this->collection->getList(1, 10, ['filter'=>'name~"Jonathan%"']);
$this->assertArrayHasKey('items', $actual, 'Key "items" does not exist in the response.');
$this->assertArrayHasKey('page', $actual, 'Key "page" does not exist in the response.');
$this->assertArrayHasKey('perPage', $actual, 'Key "perPage" does not exist in the response.');
$this->assertArrayHasKey('totalItems', $actual, 'Key "totalItems" does not exist in the response.');
$this->assertArrayHasKey('totalPages', $actual, 'Key "totalPages" does not exist in the response.');
$this->assertCount(1, $actual['items'], 'Expected no items in the response.');
}
public function test_getListCheckingDifferentName(): void
{
$actual = $this->collection->getList(1, 10, ['filter'=>'name~"%Sibylle%"']);
$this->assertArrayHasKey('items', $actual, 'Key "items" does not exist in the response.');
$this->assertArrayHasKey('page', $actual, 'Key "page" does not exist in the response.');
$this->assertArrayHasKey('perPage', $actual, 'Key "perPage" does not exist in the response.');
$this->assertArrayHasKey('totalItems', $actual, 'Key "totalItems" does not exist in the response.');
$this->assertArrayHasKey('totalPages', $actual, 'Key "totalPages" does not exist in the response.');
$this->assertCount(0, $actual['items'], 'Expected no items in the response.');
}
}

View File

@@ -0,0 +1,33 @@
<?php
use GuzzleHttp\Exception\ClientException;
use Pb\Collection;
use PHPUnit\Framework\TestCase;
final class CollectionGetOneTest extends TestCase
{
private string $url;
private Collection $collection;
protected function setUp(): void
{
$this->url = getenv('POCKETBASE_URL') ?: 'https://admin.pocketbase.dev';
$this->collection = new Collection($this->url, 'users');
}
public function test_getOne(): void
{
$id = '6588yk36406qqv1';
$actual = $this->collection->getOne($id);
$this->assertEquals($id, $actual['id']);
$this->assertCount(9, $actual);
}
public function test_getOneWrongId(): void
{
$id = '6588yk36406qqva';
$this->expectException(ClientException::class);
$this->collection->getOne($id);
}
}

View File

@@ -1,174 +0,0 @@
<?php
use PHPUnit\Framework\TestCase;
use PocketBase\ViewModel\CustomRecordViewModel;
use PocketBase\ViewModel\RecordListViewModel;
use PocketBase\ViewModel\RecordViewModel as RecordViewModelAlias;
use PocketBase\Client as Client;
use PocketBase\Collection as Collection;
use PocketBase\HttpClient as HttpClient;
final class CollectionTest extends TestCase
{
private Collection $collection;
private ?Client $client = null;
public ?HttpClient $http = null;
public string $name = '';
public function test_getFullList_empty()
{
$this->collection = new Collection(null, 'users');
$this->collection
->setClient(new Client('http://localhost:7090'));
$this->collection->setPath("/api/collections/" . $this->collection->getName() . "/records");
$data = $this->collection
->getFullList(10, []);
$this->assertEquals(RecordListViewModel::class, get_class($data));
$this->assertCount(0, $data->getItems());
}
public function test_getFullList_ownUser()
{
$this->collection = new Collection(null, 'users');
$token = $this->collection->authAsUser('admin@jonathan-martz.de', 'Password123');
$this->client = new Client('http://localhost:7090');
$this->client->setToken($token);
$this->collection->setPath('/api/collections/' . $this->collection->getName() . '/records');
$this->collection->setClient($this->client);
$data = $this->collection->getFullList(10, []);
$this->assertEquals(RecordListViewModel::class, get_class($data));
$this->assertCount(1, $data->getItems());
}
public function test_getFullList_ownAdmin()
{
$this->collection = new Collection(null, 'users');
$token = $this->collection->authAsAdmin('admin@jonathan-martz.de', 'Password123');
$this->client = new Client('http://localhost:7090');
$this->client->setToken($token);
$this->collection->setPath('/api/collections/' . $this->collection->getName() . '/records');
$this->collection->setClient($this->client);
$data = $this->collection->getFullList(10, []);
$this->assertEquals(RecordListViewModel::class, get_class($data));
$this->assertCount(2, $data->getItems());
}
public function test_create_record(): void
{
$this->client = new \PocketBase\Client(null);
$this->collection = $this->client->collection('users');
$this->collection->setPath('/api/collections/users/records');
$record = $this->collection->create([
'email' => 'admin@jonathan-martz.de',
'password' => 'Password123',
'passwordConfirm' => 'Password123',
]);
$this->assertEquals(CustomRecordViewModel::class, get_class($record));
}
public function test_update_record(): void
{
$this->client = new \PocketBase\Client(null);
$this->collection = $this->client->collection('users');
$token = $this->collection->authAsUser('admin@jonathan-martz.de', 'Password123');
$this->client->setToken($token);
$this->collection = $this->client->collection('test');
$this->collection->setClient($this->client);
$this->collection->setPath('/api/collections/test/records/');
try {
$record = $this->collection->update('ss05u9mnegvplds', [
'name' => 'Test123456'
], $token);
} catch (Exception $exception) {
$this->fail('Exception: ' . $exception->getMessage());
}
$this->assertEquals(RecordViewModelAlias::class, get_class($record));
}
public function test_getone_record(): void
{
$this->client = new \PocketBase\Client(null);
$this->collection = $this->client->collection('users');
$token = $this->collection->authAsUser('admin@jonathan-martz.de', 'Password123');
$this->client->setToken($token);
$this->collection = $this->client->collection('test');
$this->collection->setClient($this->client);
$this->collection->setPath('/api/collections/test/records/');
try {
$record = $this->collection->getOne('ss05u9mnegvplds', $token);
} catch (Exception $exception) {
$this->fail('Exception: ' . $exception->getMessage());
}
$this->assertEquals(CustomRecordViewModel::class, get_class($record));
}
public function test_getlist_record(): void
{
$this->client = new \PocketBase\Client(null);
$this->collection = $this->client->collection('users');
$token = $this->collection->authAsUser('admin@jonathan-martz.de', 'Password123');
$this->client->setToken($token);
$this->collection = $this->client->collection('test');
$this->collection->setClient($this->client);
$this->collection->setPath('/api/collections/users/records/');
try {
$record = $this->collection->getList(1, 10);
} catch (Exception $exception) {
$this->fail('Exception: ' . $exception->getMessage());
}
$this->assertEquals(RecordListViewModel::class, get_class($record));
}
public function test_delete_record(): void
{
$this->client = new \PocketBase\Client(null);
$this->collection = $this->client->collection('users');
$token = $this->collection->authAsUser('admin@jonathan-martz.de', 'Password123');
$this->client->setToken($token);
$this->collection = $this->client->collection('test');
$this->collection->setClient($this->client);
$this->collection->setPath('/api/collections/test/records/');
try {
$this->collection->delete('65uahqp4wicc88l');
} catch (Exception $exception) {
$this->fail('Exception: ' . $exception->getMessage());
}
$this->assertTrue(true);
}
public function test_upload_record(): void
{
$this->markTestSkipped('todo');
$this->client = new \PocketBase\Client(null);
$this->collection = $this->client->collection('users');
$token = $this->collection->authAsUser('admin@jonathan-martz.de', 'Password123');
$this->client->setToken($token);
$this->collection = $this->client->collection('test');
$this->collection->setPath('/api/collections/users/records/');
$this->collection->setClient($this->client);
try {
$record = $this->collection->getList(1, 10);
} catch (Exception $exception) {
$this->fail('Exception: ' . $exception->getMessage());
}
$this->assertEquals(RecordListViewModel::class, get_class($record));
}
}