Search by

ondewo / survey-client-php

ondewo

ONDEWO SURVEY (Survey) gRPC client for PHP, generated from the ondewo-survey-api protocol buffer definitions

Package info

github.com/ondewo/ondewo-survey-client-php

pkg:composer/ondewo/survey-client-php

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

2.0.1 2026-10-10 04:40 UTC

This package is auto-updated.

Last update: 2026-10-10 04:43:38 UTC


README

ONDEWO SURVEY Client PHP Library

This library is the PHP gRPC client for the ONDEWO SURVEY (Survey) server.

The entire transport surface — messages, enums and one <Service>Client stub per gRPC service — is generated from the protocol buffer definitions of the ondewo-survey-api repository by the ONDEWO proto compiler, which is vendored here as a git submodule and pinned to a release tag. The generated stubs are committed — the repository root is the composer package, Packagist serves the tree of a git tag verbatim and composer has no build step, so what is committed here is exactly what a consumer receives.

The only hand-written PHP is the bearer-token authentication surface in auth/, which turns a token into the $opts array a generated stub is constructed with.

Requirements

  • PHP >= 8.1
  • The grpc PHP extension (ext-grpc) — every generated <Service>Client extends \Grpc\BaseStub
  • The bcmath PHP extension (ext-bcmath) — only to parse integers out of the JSON wire format; google/protobuf merely suggests it, so mergeFromJsonString() on a message with an int field fails without it
  • Composer 2.x
  • Docker — only to regenerate the stubs, never to use the client

Installing the extension:

# Debian / Ubuntu
sudo apt-get install -y php-grpc php-bcmath
# or, from source
sudo pecl install grpc

Installation

The client is published on Packagist as ondewo/survey-client-php and is installed like any other composer package:

composer require ondewo/survey-client-php

The client version tracks the ONDEWO SURVEY API in major and minor version, so pin the minor series that matches the server you talk to:

composer require ondewo/survey-client-php:^2.0

or, in composer.json:

{
  "require": {
    "ondewo/survey-client-php": "^2.0"
  }
}

Two things a consumer has to know:

  • ext-grpc is a hard requirement, not an optional extra — every generated <Service>Client extends \Grpc\BaseStub, so composer refuses to install the package without it. Install it first (see Requirements above); composer require ondewo/survey-client-php --ignore-platform-req=ext-grpc will resolve, but the client will fatal at runtime. ext-bcmath is not declared — google/protobuf only suggests it — but its pure-PHP JSON parser range-checks integers with bccomp(), so install it too if you read or write the JSON wire format.
  • There is no build step. Packagist serves the tree of a git tag verbatim and the generated stubs are committed, so the package a consumer downloads is byte-for-byte the tagged repository: after composer require, vendor/ondewo/survey-client-php/src/ already holds every stub and the autoloader is generated by composer itself. Nothing needs docker, protoc or the ondewo-survey-api submodule.

Everything is then reachable through composer's autoloader:

require __DIR__ . '/vendor/autoload.php';

use Ondewo\Survey\SurveysClient;                   // generated, from src/
use Ondewo\Survey\Auth\BearerTokenAuthenticator;   // hand-written, from auth/

To work on the client itself:

git clone --recurse-submodules git@github.com:ondewo/ondewo-survey-client-php.git
cd ondewo-survey-client-php
make setup_developer_environment_locally

make help lists every documented target; make makefile_chapters lists the Makefile's sections.

Repository structure

.
├── ondewo-survey-api              <----- submodule: the .proto definitions (ondewo/ = the services, google/ = imports)
├── ondewo-proto-compiler   <----- submodule: the compiler images, pinned to tags/5.15.1
├── auth                    <----- HAND-WRITTEN sources (bearer token authenticator, ClientConfig: TLS / mutual TLS)
├── src                     <----- GENERATED stubs, committed - compiler-owned, wiped on every generation run
│   ├── GPBMetadata         <----- descriptor bootstrap, one class per .proto
│   └── Ondewo              <----- messages, enums and the <Service>Client stubs
├── tests                   <----- PHPUnit suite (not part of the published classmap)
├── tools                   <----- dev-only composer project: PHPUnit + the coverage gate
├── vendor                  <----- composer dependencies (gitignored)
├── composer.json           <----- the package manifest; MERGED with the compiler defaults on every run
├── phpunit.xml.dist        <----- test suite + coverage scope (auth/ only)
└── Makefile                <----- build, test and release automation

Three rules follow from that layout and matter more than anything else in this file:

  1. Never put hand-written PHP in src/. It is deleted and rewritten on every generation run. Hand-written code belongs in auth/ at the repository root — the compiler image detects that directory and adds it to the shipped autoloader's classmap itself.
  2. Never pin google/protobuf or grpc/grpc in composer.json to anything other than the versions the compiler image ships. The image resolves the merged manifest offline from a cache it pre-warmed at image-build time; a pin outside that cache fails the generation run.
  3. Never add require-dev to the root composer.json. composer update --no-dev still resolves dev requirements in order to write a lock file, so a single entry there makes that same offline resolution fail. Dev tooling lives in its own composer project under tools/ — see tools/README.md.

Regenerating the stubs

make build

That is the whole flow, and it is: check out the pinned submodules → build the ondewo-php-proto-compiler:latest image from the submodule → run it over the protos → hand the generated files back to your user → write the client version into composer.json.

The generation step on its own is a single container run:

docker run --rm \
  -v $(pwd):/input-volume \
  -v $(pwd):/output-volume \
  ondewo-php-proto-compiler:latest ondewo-survey-api ondewo
  • The two positional arguments are <relative_protos_dir> <target_subdir>: the proto root inside the input volume (which becomes protoc's -I root), and the sub-directory to scope generation to. ondewo keeps the vendored google/ tree out of the entry set while the image's dependency resolver still pulls in the google protos that are actually imported.
  • There is no -it. It breaks every non-interactive caller with cannot attach stdin to a TTY-enabled container because stdin is not a terminal.
  • Input and output volume are both the repository root. The image copies the input volume into an internal temporary directory and compiles there, so the mounted input is never mutated; it then writes composer.json, composer.lock, src/ and vendor/ back here, wiping its own src/ and vendor/ first so a renamed or deleted proto leaves no orphaned stub behind.
  • The container runs as root, so the files it writes are root-owned. make build chases that with make fix_generated_ownership; run it by hand if you invoke docker directly.

To poke around inside the image, and only there, -it is correct:

docker run -it --entrypoint /bin/bash \
  -v $(pwd):/input-volume \
  -v $(pwd):/output-volume \
  ondewo-php-proto-compiler:latest

Usage

<?php

require __DIR__ . '/vendor/autoload.php';

use Grpc\ChannelCredentials;
use Ondewo\Survey\Auth\BearerTokenAuthenticator;
use Ondewo\Survey\ListSurveysRequest;
use Ondewo\Survey\SurveysClient;

// The PHP namespace is protoc's UpperCamel form of the proto package:
// `package ondewo.survey;` becomes `Ondewo\Survey`, and the service `Surveys`
// becomes `SurveysClient` (grpc_php_plugin's default class suffix). The second
// service of the api is `Ondewo\Survey\FHIRClient`. Browse src/Ondewo/Survey for
// the messages your pinned API version declares.
//
// BearerTokenAuthenticator is the hand-written half: it builds the `$opts` array and
// stamps `authorization: Bearer <token>` onto the metadata of every call.
$auth = new BearerTokenAuthenticator(getenv('ONDEWO_TOKEN'));
$client = new SurveysClient(
    getenv('ONDEWO_SURVEY_HOST') ?: 'localhost:50055',
    $auth->channelOptions(ChannelCredentials::createSsl())
);

$request = new ListSurveysRequest();
$request->setPageToken('');

[$response, $status] = $client->ListSurveys($request)->wait();

if ($status->code !== \Grpc\STATUS_OK) {
    throw new RuntimeException("gRPC call failed ({$status->code}): {$status->details}");
}

echo $response->serializeToJsonString(), PHP_EOL;

For an insecure channel against a local server, call $auth->channelOptions() with no argument — null credentials is exactly what ChannelCredentials::createInsecure() returns.

TLS, mutual TLS and certificates

gRPC encrypts with TLS. "SSL" in names such as \Grpc\ChannelCredentials::createSsl() or grpc.ssl_target_name_override is legacy naming; no SSL protocol version is ever negotiated.

Ondewo\Survey\Auth\ClientConfig (hand-written, in auth/) builds the target and the $opts array of every generated <Service>Client, with the same TLS rules and channel defaults as the other ONDEWO SDKs:

Mode ClientConfig arguments
Plaintext (not for production) useSecureChannel: false
TLS, system trust store none (grpcCert empty)
TLS, custom CA grpcCert = PEM of the CA that signed the server certificate
Mutual TLS grpcCert plus grpcClientCert and grpcClientKey
<?php

use Ondewo\Survey\Auth\BearerTokenAuthenticator;
use Ondewo\Survey\Auth\ClientConfig;
use Ondewo\Survey\SurveysClient;

$config = new ClientConfig(
    host: '10.0.0.5',
    port: 50051,
    grpcCert: file_get_contents('certs/ca.pem'),
    grpcClientCert: file_get_contents('certs/client.pem'), // leave both out for server-authenticated TLS
    grpcClientKey: file_get_contents('certs/client.key'),
);
$client = new SurveysClient($config->target(), $config->channelOptions([
    'update_metadata' => new BearerTokenAuthenticator(getenv('ONDEWO_TOKEN')),
    'grpc.ssl_target_name_override' => 'survey.example.internal', // only when connecting by IP
]));

Rules the code enforces:

  • The three certificate fields hold PEM content, not file paths. Read the files yourself (file_get_contents() returns false for a missing file, which declare(strict_types=1) code rejects with a TypeError). CRLF line endings are fine.
  • grpcClientCert and grpcClientKey go together: setting only one throws InvalidArgumentException when the config is built, and channelCredentials() repeats the check before anything reaches ext-grpc. This is not pedantry: grpc-core aborts the whole PHP process on a private key without its certificate and silently connects without a client identity on a certificate without its key. Empty strings on both mean server-authenticated TLS; an empty grpcCert means the platform's default trust store.
  • useSecureChannel: false with a client certificate throws InvalidArgumentException instead of silently dropping the identity. A plaintext channel is allowed, but logs a warning naming host:port: on the PSR-3 logger passed to channelOptions(logger: ...) / channelCredentials($logger), otherwise through error_log(). The SDK never configures your logging.
  • channelOptions() refuses a credentials option of its own: TLS material goes through ClientConfig, where it is checked. Every other option (update_metadata, any grpc.* channel argument) is passed through and wins over the defaults.
  • No exception message renders a PEM or the config: they name the field and host:port.
  • target() brackets a bare IPv6 literal (::1 becomes [::1]:50051) and leaves [...] or scheme: hosts alone.
  • The server certificate is verified against grpcCert, and the host you connect to must match one of the certificate's subject alternative names (SAN). When you connect by IP and the certificate has no IP SAN, tell gRPC which name to check with the channel option grpc.ssl_target_name_override.

Channel defaults (ClientConfig::DEFAULT_CHANNEL_OPTIONS, identical to ondewo-client-utils-python): message size limit 2³¹-1 bytes both ways; grpc.keepalive_time_ms 30000 with grpc.keepalive_permit_without_calls 0 and grpc.http2.max_pings_without_data 2 (pings only during calls; a server answers endless pings on a silent stream with GOAWAY too_many_pings); grpc.keepalive_timeout_ms and grpc.http2.ping_timeout_ms 20000 (a dead connection is detected in about 40 s instead of 85 s); grpc.max_reconnect_backoff_ms 5000 (gRPC's default is 120 s). Gap: the Python SDK also installs a per-method retry policy (idempotent reads only); this PHP SDK installs none, so only gRPC's transparent retries (a request that provably never reached the server) apply.

A test PKI with openssl

A CA, a server certificate with SANs, and a client certificate with the clientAuth extended key usage. For tests only: the keys are unencrypted.

openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 365 \
  -subj "/CN=Test CA" -keyout ca.key -out ca.pem

printf 'subjectAltName=DNS:localhost,IP:127.0.0.1\nextendedKeyUsage=serverAuth\n' > server.ext
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
  -subj "/CN=localhost" -keyout server.key -out server.csr
openssl x509 -req -in server.csr -CA ca.pem -CAkey ca.key -CAcreateserial -days 365 \
  -extfile server.ext -out server.pem

printf 'extendedKeyUsage=clientAuth\n' > client.ext
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
  -subj "/CN=my-client" -keyout client.key -out client.csr
openssl x509 -req -in client.csr -CA ca.pem -CAkey ca.key -CAcreateserial -days 365 \
  -extfile client.ext -out client.pem

chmod 600 *.key
openssl verify -CAfile ca.pem server.pem client.pem

The client then uses ca.pem / client.pem / client.key; a server that requires client certificates uses server.pem / server.key and trusts ca.pem for its clients.

TLS security notes

  • (string) $config, var_dump() / print_r() (__debugInfo()) and json_encode() (jsonSerialize()) show a non-empty grpcClientKey as ***REDACTED*** (an empty one stays empty). That JSON is for logs and cannot be read back; keep the key in a file or secret store and pass it to the constructor at startup.
  • serialize(), var_export() and an (array) cast are not redacted: they carry the private key in clear text. Do not log them, and treat anything serialized from a config as a secret (file mode 0600, never committed).
  • The key parameter is #[\SensitiveParameter]: from PHP 8.2 on, stack traces show it as a SensitiveParameterValue. PHP 8.1 ignores the attribute; there, set zend.exception_ignore_args = On (the php.ini-production default) to keep arguments out of traces.

TLS troubleshooting

A failed handshake ends the call with $status->code === \Grpc\STATUS_UNAVAILABLE (14); the cause is in $status->details:

  • CERTIFICATE_VERIFY_FAILED: unable to get local issuer certificate (inside "Ssl handshake failed"): grpcCert is not the CA that issued the server certificate (or is empty, so the system trust store is used), or the server does not send its intermediate certificates.
  • Hostname Verification Check failed (older gRPC: Peer name <host> is not in peer certificate): the host you connect to is not in the server certificate's SAN. Connect by a name in the SAN, add the SAN, or set grpc.ssl_target_name_override.
  • Socket closed against a server that requires client certificates: no client certificate was presented, or one the server's CA did not issue. The server log names the reason (e.g. PEER_DID_NOT_RETURN_A_CERTIFICATE). Set grpcClientCert / grpcClientKey.
  • empty address list, with Could not load any root certificate in the gRPC log: grpcCert holds something that is not PEM, typically a file path. Pass file_get_contents(...) instead.

Testing

make ci        # what GitHub Actions runs: no submodules, no docker
make test      # the same, plus `make check_build` against the ondewo-survey-api submodule

make ci is composer validate → the credential-free Packagist dry run → php -l over the hand-written sources → PHPUnit with coverage → the coverage threshold gate. It runs on PHP 8.1 and 8.4 in GitHub Actions, against the committed stubs: no docker image is built and no proto compiler runs there.

What the suite actually asserts:

Test What it would catch
tests/Generated/GeneratedCodeTest.php A stub that does not load, a GPBMetadata descriptor whose initOnce() chain has a missing transitive import, a service whose client class was never generated, an empty src/
tests/Generated/MessageSerializationTest.php A field that never reaches the wire, a sub-message whose presence is lost, a moved enum zero constant, a broken JSON mapping (including the integer path, which needs ext-bcmath)
tests/Generated/ServiceClientTest.php A stub that cannot be constructed, a missing or re-shaped RPC method
tests/Auth/BearerTokenAuthenticatorTest.php Any regression in the hand-written auth surface
tests/Auth/ClientConfigTest.php Half a client identity reaching ext-grpc, an identity dropped on a plaintext channel, a PEM or key in a message or rendering, a wrong target or channel default
tests/Tls/MutualTlsHandshakeTest.php A broken real handshake: TLS, mutual TLS, CRLF PEMs and [::1] must connect; a missing or foreign client certificate, a wrong CA and the system roots against the test CA must fail as UNAVAILABLE
tests/ReleaseNotesTest.php A RELEASE.md heading or separator the release-notes slice would miss, i.e. a GitHub release with empty notes

The handshake test generates its PKI with ext-openssl at test time and needs python3 with grpcio for its server (tests/Tls/tls_test_server.py; PHP has no gRPC server): pip install grpcio, or point ONDEWO_TLS_TEST_PYTHON at an interpreter that has it. CI installs it.

Coverage is reported for the hand-written code only — phpunit.xml.dist's <source> is auth/, and make coverage fails below COVERAGE_MIN (100%). The generated stubs are machine output and are deliberately outside the metric, but they are not outside the tests: every one of the committed classes is loaded and every descriptor initialised by GeneratedCodeTest.

Versioning and releasing

ONDEWO_SURVEY_VERSION at the top of the Makefile is the single source of truth and must match the ONDEWO SURVEY API in major and minor version. make update_composer_version propagates it into composer.json; never edit that field by hand.

# bump ONDEWO_SURVEY_VERSION and the submodule pins, add a RELEASE.md entry, then:
make ondewo_release

ondewo_release checks that the release branch and tag are still free, fetches the credentials from the ondewo-devops-accounts repository and runs the release: build, commit, release branch, release tag, the GitHub release (whose notes are sliced out of RELEASE.md by the version heading) and finally make publish.

Publishing to Packagist

Packagist takes no upload. There is no twine upload and no npm publish equivalent: Packagist reads the git tags of this repository off GitHub and serves each tagged tree as a version. So "publishing" is two things, and only the second one is a command:

  1. the git tag — make create_release_tag pushes it, and that tag is the artifact;
  2. a ping that tells Packagist to crawl the repository now instead of at its next scheduled pass — make publish.
make publish    # validate the package, then POST to https://packagist.org/api/update-package

make publish refuses to run without credentials, then runs the full dry run, then pings the API and fails on anything but an HTTP 200 carrying {"status":"success"}. It is wired into make release, so a normal make ondewo_release needs no extra step.

One-time setup (a human, once per package)

None of the automation can do these; they need a browser and ownership of the ONDEWO organisation.

  1. Submit the package once. Log in to packagist.org with the ONDEWO account and use Submit with the repository URL https://github.com/ondewo/ondewo-survey-client-php. Packagist reads composer.json and claims the vendor namespace ondewo/ for that account. Until this is done the update API answers 404 for the package and make publish fails — deliberately.
  2. Install the GitHub service hook (optional but recommended) so a tag push updates Packagist even when a release is made by hand: on Packagist the package page offers the hook URL and token, or use GitHub Settings → Webhooks with payload URL https://packagist.org/api/github?username=<PACKAGIST_USERNAME>, content type application/json, secret = the Packagist API token, event Just the push event. The hook and make publish do the same job; having both is harmless, having neither means a release is only visible after Packagist's own crawl.
  3. Store the credentials — see the table below.

Credentials

Name What it is Where it lives
PACKAGIST_USERNAME the Packagist login name that owns the ondewo/ vendor namespace ondewo-devops-accounts → account_packagist.env, and the GitHub repository secret of the same name
PACKAGIST_API_TOKEN that account's API token, from packagist.org/profile → Show API token ondewo-devops-accounts → account_packagist.env, and the GitHub repository secret of the same name
GITHUB_GH_TOKEN the token gh release create authenticates with ondewo-devops-accounts → account_github.env (already in use)

Both Packagist variables default to an ENTER_HERE_YOUR_… placeholder in the Makefile and are only ever supplied at runtime — make ondewo_release reads them out of the devops-accounts clone, the release workflow out of GitHub secrets. Every recipe that carries one is @-prefixed so it never reaches a build log, and make TEST prints <set> / <unset> rather than the value.

What is verified without credentials

make packagist_dry_run is the credential-free half of make publish and runs in CI on every push (.github/workflows/ci.yml, and make ci locally):

Check What it would catch
composer validate a composer.json Packagist cannot parse
composer_validate_strict any new strict-mode warning — the three deliberate ones (the version field and the two exact google/protobuf / grpc/grpc pins) are enumerated in the Makefile and allowed, everything else fails
check_version_agreement ONDEWO_SURVEY_VERSION, composer.json's name and version, the RELEASE.md entry and — on a tag — the tag name drifting apart. A tag that disagrees with the version field makes Packagist publish the tree under a version nobody tagged
check_packagist_payload the update request pointing at the wrong repository — the API identifies the package by its VCS url, not by its composer name

.github/workflows/release.yml runs on a X.Y.Z tag push and does the same checks plus the full test suite before it pings the API. If either secret is missing it fails in its first step with an explicit ::error:: naming the secret, rather than posting an unauthenticated request and reporting success.

See RELEASE.md for the release history and CONTRIBUTING.md for how to contribute.

License

Apache License 2.0 — see LICENSE.