Skip to content

Instantly share code, notes, and snippets.

@jwage jwage/pseudo-code.php Secret
Last active Sep 21, 2017

Embed
What would you like to do?
This is pseudo code to demonstrate a problem
<?php
$rules = [
[
'id' => 1,
'expression' => 'x = 1 AND y = 2 AND userLogCount <= 5',
],
];
$expressionLanguage = $container->get('expression_language');
$context = [
'x' => 1,
'y' => 2,
];
$userId = 1;
foreach ($rules as $rule) {
$context['userLogCount'] = exec('SELECT COUNT(*) FROM reward_log WHERE ruleId = :ruleId AND userId = :userId', [
'ruleId' => $rule['id'],
'userId' => $userId
]);
if ($expressionLanguage->evaluate($rule['expression'], $context)) {
$rule->insertLogEntry();
$rule->executeAction();
}
}
@jwage

This comment has been minimized.

Copy link
Owner Author

commented Sep 21, 2017

This is the only way I can think of to avoid the problem by implementing some kind of atomic locking per userId using redis or something.

<?php

$userId = 1;

takeOrWaitForLock($userId);

$rules = [
    [
        'id' => 1,
        'expression' => 'x = 1 AND y = 2 AND userLogCount <= 5',
    ],
];

$expressionLanguage = $container->get('expression_language');

$context = [
    'x' => 1,
    'y' => 2,
];

foreach ($rules as $rule) {

    $context['userLogCount'] = exec('SELECT COUNT(*) FROM reward_log WHERE ruleId = :ruleId AND userId = :userId', [
        'ruleId' => $rule['id'],
        'userId' => $userId
    ]);

    if ($expressionLanguage->evaluate($rule, $context)) {
        $rule->insertLogEntry();

        $rule->executeAction();
    }    
}

releaseLock($userId);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.