diff --git a/CHANGELOG.md b/CHANGELOG.md index bc69a30..ed7c080 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [NEXT] - 2026- + +- Added: UserModel address getters for BRP API v2 (`street()`, `city()`, `houseNumberAddition()`, `nummeraanduidingIdentificatie()`) +- Added: number of residents at the residential address via BRP search query `ZoekMetNummeraanduidingIdentificatie` (`PostController::countResidents()`, `UserModel::residentsCount()`) +- Added: mappable field "Aantal bewoners" in the Gravity Forms field mapping (v2 suppliers) and the Personal Data Row block +- Fix: `zipcode()`, `houseNumber()` and `houseLetter()` of the UserModel now return values for BRP API v2 responses + ## [v2.1.2] - 2026-11-17 - Fix: use general goal binding when a form has no goal binding (V2 suppliers) diff --git a/README.md b/README.md index c414c9f..b2128a6 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,21 @@ if ( $user->isLoggedIn() ) { } ``` +### Available methods + +| Method | Returns | +|---|---| +| `isLoggedIn()` | `true` when a valid BSN is available | +| `bsn()`, `age()` | BSN and age | +| `initials()`, `firstNames()`, `lastNamePrefix()`, `lastName()`, `fullName(bool $withInitials = false)` | Name parts | +| `street()`, `houseNumber()`, `houseLetter()`, `houseNumberAddition()`, `zipcode()`, `city()` | Residential address | +| `nummeraanduidingIdentificatie()` | BAG identification (16 digits) of the residential address, or `''` | +| `residentsCount()` | Number of persons registered at the residential address, or `null` (see below) | + +When no goal binding is given (for example a Personal Data Row block without one), the count uses the general goal binding from the settings. `residentsCount()` uses the BRP search query `ZoekMetNummeraanduidingIdentificatie` and is only available for HaalCentraal BRP API v2 suppliers (e.g. `PinkRoccadeV2`, `EnableUV2`). It returns `null` when the user is not logged in, no address is known, a v1 supplier is configured or the request fails (e.g. a 403 because the goal binding does not allow the search). Only the count is cached (encrypted, one hour, requires `PG_CACHE_ENCRYPTION_KEY`); the persons in the response are discarded. + +The address methods read the HaalCentraal BRP API v2 structure (`verblijfplaats.verblijfadres.*`) first and fall back to the v1 structure. All address methods return an empty string when no address is known (e.g. a `Locatie` without address). + This model does not handle authentication itself, it only exposes data retrieved by the underlying BRP supplier controller. If a controller fails to load (e.g., misconfiguration or missing supplier), the model gracefully returns default values. @@ -109,6 +124,15 @@ Each Personal Data Row block must be configured in the block sidebar: | Processing (Verwerking) | Optional for HaalCentraal API v2. Describes for which work process or process step the BRP data is being requested. | | Personal data field | The specific BRP attribute to display (e.g. name, date of birth). | +### Number of residents + +The field **Aantal bewoners** (`aantalBewoners`) shows the number of persons registered at the residential address of the logged-in user. It is available in the Personal Data Row block ("Aantal bewoners (V2)") and in the Gravity Forms field mapping of the HaalCentraal v2 suppliers (group "Verblijfplaats"). + +- Only for HaalCentraal BRP API v2 suppliers; the goal binding must allow the search query `ZoekMetNummeraanduidingIdentificatie`. Otherwise the field stays empty and the failure is logged. +- In Gravity Forms, map it to a **Text** field; Number and Hidden fields are not prefilled. +- A count of `0` is shown as empty. +- The count is only requested when a form field is mapped to it. + ## Logging Enable logging to monitor errors during communication with the BRP suppliers. diff --git a/build/personal-data-table/personal-data-row/index.asset.php b/build/personal-data-table/personal-data-row/index.asset.php index b231319..7d5ba0f 100644 --- a/build/personal-data-table/personal-data-row/index.asset.php +++ b/build/personal-data-table/personal-data-row/index.asset.php @@ -1 +1 @@ - ['react-jsx-runtime', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-data', 'wp-element', 'wp-i18n'], 'version' => 'df0a722bfd18e3eb3f64']; + ['react-jsx-runtime', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-data', 'wp-element', 'wp-i18n'], 'version' => '4b40b98f30dca0b0680b']; diff --git a/build/personal-data-table/personal-data-row/index.js b/build/personal-data-table/personal-data-row/index.js index 78a1ced..60d6eda 100644 --- a/build/personal-data-table/personal-data-row/index.js +++ b/build/personal-data-table/personal-data-row/index.js @@ -1 +1 @@ -(()=>{"use strict";const e=window.wp.blocks,a=(window.wp.i18n,window.wp.blockEditor),l=window.wp.components,n=window.wp.data,t=window.wp.element,i=[{value:"",label:"Selecteer persoonsgegevens",disabled:!0},{label:"Burgerservicenummer (BSN)",value:"burgerservicenummer"},{label:"Geslacht",value:"geslachtsaanduiding"},{label:"Leeftijd",value:"leeftijd"},{label:"Achternaam",value:"naam.geslachtsnaam"},{label:"Voorvoegsel (tussenvoegsel)",value:"naam.voorvoegsel"},{label:"Voorletters",value:"naam.voorletters"},{label:"Voornaam",value:"naam.voornaam"},{label:"Voornamen",value:"naam.voornamen"},{label:"Aanduiding Naamgebruik (V1)",value:"naam.aanduidingNaamgebruik"},{label:"Aanduiding Naamgebruik (V2)",value:"naam.aanduidingNaamgebruik.omschrijving"},{label:"Aanschrijfwijze",value:"naam.aanschrijfwijze"},{label:"Gebruik in lopende tekst",value:"naam.gebruikInLopendeTekst"},{label:"Geboortedatum",value:"geboorte.datum.datum"},{label:"Straat",value:"verblijfplaats.straat"},{label:"Straatnaam",value:"verblijfplaats.straatnaam"},{label:"Huisnummer",value:"verblijfplaats.huisnummer"},{label:"Huisnummertoevoeging",value:"verblijfplaats.huisletter"},{label:"Postcode",value:"verblijfplaats.postcode"},{label:"Woonplaats",value:"verblijfplaats.woonplaats"},{label:"Woonplaats naam",value:"verblijfplaats.woonplaatsnaam"}],o=[{value:"",label:"Selecteer een leverancier",disabled:!0},{label:"EnableU",value:"EnableU"},{label:"EnableU V2",value:"EnableUV2"},{label:"OpenZaak",value:"OpenZaak"},{label:"PinkRoccade",value:"PinkRoccade"},{label:"PinkRoccadeV2",value:"PinkRoccadeV2"},{label:"VrijBRP",value:"VrijBRP"},{label:"WeAreFrank",value:"WeAreFrank"}],s=window.ReactJSXRuntime,r=JSON.parse('{"$schema":"https://schemas.wp.org/trunk/block.json","apiVersion":3,"name":"owc-prefill-gravity-forms/personal-data-row","version":"0.1.0","title":"Persoonsgegevens","icon":"id","description":"Toon persoonsgegevens van de ingelogde gebruiker.","example":{},"supports":{"html":false},"attributes":{"selectedSupplier":{"type":"object","default":{"value":"","label":""}},"goalBinding":{"type":"string","default":""},"processing":{"type":"string","default":""},"selectedOption":{"type":"object","default":{"value":"","label":""}},"isChildOfTable":{"type":"boolean","default":false},"htmlElement":{"type":"string","default":"p"}},"textdomain":"prefill-gravity-forms","editorScript":"file:./index.js","render":"file:./render.php"}');(0,e.registerBlockType)(r.name,{...r,edit:function({attributes:e,setAttributes:r,clientId:d}){const{selectedSupplier:v,goalBinding:c,processing:u,selectedOption:b,htmlElement:p,isChildOfTable:g}=e,{blockParents:m}=(0,n.useSelect)(e=>({blockParents:e("core/block-editor").getBlockNamesByClientId(e("core/block-editor").getBlockParents(d))}));(0,t.useEffect)(()=>{m.length>0&&"owc-prefill-gravity-forms/personal-data-table"===m[m.length-1]&&r({isChildOfTable:!0})},[m,r]);const h=(0,s.jsx)(l.SelectControl,{help:"Selecteer de juiste leverancier die ingesteld staat in de algemene instellingen.",label:"Leverancier",value:v.value,options:o,onChange:e=>{const a={value:e,label:o.find(a=>a.value===e).label};r({selectedSupplier:a})}}),j=(0,s.jsx)(l.TextControl,{help:"Algemene doelbinding voor verzoeken zonder specifieke doelbinding. Beschrijft waarom de persoonsgegevens worden opgevraagd en op basis van welke wettelijke taak of bevoegdheid de organisatie dit doet. De mogelijke waarden zijn implementatieafhankelijk en worden door de leverancier bepaald.",label:"Doelbinding (v2)",value:c,onChange:e=>{r({goalBinding:e})}}),k=(0,s.jsx)(l.TextControl,{help:"Beschrijft voor welk werkproces of welke processtap de BRP-gegevens worden opgevraagd. De mogelijke waarden zijn implementatieafhankelijk en dienen door de leverancier te worden aangeleverd.",label:"Verwerking (v2)",value:u,onChange:e=>{r({processing:e})}}),w=(0,s.jsx)(l.SelectControl,{label:"Automatisch invullen",value:b.value,options:i,onChange:e=>{const a={value:e,label:i.find(a=>a.value===e).label};r({selectedOption:a})}}),f=(0,s.jsx)(l.SelectControl,{label:"HTML Element",value:p,options:[{label:"
",value:"div"},{label:"

",value:"p"},{label:"",value:"span"}],onChange:e=>{r({htmlElement:e})}});return(0,s.jsxs)("div",{...(0,a.useBlockProps)(),children:[(0,s.jsx)(a.InspectorControls,{children:(0,s.jsx)(l.TabPanel,{activeClass:"active-tab",tabs:[{name:"settings",title:"Settings"}],children:e=>(0,s.jsx)(l.PanelBody,{initialOpen:!0,children:"settings"===e.name&&(0,s.jsxs)(s.Fragment,{children:[h,j,k,w,!g&&f]})})})}),void 0===b.value||""===b.value?(0,s.jsx)("p",{children:w}):(0,s.jsx)(s.Fragment,{children:(0,s.jsxs)("div",{className:"row",children:[g&&(0,s.jsx)("div",{className:"col-6 font-weight-bold",children:(0,s.jsx)("p",{children:b.label})}),(0,s.jsxs)("div",{className:"col-6",children:["[",(x=b.label,x?x.charAt(0).toLowerCase()+x.slice(1):x),"]"]})]})})]});var x},save:()=>null})})(); \ No newline at end of file +(()=>{"use strict";const e=window.wp.blocks,a=(window.wp.i18n,window.wp.blockEditor),l=window.wp.components,n=window.wp.data,t=window.wp.element,i=[{value:"",label:"Selecteer persoonsgegevens",disabled:!0},{label:"Burgerservicenummer (BSN)",value:"burgerservicenummer"},{label:"Geslacht",value:"geslachtsaanduiding"},{label:"Leeftijd",value:"leeftijd"},{label:"Achternaam",value:"naam.geslachtsnaam"},{label:"Voorvoegsel (tussenvoegsel)",value:"naam.voorvoegsel"},{label:"Voorletters",value:"naam.voorletters"},{label:"Voornaam",value:"naam.voornaam"},{label:"Voornamen",value:"naam.voornamen"},{label:"Aanduiding Naamgebruik (V1)",value:"naam.aanduidingNaamgebruik"},{label:"Aanduiding Naamgebruik (V2)",value:"naam.aanduidingNaamgebruik.omschrijving"},{label:"Aanschrijfwijze",value:"naam.aanschrijfwijze"},{label:"Gebruik in lopende tekst",value:"naam.gebruikInLopendeTekst"},{label:"Geboortedatum",value:"geboorte.datum.datum"},{label:"Straat",value:"verblijfplaats.straat"},{label:"Straatnaam",value:"verblijfplaats.straatnaam"},{label:"Huisnummer",value:"verblijfplaats.huisnummer"},{label:"Huisnummertoevoeging",value:"verblijfplaats.huisletter"},{label:"Postcode",value:"verblijfplaats.postcode"},{label:"Woonplaats",value:"verblijfplaats.woonplaats"},{label:"Woonplaats naam",value:"verblijfplaats.woonplaatsnaam"},{label:"Aantal bewoners (V2)",value:"aantalBewoners"}],o=[{value:"",label:"Selecteer een leverancier",disabled:!0},{label:"EnableU",value:"EnableU"},{label:"EnableU V2",value:"EnableUV2"},{label:"OpenZaak",value:"OpenZaak"},{label:"PinkRoccade",value:"PinkRoccade"},{label:"PinkRoccadeV2",value:"PinkRoccadeV2"},{label:"VrijBRP",value:"VrijBRP"},{label:"WeAreFrank",value:"WeAreFrank"}],s=window.ReactJSXRuntime,r=JSON.parse('{"$schema":"https://schemas.wp.org/trunk/block.json","apiVersion":3,"name":"owc-prefill-gravity-forms/personal-data-row","version":"0.1.0","title":"Persoonsgegevens","icon":"id","description":"Toon persoonsgegevens van de ingelogde gebruiker.","example":{},"supports":{"html":false},"attributes":{"selectedSupplier":{"type":"object","default":{"value":"","label":""}},"goalBinding":{"type":"string","default":""},"processing":{"type":"string","default":""},"selectedOption":{"type":"object","default":{"value":"","label":""}},"isChildOfTable":{"type":"boolean","default":false},"htmlElement":{"type":"string","default":"p"}},"textdomain":"prefill-gravity-forms","editorScript":"file:./index.js","render":"file:./render.php"}');(0,e.registerBlockType)(r.name,{...r,edit:function({attributes:e,setAttributes:r,clientId:d}){const{selectedSupplier:v,goalBinding:c,processing:u,selectedOption:b,htmlElement:p,isChildOfTable:g}=e,{blockParents:m}=(0,n.useSelect)(e=>({blockParents:e("core/block-editor").getBlockNamesByClientId(e("core/block-editor").getBlockParents(d))}));(0,t.useEffect)(()=>{m.length>0&&"owc-prefill-gravity-forms/personal-data-table"===m[m.length-1]&&r({isChildOfTable:!0})},[m,r]);const h=(0,s.jsx)(l.SelectControl,{help:"Selecteer de juiste leverancier die ingesteld staat in de algemene instellingen.",label:"Leverancier",value:v.value,options:o,onChange:e=>{const a={value:e,label:o.find(a=>a.value===e).label};r({selectedSupplier:a})}}),j=(0,s.jsx)(l.TextControl,{help:"Algemene doelbinding voor verzoeken zonder specifieke doelbinding. Beschrijft waarom de persoonsgegevens worden opgevraagd en op basis van welke wettelijke taak of bevoegdheid de organisatie dit doet. De mogelijke waarden zijn implementatieafhankelijk en worden door de leverancier bepaald.",label:"Doelbinding (v2)",value:c,onChange:e=>{r({goalBinding:e})}}),w=(0,s.jsx)(l.TextControl,{help:"Beschrijft voor welk werkproces of welke processtap de BRP-gegevens worden opgevraagd. De mogelijke waarden zijn implementatieafhankelijk en dienen door de leverancier te worden aangeleverd.",label:"Verwerking (v2)",value:u,onChange:e=>{r({processing:e})}}),k=(0,s.jsx)(l.SelectControl,{label:"Automatisch invullen",value:b.value,options:i,onChange:e=>{const a={value:e,label:i.find(a=>a.value===e).label};r({selectedOption:a})}}),f=(0,s.jsx)(l.SelectControl,{label:"HTML Element",value:p,options:[{label:"

",value:"div"},{label:"

",value:"p"},{label:"",value:"span"}],onChange:e=>{r({htmlElement:e})}});return(0,s.jsxs)("div",{...(0,a.useBlockProps)(),children:[(0,s.jsx)(a.InspectorControls,{children:(0,s.jsx)(l.TabPanel,{activeClass:"active-tab",tabs:[{name:"settings",title:"Settings"}],children:e=>(0,s.jsx)(l.PanelBody,{initialOpen:!0,children:"settings"===e.name&&(0,s.jsxs)(s.Fragment,{children:[h,j,w,k,!g&&f]})})})}),void 0===b.value||""===b.value?(0,s.jsx)("p",{children:k}):(0,s.jsx)(s.Fragment,{children:(0,s.jsxs)("div",{className:"row",children:[g&&(0,s.jsx)("div",{className:"col-6 font-weight-bold",children:(0,s.jsx)("p",{children:b.label})}),(0,s.jsxs)("div",{className:"col-6",children:["[",(x=b.label,x?x.charAt(0).toLowerCase()+x.slice(1):x),"]"]})]})})]});var x},save:()=>null})})(); \ No newline at end of file diff --git a/resources/js/blocks/personal-data-table/personal-data-row/config/personalDataOptions.js b/resources/js/blocks/personal-data-table/personal-data-row/config/personalDataOptions.js index 0ac5977..b368c6a 100644 --- a/resources/js/blocks/personal-data-table/personal-data-row/config/personalDataOptions.js +++ b/resources/js/blocks/personal-data-table/personal-data-row/config/personalDataOptions.js @@ -84,6 +84,10 @@ const personalDataOptions = [ label: 'Woonplaats naam', value: 'verblijfplaats.woonplaatsnaam', }, + { + label: 'Aantal bewoners (V2)', + value: 'aantalBewoners', + }, ]; export default personalDataOptions; diff --git a/resources/views/partials/gf-field-options-enable-u-v2.php b/resources/views/partials/gf-field-options-enable-u-v2.php index 1ea614e..167e9c1 100644 --- a/resources/views/partials/gf-field-options-enable-u-v2.php +++ b/resources/views/partials/gf-field-options-enable-u-v2.php @@ -42,6 +42,7 @@ + diff --git a/resources/views/partials/gf-field-options-pink-roccade-v2.php b/resources/views/partials/gf-field-options-pink-roccade-v2.php index 1ea614e..167e9c1 100644 --- a/resources/views/partials/gf-field-options-pink-roccade-v2.php +++ b/resources/views/partials/gf-field-options-pink-roccade-v2.php @@ -42,6 +42,7 @@ + diff --git a/src/PrefillGravityForms/Abstracts/PostController.php b/src/PrefillGravityForms/Abstracts/PostController.php index f28a6a8..733f530 100644 --- a/src/PrefillGravityForms/Abstracts/PostController.php +++ b/src/PrefillGravityForms/Abstracts/PostController.php @@ -4,12 +4,158 @@ namespace OWC\PrefillGravityForms\Abstracts; +use Exception; use OWC\PrefillGravityForms\Controllers\BaseController; +use OWC\PrefillGravityForms\Services\CacheService; abstract class PostController extends BaseController { protected const BRP_API_VERSION = '2'; + /** + * Mapping key of the virtual "number of residents" field. + */ + public const RESIDENTS_COUNT_KEY = 'aantalBewoners'; + + /** + * Counts the number of persons registered at the given address (BAG nummeraanduiding) + * using the BRP search query 'ZoekMetNummeraanduidingIdentificatie'. + * + * Only the count is kept: the persons in the response are discarded and never cached. + * + * @return int|null Null when the count could not be determined. + */ + public function countResidents(string $nummeraanduidingIdentificatie, string $goalBinding = '', string $processing = ''): ?int + { + if (1 !== preg_match('/^\d{16}$/', $nummeraanduidingIdentificatie)) { + return null; + } + + if ($this->settings->requestsDisabled()) { + return null; + } + + // Without a specific goal binding (e.g. a block where none is filled in) the general one from the settings is used; + // PinkRoccade refuses this search without x-doelbinding (HTTP 400). + $goalBinding = '' !== $goalBinding ? $goalBinding : $this->settings->getGoalBinding(); + $processing = '' !== $processing ? $processing : $this->settings->getProcessing(); + $transientKey = CacheService::formatTransientKey('residents_count_' . serialize([ + static::class, + $this->settings->getBaseURL(), + $nummeraanduidingIdentificatie, + $goalBinding, + $processing, + ])); + + try { + $cached = CacheService::getArrayFromTransient($transientKey); + + if (isset($cached['count']) && is_int($cached['count'])) { + return $cached['count']; + } + } catch (Exception $e) { + $this->logException($e); + } + + try { + $response = $this->executeCurlRequest([ + CURLOPT_URL => $this->settings->getBaseURL(), + CURLOPT_POSTFIELDS => json_encode($this->prepareResidentsSearchData($nummeraanduidingIdentificatie)), + CURLOPT_HTTPHEADER => $this->getCurlHeaders($goalBinding, $processing), + ]); + } catch (Exception $e) { + $this->logException($e); + + return null; + } + + $persons = $response['body']['personen'] ?? null; + + if (200 !== $response['status'] || ! is_array($persons)) { + $this->logException(new Exception( + sprintf('Residents count request failed with HTTP status %d.', $response['status']), + 0 !== $response['status'] ? $response['status'] : 500 + )); + + return null; + } + + $count = count($persons); + + try { + CacheService::setTransient($transientKey, ['count' => $count]); + } catch (Exception $e) { + $this->logException($e); + } + + return $count; + } + + /** + * Adds the number of residents to the API response, but only when one of the form fields is mapped to it. + * The count is added after the (BSN-cached) person response has been retrieved, so it is never stored in that cache. + * + * @param array $form + * @param array $apiResponse + * + * @return array + */ + protected function addResidentsCountToResponse(array $form, array $apiResponse, string $goalBinding = '', string $processing = ''): array + { + if (! $this->formHasResidentsCountField($form)) { + return $apiResponse; + } + + $verblijfplaats = $apiResponse['verblijfplaats'] ?? null; + $nummeraanduidingIdentificatie = is_array($verblijfplaats) ? ($verblijfplaats['nummeraanduidingIdentificatie'] ?? null) : null; + + if (! is_string($nummeraanduidingIdentificatie)) { + return $apiResponse; + } + + $count = $this->countResidents($nummeraanduidingIdentificatie, $goalBinding, $processing); + + if (null !== $count) { + $apiResponse[self::RESIDENTS_COUNT_KEY] = (string) $count; + } + + return $apiResponse; + } + + /** + * @param array $form + */ + private function formHasResidentsCountField(array $form): bool + { + $fields = $form['fields'] ?? []; + + if (! is_iterable($fields)) { + return false; + } + + foreach ($fields as $field) { + if (is_object($field) && self::RESIDENTS_COUNT_KEY === ($field->linkedFieldValue ?? null)) { + return true; + } + } + + return false; + } + + /** + * Request body for counting the residents of an address; only the BSN field is requested to minimise the data returned. + * + * @return array{type: string, nummeraanduidingIdentificatie: string, fields: list} + */ + protected function prepareResidentsSearchData(string $nummeraanduidingIdentificatie): array + { + return [ + 'type' => 'ZoekMetNummeraanduidingIdentificatie', + 'nummeraanduidingIdentificatie' => $nummeraanduidingIdentificatie, + 'fields' => ['burgerservicenummer'], + ]; + } + /** * Returns the goal binding of the form, falls back to the general goal binding of the plugin settings. */ diff --git a/src/PrefillGravityForms/Controllers/BaseController.php b/src/PrefillGravityForms/Controllers/BaseController.php index 0a8c534..39df62d 100644 --- a/src/PrefillGravityForms/Controllers/BaseController.php +++ b/src/PrefillGravityForms/Controllers/BaseController.php @@ -392,6 +392,55 @@ protected function handleCurl(array $args, string $transientKey, array $location } } + /** + * Executes a cURL request without caching and returns the HTTP status code and the decoded JSON body. + * + * Unlike handleCurl(), this method does not require a BSN in the response and never + * includes the raw response in exception messages. + * + * @param array $args cURL options, merged with the default arguments. + * + * @throws Exception With a fixed message when the request fails or the body is not valid JSON. + * + * @return array{status: int, body: array} + */ + protected function executeCurlRequest(array $args): array + { + $curl = curl_init(); + + try { + curl_setopt_array($curl, $this->getDefaultCurlArgs() + $args); + + $passphrase = $this->settings->getPassphrase(); + + if ('' !== $passphrase) { + curl_setopt($curl, CURLOPT_SSLKEYPASSWD, $passphrase); + } + + $this->applyCurlSSLOptions($curl); + + $output = curl_exec($curl); + $errorNumber = curl_errno($curl); + + if (0 !== $errorNumber || ! is_string($output)) { + throw new Exception(sprintf('cURL request failed with error number %d.', $errorNumber), 500); + } + + $body = json_decode($output, true); + + if (! is_array($body)) { + throw new Exception('Response body is not valid JSON.', 500); + } + + return [ + 'status' => curl_getinfo($curl, CURLINFO_HTTP_CODE), + 'body' => $body, + ]; + } finally { + unset($curl); + } + } + /** * Verification of the peer's SSL certificate and host is only necessary when * SSL certificates are used and a supplier certificate is provided. diff --git a/src/PrefillGravityForms/Controllers/EnableUV2Controller.php b/src/PrefillGravityForms/Controllers/EnableUV2Controller.php index a3844f5..7771700 100644 --- a/src/PrefillGravityForms/Controllers/EnableUV2Controller.php +++ b/src/PrefillGravityForms/Controllers/EnableUV2Controller.php @@ -32,6 +32,8 @@ public function handle(array $form): array return $form; } + $apiResponse = $this->addResidentsCountToResponse($form, $apiResponse, $goalBinding, $processing); + echo $this->disableFormFields(); return $this->preFillFields($form, $apiResponse); diff --git a/src/PrefillGravityForms/Controllers/PinkRoccadeV2Controller.php b/src/PrefillGravityForms/Controllers/PinkRoccadeV2Controller.php index 0667702..d7d5aad 100644 --- a/src/PrefillGravityForms/Controllers/PinkRoccadeV2Controller.php +++ b/src/PrefillGravityForms/Controllers/PinkRoccadeV2Controller.php @@ -32,6 +32,8 @@ public function handle(array $form): array return $form; } + $apiResponse = $this->addResidentsCountToResponse($form, $apiResponse, $goalBinding, $processing); + echo $this->disableFormFields(); return $this->preFillFields($form, $apiResponse); diff --git a/src/PrefillGravityForms/Models/UserModel.php b/src/PrefillGravityForms/Models/UserModel.php index 657300e..77a5d9f 100644 --- a/src/PrefillGravityForms/Models/UserModel.php +++ b/src/PrefillGravityForms/Models/UserModel.php @@ -5,6 +5,7 @@ namespace OWC\PrefillGravityForms\Models; use Exception; +use OWC\PrefillGravityForms\Abstracts\PostController; use OWC\PrefillGravityForms\Controllers\BaseController; use OWC\PrefillGravityForms\GravityForms\GravityFormsSettings; use OWC\PrefillGravityForms\Traits\ControllerTrait; @@ -18,6 +19,8 @@ class UserModel protected string $supplier; protected ?BaseController $controller; protected array $data; + private ?int $residentsCount = null; + private bool $residentsCountResolved = false; public function __construct() { @@ -95,16 +98,111 @@ public function fullName(bool $withInitials = false): string public function zipcode(): string { - return (string) ($this->data['verblijfplaats']['postcode'] ?? ''); + return $this->stringValue('verblijfplaats.verblijfadres.postcode', 'verblijfplaats.postcode'); } public function houseNumber(): string { - return (string) ($this->data['verblijfplaats']['huisnummer'] ?? ''); + return $this->stringValue('verblijfplaats.verblijfadres.huisnummer', 'verblijfplaats.huisnummer'); } public function houseLetter(): string { - return (string) ($this->data['verblijfplaats']['huisletter'] ?? ''); + return $this->stringValue('verblijfplaats.verblijfadres.huisletter', 'verblijfplaats.huisletter'); + } + + public function houseNumberAddition(): string + { + return $this->stringValue('verblijfplaats.verblijfadres.huisnummertoevoeging', 'verblijfplaats.huisnummertoevoeging'); + } + + public function street(): string + { + return $this->stringValue( + 'verblijfplaats.verblijfadres.officieleStraatnaam', + 'verblijfplaats.straat', + 'verblijfplaats.straatnaam' + ); + } + + public function city(): string + { + return $this->stringValue( + 'verblijfplaats.verblijfadres.woonplaats', + 'verblijfplaats.woonplaats', + 'verblijfplaats.woonplaatsnaam' + ); + } + + /** + * BAG identification (16 digits) of the address the person is registered at, or an empty string. + */ + public function nummeraanduidingIdentificatie(): string + { + $value = $this->stringValue( + 'verblijfplaats.nummeraanduidingIdentificatie', + 'verblijfplaats.identificatiecodeNummeraanduiding' + ); + + return 1 === preg_match('/^\d{16}$/', $value) ? $value : ''; + } + + /** + * Number of persons registered at the residential address of the logged-in user. + * Only available for BRP API v2 suppliers; null when it cannot be determined. + */ + public function residentsCount(): ?int + { + if ($this->residentsCountResolved) { + return $this->residentsCount; + } + + $this->residentsCountResolved = true; + $controller = $this->controller ?? null; + $nummeraanduidingIdentificatie = $this->nummeraanduidingIdentificatie(); + + if (! $controller instanceof PostController || ! $this->isLoggedIn() || '' === $nummeraanduidingIdentificatie) { + return $this->residentsCount = null; + } + + $settings = GravityFormsSettings::make(); + + return $this->residentsCount = $controller->countResidents( + $nummeraanduidingIdentificatie, + $settings->getGoalBinding(), + $settings->getProcessing() + ); + } + + /** + * Returns the first non-empty scalar found at one of the given dot-notated paths, as a string. + */ + private function stringValue(string ...$paths): string + { + foreach ($paths as $path) { + $value = $this->data; + + foreach (explode('.', $path) as $segment) { + if (! is_array($value) || ! array_key_exists($segment, $value)) { + $value = null; + + break; + } + + $value = $value[$segment]; + } + + if (is_bool($value) || ! is_scalar($value)) { + continue; + } + + $value = trim((string) $value); + + if ('' !== $value) { + return $value; + } + } + + return ''; } } diff --git a/src/PrefillGravityForms/Services/PersonalDataService.php b/src/PrefillGravityForms/Services/PersonalDataService.php index bb248bf..9e0c381 100644 --- a/src/PrefillGravityForms/Services/PersonalDataService.php +++ b/src/PrefillGravityForms/Services/PersonalDataService.php @@ -5,6 +5,7 @@ namespace OWC\PrefillGravityForms\Services; use Exception; +use OWC\PrefillGravityForms\Abstracts\PostController; use OWC\PrefillGravityForms\Controllers\BaseController; use OWC\PrefillGravityForms\Traits\ControllerTrait; use OWC\PrefillGravityForms\Traits\Logger; @@ -40,6 +41,10 @@ public function get(string $key, string $goalBinding = '', string $processing = return ''; } + if (PostController::RESIDENTS_COUNT_KEY === $key) { + return $this->residentsCount($goalBinding, $processing); + } + $data = $this->controller->get($goalBinding, $processing); if ($this->controller->getApiVersion() === '1') { @@ -55,6 +60,32 @@ public function get(string $key, string $goalBinding = '', string $processing = return $this->format($key, $value); } + /** + * Virtual field: number of persons registered at the residential address of the logged-in user (BRP API v2 only). + */ + private function residentsCount(string $goalBinding, string $processing): string + { + if (! $this->controller instanceof PostController) { + return ''; + } + + if ('' === $goalBinding) { + $goalBinding = \OWC\PrefillGravityForms\GravityForms\GravityFormsSettings::make()->getGoalBinding(); + } + + $data = $this->controller->get($goalBinding, $processing); + $verblijfplaats = $data['verblijfplaats'] ?? null; + $nummeraanduidingIdentificatie = is_array($verblijfplaats) ? ($verblijfplaats['nummeraanduidingIdentificatie'] ?? null) : null; + + if (! is_string($nummeraanduidingIdentificatie)) { + return ''; + } + + $count = $this->controller->countResidents($nummeraanduidingIdentificatie, $goalBinding, $processing); + + return null === $count ? '' : (string) $count; + } + /** * In API version 1, some keys had different names or were structured differently. This method maps the old * keys to their new counterparts for suppliers that haven't updated to the new structure. diff --git a/tests/Stubs/WordPress/GF_Field.php b/tests/Stubs/WordPress/GF_Field.php new file mode 100644 index 0000000..72ab8ee --- /dev/null +++ b/tests/Stubs/WordPress/GF_Field.php @@ -0,0 +1,18 @@ +controller(PinkRoccadeV2Controller::class); + $controller->shouldReceive('countResidents')->once()->with(self::ID, 'doelbinding', 'verwerking')->andReturn(3); + + $response = $this->invokeMethod($controller, 'addResidentsCountToResponse', [ + $this->form(['aantalBewoners']), + $this->person(), + 'doelbinding', + 'verwerking', + ]); + + $this->assertSame('3', $response['aantalBewoners']); + } + + public function test_does_not_count_when_no_field_is_mapped(): void + { + $controller = $this->controller(PinkRoccadeV2Controller::class); + $controller->shouldNotReceive('countResidents'); + + $response = $this->invokeMethod($controller, 'addResidentsCountToResponse', [ + $this->form(['verblijfplaats.verblijfadres.postcode']), + $this->person(), + ]); + + $this->assertSame($this->person(), $response); + } + + public function test_response_is_unchanged_when_count_is_unknown(): void + { + $controller = $this->controller(PinkRoccadeV2Controller::class); + $controller->shouldReceive('countResidents')->once()->andReturnNull(); + + $response = $this->invokeMethod($controller, 'addResidentsCountToResponse', [ + $this->form(['aantalBewoners']), + $this->person(), + ]); + + $this->assertArrayNotHasKey('aantalBewoners', $response); + } + + public function test_does_not_count_without_nummeraanduiding(): void + { + $controller = $this->controller(PinkRoccadeV2Controller::class); + $controller->shouldNotReceive('countResidents'); + + $person = $this->person(); + unset($person['verblijfplaats']['nummeraanduidingIdentificatie']); + + $response = $this->invokeMethod($controller, 'addResidentsCountToResponse', [$this->form(['aantalBewoners']), $person]); + + $this->assertSame($person, $response); + } + + /** + * @dataProvider v2ControllerProvider + */ + public function test_text_field_mapped_to_residents_count_is_prefilled(string $controllerClass): void + { + $controller = $this->controller($controllerClass); + $controller->shouldReceive('isBlockEditor')->andReturnFalse(); + $controller->shouldReceive('getBSN')->andReturn('999990019'); + $controller->shouldReceive('fetchApiResponse')->once()->andReturn($this->person()); + $controller->shouldReceive('disableFormFields')->andReturn(''); + $controller->shouldReceive('countResidents')->once()->with(self::ID, 'doelbinding', 'verwerking')->andReturn(3); + + WP_Mock::userFunction('rgar', [ + 'return' => function (array $form, string $key, $default = null) { + return $form[$key] ?? $default; + }, + ]); + + $form = $this->form(['aantalBewoners']); + $form['owc-iconnect-doelbinding'] = 'doelbinding'; + $form['owc-iconnect-processing'] = 'verwerking'; + + $result = $controller->handle($form); + + $this->assertSame('3', $result['fields'][0]->defaultValue); + $this->assertSame('owc_prefilled', $result['fields'][0]->cssClass); + } + + public static function v2ControllerProvider(): array + { + return [ + 'PinkRoccadeV2' => [PinkRoccadeV2Controller::class], + 'EnableUV2' => [EnableUV2Controller::class], + ]; + } + + /** + * @template T of BaseController + * + * @param class-string $class + * + * @return T&MockInterface + */ + private function controller(string $class): BaseController + { + WP_Mock::userFunction('get_option', ['return' => []]); + + /** @var T&MockInterface $controller */ + $controller = Mockery::mock($class)->makePartial()->shouldAllowMockingProtectedMethods(); + + $settings = new ReflectionProperty(BaseController::class, 'settings'); + $settings->setValue($controller, GravityFormsSettings::make()); + + return $controller; + } + + /** + * @param list $mappings + */ + private function form(array $mappings): array + { + $fields = array_map(function (string $mapping): GF_Field { + $field = new GF_Field(); + $field->type = 'text'; + $field->linkedFieldValue = $mapping; + + return $field; + }, $mappings); + + return ['fields' => $fields]; + } + + private function person(): array + { + $data = json_decode((string) file_get_contents(__DIR__ . '/../Fixtures/brp-v2-raadpleeg-persoon.json'), true); + + return is_array($data) ? $data : []; + } +} diff --git a/tests/Unit/Abstracts/PostControllerResidentsCountTest.php b/tests/Unit/Abstracts/PostControllerResidentsCountTest.php new file mode 100644 index 0000000..abc4ecd --- /dev/null +++ b/tests/Unit/Abstracts/PostControllerResidentsCountTest.php @@ -0,0 +1,258 @@ + 'https://brp.example.test/personen', + 'owc-iconnect-oin-number' => '00000001234567890000', + 'owc-iconnect-processing' => 'StandaardVerwerking', + 'owc-iconnect-goal-binding' => 'AlgemeneDoelbinding', + ]; + + public function setUp(): void + { + parent::setUp(); + + // The test without encryption key runs in a separate process where the constant must stay undefined. + if ('test_count_is_returned_without_encryption_key' !== $this->getName(false) && ! defined('PG_CACHE_ENCRYPTION_KEY')) { + define('PG_CACHE_ENCRYPTION_KEY', str_repeat('k', 32)); + } + } + + public function test_counts_residents_and_caches_only_the_count(): void + { + $controller = $this->controller(); + $controller->shouldReceive('executeCurlRequest')->once()->andReturn([ + 'status' => 200, + 'body' => $this->fixture('brp-v2-zoek-nummeraanduiding.json'), + ]); + $controller->shouldNotReceive('logException'); + + WP_Mock::userFunction('get_transient', ['return' => false]); + + $stored = null; + WP_Mock::userFunction('set_transient', [ + 'times' => 1, + 'args' => [hash('sha256', 'residents_count_' . self::ID), '*', HOUR_IN_SECONDS], + 'return' => function (string $key, string $value) use (&$stored): bool { + $stored = $value; + + return true; + }, + ]); + + $this->assertSame(3, $controller->countResidents(self::ID)); + $this->assertIsString($stored); + $this->assertSame(['count' => 3], EncryptionService::decrypt($stored)); + } + + public function test_returns_cached_count_without_request(): void + { + $controller = $this->controller(); + $controller->shouldNotReceive('executeCurlRequest'); + + WP_Mock::userFunction('get_transient', [ + 'args' => [hash('sha256', 'residents_count_' . self::ID)], + 'return' => EncryptionService::encrypt(['count' => 2]), + ]); + + $this->assertSame(2, $controller->countResidents(self::ID)); + } + + public function test_empty_persons_list_counts_as_zero(): void + { + $controller = $this->controller(); + $controller->shouldReceive('executeCurlRequest')->once()->andReturn(['status' => 200, 'body' => ['personen' => []]]); + + WP_Mock::userFunction('get_transient', ['return' => false]); + WP_Mock::userFunction('set_transient', ['times' => 1, 'return' => true]); + + $this->assertSame(0, $controller->countResidents(self::ID)); + } + + /** + * @dataProvider failedStatusProvider + */ + public function test_failed_status_returns_null_and_logs_without_caching(int $status): void + { + $controller = $this->controller(); + $controller->shouldReceive('executeCurlRequest')->once()->andReturn([ + 'status' => $status, + 'body' => ['title' => 'Probleem', 'detail' => 'Nummeraanduiding ' . self::ID . ' niet toegestaan'], + ]); + $controller->shouldReceive('logException')->once()->with(Mockery::on(function (Exception $e) use ($status): bool { + return sprintf('Residents count request failed with HTTP status %d.', $status) === $e->getMessage(); + })); + + WP_Mock::userFunction('get_transient', ['return' => false]); + WP_Mock::userFunction('set_transient', ['times' => 0]); + + $this->assertNull($controller->countResidents(self::ID)); + } + + public static function failedStatusProvider(): array + { + return [ + 'forbidden (goal binding)' => [403], + 'server error' => [500], + ]; + } + + public function test_request_exception_returns_null_and_logs_fixed_message(): void + { + $controller = $this->controller(); + $controller->shouldReceive('executeCurlRequest')->once()->andThrow(new Exception('Response body is not valid JSON.', 500)); + $controller->shouldReceive('logException')->once()->with(Mockery::on(function (Exception $e): bool { + return 'Response body is not valid JSON.' === $e->getMessage(); + })); + + WP_Mock::userFunction('get_transient', ['return' => false]); + WP_Mock::userFunction('set_transient', ['times' => 0]); + + $this->assertNull($controller->countResidents(self::ID)); + } + + /** + * @dataProvider invalidIdProvider + */ + public function test_invalid_id_returns_null_without_request(string $id): void + { + $controller = $this->controller(); + $controller->shouldNotReceive('executeCurlRequest'); + $controller->shouldNotReceive('logException'); + + $this->assertNull($controller->countResidents($id)); + } + + public static function invalidIdProvider(): array + { + return [ + 'empty' => [''], + 'letters' => ['abc'], + 'too short' => ['123'], + ]; + } + + public function test_requests_disabled_returns_null_without_request(): void + { + $controller = $this->controller(['owc-iconnect-disable-requests' => '1']); + $controller->shouldNotReceive('executeCurlRequest'); + + $this->assertNull($controller->countResidents(self::ID)); + } + + public function test_request_body_and_headers(): void + { + $controller = $this->controller(); + $captured = []; + $controller->shouldReceive('executeCurlRequest')->once()->with(Mockery::on(function (array $args) use (&$captured): bool { + $captured = $args; + + return true; + }))->andReturn(['status' => 200, 'body' => ['personen' => []]]); + + WP_Mock::userFunction('get_transient', ['return' => false]); + WP_Mock::userFunction('set_transient', ['return' => true]); + + $controller->countResidents(self::ID, 'BRPDoelbinding'); + + $this->assertSame( + '{"type":"ZoekMetNummeraanduidingIdentificatie","nummeraanduidingIdentificatie":"0599200000219678","fields":["burgerservicenummer"]}', + $captured[CURLOPT_POSTFIELDS] + ); + $this->assertSame(self::OPTIONS['owc-iconnect-base-url'], $captured[CURLOPT_URL]); + $this->assertContains('x-doelbinding: BRPDoelbinding', $captured[CURLOPT_HTTPHEADER]); + $this->assertContains('x-verwerking: StandaardVerwerking', $captured[CURLOPT_HTTPHEADER]); + } + + public function test_general_goal_binding_is_used_when_none_is_given(): void + { + $controller = $this->controller(); + $captured = []; + $controller->shouldReceive('executeCurlRequest')->once()->with(Mockery::on(function (array $args) use (&$captured): bool { + $captured = $args; + + return true; + }))->andReturn(['status' => 200, 'body' => ['personen' => []]]); + + WP_Mock::userFunction('get_transient', ['return' => false]); + WP_Mock::userFunction('set_transient', ['return' => true]); + + $controller->countResidents(self::ID); + + $this->assertContains('x-doelbinding: AlgemeneDoelbinding', $captured[CURLOPT_HTTPHEADER]); + } + + public function test_bsn_cache_keys_are_never_used(): void + { + $controller = $this->controller(); + $controller->shouldReceive('executeCurlRequest')->andReturn([ + 'status' => 200, + 'body' => $this->fixture('brp-v2-zoek-nummeraanduiding.json'), + ]); + + $residentsKey = hash('sha256', 'residents_count_' . self::ID); + WP_Mock::userFunction('get_transient', ['times' => 1, 'args' => [$residentsKey], 'return' => false]); + WP_Mock::userFunction('set_transient', ['times' => 1, 'args' => [$residentsKey, '*', '*'], 'return' => true]); + + $this->assertSame(3, $controller->countResidents(self::ID)); + } + + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function test_count_is_returned_without_encryption_key(): void + { + $controller = $this->controller(); + $controller->shouldReceive('executeCurlRequest')->once()->andReturn([ + 'status' => 200, + 'body' => $this->fixture('brp-v2-zoek-nummeraanduiding.json'), + ]); + $controller->shouldReceive('logException')->once(); + + WP_Mock::userFunction('get_transient', ['return' => false]); + WP_Mock::userFunction('set_transient', ['times' => 0]); + + $this->assertSame(3, $controller->countResidents(self::ID)); + } + + /** + * @return PinkRoccadeV2Controller&MockInterface + */ + private function controller(array $options = []): PinkRoccadeV2Controller + { + WP_Mock::userFunction('get_option', ['return' => $options + self::OPTIONS]); + + /** @var PinkRoccadeV2Controller&MockInterface $controller */ + $controller = Mockery::mock(PinkRoccadeV2Controller::class)->makePartial()->shouldAllowMockingProtectedMethods(); + + $settings = new ReflectionProperty(BaseController::class, 'settings'); + $settings->setValue($controller, GravityFormsSettings::make()); + + return $controller; + } + + private function fixture(string $name): array + { + $data = json_decode((string) file_get_contents(__DIR__ . '/../Fixtures/' . $name), true); + + return is_array($data) ? $data : []; + } +} diff --git a/tests/Unit/Fixtures/brp-v1-ingeschrevenpersoon.json b/tests/Unit/Fixtures/brp-v1-ingeschrevenpersoon.json new file mode 100644 index 0000000..6c502e7 --- /dev/null +++ b/tests/Unit/Fixtures/brp-v1-ingeschrevenpersoon.json @@ -0,0 +1,18 @@ +{ + "burgerservicenummer": "999990019", + "leeftijd": 42, + "naam": { + "voornamen": "Voorbeeld", + "voorletters": "V.", + "geslachtsnaam": "Testpersoon" + }, + "verblijfplaats": { + "straat": "Voorbeeldstraat", + "huisnummer": 31, + "huisletter": "A", + "huisnummertoevoeging": "2", + "postcode": "1234AB", + "woonplaats": "Voorbeeldstad", + "identificatiecodeNummeraanduiding": "0599200000219678" + } +} diff --git a/tests/Unit/Fixtures/brp-v2-raadpleeg-persoon.json b/tests/Unit/Fixtures/brp-v2-raadpleeg-persoon.json new file mode 100644 index 0000000..1135570 --- /dev/null +++ b/tests/Unit/Fixtures/brp-v2-raadpleeg-persoon.json @@ -0,0 +1,22 @@ +{ + "burgerservicenummer": "999990019", + "leeftijd": 42, + "naam": { + "voornamen": "Voorbeeld", + "voorletters": "V.", + "geslachtsnaam": "Testpersoon" + }, + "verblijfplaats": { + "type": "Adres", + "verblijfadres": { + "officieleStraatnaam": "Voorbeeldstraat", + "korteStraatnaam": "Voorbeeldstr", + "huisnummer": 31, + "huisletter": "A", + "huisnummertoevoeging": "2", + "postcode": "1234AB", + "woonplaats": "Voorbeeldstad" + }, + "nummeraanduidingIdentificatie": "0599200000219678" + } +} diff --git a/tests/Unit/Fixtures/brp-v2-zoek-nummeraanduiding.json b/tests/Unit/Fixtures/brp-v2-zoek-nummeraanduiding.json new file mode 100644 index 0000000..de22c85 --- /dev/null +++ b/tests/Unit/Fixtures/brp-v2-zoek-nummeraanduiding.json @@ -0,0 +1,8 @@ +{ + "type": "ZoekMetNummeraanduidingIdentificatie", + "personen": [ + { "burgerservicenummer": "999990019" }, + { "burgerservicenummer": "999990020" }, + { "burgerservicenummer": "999990031" } + ] +} diff --git a/tests/Unit/Models/UserModelTest.php b/tests/Unit/Models/UserModelTest.php new file mode 100644 index 0000000..035fa18 --- /dev/null +++ b/tests/Unit/Models/UserModelTest.php @@ -0,0 +1,205 @@ +userModel($this->fixture('brp-v2-raadpleeg-persoon.json')); + + $this->assertSame('1234AB', $user->zipcode()); + $this->assertSame('31', $user->houseNumber()); + $this->assertSame('A', $user->houseLetter()); + $this->assertSame('2', $user->houseNumberAddition()); + $this->assertSame('Voorbeeldstraat', $user->street()); + $this->assertSame('Voorbeeldstad', $user->city()); + $this->assertSame('0599200000219678', $user->nummeraanduidingIdentificatie()); + } + + public function test_v1_address_getters_are_unchanged(): void + { + $user = $this->userModel($this->fixture('brp-v1-ingeschrevenpersoon.json')); + + $this->assertSame('1234AB', $user->zipcode()); + $this->assertSame('31', $user->houseNumber()); + $this->assertSame('A', $user->houseLetter()); + $this->assertSame('2', $user->houseNumberAddition()); + $this->assertSame('Voorbeeldstraat', $user->street()); + $this->assertSame('Voorbeeldstad', $user->city()); + $this->assertSame('0599200000219678', $user->nummeraanduidingIdentificatie()); + } + + public function test_v1_alternative_street_and_city_keys(): void + { + $user = $this->userModel(['verblijfplaats' => ['straatnaam' => 'Laan', 'woonplaatsnaam' => 'Dorp']]); + + $this->assertSame('Laan', $user->street()); + $this->assertSame('Dorp', $user->city()); + } + + public function test_v2_path_takes_precedence_over_v1_path(): void + { + $user = $this->userModel([ + 'verblijfplaats' => [ + 'postcode' => '9999ZZ', + 'verblijfadres' => ['postcode' => '1234AB'], + ], + ]); + + $this->assertSame('1234AB', $user->zipcode()); + } + + public function test_empty_data_returns_empty_strings(): void + { + $user = $this->userModel([]); + + foreach (self::ADDRESS_GETTERS as $getter) { + $this->assertSame('', $user->{$getter}(), $getter); + } + } + + public function test_location_without_address_returns_empty_strings(): void + { + $user = $this->userModel([ + 'verblijfplaats' => [ + 'type' => 'Locatie', + 'verblijfadres' => ['locatiebeschrijving' => 'Woonboot bij de brug'], + ], + ]); + + foreach (self::ADDRESS_GETTERS as $getter) { + $this->assertSame('', $user->{$getter}(), $getter); + } + } + + /** + * @dataProvider invalidNummeraanduidingProvider + */ + public function test_invalid_nummeraanduiding_returns_empty_string(mixed $value): void + { + $user = $this->userModel(['verblijfplaats' => ['nummeraanduidingIdentificatie' => $value]]); + + $this->assertSame('', $user->nummeraanduidingIdentificatie()); + } + + public static function invalidNummeraanduidingProvider(): array + { + return [ + 'letters' => ['abc'], + 'too short' => ['123'], + 'too long' => ['05992000002196789'], + 'array' => [['0599200000219678']], + 'null' => [null], + 'bool' => [true], + ]; + } + + public function test_non_array_verblijfplaats_does_not_throw(): void + { + $user = $this->userModel(['verblijfplaats' => 'onbekend']); + + foreach (self::ADDRESS_GETTERS as $getter) { + $this->assertSame('', $user->{$getter}(), $getter); + } + } + + public function test_residents_count_uses_v2_controller_and_is_memoized(): void + { + $this->mockSettings(['owc-iconnect-goal-binding' => 'BRPDoelbinding', 'owc-iconnect-processing' => 'Verwerking']); + + $controller = Mockery::mock(PinkRoccadeV2Controller::class); + $controller->shouldReceive('countResidents') + ->once() + ->with('0599200000219678', 'BRPDoelbinding', 'Verwerking') + ->andReturn(3); + + $user = $this->userModel($this->fixture('brp-v2-raadpleeg-persoon.json'), $controller); + + $this->assertSame(3, $user->residentsCount()); + $this->assertSame(3, $user->residentsCount()); + } + + public function test_residents_count_is_null_for_v1_supplier(): void + { + $controller = Mockery::mock(PinkRoccadeController::class); + $controller->shouldNotReceive('countResidents'); + + $user = $this->userModel($this->fixture('brp-v1-ingeschrevenpersoon.json'), $controller); + + $this->assertNull($user->residentsCount()); + } + + public function test_residents_count_is_null_without_controller(): void + { + $user = $this->userModel($this->fixture('brp-v2-raadpleeg-persoon.json')); + + $this->assertNull($user->residentsCount()); + } + + public function test_residents_count_is_null_when_not_logged_in(): void + { + $data = $this->fixture('brp-v2-raadpleeg-persoon.json'); + unset($data['burgerservicenummer']); + + $controller = Mockery::mock(PinkRoccadeV2Controller::class); + $controller->shouldNotReceive('countResidents'); + + $this->assertNull($this->userModel($data, $controller)->residentsCount()); + } + + public function test_residents_count_is_null_without_nummeraanduiding(): void + { + $data = $this->fixture('brp-v2-raadpleeg-persoon.json'); + unset($data['verblijfplaats']['nummeraanduidingIdentificatie']); + + $controller = Mockery::mock(PinkRoccadeV2Controller::class); + $controller->shouldNotReceive('countResidents'); + + $this->assertNull($this->userModel($data, $controller)->residentsCount()); + } + + private function userModel(array $data, ?BaseController $controller = null): UserModel + { + return new class($data, $controller) extends UserModel { + public function __construct(array $data, ?BaseController $controller) + { + $this->data = $data; + $this->controller = $controller; + } + }; + } + + private function mockSettings(array $options): void + { + WP_Mock::userFunction('get_option', ['return' => $options]); + } + + private function fixture(string $name): array + { + $contents = file_get_contents(__DIR__ . '/../Fixtures/' . $name); + $data = json_decode((string) $contents, true); + + return is_array($data) ? $data : []; + } +} diff --git a/tests/Unit/Services/PersonalDataServiceTest.php b/tests/Unit/Services/PersonalDataServiceTest.php new file mode 100644 index 0000000..24bc912 --- /dev/null +++ b/tests/Unit/Services/PersonalDataServiceTest.php @@ -0,0 +1,115 @@ +makePartial(); + $controller->shouldReceive('get')->with('doelbinding', '')->andReturn($this->person()); + $controller->shouldReceive('countResidents')->once()->with(self::ID, 'doelbinding', '')->andReturn(3); + + $this->assertSame('3', $this->service($controller)->get('aantalBewoners', 'doelbinding')); + } + + public static function v2ControllerProvider(): array + { + return [ + 'PinkRoccadeV2' => [PinkRoccadeV2Controller::class], + 'EnableUV2' => [EnableUV2Controller::class], + ]; + } + + public function test_residents_count_is_empty_for_v1_supplier(): void + { + $controller = Mockery::mock(PinkRoccadeController::class)->makePartial(); + $controller->shouldNotReceive('get'); + + $this->assertSame('', $this->service($controller)->get('aantalBewoners')); + } + + public function test_residents_count_is_empty_without_controller(): void + { + $this->assertSame('', $this->service(null)->get('aantalBewoners')); + } + + public function test_residents_count_is_empty_without_session(): void + { + $controller = Mockery::mock(PinkRoccadeV2Controller::class)->makePartial(); + $controller->shouldReceive('get')->andReturn([]); + $controller->shouldNotReceive('countResidents'); + + $this->assertSame('', $this->service($controller)->get('aantalBewoners')); + } + + public function test_residents_count_is_empty_without_nummeraanduiding(): void + { + $person = $this->person(); + unset($person['verblijfplaats']['nummeraanduidingIdentificatie']); + + $controller = Mockery::mock(PinkRoccadeV2Controller::class)->makePartial(); + $controller->shouldReceive('get')->andReturn($person); + $controller->shouldNotReceive('countResidents'); + + $this->assertSame('', $this->service($controller)->get('aantalBewoners')); + } + + public function test_residents_count_is_empty_when_count_is_unknown(): void + { + $controller = Mockery::mock(PinkRoccadeV2Controller::class)->makePartial(); + $controller->shouldReceive('get')->andReturn($this->person()); + $controller->shouldReceive('countResidents')->once()->andReturnNull(); + + $this->assertSame('', $this->service($controller)->get('aantalBewoners')); + } + + public function test_other_keys_are_unchanged(): void + { + $controller = Mockery::mock(PinkRoccadeV2Controller::class)->makePartial(); + $controller->shouldReceive('get')->andReturn($this->person()); + $controller->shouldNotReceive('countResidents'); + + $service = $this->service($controller); + + $this->assertSame('1234AB', $service->get('verblijfplaats.postcode')); + $this->assertSame('Voorbeeldstraat', $service->get('verblijfplaats.straat')); + $this->assertSame('31', $service->get('verblijfplaats.huisnummer')); + } + + private function service(?BaseController $controller): PersonalDataService + { + WP_Mock::userFunction('get_option', ['return' => []]); + + $service = new PersonalDataService('PinkRoccadeV2'); + + $property = new ReflectionProperty(PersonalDataService::class, 'controller'); + $property->setValue($service, $controller); + + return $service; + } + + private function person(): array + { + $data = json_decode((string) file_get_contents(__DIR__ . '/../Fixtures/brp-v2-raadpleeg-persoon.json'), true); + + return is_array($data) ? $data : []; + } +} diff --git a/tests/Unit/bootstrap.php b/tests/Unit/bootstrap.php index 3526a8e..75403d5 100644 --- a/tests/Unit/bootstrap.php +++ b/tests/Unit/bootstrap.php @@ -20,6 +20,10 @@ define('WP_PLUGIN_DIR', __DIR__); define('WP_DEBUG', false); +if (! defined('HOUR_IN_SECONDS')) { + define('HOUR_IN_SECONDS', 3600); +} + /** * Bootstrap WordPress Mock. */