Completed
Push — componentlibrary ( 67a692...eed31d )
by Doğa
01:48
created

timberLoader.php ➔ formatGallery()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
1
<?php
2
/**
3
 * - Enables rendering with Timber and Twig.
4
 * - Converts ACF Images to Timber Images if ACF is enabled.
5
 * - Convert ACF Field of type post_object to a Timber\Post and add all ACF Fields of that Post
6
 */
7
namespace Flynt\TimberLoader;
8
9
use Flynt\Utils\TwigExtensionFlynt;
10
use Flynt;
11
use Timber\Image;
12
use Timber\Post;
13
use Timber\Timber;
14
use Twig_SimpleFunction;
15
16
define(__NAMESPACE__ . '\NS', __NAMESPACE__ . '\\');
17
18
// Convert ACF Images to Timber Images
19
add_filter('acf/format_value/type=image', NS . 'formatImage', 100);
20
21
// Convert ACF Gallery Images to Timber Images
22
add_filter('acf/format_value/type=gallery', NS . 'formatGallery', 100);
23
24
// Convert ACF Field of type post_object to a Timber\Post and add all ACF Fields of that Post
25
add_filter('acf/format_value/type=post_object', NS . 'formatPostObject', 100);
26
27
// Convert ACF Field of type relationship to a Timber\Post and add all ACF Fields of that Post
28
add_filter('acf/format_value/type=relationship', NS . 'formatPostObject', 100);
29
add_filter('get_twig', function ($twig) {
30
    $twig->addExtension(new TwigExtensionFlynt());
31
    return $twig;
32
});
33
34
function formatImage($value)
35
{
36
    if (!empty($value)) {
37
        $value = new Image($value);
38
    }
39
    return $value;
40
}
41
42
function formatGallery($value)
43
{
44
    if (!empty($value)) {
45
        $value = array_map(function ($image) {
46
            return new Image($image);
47
        }, $value);
48
    }
49
    return $value;
50
}
51
52
function formatPostObject($value)
53
{
54
    if (is_array($value)) {
55
        $value = array_map(NS . 'convertToTimberPost', $value);
56
    } else {
57
        $value = convertToTimberPost($value);
58
    }
59
    return $value;
60
}
61
62
function convertToTimberPost($value)
63
{
64
    if (!empty($value) && is_object($value) && get_class($value) === 'WP_Post') {
65
        $value = new Post($value);
66
    }
67
    return $value;
68
}
69
70
add_action('timber/twig/filters', function ($twig) {
71
    $twig->addFunction(new \Twig_SimpleFunction('placeholderImage', function ($width, $height, $color = null) {
72
        $width = round($width);
73
        $height = round($height);
74
        $colorRect = $color ? "<rect width='{$width}' height='{$height}' style='fill:$color' />" : '';
75
        $svg = "<svg width='{$width}' height='{$height}' xmlns='http://www.w3.org/2000/svg'>{$colorRect}</svg>";
76
        return "data:image/svg+xml;base64," . base64_encode($svg);
77
    }));
78
79
    return $twig;
80
});
81