1<?php
2
3namespace Cron;
4
5use InvalidArgumentException;
6
7/**
8 * CRON field factory implementing a flyweight factory
9 * @link http://en.wikipedia.org/wiki/Cron
10 */
11class FieldFactory
12{
13    /**
14     * @var array Cache of instantiated fields
15     */
16    private $fields = array();
17
18    /**
19     * Get an instance of a field object for a cron expression position
20     *
21     * @param int $position CRON expression position value to retrieve
22     *
23     * @return FieldInterface
24     * @throws InvalidArgumentException if a position is not valid
25     */
26    public function getField($position)
27    {
28        if (!isset($this->fields[$position])) {
29            switch ($position) {
30                case 0:
31                    $this->fields[$position] = new MinutesField();
32                    break;
33                case 1:
34                    $this->fields[$position] = new HoursField();
35                    break;
36                case 2:
37                    $this->fields[$position] = new DayOfMonthField();
38                    break;
39                case 3:
40                    $this->fields[$position] = new MonthField();
41                    break;
42                case 4:
43                    $this->fields[$position] = new DayOfWeekField();
44                    break;
45                case 5:
46                    $this->fields[$position] = new YearField();
47                    break;
48                default:
49                    throw new InvalidArgumentException(
50                        $position . ' is not a valid position'
51                    );
52            }
53        }
54
55        return $this->fields[$position];
56    }
57}
58