summaryrefslogtreecommitdiffstats
path: root/plugins/apachesolr_context_conditions_context_condition_max_results.inc
blob: 116579154fb358744e6dae4c7f137119bef85001 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php

/**
 * Expose paths as a context condition.
 */
class apachesolr_context_conditions_context_condition_max_results extends context_condition {

  // If we just set the value to zero then context will helpfully delete it
  // http://drupal.org/node/1842566
  const FAKE_ZERO = 'FAKE ZERO';
  
  /**
   * Omit condition values. We will provide a custom input form for our conditions.
   */
  function condition_values() {
    return array();
  }

  /**
   * Condition form.
   */
  function condition_form($context) {
    $form = parent::condition_form($context);
    unset($form['#options']);

    $form['#type'] = 'textfield';
    $form['#default_value'] = implode("\n", $this->fetch_from_context($context, 'values'));
    if ($form['#default_value'] == self::FAKE_ZERO) {
      $form['#default_value'] = 0;
    }
    $form['#description'] = 'Set this context when there are no more than the above number of results returned by the last Apachesolr search. Particularly useful to provide no results messages by setting it to 0.';
    return $form;
  }

  /**
   * Condition form submit handler.
   */
  function condition_form_submit($values) {
    $parsed = array();
    $items = explode("\n", $values);
    if (count($items)) {
      foreach ($items as $v) {
        if ($v === '0') {
          $v = self::FAKE_ZERO;
        }
        $parsed[$v] = trim($v);
      }
    }
    return $parsed;
  }

  /**
   * Execute.
   */
  function execute($num_results = 0) {
    if ($this->condition_used()) {
      foreach ($this->get_contexts() as $context) {
        $required_max = $this->fetch_from_context($context, 'values');
        if (array_pop($required_max) == self::FAKE_ZERO) {
          $required_max = 0;
        }
        if ($num_results <= $required_max) {
          $this->condition_met($context);
        }
      }
    }
  }
}