PHP code example of openstudio / query-builder-bundle

1. Go to this page and download the library: Download openstudio/query-builder-bundle 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/ */

    

openstudio / query-builder-bundle example snippets


// config/bundles.php
return [
    // ...
    OpenStudio\QueryBuilderBundle\OpenStudioQueryBuilderBundle::class => ['all' => true],
];

use OpenStudio\QueryBuilderBundle\Dto\Field;
use OpenStudio\QueryBuilderBundle\Enum\ValueType;
use OpenStudio\QueryBuilderBundle\Form\QueryBuilderType;

$builder->add('conditions', QueryBuilderType::class, [
    'fields' => [
        new Field(name: 'email', label: 'Email'),
        new Field(name: 'total_orders', type: ValueType::Number, label: 'Total orders'),
    ],
]);

new Field(
    name: 'created_at',          // identifier used in the output tree (to ValueType::Text
    label: 'Creation date',      // shown in the field select, defaults to the name
    labelInformation: 'UTC',     // appended to the label in parentheses
    values: null,                // fixed list of FieldOption, see below
    operators: null,             // its own list of operators, see Per-field operators below
);

['name' => 'created_at', 'type' => 'date', 'label' => 'Creation date']

use OpenStudio\QueryBuilderBundle\Dto\FieldOption;

new Field(
    name: 'status',
    label: 'Status',
    values: [
        new FieldOption(name: 'draft'),
        new FieldOption(name: 'published', label: 'Published'),
        new FieldOption(name: 'archived', label: 'Archived', value: '3'),
    ],
);

values: [
    ['name' => 'published', 'label' => 'Published'],
    ['name' => 'archived', 'label' => 'Archived', 'value' => '3'],
],
// or
values: ['draft' => 'Draft', 'published' => 'Published'],

use OpenStudio\QueryBuilderBundle\Enum\Operator;

$builder->add('conditions', QueryBuilderType::class, [
    'fields' => $fields,
    'operators' => [Operator::Equal, Operator::NotEqual, Operator::Contains, Operator::Null],
]);

'operators' => ['=', '!=', 'contains', 'null'],

'operators' => [Operator::ValuesList, Operator::Null],

new Field(
    name: 'total_orders',
    type: ValueType::Number,
    operators: [Operator::Equal, Operator::In, Operator::NotIn],
),

use OpenStudio\QueryBuilderBundle\Enum\QueryBuilderProcessor;
use OpenStudio\QueryBuilderBundle\Form\QueryBuilderType;

$builder->add('conditions', QueryBuilderType::class, [
    'fields' => $fields,
    'processor' => QueryBuilderProcessor::Parameterized,
]);

$builder->add('conditions', QueryBuilderType::class, [
    'lang' => 'en',
    // ...
]);

// src/Form/SegmentType.php
use OpenStudio\QueryBuilderBundle\Dto\Field;
use OpenStudio\QueryBuilderBundle\Dto\FieldOption;
use OpenStudio\QueryBuilderBundle\Enum\ValueType;
use OpenStudio\QueryBuilderBundle\Form\QueryBuilderType;

final class SegmentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('name', TextType::class)
            ->add('conditions', QueryBuilderType::class, [
                'fields' => [
                    new Field(name: 'email', label: 'Email'),
                    new Field(name: 'total_orders', type: ValueType::Number, label: 'Total orders'),
                    new Field(name: 'created_at', type: ValueType::Date, label: 'Sign-up date'),
                    new Field(name: 'newsletter', type: ValueType::Boolean, label: 'Newsletter opt-in'),
                    new Field(
                        name: 'status',
                        label: 'Status',
                        values: [
                            new FieldOption(name: 'active', label: 'Active'),
                            new FieldOption(name: 'inactive', label: 'Inactive'),
                            new FieldOption(name: 'banned', label: 'Banned'),
                        ],
                    ),
                ],
            ]);
    }
}

#[Route('/segments/new', name: 'segment_new', methods: ['GET', 'POST'])]
public function new(Request $request, EntityManagerInterface $entityManager): Response
{
    $segment = new Segment();
    $form = $this->createForm(SegmentType::class, $segment);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        // $segment->getConditions() holds the JsonLogic tree as an array, or null when the
        // builder was left empty. It only mentions declared fields and operators: a tree that
        // stepped outside them made the form invalid (see the Security section).
        $entityManager->persist($segment);
        $entityManager->flush();

        return $this->redirectToRoute('segment_list');
    }

    return $this->render('segment/new.html.twig', ['form' => $form]);
}

->add('conditions', QueryBuilderType::class, [
    'mapped' => false,
    'processor' => QueryBuilderProcessor::Parameterized,
    'fields' => [/* same fields as above */],
])

if ($form->isSubmitted() && $form->isValid()) {
    // null when the builder was left empty, otherwise the two parts below.
    $data = $form->get('conditions')->getData();

    // The value to persist: the JsonLogic tree, already checked against the declared fields and
    // operators, see the Security section.
    $conditionTree = $data['conditionTree'] ?? null;
    $segment->setConditions(is_array($conditionTree) ? $conditionTree : null);

    // ['sql' => '...', 'params' => [...]], untrusted browser input: log it,
    // display it as a preview, but never execute it as-is.
    $parameterizedSql = $data['parameterizedSql'] ?? null;

    $entityManager->persist($segment);
    $entityManager->flush();

    return $this->redirectToRoute('segment_list');
}

->add('conditions', QueryBuilderType::class, [
    'processor' => QueryBuilderProcessor::Native,
    'fields' => [/* same fields as above */],
])

use JWadhams\JsonLogic;
use OpenStudio\QueryBuilderBundle\Service\JsonLogicOperations;

JsonLogicOperations::register(JsonLogic::add_operation(...));

$belongsToSegment = JsonLogic::apply($segment->getConditions(), $customer);

$builder->add('conditions', QueryBuilderType::class, [
    'fields' => $fields,
    'validate_condition_tree' => false,
]);

use OpenStudio\QueryBuilderBundle\Enum\Operator;
use OpenStudio\QueryBuilderBundle\Service\ConditionTreeValidator;

// Same guarantee outside a form: validating a tree read back from storage.
$validator = new ConditionTreeValidator(['email', 'total_orders'], Operator::cases());
$validator->assertValid($segment->getConditions());