Insphpect

This tool is currently proof-of-concept. Your feedback and evaluation is valuable in helping to improve it and ensure its reports are meaninful.

Please click here to complete a short survey to tell us what you think. It should take less than 5 minutes and help further this research project!

Transphporm\Template

Detected issues

Issue Method Line number
Using `new` in constructor __construct 18
Using `new` in constructor __construct 23

Code

Click highlighted lines for details

<?php/* @description     Transformation Style Sheets - Revolutionising PHP templating    * * @author          Tom Butler tom@r.je                                             * * @copyright       2017 Tom Butler <tom@r.je> | https://r.je/                      * * @license         http://www.opensource.org/licenses/bsd-license.php  BSD License * * @version         1.2                                                             */namespace Transphporm;/** Loads an XML string into a DomDocument and allows searching for specific elements using xpath based hooks */class Template {	private $hooks = [];	private $document;	private $xpath;	private $prefix = '';	private $save;	/** Takes an XML string and loads it into a DomDocument object */	public function __construct($doc) {

Usage of the new keyword in a constructor

Summary of issues

Background

If a dependency is constructed inside the object that requires it rather than passed in as a reference then flexibility is lost[1][2]

 public class Car {

    private 
Engine engine;
    
    public 
Car() {
        
this.engine = new Engine();
    }
}

Here, the Car constructor creates the Engine instance. This is inflexible as it forces all Car objects to use the exact same Engine type. Instead, it would encourage reuse if the program supported different engine types (e.g. DieselEngine, PetrolEngine or HybridEngine).

The same is true when an instance variable is created when the class is defined:

 public class Car {
    private 
Engine engine = new Engine();
}

By using the new keyword to instantiate a dependency, the specific implementation of that dependency is hardcoded and cannot be substituted.

Instead, the dependency should be constructed outside the class and injected in:

 public class Car {
    private 
Engine engine;

    public 
Car(Engine engine) {
        
this.engine engine;
    }
}

Using dependency injection it is possible to pass in any engine type:

 //Instead of
Car myCar = new Car();

//It's now possible to construct different types of car:
Car petrolCar = new Car(new PetrolEngine);
Car electricCar = new Car(new ElectricEngine);

A secondary advantage to Dependency Injection with regards to flexibility and encapsulation is that the class which has the dependency (Car, in this example) it not aware of the dependencies of the Engine class.

For example, if the Engine class required a Gearbox instance as a constructor argument, the Car class would need to instantiate and pass in the relevant Gearbox instance. And provide any dependencies of the Gearbox class when instantiating it.

If the constructor arguments of any of the classes which need to be instantiated are modified during development, any class which creates an instance of the class must also be modified. A change to the constructor for Engine would require modifying the Car class. Instead, if the fully constructed Engine instance

By loosely coupling the Engine class to the Car class, the author of the Car class does not need to know anything about the implementation of Engine class or have knowledge of what dependencies it has.

 
public Car() {

    
this.engine = new Engine(new Gearbox());
}

Further reading

Additional resources:

References

  1. Hevery, M. (2008) How to Think About the “new” Operator with Respect to Unit Testing [online]. Available from: http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/
  2. Hevery, M. (2008) Code Reviewers Guide [online]. Available from: http://misko.hevery.com/code-reviewers-guide/

Please note: This feature is currently proof-of-concept, the instructions may not always be completely accurate.

\DomDocument is instantiated inside the constructor of Transphporm\Template

1) Remove the new expression and replace it with a variable:

 

$this->document = new \DomDocument;

becomes:

 

        $this->document = new \DomDocument;

2) Add a constructor argument for the new variable: Replace:

 

public function __construct($doc) {

with:

 

public function __construct($doc) {

3) Find any occurance of new Transphporm\Template and provide the new dependency.

\Transphporm\Template is being instantiated in src/Builder.php:0

Replace:

 

$template = new Template($this->isValidDoc($body) ? str_ireplace('<!doctype''<!DOCTYPE'$body) : '<template>' $body '</template>' );

With:

Please note: This feature is currently proof-of-concept, this patch may not work, please don't blindly apply it.

diff --git a/src/Builder.php b/src/Builder.php
index 78c369b..1a2fb0d 100644
--- a/src/Builder.php
+++ b/src/Builder.php
@@ -82,7 +82,7 @@ class Builder {
 		$elementData = new \Transphporm\Hook\ElementData(new \SplObjectStorage(), $data);
 		$functionSet = new FunctionSet($elementData);
 		//To be a valid XML document it must have a root element, automatically wrap it in <template> to ensure it does
-		$template = new Template($this->isValidDoc($body) ? str_ireplace('<!doctype', '<!DOCTYPE', $body) : '<template>' . $body . '</template>' );
+		$template = new Template(new \DomDocument, $this->isValidDoc($body) ? str_ireplace('<!doctype', '<!DOCTYPE', $body) : '<template>' . $body . '</template>');

 		$valueParser = new Parser\Value($functionSet);
 		$this->config = new Config($functionSet, $valueParser, $elementData, new Hook\Formatter(), new Parser\CssToXpath($functionSet, $template->getPrefix(), md5($this->tss)), $this->filePath, $headers);
diff --git a/src/Template.php b/src/Template.php
index f46567f..a52c54c 100644
--- a/src/Template.php
+++ b/src/Template.php
@@ -14,8 +14,8 @@ class Template {
 	private $save;

 	/** Takes an XML string and loads it into a DomDocument object */
-	public function __construct($doc) {
-		$this->document = new \DomDocument;
+	public function __construct(\DomDocument $domDocument, $doc) {
+		$this->document = $domDocument;
 		//This should remove whitespace left behind after ->removeChild but it doesn't
 		$this->document->preserveWhiteSpace = false;
 		$this->loadDocument($doc);
@@ -104,4 +104,4 @@ class Template {
 		return trim($output);
 	}

-}
+}
\ No newline at end of file
//This should remove whitespace left behind after ->removeChild but it doesn't $this->document->preserveWhiteSpace = false; $this->loadDocument($doc);

Usage of the new keyword in a constructor

Summary of issues

Background

If a dependency is constructed inside the object that requires it rather than passed in as a reference then flexibility is lost[1][2]

 public class Car {

    private 
Engine engine;
    
    public 
Car() {
        
this.engine = new Engine();
    }
}

Here, the Car constructor creates the Engine instance. This is inflexible as it forces all Car objects to use the exact same Engine type. Instead, it would encourage reuse if the program supported different engine types (e.g. DieselEngine, PetrolEngine or HybridEngine).

The same is true when an instance variable is created when the class is defined:

 public class Car {
    private 
Engine engine = new Engine();
}

By using the new keyword to instantiate a dependency, the specific implementation of that dependency is hardcoded and cannot be substituted.

Instead, the dependency should be constructed outside the class and injected in:

 public class Car {
    private 
Engine engine;

    public 
Car(Engine engine) {
        
this.engine engine;
    }
}

Using dependency injection it is possible to pass in any engine type:

 //Instead of
Car myCar = new Car();

//It's now possible to construct different types of car:
Car petrolCar = new Car(new PetrolEngine);
Car electricCar = new Car(new ElectricEngine);

A secondary advantage to Dependency Injection with regards to flexibility and encapsulation is that the class which has the dependency (Car, in this example) it not aware of the dependencies of the Engine class.

For example, if the Engine class required a Gearbox instance as a constructor argument, the Car class would need to instantiate and pass in the relevant Gearbox instance. And provide any dependencies of the Gearbox class when instantiating it.

If the constructor arguments of any of the classes which need to be instantiated are modified during development, any class which creates an instance of the class must also be modified. A change to the constructor for Engine would require modifying the Car class. Instead, if the fully constructed Engine instance

By loosely coupling the Engine class to the Car class, the author of the Car class does not need to know anything about the implementation of Engine class or have knowledge of what dependencies it has.

 
public Car() {

    
this.engine = new Engine(new Gearbox());
}

Further reading

Additional resources:

References

  1. Hevery, M. (2008) How to Think About the “new” Operator with Respect to Unit Testing [online]. Available from: http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/
  2. Hevery, M. (2008) Code Reviewers Guide [online]. Available from: http://misko.hevery.com/code-reviewers-guide/

Please note: This feature is currently proof-of-concept, the instructions may not always be completely accurate.

\DomXPath is instantiated inside the constructor of Transphporm\Template

1) Remove the new expression and replace it with a variable:

 

$this->xpath = new \DomXPath($this->document);

becomes:

 

        $this->xpath = new \DomXPath($this->document);

2) Add a constructor argument for the new variable: Replace:

 

public function __construct($doc) {

with:

 

public function __construct($doc) {

3) Find any occurance of new Transphporm\Template and provide the new dependency.

\Transphporm\Template is being instantiated in src/Builder.php:0

Replace:

 

$template = new Template(new \DomDocument$this->isValidDoc($body) ? str_ireplace('<!doctype''<!DOCTYPE'$body) : '<template>' $body '</template>');

With:

Please note: This feature is currently proof-of-concept, this patch may not work, please don't blindly apply it.

diff --git a/src/Builder.php b/src/Builder.php
index 78c369b..225f265 100644
--- a/src/Builder.php
+++ b/src/Builder.php
@@ -82,7 +82,7 @@ class Builder {
 		$elementData = new \Transphporm\Hook\ElementData(new \SplObjectStorage(), $data);
 		$functionSet = new FunctionSet($elementData);
 		//To be a valid XML document it must have a root element, automatically wrap it in <template> to ensure it does
-		$template = new Template($this->isValidDoc($body) ? str_ireplace('<!doctype', '<!DOCTYPE', $body) : '<template>' . $body . '</template>' );
+		$template = new Template(new \DomXPath(false), new \DomDocument, $this->isValidDoc($body) ? str_ireplace('<!doctype', '<!DOCTYPE', $body) : '<template>' . $body . '</template>');

 		$valueParser = new Parser\Value($functionSet);
 		$this->config = new Config($functionSet, $valueParser, $elementData, new Hook\Formatter(), new Parser\CssToXpath($functionSet, $template->getPrefix(), md5($this->tss)), $this->filePath, $headers);
diff --git a/src/Template.php b/src/Template.php
index f46567f..057ff6a 100644
--- a/src/Template.php
+++ b/src/Template.php
@@ -14,13 +14,13 @@ class Template {
 	private $save;

 	/** Takes an XML string and loads it into a DomDocument object */
-	public function __construct($doc) {
-		$this->document = new \DomDocument;
+	public function __construct(\DomXPath $domXPath, $doc) {
+		$this->document = $domDocument;
 		//This should remove whitespace left behind after ->removeChild but it doesn't
 		$this->document->preserveWhiteSpace = false;
 		$this->loadDocument($doc);

-		$this->xpath = new \DomXPath($this->document);
+		$this->xpath = $domXPath;
 		$this->xpath->registerNamespace('php', 'http://php.net/xpath');
 		$this->xpath->registerPhpFunctions();

@@ -104,4 +104,4 @@ class Template {
 		return trim($output);
 	}

-}
+}
\ No newline at end of file
$this->xpath->registerNamespace('php', 'http://php.net/xpath'); $this->xpath->registerPhpFunctions(); if ($this->document->documentElement->namespaceURI !== null) { $this->xpath->registerNamespace('nsprefix', $this->document->documentElement->namespaceURI); $this->prefix = 'nsprefix:'; } } /** Loads a HTML or XML document */ private function loadDocument($doc) { libxml_use_internal_errors(true); if (strpos(trim($doc), '<?xml') === false) { //If HTML is loaded, make sure the document is also saved as HTML $this->save = function($content = null) { return $this->document->saveHtml($content); }; $this->document->loadHtml('<' . '?xml encoding="UTF-8">' . $doc, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED); } else { $this->document->loadXml($doc); //XML was loaded, save as XML. $this->save = function($content = null) { return $this->document->saveXml($content, LIBXML_NOEMPTYTAG); }; } libxml_clear_errors(); } /** Returns the document's XML prefix */ public function getPrefix() { return $this->prefix; } /** Assigns a $hook which will be run on any element that matches the given $xpath query */ public function addHook($xpath, $hook) { $this->hooks[] = [$xpath, $hook]; } /** Loops through all assigned hooks, runs the Xpath query and calls the hook */ private function processHooks() { foreach ($this->hooks as list($query, $hook)) { foreach ($this->xpath->query($query) as $element) { if ($element->getAttribute('transphporm') !== 'immutable' || $hook->runOnImmutableElements()) { $hook->run($element); } } } $this->hooks = []; } /** Prints out the current DomDocument as HTML */ private function printDocument() { $output = ''; foreach ($this->document->documentElement->childNodes as $node) $output .= call_user_func($this->save, $node); return $output; } /** Outputs the template's header/body. Returns an array containing both parts */ public function output($document = false) { //Process all hooks $this->processHooks(); //Generate the document by taking only the childnodes of the template, ignoring the <template> and </template> tags //TODO: Is there a faster way of doing this without string manipulation on the output or this loop through childnodes? //Either return a whole DomDocument or return the output HTML if ($document) return $this->document; //Print the doctype... saveHtml inexplicably does not support $doc->doctype as an argument $output = ($this->document->doctype) ? $this->document->saveXml($this->document->doctype) . "\n" : ''; if ($this->document->documentElement->tagName !== 'template') $output .= call_user_func($this->save, $this->document->documentElement); else $output = $this->printDocument(); //repair empty tags. Browsers break on <script /> and <div /> so can't avoid LIBXML_NOEMPTYTAG but they also break on <base></base> so repair them $output = str_replace(['></img>', '></br>', '></meta>', '></base>', '></link>', '></hr>', '></input>'], ' />', $output); return trim($output); }}