PHP code example of helsingborg-stad / acfservice

1. Go to this page and download the library: Download helsingborg-stad/acfservice library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

helsingborg-stad / acfservice example snippets


use AcfService\Implementations\NativeAcfService;

$acfService = new NativeAcfService();
$fields = $acfService->getFields(123);

use AcfService\Contracts\GetFields;

class MyService
{
    public function __construct(private GetFields $acfService)
    {
    }

    public function getFields(): int
    {
        return $this->acfService->getFields();
    }
}

use AcfService\Implementations\FakeAcfService;
use PHPUnit\Framework\TestCase;

class MyServiceTest extends TestCase
{
    public function testGetFields()
    {
        // Given
        $fakeAcfService = new FakeAcfService(['getFields' => ['fieldName' => 'fieldValue']]);
        $myService = new MyService($fakeAcfService);

        // When
        $fields = $myService->getFields();

        // Then
        $this->assertEquals([], $acfService->methodCalls['getFields'][0]);
        $this->assertEquals(['fieldName' => 'fieldValue'], $fields);
    }
}

# Using a generic return value for all calls to the method.
$fakeAcfService = new FakeAcfService(['getFields' => ['field' => 'value']]);
$fakeAcfService->getFields(); // Returns ['field' => 'value']
$fakeAcfService->getFields(321); // Returns ['field' => 'value']
$fakeAcfService->getFields(123); // Returns ['field' => 'value']

# Using a callback to determine the return value based on the arguments passed to the method.
$return         = fn($postId) => $postId === 123 ? ['field' => 'value'] : [];
$fakeAcfService = new FakeAcfService(['getFields' => $return]);
$fakeAcfService->getFields(); // Returns false
$fakeAcfService->getFields(321); // Returns false
$fakeAcfService->getFields(123); // Returns ['field' => 'value']