BuildVFI   A
last analyzed

Complexity

Total Complexity 27

Size/Duplication

Total Lines 109
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 6

Importance

Changes 8
Bugs 1 Features 5
Metric Value
wmc 27
c 8
b 1
f 5
lcom 0
cbo 6
dl 0
loc 109
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
B old_run() 0 36 5
C run() 0 56 20
A runFrom() 0 6 2
1
<?php
2
/**
3
 * Rebuilds all VirtualFieldIndexes
4
 *
5
 * @author Mark Guinn <[email protected]>
6
 * @date 9.26.13
7
 * @package shop_search
8
 * @subpackage tasks
9
 */
10
class BuildVFI extends BuildTask
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
11
{
12
	protected $title = 'Rebuild Virtual Field Indexes';
13
	protected $description = 'Rebuild all VFI fields on all tables and records.';
14
15
	static $recordsPerRequest = 200;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $recordsPerRequest.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
16
17
	function old_run($request) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
18
		$classes = VirtualFieldIndex::get_classes_with_vfi();
19
		ini_set('memory_limit', '1G');
20
		$start = (int)$request->requestVar('start');
21
		$n = $start;
22
23
		// rebuild the indexes
24
		foreach ($classes as $c) {
25
			echo "Rebuilding $c...";
26
			$list   = DataObject::get($c);
27
			$count  = $list->count();
28
			for ($i = $n; $i < $count; $i += 10) {
29
				$chunk = $list->limit(10, $i);
30
				if (Controller::curr() instanceof TaskRunner) echo "Processing VFI #$i...\n";
31
				foreach ($chunk as $rec) $rec->rebuildVFI();
32
			}
33
			VirtualFieldIndex::build($c);
34
35
//			echo "Republishing changed records...";
0 ignored issues
show
Unused Code Comprehensibility introduced by
52% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
36
//			$list   = DataObject::get($c);
37
//			$count  = $list->count();
38
//			for ($i = 0; $i < $count; $i += 10) {
39
//				$chunk = $list->limit(10, $i);
40
//				foreach ($chunk as $rec) {
41
//					if ($rec->isPublished()) {
42
//						$rec->publish('Stage', 'Live');
43
//						$rec->flushCache();
44
//					}
45
//				}
46
//			}
47
48
			echo "<br>\n";
49
		}
50
51
		echo "Task complete.\n\n";
52
	}
53
54
	function run($request) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Coding Style introduced by
run uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
55
		increase_time_limit_to();
56
		$self = get_class($this);
57
		$verbose = isset($_GET['verbose']);
58
59
		if (isset($_GET['class']) && isset($_GET['id'])) {
60
			$item = DataObject::get($_GET['class'])->byID($_GET['id']);
61
			if (!$item || !$item->exists()) die('not found: ' . $_GET['id']);
0 ignored issues
show
Coding Style Compatibility introduced by
The method run() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
62
			$item->rebuildVFI();
63
			echo "done";
64
			return;
65
		}
66
67
		if (isset($_GET['link'])) {
68
			$item = SiteTree::get_by_link($_GET['link']);
69
			if (!$item || !$item->exists()) die('not found: ' . $_GET['link']);
0 ignored issues
show
Coding Style Compatibility introduced by
The method run() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
70
			$item->rebuildVFI();
71
			echo "done";
72
			return;
73
		}
74
75
		if (isset($_GET['start'])) {
76
			$this->runFrom($_GET['class'], $_GET['start'], $_GET['field']);
77
		}
78
		else {
79
			foreach(array('framework','sapphire') as $dirname) {
80
				$script = sprintf("%s%s$dirname%scli-script.php", BASE_PATH, DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR);
81
				if(file_exists($script)) {
82
					break;
83
				}
84
			}
85
86
			$classes = VirtualFieldIndex::get_classes_with_vfi();
87
			foreach ($classes as $class) {
88
				if (isset($_GET['class']) && $class != $_GET['class']) continue;
89
				$singleton = singleton($class);
90
				$query = $singleton->get($class);
91
				$dtaQuery = $query->dataQuery();
92
				$sqlQuery = $dtaQuery->getFinalisedQuery();
93
				$singleton->extend('augmentSQL',$sqlQuery,$dtaQuery);
94
				$total = $query->count();
95
				$startFrom = isset($_GET['startfrom']) ? $_GET['startfrom'] : 0;
96
				$field = isset($_GET['field']) ? $_GET['field'] : '';
97
98
				echo "Class: $class, total: $total\n\n";
99
100
				for ($offset = $startFrom; $offset < $total; $offset += $this->stat('recordsPerRequest')) {
101
					echo "$offset..";
102
					$cmd = "php $script dev/tasks/$self class=$class start=$offset field=$field";
0 ignored issues
show
Bug introduced by
The variable $script does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
103
					if($verbose) echo "\n  Running '$cmd'\n";
104
					$res = $verbose ? passthru($cmd) : `$cmd`;
105
					if($verbose) echo "  ".preg_replace('/\r\n|\n/', '$0  ', $res)."\n";
106
				}
107
			}
108
		}
109
	}
110
111
	protected function runFrom($class, $start, $field) {
112
		$items = DataList::create($class)->limit($this->stat('recordsPerRequest'), $start);
113
		foreach ($items as $item) {
114
			$item->rebuildVFI($field);
115
		}
116
	}
117
118
}
119