Skip to content

Instantly share code, notes, and snippets.

@FatBoyXPC
Last active August 12, 2019 21:31
Show Gist options
  • Select an option

  • Save FatBoyXPC/0d44c802494d77d09c3470d81da22772 to your computer and use it in GitHub Desktop.

Select an option

Save FatBoyXPC/0d44c802494d77d09c3470d81da22772 to your computer and use it in GitHub Desktop.
callback example
<?php
class Foo
{
public function checkFacebookCode($jobId)
{
return $this->checkCode($jobId, function ($job) {
return $job->facebook->sortByDesc('id')->first()->checkForCodeAtUrl();
});
}
private function checkCode($jobId, $callback)
{
$job = Job::findOrFail($jobId);
$response = [];
try {
$response['code_found'] = $callback($job);
$status = 200;
} catch (Exception $e) {
$status = 500;
}
return response()->json($response, $status);
}
public function checkRemarketingCode($jobId)
{
return $this->checkCode($jobId, function ($job) {
return $job->remarketing->sortByDesc('id')->first()->checkForCodeAtUrl();
});
}
// from another project:
public function updateRecords($beforeCallback, $afterCallback)
{
$db = Database::factory()->mysqli();
$table = Payment::$TABLE;
$sql = "UPDATE {$table} SET type = '%s' where id = %s";
$this->walkRecords(function ($record) use ($db, $sql, $beforeCallback, $afterCallback) {
$beforeCallback($record);
$payment = new Payment;
$payment->id = $record['id'];
$payment->type = $record['type'];
$payment->token_id = $record['token_id'];
$payment->card_type = $record['card_type'];
$query = sprintf($sql, $payment->getPaymentType(), $payment->getId());
$result = $db->query($query);
$afterCallback($record);
// Hoping that GC might pick this up and we don't blow up memory
unset($payment, $record);
});
}
public function walkRecords($callback)
{
$payments = [];
$db = Database::factory()->mysqli();
$query = $db->query($this->sql());
while ($row = mysqli_fetch_assoc($query)) {
$callback($row);
}
}
protected function execute(InputInterface $input, OutputInterface $output)
{
set_time_limit(0);
$beforeCallback = function ($record) use ($output) {
$output->writeln("Starting: {$record['id']}");
};
$afterCallback = function ($record) use ($output) {
$output->writeln("Finished: {$record['id']}");
};
$this->updateRecords($beforeCallback, $afterCallback);
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment