1<?php
2
3namespace ILIAS\BackgroundTasks\Implementation\TaskManager;
4
5use ILIAS\BackgroundTasks\Bucket;
6use ILIAS\BackgroundTasks\Implementation\Bucket\State;
7use ILIAS\BackgroundTasks\Implementation\Tasks\UserInteraction\UserInteractionRequiredException;
8use ILIAS\BackgroundTasks\Implementation\Tasks\UserInteraction\UserInteractionSkippedException;
9use ILIAS\BackgroundTasks\Persistence;
10
11/**
12 * Class BasicTaskManager
13 *
14 * @package ILIAS\BackgroundTasks\Implementation
15 *
16 * @author  Oskar Truffer <ot@studer-raimann.ch>
17 *
18 * Basic Task manager. Will execute tasks immediately.
19 *
20 * Some important infos:
21 *         - The bucket and its tasks are not saved into the db upon execution
22 *         - The percentage and current task are not updated during execution.
23 *         - The bucket and its tasks inkl. percentage and current task are only saved into the DB
24 *         when a user interaction occurs.
25 *
26 */
27class SyncTaskManager extends BasicTaskManager
28{
29
30    /**
31     * @var Persistence
32     */
33    protected $persistence;
34
35
36    public function __construct(Persistence $persistence)
37    {
38        $this->persistence = $persistence;
39    }
40
41
42    /**
43     * This will add an Observer of the Task and start running the task.
44     *
45     * @param Bucket $bucket
46     *
47     * @return mixed|void
48     * @throws \Exception
49     *
50     */
51    public function run(Bucket $bucket)
52    {
53        $task = $bucket->getTask();
54        $bucket->setCurrentTask($task);
55        $observer = new NonPersistingObserver($bucket);
56
57        try {
58            $this->executeTask($task, $observer);
59            $bucket->setState(State::FINISHED);
60        } catch (UserInteractionSkippedException $e) {
61            $bucket->setState(State::FINISHED);
62        } catch (UserInteractionRequiredException $e) {
63            // We're okay!
64            $this->persistence->saveBucketAndItsTasks($bucket);
65        }
66    }
67}
68