# Phing User Guide

Phing 3.x

2021-03-29 11:55:15

Preface
1.1. Contributors (present and past)
1.4. DocBook
2. Introduction
2.1. What Phing Is
2.2. Phing & Binarycloud: History
2.3. How Phing Works
2.4. Cool, so how can I help?
3. Setting-up Phing
3.1. System Requirements
3.2. Obtaining Phing
3.3. Running Phing
4. Getting started
4.1. XML And Phing
4.2. Writing A Simple Buildfile
4.3. More Complex Buildfile
4.4. Relax NG Grammar
5. Project components
5.1. Projects
5.2. Version
5.3. Project Components in General
5.4. Targets
5.6. Types
5.7. Basic Types
5.8. Conditions
6. Extending Phing
6.1. Extension Possibilities
6.2. Source Layout
6.3. System Initialization
6.4. System Services
6.5. Build Lifecycle
6.7. Writing Types
6.8. Writing Mappers
6.9. Writing Selectors
6.10. Writing Conditions
A. Fact Sheet
A.1. Built-In Properties
A.2. Command Line Arguments
A.3. Distribution File Layout
A.4. Program Exit Codes
B.6. Augment
B.9. Basename
B.10. Bindtargets
B.15. DefaultExcludes
B.17. DependSet
B.18. Diagnostics
B.19. Dirname
B.22. EchoXML
B.37. PathConvert
B.42. Phingversion
B.45. PropertyCopy
B.48. PropertySelector
B.50. Record
B.54. Relentless
B.55. Retry
B.58. SortList
B.71. Variable
C.69. PHPUnitReport
D. Core Types
D.1. Description
D.2. Excludes
D.3. FileList
D.4. FileSet
D.5. DirSet
D.6. PatternSet
D.7. Path / Classpath
D.8. Regexp
E. Core filters
E.2. ExpandProperties
E.3. ConcatFilter
E.5. IconvFilter
E.6. Line Contains
E.7. LineContainsRegexp
E.8. PrefixLines
E.9. ReplaceTokens
E.10. ReplaceTokensWithFile
E.11. ReplaceRegexp
E.12. SortFilter
E.13. StripLineBreaks
E.16. StripWhitespace
E.17. TabToSpaces
E.18. TailFilter
E.19. TidyFilter
E.20. XincludeFilter
E.21. XsltFilter
E.22. ClassConstants
F. Core mappers
F.1. Common Attributes
F.2. ChainedMapper
F.3. CompositeMapper
F.4. FirstMatchMapper
F.5. CutDirsMapper
F.6. FlattenMapper
F.7. GlobMapper
F.8. IdentityMapper
F.9. MergeMapper
F.10. RegexpMapper
G. Core selectors
G.1. Contains
G.2. Date
G.3. Depend
G.4. Depth
G.5. Different
G.6. Filename
G.7. Present
G.8. Containsregexp
G.9. Size
G.10. Type
G.11. And
G.12. Majority
G.13. Modified
G.14. None
G.15. Not
G.16. Or
G.18. Writable
G.19. Executable
G.20. Selector
G.22. PosixPermissions Selector
H. Project Components
H.1. Phing Projects
H.2. Targets and Extension-Points
I. Loggers and Listeners
I.1. Listeners
I.2. Loggers
I.3. DefaultLogger
I.4. AnsiColorLogger
I.5. MailLogger
I.6. NoBannerLogger
I.7. ProfileLogger
I.8. StatisticsListener
I.9. TimestampedLogger
I.10. SilentLogger
I.11. MonologListener
J. File Formats
J.1. Build File Format
J.2. Property File Format
Bibliography

# Preface

PHing Is Not GNU make; it's a PHP project build system or build tool based on Apache Ant. You can do anything with it that you could do with a traditional build system like GNU make, and its use of simple XML build files and extensible PHP "task" classes make it an easy-to-use and highly flexible build framework. Features include running PHPUnit and SimpleTest unit tests (including test result and coverage reports), file transformations (e.g. token replacement, XSLT transformation, Smarty template transformations), file system operations, interactive build support, SQL execution, CVS/SVN operations, documentation generation (PhpDocumentor) and much more.

If you find yourself writing custom scripts to handle the packaging, deploying, or testing of your applications, then we suggest looking at the Phing framework. Phing comes packaged with numerous out-of-the-box operation modules (tasks), and an easy-to-use OO model for adding your own custom tasks.

## 1.1 Contributors (present and past)

This documentation is made available under the GNU Free Document License (see Section A.6, “The GFDL License”)

Copyright (c) 2002 - 2020, The Phing Project

Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1 or
any later version published by the Free Software Foundation;

## 1.4 DocBook

All Phing reference documentation is written using the DocBook5 XML markup (see DocBook Project). The main advantage with DocBook is that it is a single source but multiple outputs. These document sources can be rendered into many possible output formats such as (X)HTML, PDF, EPub, Webhelp, RTF, Text and many more. Another advantage, inherit with the text based XML format, is that the document sources are all completely text based written using UTF-8 encoding. Only a plain text editor is required to extend or edit this documentation.

However, XML tends to be quite verbose and even if a plain text editor technically is all that is needed the actual entering of text will be made much easier with custom XML editor. These editors can be used to hide the XML tags and do auto-completion and on-the-fly validation to make sure that what is written is a valid DocBook5 document.

To work with the documentation we recommend to use one of the free XML/DocBook aware editors available. For example

The sources for the documentation are included under the docs/ directory. The DocBook sources are split into several files in order to make it more maintainable using the XML standard XInclude (see XML Inclusions (XInclude) Version 1.0).

For the writing of the book only a subset of all available DocBook elements are used as shown in Section 1.4.4, “DocBook v5 elements used in the manual and their meaning”

As of this writing the build process has been validated using version 1.78.1 of the DocBook5 stylesheets.

### Important

Make sure all documentation is written using UTF-8 text encoding.

### 1.4.1 Building the documentation

In order to build the documentation it is necessary to have the DocBook5 XSL stylesheets installed together with "xsltproc" which is used to transform the source into various output formats. In addition, to build the versions (either HTML or PDF) that supports highlighting of included source (within the <programlisting> element) the Saxon 6.5.5 XSL processor must be used. This is necessary since the syntax highlighting in DocBook is based on a Java extension (xslthl-2.x.x) which requires a Java based processor (such as Saxon).

### Tip

The easiest way to setup a complete build environment for DocBook5 for people new to DocBook is to install a clean version of Debian 7.x and then run the "deb-setup.sh" shell script. This will create a fully tested and working build environment for DocBook5 as it is used with Phing. This could easily be done using a virtual setup (for example using VirtualBox).

All DocBook sources are structured in a tree under docs/docbook5. The top level is the language of the manual. As of this writing only an English manual is available and hence the only top level directory available is "en". Under this directory the following structure applies (also for any new language translation that is added):

|-- scripts
|-- source
|   |-- appendixes
|   -- chapters
-- stylesheets
|-- css
|   -- img
-- xsl
-- images

All document sources are stored under the subdirectory "source" and the master document is aptly named "master.xml". This document pulls in all chapters and appendixes in the right order. For example, new tasks added should normally be documented in the "appendix/optionaltasks.xml" file. Look at the existing tasks and follow the same structure.

### Important

In order to get highlighting to work both the "xslthl-2.x.x.jar" package must be installed as well as Saxon 6.5.x. The jar file must be installed somewhere in the CLASSPATH , for example "/usr/share/java" if you run this on Linux. The xslthl package is available on SourceForge, please see XSLT syntax highlighting. By using the automated setup for Debian 7.x all these dependencies will be taken care of!

The customized stylesheets used are stored under "stylesheets" which uses one sub-folder for the customized XSL stylesheets (responsible for the transformation from DocBook to the chosen output format) and one sub-folder for the CSS stylesheets used to give the generated HTML documents there "look & feel".

Finally the "scripts" directory stores utility scripts. This currently contains two scripts, deb-setup.sh and "hlsaxon". The first scripts helps to create a full build environment for DocBook5 starting with a clean Debian 7 installation. This is meant to help people new to DocBook5 to get a working build environment as easy as possible. This script takes care of all detailed setup and will make a fulloy working DocBook5 build environment out-of-the-box.

The second script (hlsaxon) is wrapper file used from the buildfiles to call the Saxon translator (a Java based XSL procesor) with highlighting enabled and suitable paths to supporting libraries In this script the path to the DocBook installed stylesheets must be adjusted depending on your system (unless the automated setup have been used - with the deb-setup.sh file which takes care of that setup automatically). Mutatis mutandis.

In order to drive the transformation a Phing build script is available in the docbook root, build.xml. The build script supports the following public targets

 all*         Builds all available targets (default)
chunk        Builds the chunked HTML
clean        Removes all output files
epub         Builds the EPUB version
hlhtml       Builds the HTML version with syntax highlight
html         Builds the HTML version
htmlfancy    Builds the HTML version with an alternative styling for screen output
webhelp      Builds the webhelp version (Note: This requires Java and Ant
to be installed!)
validate     Validates all sources against the DocBook5 grammar


All generated output is stored under the directory "output" (which is created if it doesn't exist) with a subdirectory corresponding to the name of the chosen output format.

### 1.4.2 Template for new tasks

For creating documentation for new tasks the easistes thing is to use the included template template_for_tasks.xml which is a skeleton tasks with all commonly used elements. This will ensure a correct setting of all attributes. The skeleton can then be added to a suitable appendix as needed.

### Note

All new task description should go into one of the Appendices.

### Note

The following section is only meant for the maintainers that work on the core layout of the official Phing manual and is not necessary for developers adding documentation for new tasks of improving documentation for existing tasks.

Furthermore, by necessity this assumes a rudimentary knowledge of Docbook5 bubild process and what XSL and CSS stylesheets are. It is not possible in this short space to give a full description of that setup.

XSL Customization layer

All DocBook5 renderings are started from one of the customized XSL stylesheet under "stylesheets/xsl" . All commonly adjusted properties should go into the appropriate stylesheet for that rendering. No properties should be passed on via the command line. To keep the customization layer as future proof as possible only in very rare circumstances should any cores XSL templates be copied and modified. As usual the recommended way is to use the provided hooks.

CSS styelsheets

The CSS stylesheets are used to create the look & feel for the HTML based renderings. These are entirely standard CSS files which by design are kept very simple. It should be noted that a few styling option depends in turn of the modified XSL transformations in the XSL customization layer. This had to be done in order to gain some more detialed control not provided by DocBook5 out-of-the-box.

Webhelp

The webhelp output rendering is a bit of a special case. This rendering depends not only on DocBook5 but also on Java as well as Ant build processor. These dependencies are inherited from the official DocBook5 webhelp process and will remain. Unfortunately adjusting the look & fell for this rendering is not as simple as for the other outputs since a fair amount of the layout (as well as look & feel) are hard-coded in the Webhelp build system. While it is perfectly possible to adjust the hard coded values and design choises it is not future proof. Since the Webhelp rendering is the newest and fastest improving output from DocBook the intention for the Phing documentation is to track these improvements and not spend time ourself to duplicate this effor with a parallell development.

### 1.4.4 DocBook v5 elements used in the manual and their meaning

To keep things simple the manual uses only a small subset of all available elements in the DocBook schema. This makes it fairly easy to quickly get up to speed with adding and editing the manual. It also helps to keep the look&feel consistent and makes the writing of the CSS and XSL stylesheets a little bit easer.

The following list shows the supported elements and how they should be used in the manual

<chapter>, <appendix>

This is the top element for each chapter and appendix in the manual. Each <chapter> or <appendix> must also have a title.

Table 1.1: Required attributes

AttributeValueDescription
xmlnshttp://docbook.org/ns/docbookName space for DocBook. Always needed.
xmlns:xihttp://www.w3.org/2001/XIncludeName space for XInclude. Needed since we use XInclude to split the manual into different files.
xmlns:xlinkhttp://www.w3.org/1999/xlinkName space for xlink. Needed sine we make use of link and xref elements to link to other sites and cross references within the manual.
version5.0Versions of DocBook. Always needed.
xml:idapp.XXX , ch.XXXThe id for the chapter or the appendix. Used in other part of the manual to refer to this chapter/appendix with an <xref> element.

Table 1.2: Required nested elements

ElementValue
<title>The title of the chapter/appendix.

Example:

<appendix xmlns="http://docbook.org/ns/docbook"
xmlns:xi="http://www.w3.org/2001/XInclude"
version="5.0"
...
</appendix>
<sectN>

The section tags divides each chapter and appendix into logical parts. Each task description must be contained in a <sect1> element and each example section for the task must be contained within a <sect2> element. Depending on the description needed for each task additional <sect2> may be added as needed to make the text logically structured. If needed, a further nesting level may be used by using <sect3> elements within each <sect2> element. No deeper nestings than <sect3> should ever be used.

Each top level section must have the xml:id attribute which is used to reference the section from other parts of the document. Each section must have a nested title element.

Table 1.3: Required attributes

AttributeValueDescription
roletaskdefThis is only used and required for <sect1> elements for task description. This role is not currently used in the any of the XSL sheets. This is for future use.
xml:idName of sectionThe id for task definition should be the same as the task name for task description. For other sections the id should be a logical name that descrobes the content.

Table 1.4: Required nested elements

ElementValue
<title>The title of the section

Example:

<sect1 role="taskdef" xml:id="AdhocTaskdefTask">
...
</sect1>
<para>

Division between paragraphs in flowing text.

<screen>

Used to mark command lines and multi-line computer output. For inline screen output use the <literal> element

<programlisting>

Used for all PHP and XML program listings in the manual. Please note that this tag should not be used for command lines as entered in a terminal. Use the <screen> element for this.

Note: Remember to write all opening '<' as &lt;

Table 1.5: Required attributes

AttributeValueDescription
languagephp, xmlThe language attribute should indicate what programming language the programlisting contains. This is used to control what syntax highlighting should be used.

Example:

<programlisting language="xml">
<append
destFile="${process.outputfile}"> <filterchain> <xsltfilter style="${process.stylesheet}">
<param name="mode"

### 3.2.4 Getting the latest source from Phing's Github repository

The latest snapshot can always be downloaded directly the official Phing Git repository. However, be warned that there is not guarantee that the momentous state of the repository represents a completely stable application without any problems.

## 3.3 Running Phing

Now you are prepared to execute Phing on the command line or via script files. The following section briefly describe how to properly execute phing.

### 3.3.1 Command Line

Phing execution on the command line is simple. Just change to the directory where your buildfile resides and type

$phing [target [target2 [target3] ...]] at the command line (where [target...] are the target(s) you want to be executed). If no target is specified Phing will try to execute the default target, as specified in the project tag. When calling multipe targets, Phing will invoke each target independently of the other targets. Optionally, you may specify command line arguments as listed in Appendix A. For example, the following command line calls the default buildscript build.xml using the default target with the property ftp.upload set to true. $ phing -Dftp.upload=true

### 3.3.2 Supported command line arguments

The following command line arguments are supported

  -h -help               print this message
-l -list               list available targets in this project
-i -init [file]        generates an initial buildfile
-v -version            print the version information and exit
-q -quiet              be extra quiet
-S -silent             print nothing but task outputs and build failures
-verbose               be extra verbose
-debug                 print debugging information
-emacs, -e             produce logging information without adornments
-diagnostics           print diagnostics information
-strict                runs build in strict mode, considering a warning as error
-no-strict             runs build normally (overrides buildfile attribute)
-longtargets           show target descriptions during build
-logfile <file>        use given file for log
-logger <classname>    the class which is to perform logging
-listener <classname>  add an instance of class as a project listener
-f -buildfile <file>   use given buildfile
-D<property>=<value>   use value for given property
-keep-going, -k        execute all targets that do not depend
on failed target(s)
-propertyfile <file>   load all properties from file
-propertyfileoverride  values in property file override existing values
-find <file>           search for buildfile towards the root of the
filesystem and use it
-inputhandler <file>   the class to use to handle user input

# Chapter 4 Getting started

Phing buildfiles are written in XML, and so you will need to know at least some basic things about XML to understand the following chapter. There is a lot of information available on the web:

## 4.1 XML And Phing

A valid Phing buildfile has the following basic structure:

• The document prolog

• Exactly one root element called <project> .

• Several Phing type elements (i.e. <property> , <fileset> , <patternset> etc.)

• One or more <target> elements containing built-in or user defined Phing task elements (i.e. <install> , <bcc> , etc).

## 4.2 Writing A Simple Buildfile

The Foobar project installs some PHP files from a source location to a target location, creates an archive of this files and provides an optional clean-up of the build tree:

<?xml version="1.0" encoding="UTF-8"?>

<project name="FooBar" default="dist">

<!-- ============================================  -->
<!-- Target: prepare                               -->
<!-- ============================================  -->
<target name="prepare">
<echo msg="Making directory ./build" />
<mkdir dir="./build" />
</target>

<!-- ============================================  -->
<!-- Target: build                                 -->
<!-- ============================================  -->
<target name="build" depends="prepare">
<echo msg="Copying files to build directory..." />

<echo msg="Copying ./about.php to ./build directory..." />

<echo msg="Copying ./browsers.php to ./build directory..." />
<copy file="./browsers.php" tofile="./build/browsers.php" />

<echo msg="Copying ./contact.php to ./build directory..." />
<copy file="./contact.php" tofile="./build/contact.php" />
</target>

<!-- ============================================  -->
<!-- (DEFAULT)  Target: dist                       -->
<!-- ============================================  -->
<target name="dist" depends="build">
<echo msg="Creating archive..." />

<tar destfile="./build/build.tar.gz" compression="gzip">
<fileset dir="./build">
<include name="*" />
</fileset>
</tar>

<echo msg="Files copied and compressed in build directory OK!" />
</target>
</project>

A phing build file is normally given the name build.xml which is the default file name that the Phing executable will look for if no other file name is specified.

To run the above build file and execute the default target (assuming it is stored in the current directory with the default name) is only a matter of calling: $phing This will then execute the dist target. While executing the build file each task performed will print some information on what actions and what files have been affected. To run any of the other target is only a matter of providing the name of the target on the command line. So for example to run the build target one would have to execute $ phing build 

It is also possible to specify a number of additional command line arguments as described in Appendix A, Fact Sheet

### 4.2.1 Project Element

The first element after the document prolog is the root element named <project> on line 3. This element is a container for all other elements and can/must have the following attributes:

Table 4.1: <project> Attributes

AttributeDescriptionRequired
nameThe name of the projectNo
basedirThe base directory of the project. This attribute controls the value of the ${project.basedir} property which can be used to reference files with paths relative to the project root folder. Can be a path relative to the position of the buildfile itself. If omitted, "." will be used, which means that the build file should be located in the project's root folder. No defaultThe default target that is to be executed if no target(s) are specified when calling this build file.Yes descriptionThe description of the project.No strictEnables the strict-mode for the project build process.No See Section H.1, “Phing Projects” for a complete reference. ### 4.2.2 Target Element A target can depend on other targets. You might have a target for installing the files in the build tree, for example, and a target for creating a distributable tar.gz archive. You can only build a distributable when you have installed the files first, so the distribute target depends on the install target. Phing resolves these dependencies. It should be noted, however, that Phing's depends attribute only specifies the order in which targets should be executed - it does not affect whether the target that specifies the dependency(s) gets executed if the dependent target(s) did not (need to) run. Phing tries to execute the targets in the depends attribute in the order they appear (from left to right). Keep in mind that it is possible that a target can get executed earlier when an earlier target depends on it, in this case the dependent is only executed once: <target name="A" /> <target name="B" depends="A" /> <target name="C" depends="B" /> <target name="D" depends="C,B,A" /> Suppose we want to execute target D. Looking at its depends attribute, you might think that first target C, then B and then A is executed. Wrong! C depends on B, and B depends on A, so first A is executed, then B, then C, and finally D. A target gets executed only once, even when more than one target depends on it (see the previous example). The optional description attribute can be used to provide a one-line description of this target, which is printed by the -projecthelp command-line option. #### Target attributes You can specify one or more of the following attributes within the target element. Table 4.2: <target> Attributes AttributeDescriptionRequired nameThe name of the targetYes dependsA comma-separated list of targets this target depends on.No ifThe name of the Property that has to be set in order for this target to be executedNo unlessThe name of the Property that must not be set in order for this target to be executed. See Section H.2, “Targets and Extension-Points” for a complete reference. ### 4.2.3 Task Elements A task is a piece of PHP code that can be executed. This code implements a particular action to perform (i.e. install a file). Therefore it must be defined in the buildfile so that it is actually invoked by Phing. These references will be resolved before the task is executed. Tasks have a common structure: <name attribute1="value1" attribute2="value2" ... /> where name is the name of the task, attributeN is the attribute name, and valueN is the value for this attribute. There is a set of core tasks (see Appendix B, Core tasks) along with a number of optional tasks. It is also very easy to write your own tasks (see Chapter 6, Extending Phing). Tasks can be assigned an id attribute: <taskname id="taskID" ... /> By doing this you can refer to specific tasks later on in the code of other tasks. ### 4.2.4 Property Element Properties are essentially variables that can be used in the buildfile. These might be set in the buildfile by calling the property task, or might be set outside Phing on the command line (properties set on the command line always override the ones in the buildfile). A property has a name and a value only. Properties may be used in the value of task attributes. This is done by placing the property name between " ${ " and " } " in the attribute value. For example, if there is a BC_BUILD_DIR property with the value 'build', then this could be used in an attribute like this: ${BC_BUILD_DIR}/en . This is resolved to build/en. Getting the value of a Reference with ${toString:} Any Phing type item which has been declared with a reference can also its string value extracted by using the ${toString:} operation, with the name of the reference listed after the toString: text. The __toString() method of the php class instance that is referenced is invoked all built in types strive to produce useful and relevant output in such an instance. For example, here is how to get a listing of the files in a fileset: <fileset id="sourcefiles" dir="src" includes="**/*.php"/> <echo> sourcefiles =${toString:sourcefiles} </echo>

There is no guarantee that external types provide meaningful information in such a situation

Phing provides access to system properties as if they had been defined using a <property> task. For example, ${os.name} expands to the name of the operating system. See Appendix A, Fact Sheet for a complete list ## 4.3 More Complex Buildfile <?xml version="1.0" encoding="UTF-8" ?> <project name="testsite" basedir="." default="main"> <property file="./build.properties" /> <property name="package" value="${phing.project.name}" override="true" />
<property name="builddir" value="./build/testsite" override="true" />
<property name="srcdir"   value="${project.basedir}" override="true" /> <!-- Fileset for all files --> <fileset dir="." id="allfiles"> <include name="**" /> </fileset> <!-- ============================================ --> <!-- (DEFAULT) Target: main --> <!-- ============================================ --> <target name="main" description="main target"> <copy todir="${builddir}">
<fileset refid="allfiles" />
</copy>
</target>

<!-- ============================================  -->
<!-- Target: Rebuild                               -->
<!-- ============================================  -->
<target name="rebuild" description="rebuilds this package">
<delete dir="${builddir}" /> <phingcall target="main" /> </target> </project> This build file first defines some properties with the <property> task call to PropertyTask. Then, it defines a fileset and two targets. Let us have a quick rundown of this build file. The first four tags within the project tag define properties. They appear in two possible variants: • The first property tag contains only the file attribute. The value has to be a relative or absolute path to a property file (for the format, see Appendix J, File Formats). • The other times, the tag has a name and a value attribute. After the call, the value defined in the attribute value is available through the key enclosed in "${" and "}".

The next noticeable thing in the build file is the <fileset> tag. It defines a fileset, i.e. a set of multiple files. You can include and exclude files with the include and exclude tags within the fileset tag. For more information concerning Filesets (i.e. Patterns) see Appendix D, Core Types. The fileset is given an id attribute, so it can be referenced later on.

One thing is worth noting here though and that is the use of double star expression, i.e. "**". This special regexp refers to all files in all subdirectories as well. Compare this with a single "*" which would only refer to all files in the current subdirectory. So for example the expression "**/*.phps" would refer to all files with suffix "'.phps" in all subdirectories below the current directory.

The first task only contains a call to CopyTask via <copy>. The interesting thing is within the copy tag. Here, a fileset task is not written out with nested include or exclude elements, but via the refid, the Fileset created earlier is referenced. This way, you can use a once defined fileset multiple times in your build files.

The only noticeable thing in the second target is the call to PhingTask with the <phingcall> tag (see Appendix B, Core tasks for more information). The task executes a specified target within the same build file. So, the second target removes the build directory and calls main again, thus rebuilding the project.

A variant is to override properties defined in the build file with properties specified on the command line using the -D switch. For example to override the builddir in the build file above one could call Phing as

$phing -Dbuilddir=/tmp/system-test  ### 4.3.1 Handling source dependencies A common task required in many build files is to keep some target which has a number of dependencies up to date. In traditional make files this could for example be an executable that needs to be recompiled if any of the source files have been updated. In Phing such a condition is handled by the UpToDateTask , see Section B.69, “UpToDateTask ” for examples on how this task us used. ## 4.4 Relax NG Grammar With a little bit of experience it is not that difficult to write and understand Phing build files since the XML format in itself tends to be quite verbose. However, it can become a bit tedious and the large (and growing) amount of built-in tasks and filters can sometimes make it difficult to remember the exact syntax of all the available features. To help with this the Phing distribution contains a Relax NG Grammar (REgular LAnguage for XML Next Generation, http://www.relaxng.org/) file that describes the (formal) syntax of the build files. This grammar can be used to validate build files. However, the most beneficial use of the grammar is together with a schema aware XML editor. Such an editor can make auto-completion based on the grammar. This feature makes writing complex build files significantly easier since it is usually enough to enter the first letter of an element to have the rest of the element written automatically as well as any compulsory attributes. Most XML editors can be told to what schema (or model) to use for validation and auto-completion by adding a specification in the beginning of the XML file. For example, the following two lines in the beginning of an XML file would do (of course the exact path to the grammar will depend on your system setup) <?xml version="1.0" encoding="UTF-8"?> <?xml-model xlink:href="/usr/share/php5/PEAR/data/phing/etc/phing-grammar.rng" type="application/xml" schematypens="http://relaxng.org/ns/structure/1.0" ?> Using auto-completion will make it substantially easier to edit large build files. Please note that since the phing-grammar does not have an official designation we must use the absolute filename to specify the grammar (instead of a canonical URI that is resolved by the systems XML-catalogue). This grammar is available (as a plain text file) in the distribution at: /etc/phing-grammar.rng Since we do not want to neither endorse nor forget any particular XML editor with this capability we do not make available such a list of editors. Instead, spending a few minutes with Google searching for XML-editors is bound to find a number of editors with this capability. If you wish to validate your Phing build file, there are numerous options. Links to various validation tools and XML editors are available at the RELAX NG home page, http://www.relaxng.org/. The command line tool xmllint that comes with libxml2 is also able to validate a given XML file against the supplied grammar. For example, to use xmllint to validate a Phing build file the following command line could be used: $ xmllint -noout -relaxng phing-grammar.rng build.xml
build.xml validates

# Chapter 5 Project components

This goal of this chapter is to make you familiar with the basic components of a buildfile. After reading this chapter, you should be able to read and understand the basic structure of any buildfile even if you don't know exactly what the individual pieces do.

For supplemental reference information, you should see Appendix B, Core tasks, Appendix D, Core Types and Appendix H, Project Components.

## 5.1 Projects

In the structure of a Phing buildfile, there must be exactly one Project defined; the <project> tag is the root element of the buildfile, meaning that everything else in the buildfile is contained within the <project > element.

<?xml version="1.0"?>

<project name="test" description="Simple test build file" default="main" >
<!-- Everything else here -->
<project>

The listing above shows a sample <project> tag that has all attributes available for Projects. The name and description attributes are fairly self-explanatory; the default attribute specifies the default Target to execute if no target is specified (Section H.2, “Targets and Extension-Points” are described below). For a complete reference, see Appendix H, Project Components.

## 5.2 Version

Since Phing 2.4.2 it is possible to include a phingVersion attribute in the <project> tag. This attribute allows you to define the minimum Phing version required to execute a build file, in order to prevent compatibility issues.

<?xml version="1.0"?>

<project name="test" phingVersion="2.4.2" >
<!-- Everything else here -->
<project>

## 5.3 Project Components in General

Project Components are all the elements found inside a project, i.e. targets, tasks, types, etc. Project components may have attributes and nested tags. Attributes only contain simple values, i.e. strings, integers etc. Nested elements may be complex Phing types (like FileSets) or simple wrapper classes for values with custom keys (see Appendix D, Core Types for example).

Any nested elements must be supported by the class that implements the project component, and because the nested tags are handled by the project component class the same nested tag may have different meanings (and different attributes) depending on the context. So, for example, the nested tag <param.../> within the <phingcall> tag is handled very differently from the<param.../> tag within the <xsltfilter> tag -- in the first case setting project properties, in the second case setting XSLT parameters.

## 5.4 Targets

Targets are collections of project components (but not other targets) that are assigned a unique name within their project. A target generally performs a specific task -- or calls other targets that perform specific tasks -- and therefore a target is a bit like a  function (but a target has no return value).

Targets may depend on other targets. For example, if target A depends on a target B, then when target A is called to be executed, target B will be executed first. Phing automatically resolves these dependencies. You cannot have circular references like: "target A depends on target B that depends on target A".

The following code snippet shows an example of the use of targets.

<target name="othertask" depends="buildpage" description="Whatever">
<target>

<target name="buildpage" description="Some description">
<target>

When Phing is asked to execute the othertask target, it will see the dependency and execute buildpage first. Notice that the dependency task can be defined after the dependent task.

Tasks are responsible for doing the work in Phing. Basically, tasks are the individual actions that your buildfile can perform. For example, tasks exist to copy a file, create a directory, TAR files in a directory. Tasks may also be more complex such as XsltTask which copies a file and transforms the file using XSLT, SmartyTask which does something similar using Smarty templates, or CreoleTask which executes SQL statements against a specified DB. See Appendix B, Core tasks for descriptions of Phing tasks.

Tasks support parameters in the form of:

• Simple parameters (i.e. strings) passed as XML attributes, or

• More complex parameters that are passed by nested tags

Simple parameters are basically strings. For example, if you pass a value "A simple string." as a parameter, it is evaluated as a string and accessible as one. You can also reference properties as described in Chapter 4, Getting started.

Note: There are special values that are not mapped to strings, but to boolean values instead. The values true, false, yes, no, on and off are translated to true/false boolean values.

<property name="myprop" value="value" override="true"/>

However, some tasks support more complex data types as parameters. These are passed to the task with nested tags. Consider the following example:

<copy>
<fileset dir=".">
<include name="**" />
</fileset>
</copy>

Here, CopyTask is passed a complex parameter, a Fileset. Tasks may support multiple complex types in addition to simple parameters. Note that the names of the nested tags used to create the complex types depend on the task implementation. Tasks may support default Phing types (see Section 5.6, “ Types ”) or may introduce other types, for example to wrap key/value pairs.

Refer to Appendix B, Core tasks for a list of system tasks and their parameters.

## 5.6 Types

### 5.6.1 Basics

Besides the simple types (strings, integer, booleans) you can use in the parameters of tasks, there are more complex Phing Types. As mentioned above, they are passed to a task by using nesting tags:

<task>
<type />

<!-- or: -->

<type1>
<subtype1>
<!-- etc. -->
</subtype1>
</type1>
</task>

Note that types may consist of multiple nested tags -- and multiple levels of nested tags, as you can see in the second task call above.

### 5.6.2 Referencing Types

An additional fact about types you should notice is the possibility of referencing type instances, i.e. you define your type somewhere in your build file and assign an id to it. Later, you can refer to that type by the id you assigned. Example:

<project>
<fileset id="foo">
<include name="*.php" />
</fileset>

<!-- Target that uses the type -->
<target name="foo" >
<copy todir="/tmp">
<fileset refid="foo" />
</copy>
</target>
</project>

As you can see, the type instance is assigned an id with the id attribute and later on called by passing a plain fileset tag to CopyTask that only contains the refid attribute.

## 5.7 Basic Types

The following section gives you a quick introduction into the basic Phing types. For a complete reference see Appendix D, Core Types.

### 5.7.1 FileSet

FileSets are groups of files. You can include or exclude specific files and patterns to/from a FileSet. The use of patterns is explained below. For a start, look at the following example:

<fileset dir="/tmp" id="fileset1">
<include name="sometemp/file.txt" />
<include name="othertemp/**" />
<exclude name="othertemp/file.txt" />
</fileset>

<fileset dir="/home" id="fileset2">
<include name="foo/**" />
<include name="bar/**/*.php" />
<exclude name="foo/tmp/**" />
</fileset>

The use of patterns is quite straightforward: If you simply want to match a part of a filename or dirname, you use *. If you want to include multiple directories and/or files, you use **. This way, filesets provide an easy but powerful way to include files.

### 5.7.2 FileList

FileLists, like FileSets, are collections of files; however, a FileList is an explicitly defined list of files -- and the files don't necessarily have to exist on the filesystem.

Besides being able to refer to nonexistent files, another thing that FileLists allow you to do is specify files in a certain order. Files in FileSets are ordered based on the OS-level directory listing functions, in some cases you may want to specify a list of files to be processed in a certain order -- e.g. when concatenating files using the <append> task.

<filelist dir="base/" files="file1.txt,file2.txt,file3.txt"/>

<!-- OR: -->
<filelist dir="basedir/" listfile="files_to_process.txt"/>

### 5.7.3 FilterChains and Filters

FilterChains can be compared to Unix pipes. Unix pipes add a great deal of flexibility to command line operations; for example, if you wanted to copy just those lines that contained the string blee from the first 10 lines of a file called foo to a file called bar, you could do:

cat foo | head -n10 | grep blee > bar

Something like this is not possible with the tasks and types that we have learned about thus far, and this is where the incredible usefulness of FilterChains becomes apparent. They emulate Unix pipes and provide a powerful dimension of file/stream manipulation for the tasks that support them.

FilterChain usage is quite straightforward: you pass the complex Phing type filterchain to a task that supports FilterChains and add individual filters to the FilterChain. In the course of executing the task, the filters are applied (in the order in which they appear in the XML) to the contents of the files that are being manipulated by your task.

<filterchain>
<replacetokens>
<token key="BC_PATH" value="${top.builddir}/"/> <token key="BC_PATH_USER" value="${top.builddir}/testsite/user/${lang}/"/> </replacetokens> <filterreader classname="Phing\Filter\TailFilter"> <param name="lines" value="10"/> </filterreader> </filterchain> The code listing above shows you some example of how to use filter chains. For a complete reference see Appendix D, Core Types. This filter chain would replace all occurrences of BC_PATH and BC_PATH_USER with the values assigned to them in lines 4 and 5. Additionally, it will only return the last 10 lines of the files. Notice above that FilterChain filters have a "shorthand" notation and a long, generic notation. Most filters can be described using both of these forms: <replacetokens> <token key="BC_PATH" value="${top.builddir}/"/>
<token key="BC_PATH_USER" value="${top.builddir}/testsite/user/${lang}/"/>
</replacetokens>

<!-- OR: -->

<hgarchive destination="${version}.tgz" /> ## C.27 HgCloneTask Make a copy of an existing Mercurial repository. This is available for PHP 5.4 and higher. Table C.28: Attributes NameTypeDescriptionDefaultRequired insecureBooleanDo not verify server certificate.falseNo repositoryStringPath to Mercurial repository.n/aYes targetPathStringDirectory to clone into.n/aYes quietBooleanWork silently unless an error occurs.falseNo ### C.27.1 Example <property name="repo.dir" value="./repo.directory" /> <property name="repo.url" value="https://bitbucket.org/spaetz/ceyx-mapcss" /> <resolvepath propertyName="repo.dir.resolved" file="${repo.dir}" />
<hgclone repository="${repo.url}" quiet="false" insecure="true" targetPath="${repo.dir.resolved}"/> 

Commit changes to a Mercurial repository. This is available for PHP 5.4 and higher.

Table C.29: Attributes

NameTypeDescriptionDefaultRequired
messageStringCommit message.n/aYes
quietBooleanWork silently unless an error occurs.falseNo
repositoryStringPath to Mercurial repository.n/aNo
userStringUser to record as the committer.n/aNo

### C.28.1 Example

<property name="repo.dir" value="./repo.directory" />
<resolvepath propertyName="repo.dir.resolved" file="${repo.dir}" /> <hgcommit message="[ci skip] Compress .js files." user="phingbot" repository="${repo.dir.resolved}"/> 

Create a new Mercurial repository. This is available for PHP 5.4 and higher.

Table C.30: Attributes

NameTypeDescriptionDefaultRequired
insecureBooleanDo not verify server certificate.falseNo
quietBooleanWork silently unless an error occurs.falseNo
repositoryStringPath to Mercurial repository.n/aNo

### C.29.1 Example

<property name="repo.dir" value="./repo.directory" />
<resolvepath propertyName="repo.dir.resolved" file="${repo.dir}" /> <hginit repository="${repo.dir.resolved}"/> 

Show revision history of entire Mercurial repository or files, or limit to a number of revisions. Optionally store the history to a phing property. This is available for PHP 5.4 and higher.

Table C.31: Attributes

NameTypeDescriptionDefaultRequired
formatStringDisplay with template, e.g. "{rev}\n", "{branch}" etc.n/aNo
maxCountIntegerNumber of commits to show/limit.n/aNo
outputPropertyStringProperty name to set output value to from the execution.n/aNo
repositoryStringPath to Mercurial repository.n/aYes
revisionStringShow the specified revision or range.n/aYes

### C.30.1 Example

<property name="repo.dir" value="./repo.directory" />
<resolvepath propertyName="repo.dir.resolved" file="${repo.dir}" /> <hglog maxCount="1" format="{files}\n" outputproperty="hgfiles" repository="${repo.dir.resolved}"/> 

Pull changes from a specified Mercurial repository to a local one. This is available for PHP 5.4 and higher.

Table C.32: Attributes

NameTypeDescriptionDefaultRequired
insecureBooleanDo not verify server certificate.falseNo
quietBooleanWork silently unless an error occurs.falseNo
repositoryStringPath to Mercurial repository.n/aNo

<hgpull quiet="false" insecure="true" repository="${repo.dir}"/>  ## C.32 HgPushTask Push changes from the local Mercurial repository to the specified destination. This is available for PHP 5.4 and higher. Table C.33: Attributes NameTypeDescriptionDefaultRequired insecureBooleanDo not verify server certificate.falseNo quietBooleanWork silently unless an error occurs.falseNo repositoryStringPath to Mercurial repository.n/aNo ### C.32.1 Example <property name="repo.dir" value="./repo.directory" /> <hgpush haltonerror="true" repository="{repo.dir.resolved}"/>  ## C.33 HgRevertTask Revert files to their checkout state from the Mercurial repository. This is available for PHP 5.4 and higher. Table C.34: Attributes NameTypeDescriptionDefaultRequired allBooleanRevert all Changes when no other details are given.falseNo nameStringName of file to revert.n/aNo quietBooleanWork silently unless an error occurs.falseNo revisionStringRevision to revert to.n/aNo ### C.33.1 Example <hgrevert all="true"/>  ## C.34 HgTagTask Add a tag for the current or specified revision of the local Mercurial repository. This is available for PHP 5.4 and higher. Table C.35: Attributes NameTypeDescriptionDefaultRequired messageStringMessage to add/edit tag with.n/aNo nameStringName of tag.n/aYes repositoryStringPath to Mercurial repository.n/aNo revisionStringRevision to tag.n/aNo userStringUser to record as the committer.n/aNo ### C.34.1 Example <hgtag user="phingbot" message="tagging new release" name="v0.1.2"/>  ## C.35 HgUpdateTask Update the Mercurial repository's working directory or switch revisions. This is available for PHP 5.4 and higher. Table C.36: Attributes NameTypeDescriptionDefaultRequired branchStringA specific branch to pull.n/aNo cleanBooleanDiscard uncommitted changes.falseNo quietBooleanWork silently unless an error occurs.falseNo repositoryStringPath to Mercurial repository.n/aYes ### C.35.1 Example <property name="repo.dir" value="./repo.directory" /> <hgupdate repository="${repo.dir.resolved}" branch="dev"/> 

Table C.37: Attributes

NameTypeDescriptionDefaultRequired
roomIntegerRoomIDn/aYes
authTokenStringAuthentication Tokenn/aYes
colorStringValid colors at this time are: yellow, green, red, purple, gray, randomyellowNo
notifyBooleanWhether this message should trigger a user notification or just add a note to the room.falseNo
formatStringhtml or texttextNo
domainStringDomain name of your HipChat server.api.hipchat.comNo

### C.36.1 Example

<hipchat room="3366876" authToken="**************">
Success
</hipchat>

<hipchat room="3366876" authToken="**************" color="red" notify="true" domain="hipchat.example.com">
Failure
</hipchat>

This task will download a file through HTTP GET and save it to a specified directory. You need an installed version of Guzzle to use this task.

Table C.38: Attributes

NameTypeDescriptionDefaultRequired
urlStringThe request URLn/aYes
dirStringThe directory to save the filen/aYes
filenameStringThe filename for the downloaded fileThe filename part of the URLNo
followRedirectsBooleanWhether to follow HTTP redirectsfalseNo
sslVerifyPeerBooleanWhether to verify SSL certificatestrueNo
authUserStringThe authentication user namen/aNo
authPasswordStringThe authentication passwordn/aNo
authSchemeStringThe authentication schemebasicNo
quietBooleanIf true, set default log level to Project.MSG_ERRfalseNo

### C.37.1 Example

<httpget url="http://buildserver.com/builds/latest.stable.tar.bz2" dir="/usr/local/lib"/>

### C.37.2 Supported Nested Tags

• config

Holds additional config data. See Guzzle documentation for supported values.

Table C.39: Attributes

NameTypeDescriptionDefaultRequired
nameStringConfig parameter namen/aYes
valueMixedConfig valuen/aYes

• header

Holds additional header name and value.

Table C.40: Attributes

NameTypeDescriptionDefaultRequired
nameStringHeader namen/aYes
valueStringHeader valuen/aYes

### C.37.3 Global configuration

In addition to configuring a particular instance of Guzzle via nested <config> tags it is also possible to set default configuration values for HttpGetTask / HttpRequestTask / VisualizerTask by setting phing.http.* properties.

<property name="phing.http.proxy" value="socks5://localhost:1080/"/>
<!-- This request will go through the default proxy -->
<httpget url="http://example.com/file.zip" dir="./"/>
<httpget url="http://example.org/file.exe" dir="./">
<!-- This proxy will be used instead of the default one -->
<config name="proxy" value="http://foo:[email protected]:3128/"/>
</httpget>


This task will make an HTTP request to the provided URL and match the response against the provided regular expression. If an regular expression is provided and doesn't match the build will fail. You need an installed version of Guzzle to use this task.

Table C.41: Attributes

NameTypeDescriptionDefaultRequired
urlStringThe request URLn/aYes
responseRegexStringThe regular expression for matching the responsen/aNo
responseCodeRegexStringThe regular expression for matching the response coden/aNo
authUserStringThe authentication user namen/aNo
authPasswordStringThe authentication passwordn/aNo
authSchemeStringThe authentication schemebasicNo
verboseBooleanWhether to enable detailed loggingfalseNo
methodStringThe HTTP method of the request, currently only GET or POST supportedGETNo

### C.38.1 Example

<http-request url="http://my-production.example.com/check-deployment.php"/>

Just perform a HTTP request to the given URL.

<http-request
url="http://my-production.example.com/check-deployment.php"
responseRegex="/Heartbeat/"
verbose"true"
observerEvents="connect, disconnect"/>

Perform a HTTP request to the given URL and matching the response against the given regex pattern. Enable detailed logging and log only the specified events.

<http-request url="http://my-production.example.com/check-deployment.php">
</http-request>

<http-request
url="http://my-production.example.com/check-deployment.php"
verbose"true"
method="POST">
<postparameter name="param1" value="value1" />
<postparameter name="param2" value="value2" />
</http-request>


Perform an HTTP POST request to the given URL. Setting POST request parameters to emulate form submission.

### C.38.2 Supported Nested Tags

• config

Holds additional config data. See Guzzle documentation for supported values.

Table C.42: Attributes

NameTypeDescriptionDefaultRequired
nameStringConfig parameter namen/aYes
valueMixedConfig valuen/aYes

• header

Holds additional header name and value.

Table C.43: Attributes

NameTypeDescriptionDefaultRequired
nameStringHeader namen/aYes
valueStringHeader valuen/aYes

• postparameter

Used when performing a POST request. Contains name and value of a form field.

Table C.44: Attributes

NameTypeDescriptionDefaultRequired
nameStringField namen/aYes
valueStringField valuen/aYes

### C.38.3 Global configuration

In addition to configuring a particular instance of Guzzle via nested <config> tags it is also possible to set default configuration values for HttpGetTask / HttpRequestTask / VisualizerTask by setting phing.http.* properties.

<property name="phing.http.proxy" value="socks5://localhost:1080/"/>
<!-- This request will go through the default proxy -->
<http-request url="http://example.com/foo"/>
<http-request url="http://example.org/restricted" dir="./">
<!-- This proxy will be used instead of the default one -->
<config name="proxy" value="http://foo:[email protected]:3128/"/>
</http-request>


The IniFileTask is inspired by the Ant-Contrib IniFile and can be used to build and edit .ini files. Unlike the Ant equivalent, it can also read values from different sections of an .ini file and set the retrieved values to specified properties.

Table C.45: Attributes

NameTypeDescriptionDefaultRequired
deststringThe name of the .ini file to write to. If not specified, the source file will be modified instead.noneNo
haltOnErrorbooleanShould the build fail when problems occur?falseNo
sourcestringThe name of the .ini file to read from. If not specified, the dest file will be used instead.noneNo

### C.39.1 Supported Nested Tags

• get

Use to read a value from a specific key and section of an .ini file

Table C.46: Attributes

NameTypeDescriptionDefaultRequired
defaultStringValue to return if section, property or value are not setn/aNo
sectionStringName of the section.n/aYes
propertyStringName of the key, in the specified section, to readn/aYes
outputpropertyStringName of the property to set the value ton/aYes

• remove

Use to remove either a specific key or section from an .ini file

Table C.47: Attributes

NameTypeDescriptionDefaultRequired
sectionStringName of the section.n/aYes
propertyStringName of the key to remove. If not specified the entire section is removed.n/aNo

• set

Use to set a key in a section to a specific value

Table C.48: Attributes

NameTypeDescriptionDefaultRequired
sectionStringName of the section.n/aYes
propertyStringName of the key/property.n/aYes
operationStringThe operation to perform on the existing value, which must be numeric. Possible values are "+" and "-", which add and subtract 1, respectively from the existing value. If the value doesn't already exist, the set is not performed, triggering an error.n/aNo
valueStringThe new value for the property.n/aNo, if operation is specified.

### C.39.2 Example

<inifile
haltonerror="no"
password="${deploy.password}" url="jdbc:mysql://${database.host}/${database.name}" display='true' checkreturn="true" passthru='false' outputProperty="liquibase.updateSQL.output" command="updateSQL" > <parameter name="logLevel" value="info" /> <property name="tablename" value="Person" /> </liquibase>  The nested parameters in the example above will result in the command:  --logLevel='info' updateSQL -Dtablename='Person'  ### C.45.2 Supported Nested Tags • parameter Use these nested parameter tags to set optional liquibase commands like --logLevel or --defaultsFile. Table C.55: Attributes NameTypeDescriptionDefaultRequired nameStringName of the liquibase parameter. Do not include the '--'.n/aYes valueStringValue of the liquibase parameter.n/aYes • property These tags are used to set what Liquibase calls "Change Log Properties" which are used for substitution in the change log(s). Note that they are not the same thing as regular Phing properties. Table C.56: Attributes NameTypeDescriptionDefaultRequired nameStringName of the property. Do not include the '-D'.n/aYes valueStringValue of the property.n/aYes ## C.46 LiquibaseChangeLogTask The LiquibaseChangeLogTask writes the Change Log XML to copy the current state of the database to the given changeLogFile. Table C.57: Attributes NameTypeDescriptionDefaultRequired jarStringLocation of the Liquibase jar file.n/aYes classpathStringAdditional classpath entries.n/aYes changeLogFileStringLocation of the changelog file in which the changes get written or read from.n/aYes usernameStringThe username needed to connect to the database.n/aYes passwordStringThe password needed to connect to the database.n/aYes urlStringThe JDBC Url representing the database datasource, e.g jdbc:mysql://localhost/mydatabasen/aYes displayBooleanWhether to display the output of the command. Only used if passthru isn't true.falseNo passthruBooleanWhether to use PHP's passthru() function instead of exec(). True by default for backwards compatibility. When true, the attributes display, outputProperty and checkReturnare ignored.trueNo checkreturnBooleanWhether to check the return code of the execution, throws a BuildException when returncode != 0.falseNo outputPropertyStringProperty name to set output value to from the execution. Ignored if passthru attribute is true.n/aNo ### C.46.1 Example <liquibase-changelog jar="/usr/local/lib/liquibase/liquibase.jar" classpathref="/usr/local/lib/liquibase/lib/mysql-connector-java-5.1.15-bin.jar" changelogFile="./changelogTest.xml" username="liquibase" password="liquibase" url="jdbc:mysql://localhost/mydatabase" /> ### C.46.2 Supported Nested Tags ## C.47 LiquibaseDbDocTask The LiquibaseDbDocTask generates a Javadoc-like documentation based on current database and the given changelog file. Table C.58: Attributes NameTypeDescriptionDefaultRequired jarStringLocation of the Liquibase jar file.n/aYes classpathStringAdditional classpath entries.n/aYes changeLogFileStringLocation of the changelog file in which the changes get written or read from.n/aYes usernameStringThe username needed to connect to the database.n/aYes passwordStringThe password needed to connect to the database.n/aYes urlStringThe JDBC URL representing the database data source, e.g jdbc:mysql://localhost/mydatabasen/aYes outputDirStringAbsolute path where the documentation gets written to. If the given directory does not exist, it gets created automatically.n/aYes displayBooleanWhether to display the output of the command. Only used if passthru isn't true.falseNo passthruBooleanWhether to use PHP's passthru() function instead of exec(). True by default for backwards compatibility. When true, the attributes display, outputProperty and checkReturnare ignored.trueNo checkreturnBooleanWhether to check the return code of the execution, throws a BuildException when returncode != 0.falseNo outputPropertyStringProperty name to set output value to from the execution. Ignored if passthru attribute is true.n/aNo ### C.47.1 Example <liquibase-dbdoc jar="/usr/local/lib/liquibase/liquibase.jar" classpathref="/usr/local/lib/liquibase/lib/mysql-connector-java-5.1.15-bin.jar" changelogFile="./changelogTest.xml" username="liquibase" password="liquibase" url="jdbc:mysql://localhost/mydatabase" outputDir="/tmp/generateddocs" /> ### C.47.2 Supported Nested Tags ## C.48 LiquibaseDiffTask The LiquibaseDiffTask creates a diff between two databases. Will output the changes needed to convert the reference database to the state of the database. Table C.59: Attributes NameTypeDescriptionDefaultRequired jarStringLocation of the Liquibase jar file.n/aYes classpathStringAdditional classpath entries.n/aYes changeLogFileStringLocation of the changelog file in which the changes get written or read from.n/aYes usernameStringThe username needed to connect to the database.n/aYes passwordStringThe password needed to connect to the database.n/aYes urlStringThe JDBC Url representing the database datasource, e.g jdbc:mysql://localhost/mydatabasen/aYes referenceUsernameStringThe username needed to connect to the reference database.n/aYes referencePasswordStringThe password needed to connect to the reference database.n/aYes referenceUrlStringThe JDBC Url representing the database reference datasource, e.g jdbc:mysql://localhost/refdatabasen/aYes displayBooleanWhether to display the output of the command. Only used if passthru isn't true.falseNo passthruBooleanWhether to use PHP's passthru() function instead of exec(). True by default for backwards compatibility. When true, the attributes display, outputProperty and checkReturnare ignored.trueNo checkreturnBooleanWhether to check the return code of the execution, throws a BuildException when returncode != 0.falseNo outputPropertyStringProperty name to set output value to from the execution. Ignored if passthru attribute is true.n/aNo ### C.48.1 Example <liquibase-diff jar="/usr/local/lib/liquibase/liquibase.jar" classpathref="/usr/local/lib/liquibase/lib/mysql-connector-java-5.1.15-bin.jar" changelogFile="./changelogTest.xml" username="liquibase" password="liquibase" url="jdbc:mysql://localhost/mydatabase" referenceUsername="liquibase" referencePassword="liquibase" referenceUrl="jdbc:mysql://localhost/refdatabase" /> ### C.48.2 Supported Nested Tags ## C.49 LiquibaseRollbackTask The LiquibaseRollbackTask rolls back the database to the state is was when the tag was applied. Table C.60: Attributes NameTypeDescriptionDefaultRequired jarStringLocation of the Liquibase jar file.n/aYes classpathStringAdditional classpath entries.n/aYes changeLogFileStringLocation of the changelog file in which the changes get written or read from.n/aYes usernameStringThe username needed to connect to the database.n/aYes passwordStringThe password needed to connect to the database.n/aYes urlStringThe JDBC Url representing the database datasource, e.g jdbc:mysql://localhost/mydatabasen/aYes rollbackTagStringThe name of the tag to roll the database back to.n/aYes displayBooleanWhether to display the output of the command. Only used if passthru isn't true.falseNo passthruBooleanWhether to use PHP's passthru() function instead of exec(). True by default for backwards compatibility. When true, the attributes display, outputProperty and checkReturnare ignored.trueNo checkreturnBooleanWhether to check the return code of the execution, throws a BuildException when returncode != 0.falseNo outputPropertyStringProperty name to set output value to from the execution. Ignored if passthru attribute is true.n/aNo ### C.49.1 Example <liquibase-rollback jar="/usr/local/lib/liquibase/liquibase.jar" classpathref="/usr/local/lib/liquibase/lib/mysql-connector-java-5.1.15-bin.jar" changelogFile="./changelogTest.xml" username="liquibase" password="liquibase" url="jdbc:mysql://localhost/mydatabase" rollbackTag="tag_0_1" /> ### C.49.2 Supported Nested Tags ## C.50 LiquibaseTagTask The LiquibaseTagTask tags the current database state for future rollback. Table C.61: Attributes NameTypeDescriptionDefaultRequired jarStringLocation of the Liquibase jar file.n/aYes classpathStringAdditional classpath entries.n/aYes changeLogFileStringLocation of the changelog file in which the changes get written or read from.n/aYes usernameStringThe username needed to connect to the database.n/aYes passwordStringThe password needed to connect to the database.n/aYes urlStringThe JDBC Url representing the database datasource, e.g jdbc:mysql://localhost/mydatabasen/aYes tagStringThe name of the tag to apply.n/aYes displayBooleanWhether to display the output of the command. Only used if passthru isn't true.falseNo passthruBooleanWhether to use PHP's passthru() function instead of exec(). True by default for backwards compatibility. When true, the attributes display, outputProperty and checkReturnare ignored.trueNo checkreturnBooleanWhether to check the return code of the execution, throws a BuildException when returncode != 0.falseNo outputPropertyStringProperty name to set output value to from the execution. Ignored if passthru attribute is true.n/aNo ### C.50.1 Example <liquibase-tag jar="/usr/local/lib/liquibase/liquibase.jar" classpathref="/usr/local/lib/liquibase/lib/mysql-connector-java-5.1.15-bin.jar" changelogFile="./changelogTest.xml" username="liquibase" password="liquibase" url="jdbc:mysql://localhost/mydatabase" tag="tag_0_1" /> ### C.50.2 Supported Nested Tags ## C.51 LiquibaseUpdateTask The LiquibaseUpdateTask applies the latest changes from the changelog file to the definied database. Table C.62: Attributes NameTypeDescriptionDefaultRequired jarStringLocation of the Liquibase jar file.n/aYes classpathStringAdditional classpath entries.n/aYes changeLogFileStringLocation of the changelog file in which the changes get written or read from.n/aYes usernameStringThe username needed to connect to the database.n/aYes passwordStringThe password needed to connect to the database.n/aYes urlStringThe JDBC Url representing the database datasource, e.g jdbc:mysql://localhost/mydatabasen/aYes displayBooleanWhether to display the output of the command. Only used if passthru isn't true.falseNo passthruBooleanWhether to use PHP's passthru() function instead of exec(). True by default for backwards compatibility. When true, the attributes display, outputProperty and checkReturnare ignored.trueNo checkreturnBooleanWhether to check the return code of the execution, throws a BuildException when returncode != 0.falseNo outputPropertyStringProperty name to set output value to from the execution. Ignored if passthru attribute is true.n/aNo ### C.51.1 Example <liquibase-update jar="/usr/local/lib/liquibase/liquibase.jar" classpathref="/usr/local/lib/liquibase/lib/mysql-connector-java-5.1.15-bin.jar" changelogFile="./changelogTest.xml" username="liquibase" password="liquibase" url="jdbc:mysql://localhost/mydatabase" /> ### C.51.2 Supported Nested Tags ## C.52 MailTask A task to send email. Attachments are supported if the PEAR Mail package is installed. Table C.63: Attributes NameTypeDescriptionDefaultRequired fromStringEmail address of sender.noneYes tolistStringComma-separated list of recipients.noneYes messageStringMessage to send in the body of the email.noneNo subjectStringEmail subject line.noneNo backendStringPEAR Mail backend (see here for possible values).mailNo backendParamsStringComma-separated key-value pairs with backend specific parameters (see here for possible values).noneNo ### C.52.1 Example <mail tolist="[email protected]" subject="build complete""> The build process is a success... </mail> ### C.52.2 Supported Nested Tags • fileset Files to be attached. ## C.53 NotifySendTask This is a wrapper for <em>notify-send</em>, a Linux program that sends desktop notifications to a notification daemon. On Windows machines, this port may help. Table C.64: Attributes NameTypeDescriptionDefaultRequired iconstringSpecify an icon filename or stock icon to display.infoNo messageStringText to display. Use \n to specify a line breakn/aYes titleStringTitle, or summary, of the notification.noneNo ## C.54 PackageAsPathTask Converts dot-notation packages to relative paths and stores it in a property. Table C.65: Attributes NameTypeDescriptionDefaultRequired packageStringThe package to convert.n/aYes nameStringThe property to store the path in.n/aYes ### C.54.1 Example Sample build command: <packageaspath package="phing.classes" name="path"/> ## C.55 ParallelTask Executes nested tasks in parallel. Parallel tasks have a number of uses in a Phing build file including: • Taking advantage of available processing resources to execute external programs simultaneously. • Testing servers, where the server can be run in one thread and the test harness is run in another thread. Any valid Phing task may be embedded within a parallel task, including other parallel tasks. While the tasks within the parallel task are being run, the main thread will be blocked waiting for all the child threads to complete. If one of the tasks within the parallel task fails, the remaining tasks will continue to run until all tasks have completed. In this situation, the parallel task will also fail. The threadCount attribute can be used to place a maximum number of available threads for the execution. When not present the value is based on the number of processors present. When present then the maximum number of concurrently executing tasks will not exceed the number of threads specified. Furthermore, each task will be started in the order they are given. But no guarantee is made as to the speed of execution or the order of completion of the tasks, only that each will be started before the next. ### Warning This task is highly experimental, and will only work on *nix machines that have the PHP pcntl extension installed. Table C.66: Attributes NameTypeDescriptionDefaultRequired threadCountIntegerMaximum number of threads / processes to use.n/aNo ### C.55.1 Example <parallel threadCount="4"> <echo>Job 1</echo> <echo>Job 2</echo> <echo>Job 3</echo> <echo>Job 4</echo> </parallel> ## C.56 PatchTask The PatchTask uses the patch program to apply diff file to originals. NB: the patch program must be in the system path! Table C.67: Attributes NameTypeDescriptionDefaultRequired patchfileStringFile that includes the diff outputn/aYes originalfileStringFile to patch. If not specified Task tries to guess it from the diff filenoneNo destfileStringFile to send the output to instead of patching the file in placenoneNo backupsBooleanKeep backups of the unpatched filesfalseNo quietBooleanWork silently unless an error occursfalseNo reverseBooleanAssume patch was created with old and new files swappedfalseNo ignorewhitespaceBooleanIgnore whitespace differencesfalseNo stripIntegerStrip the smallest prefix containing specified number of leading slashes from filenamesnoneNo dirStringThe directory in which to run the patch commandnoneNo haltonfailureBooleanStop the build process if the patching process encounters an error.falseNo forwardBooleanIgnore patches that appear to be reversed or already applied.falseNo fuzzStringSet the fuzz factor to LINES for inexact matching.n/aNo ### C.56.1 Example <patch patchfile="/path/to/patches/file.ext.patch" dir="/path/to/original" /> Apply "file.ext.path" to original file locataed in "/path/to/original" folder. ## C.57 PDOSQLExecTask The PDOSQLExecTask executes SQL statements using PDO. ### Note The combination of large SQL files and delimitertype set to normal can trigger segmentation faults with large files. Table C.68: Attributes NameTypeDescriptionDefaultRequired urlStringPDO connection URL (DSN)noneYes useridStringUsername for connection (if it cannot be specified in URL) noneNo passwordStringThe password to use for the connection (if it cannot be specified in URL)noneNo srcFileA single source file of SQL statements to execute.noneNo onerrorStringThe action to perform on error (continue, stop, or abort)abortNo delimiterStringThe delimiter to separate SQL statements (e.g. "GO" in MSSQL);No delimitertypeStringThe delimiter type ("normal", "row" or "none"). Normal means that any occurrence of the delimiter terminate the SQL command whereas with row, only a line containing just the delimiter is recognized as the end of the command. None disables all delimiter detection.noneNo autocommitBooleanWhether to auto (implicitly) commit every single statement, disabling transactions.falseNo encodingStringEncoding to use for read SQL filesnoneNo You can also use PDOSQLExecTask as condition ### C.57.1 Example <pdosqlexec url="pgsql:host=localhost dbname=test"> <fileset dir="sqlfiles"> <include name="*.sql"/> </fileset> </pdosqlexec> <pdosqlexec url="mysql:host=localhost;dbname=test" userid="username" password="password"> <transaction src="path/to/sqlfile.sql"/> <formatter type="plain" outfile="path/to/output.txt"/> </pdosqlexec> <property name="color" value="orange"/> <pdosqlexec url="mysql:host=localhost;dbname=test" userid="username" password="password"> <transaction> SELECT * FROM products WHERE color = '${color}';
</transaction>
<formatter type="xml" outfile="path/to/output.xml"/>
</pdosqlexec>

### Note

Because of backwards compatibility, the PDOSQLExecTask can also be called using the 'pdo' statement.

<pdo url="pgsql:host=localhost dbname=test">
<fileset dir="sqlfiles">
<include name="*.sql"/>
</fileset>

<!-- xml formatter -->
<formatter type="xml" output="output.xml"/>

<!-- custom formatter -->
<formatter classname="path.to.CustomFormatterClass">
<param name="someClassAttrib" value="some-value"/>
</formatter>

<!-- No output file + usefile=false means it goes to phing log -->
<formatter type="plain" usefile="false" />
</pdo>

### C.57.2 Supported Nested Tags

• transaction

Wrapper for a single transaction. Transactions allow several files or blocks of statements to be executed using the same PDO connection and commit operation in between.

Table C.69: Attributes

NameTypeDescriptionDefaultRequired
srcStringFile with statements to be run as one transactionn/aNo

• fileset

Files containing SQL statements.

• filelist

Files containing SQL statements.

• formatter

The results of any queries that are executed can be printed in different formats. Output will always be sent to a file, unless you set the usefile attribute to false. The path to the output file can be specified by the outfile attribute; there is a default filename that will be returned by the formatter if no output file is specified.

There are three predefined formatters - one prints the query results in XML format, the other emits plain text. Custom formatters that extend Phing\Task\System\Pdo\PDOResultFormatter can be specified.

Table C.70: Attributes

NameTypeDescriptionDefaultRequired
typeStringUse a predefined formatter (either xml or plain). n/aOne of these attributes is required.
classnameStringName of a custom formatter class (must extend Phing\Task\System\Pdo\PDOResultFormatter).n/a
usefileBooleanBoolean that determines whether output should be sent to a file.trueNo
outfileFilePath to file in which to store result.Depends on formatterNo
showheadersBoolean(only applies to plain formatter) Whether to show column headers.falseNo
coldelimString(only applies to plain formatter) The column delimiter.,No
rowdelimString(only applies to plain formatter) The row delimiter.\nNo
encodingString(only applies to XML formatter) The xml document encoding.(PHP default)No
formatoutputBoolean(only applies to XML formatter) Whether to format XML output.trueNo

PharData archives generating with Phing. This task require PECL's Phar extension to be installed on your system. Phar is built-in in PHP from 5.3 version.

Table C.71: Attributes

NameTypeDescriptionDefaultRequired
basedirStringBase directory, which will be deleted from each included file (from path). Paths with deleted basedir part are local paths in archive.n/aYes
destfileStringDestination (output) file. Will be recreated, if exists!n/aYes
compressionStringCompression type (gzip, bzip2, none) to apply to the archive.noneNo

### C.58.1 Example

Sample build command:

<phardata
destfile="./build/archive.tar"
basedir="./"
compression="gzip">
<fileset dir="./classes">
<include name="**/**" />
</fileset>
</phardata>

### C.58.2 Supported Nested Tags

• fileset

Phar packages generating with Phing. This task require PECL's Phar extension to be installed on your system. Phar is built-in in PHP from 5.3 version.

Table C.72: Attributes

NameTypeDescriptionDefaultRequired
basedirStringBase directory, which will be deleted from each included file (from path). Paths with deleted basedir part are local paths in package.n/aYes
destfileStringDestination (output) file. Will be recreated, if exists!n/aYes
compressionStringCompression type (gzip, bzip2, none) to apply to the packed files.noneNo
webstubStringRelative path within the phar package to run, if accessed through a web browser.n/aNo
clistubStringRelative path within the phar package to run, if accessed on the command line.n/aNo
stubStringA path to a php file that contains a custom stubn/aNo
aliasStringAn alias to assign to the phar packagen/aNo
signatureStringSignature algorithm (md5, sha1, sha256, sha512), used for this package.sha1No
keyStringThe private key to sign the phar package with (PEM or PKCS#12 encoded)n/aNo
keyPasswordStringThe password to use for the private keyn/aNo

### C.59.1 Example

Sample build command:

<pharpackage
destfile="./build/package.phar"
basedir="./">
<fileset dir="./classes">
<include name="**/**" />
</fileset>
<element name="version" value="1.0" />
<element name="authors">
<element name="John Doe">
<element name="e-mail" value="[email protected]" />
</element>
</element>
</pharpackage>

### C.59.2 Supported Nested Tags

• fileset

• metadata

Table C.73: Attributes

NameTypeDescriptionDefaultRequired
phkcreatorpathStringPath to PHK_Creator.phk.n/aYes
inputdirectoryStringPath to directory, that will be packed.n/aYes
outputfileStringOutput PHK-file. Directory, where file will be stored, must exist!n/aYes
compressStringCompression type (gzip, bzip2, none) to apply to the packed files.noneNo
stripBooleanWhen true, PHP source file(s) are stripped (filtered through php_strip_whitespace()) before being stored into the archive.falseNo
nameStringThe package's name (Information only).n/aNo
webrunscriptStringThe script to run in web direct access mode. Subfile path.n/aNo
crccheckBooleanIf true, a CRC check will be forced every time the package is mounted.falseNo

### C.60.1 Example

Sample build command:

<phkpackage
phkcreatorpath="/path/to/PHK_Creator.phk"
inputdirectory="src"
outputfile="build/sample-project.phk"
compress="gzip"
strip="true"
name="Sample Project"
webrunscript="index.php">
<webaccess>
<paentry>/</paentry>
</webaccess>
</phkpackage>

### C.60.2 Supported Nested Tags

• webaccess

Collection of path tags (see example below), that will be visible outside package in web mode.

This task runs PHP_CodeSniffer Version 3+ to detect violations of a defined set of coding standards.

Table C.74: Attributes

NameTypeDescriptionDefaultRequired
fileStringFile or directory to check.n/aYes
binStringPath to phpcs binary.phpcsNo
cacheBooleanCache results between runs.falseNo
ignoreAnnotationsBooleanIgnore all phpcs annotations in code comments.falseNo
checkreturnBooleanWhether to check the return code.falseNo
levelStringSet the log level of generated messages. Change this to verbose, if you only want output in verbose mode for example. Valid log levels are one of debug, info, verbose, warning or errorinfoNo

### C.61.1 Supported Nested Tags

• FileSet

### C.61.2 Examples

<phpcs bin="bin/phpcs" file="classes" checkreturn="true"/>

This task runs phpcpd, a Copy/Paste Detector (CPD) for PHP Code. You need an installed version of this software to use this task.

NB: if you have installed the PHPCPD PHAR, make sure you set the pharlocation attribute!

Table C.75: Attributes

NameTypeDescriptionDefaultRequired
fileStringPath to source file or pathn/aOnly when there are no nested fileset elements
minTokensIntegerSets the minimum number of identical tokens (default: 70)70No
minLinesIntegerSets the minimum number of identical lines (default: 5)5No
formatStringThe format for the report when no nested formatter is used.defaultNo
fuzzyBooleanIf fuzzy is set to true, the task will perform a fuzzy match.falseNo
pharlocationStringLocation of the PHPCPD PHAR package.n/aNo

### C.62.1 Examples

<phpcpd file="path/to/source.php"/>

Checking for copy/paste code in one particular source file. Sending Default-Report to STDOUT.

<phpcpd file="path/to/source">
<formatter type="pmd" outfile="reports/pmd-cpd.xml"/>
</phpcpd>

Checking for copy/paste code in files of the given path.

<phpcpd>
<fileset dir="${builddir}" id="filestocpd"> <include name="apps/**/*.php" /> <include name="lib/de/**/*.php" /> <include name="lib/task/**/*.php" /> <include name="lib/services/**/*.php" /> <include name="lib/form/**/*.php" /> <include name="lib/model/**/*.php" /> </fileset> <formatter type="pmd" outfile="reports/pmd-cpd.xml"/> </phpcpd> ### C.62.2 Supported Nested Tags • fileset This nested tag is required when the file attribute is not set. • formatter The results of the copy/paste scan can be printed in different formats. Output will always be sent to a file, unless you set the usefile attribute to false. Table C.76: Attributes NameTypeDescriptionDefaultRequired typeStringThe output format. Accepts the same values as the format attribute (default, pmd).n/aYes useFileBooleanFlag that determines whether output should be sent to a file or not.trueNo outfileStringPath to write output file to.n/aYes ## C.63 PhpDependTask This task runs PHP_Depend, a software analyzer and metric tool for PHP Code. You need an installed version of this software to use this task. NB: if you have installed the PHP_Depend Phar file, make sure you set the pharLocation attribute! Table C.77: Attributes NameTypeDescriptionDefaultRequired fileStringPath to source file or pathn/aOnly when there are no nested fileset elements configFileStringPath to PHP_Depend configuration filen/aNo allowedFileExtensionsStringComma-separated list of valid file extensions (without dot) for analyzed files.php,php5No excludeDirectoriesStringComma-separated list of directory patterns to ignore..git, .svn, CVSNo excludePackagesStringComma-separated list of packages to ignore.n/aNo withoutAnnotationsBooleanShould the parse ignore doc comment annotations?falseNo supportBadDocumentationBooleanShould PHP_Depend treat +global as a regular project package?falseNo debugBooleanEnable debug output?falseNo haltonerrorBooleanStop the build process if errors occurred during the run.falseNo pharlocationStringLocation of the PHP_Depend Phar file.n/aNo ### C.63.1 Example <phpdepend file="path/to/source"> <logger type="phpunit-xml" outfile="reports/metrics.xml"/> </phpdepend> Running code analysis for source files in the given path. <phpdepend> <fileset dir="${builddir}">
<include name="apps/**/*.php" />
<include name="lib/de/**/*.php" />
</fileset>
<logger type="jdepend-xml" outfile="reports/jdepend.xml"/>
<analyzer type="coderank-mode" value="method"/>
</phpdepend>

Running code analysis for source files in the fileset pathes with CodeRank strategy method.

### C.63.2 Supported Nested Tags

• fileset

This nested tag is required when the file attribute is not set.

• logger

The results of the analysis can be parsed by differed loggers. At least one logger is required. Output will always be sent to a file.

Table C.78: Attributes

NameTypeDescriptionDefaultRequired
typeStringThe name of the logger. Valid loggers are: jdepend-chart, jdepend-xml, overview-pyramid, phpunit-xml and summary-xml.n/aYes
outfileStringPath to write output file to.n/aYes

• analyzer

Table C.79: Attributes

NameTypeDescriptionDefaultRequired
typeStringThe name of the analyzer. Valid analyzers are: coderank-mode.n/aYes
valueStringThe value for the analyzer.n/aYes

This task runs phpDocumentor 2, a PHP 5.3-compatible API documentation tool. This project is the result of the merge of the phpDocumentor and DocBlox projects.

Table C.80: Attributes

NameTypeDescriptionDefaultRequired
titleStringTitle of the project.n/aNo
destdirStringDestination directory for output files.n/aYes
templateStringName of the documentation template to use.responsive-twigNo
defaultPackageNameStringName of the default package.DefaultNo
pharlocationStringLocation of the phpDocumentor PHAR package.n/aNo

### C.64.1 Example

<phpdoc2 title="API Documentation"
destdir="apidocs"
template="responsive-twig">
<fileset dir="./classes">
<include name="**/*.php" />
</fileset>
</phpdoc2>

### C.64.2 Supported Nested Tags

• fileset - Files that should be included for parsing

This task runs phploc, a tool for measuring the size of PHP projects. You need an installed version of this tool (installable via PEAR) to use this task.

NB: if you have installed the PHPLOC PHAR, make sure you set the pharlocation attribute!

Table C.81: Attributes

NameTypeDescriptionDefaultRequired
reportTypeStringThe type of the report. Available types are cli|csv|txt|xml.cliNo
reportNameStringThe name of the report type without a file extension.phploc-reportNo
reportDirectoryStringThe directory to write the report file to.falseYes, when report type csv, txt, xml or json is defined.
countTestsBooleanFlag to count the projects tests or not.falseNo
fileStringThe name of the file to check.n/aYes, when no nested fileset is defined.
suffixesStringA comma-separated list of file suffixes to check.phpNo
pharlocationStringLocation of the PHPLOC PHAR package.n/aNo

### C.65.1 Examples

<target name="-measure-and-log"
description="Measures and logs the size of the project" hidden="true">
<tstamp>
<format property="check.date.time" pattern="%Y%m%d-%H%M%S" locale="en_US"/>
</tstamp>
<phploc reportType="txt" reportName="${check.date.time}-report" reportDirectory="phploc-reports"> <fileset dir="."> <include name="**/*.php" /> <include name="*.php" /> </fileset> </phploc> </target> Checks the size of the project living in${project.basedir} and writes the result as a txt report to ${project.basedir}/phploc-reports/${check.date.time}-report.txt.

<target name="project-size-and-tests"
description="Measures the size of the project and counts the tests">
<phploc countTests="true">
<fileset dir=".">
<include name="**/*.php" />
<include name="*.php" />
</fileset>
</phploc>
</target>

Checks the size of the project living in ${project.basedir}, counts the project tests and writes/logs the result to the CLI. ### C.65.2 Supported Nested Tags • fileset • formatter The results of the analysis can be printed in different formats. A formatter is required when reportType is not set. Table C.82: Attributes NameTypeDescriptionDefaultRequired typeStringThe output format. Accepts the same values as the reportType attribute (xml, csv, text, cli).n/aYes usefileBooleanBoolean that determines whether output should be sent to a file.trueNo outfileStringPath to write output file to.n/aYes, if usefile> is true ## C.66 PHPMDTask This task runs phpmd, a Project Mess Detector (PMD) for PHP Code. You need an installed version of this software to use this task. NB: if you have installed the PHPMD Phar file, make sure you set the pharLocation attribute! Table C.83: Attributes NameTypeDescriptionDefaultRequired fileStringPath to source file or pathn/aOnly when there are no nested fileset elements rulesetsStringSets the rulesets used for analyzing the source codecodesize, unusedcodeNo minimumPriorityIntegerThe minimum priority for rules to load.5No allowedFileExtensionsStringComma-separated list of valid file extensions (without dot) for analyzed files.phpNo ignorePatternsStringComma-separated list of directory patterns to ignore..git, .svn, CVS, .bzr, .hgNo formatStringThe format for the report when no nested formatter is used.textNo pharlocationStringLocation of the PHPMD Phar file.n/aNo cachefileStringIf set, enables writing of last-modified times to cachefile, to speed up processing of files that rarely changenoneNo ### C.66.1 Example <phpmd file="path/to/source.php"/> Checking syntax of one particular source file. Sending Text-Report to STDOUT. <phpmd file="path/to/source"> <formatter type="html" outfile="reports/pmd.html"/> </phpmd> Checking syntax of source files in the given path. <phpmd> <fileset dir="${builddir}">
<include name="apps/**/*.php" />
<include name="lib/de/**/*.php" />
</fileset>
<formatter type="xml" outfile="reports/pmd.xml"/>
</phpmd>

Checking syntax of source files in the fileset pathes.

### C.66.2 Supported Nested Tags

• fileset

This nested tag is required when the file attribute is not set.

• formatter

The results of the analysis can be printed in different formats. Output will always be sent to STDOUT, unless you set the usefile attribute to true and set an filename in the outfile attribute.

Table C.84: Attributes

NameTypeDescriptionDefaultRequired
typeStringThe output format. Accepts the same values as the format attribute (xml, html, text).n/aYes
usefileBooleanBoolean that determines whether output should be sent to a file.trueNo
outfileStringPath to write output file to.n/aYes

The PHPStanTask executes PHPStan - a PHP static analysis tool - with given configuration.

Table C.85: Base attributes

NameTypeDescriptionDefaultRequired
commandStringPHPStan command nameanalyseNo
executableStringPath to PHPStan executablephpstanNo
checkReturnBooleanWhether to check the return code.falseNo

Table C.86: Analyse command attributes

NameTypeDescriptionDefaultRequired
configurationStringPath to configuration No
levelStringAnalyse level No
noProgressStringNO progress flagfalseNo
debugStringDebug flagfalseNo
autoloadFileStringPath to autoload file No
errorFormatStringError format No
memoryLimitStringMemory limit No
pathsStringPaths (space separated) No

Table C.87: List command attributes

NameTypeDescriptionDefaultRequired
formatStringHelp format No
rawStringRaw flagfalseNo
namespaceStringNamespace No

Table C.88: Help command attributes

NameTypeDescriptionDefaultRequired
formatStringHelp format No
rawStringRaw flagfalseNo
commandNameStringCommand name No

Table C.89: Common attributes

NameTypeDescriptionDefaultRequired
helpStringHelp flagfalseNo
quietStringQuiet flagfalseNo
versionStringVersion flagfalseNo
ansiStringANSI flagfalseNo
noAnsiStringNo ANSI flagfalseNo
noInteractionStringNo interaction flagfalseNo
verboseStringVerbose flagfalseNo

### C.67.1 Supported Nested Tags

• fileset

### C.67.2 Example

                <phpstan
command="analyse"
configuration="anyConfiguration"
level="anyLevel"
noProgress="true"
debug="true"
errorFormat="anyErrorFormat"
memoryLimit="anyMemoryLimit"
paths="path1 path2"
/>

                <phpstan command="analyse">
<fileset refid="files-to-analyse"/>
</phpstan>


This task runs testcases using the PHPUnit framework. It is a functional port of the Ant JUnit task.

NB: if you want to use the PHPUnit .phar file, please make sure you download the library version (phpunit-library.phar) and you set the pharlocation attribute!

Table C.90: Attributes

NameTypeDescriptionDefaultRequired
printsummaryBooleanPrint one-line statistics for each testcase.falseNo
bootstrapStringThe name of a bootstrap file that is run before executing the tests.noneNo
codecoverageBooleanGather code coverage information while running tests (requires Xdebug).falseNo
haltonerrorBooleanStop the build process if an error occurs during the test run.falseNo
haltonfailureBooleanStop the build process if a test fails (errors are considered failures as well).falseNo
haltondefectBooleanStop the build process if a test has failures, errors or warnings.falseNo
haltonincompleteBooleanStop the build process if any incomplete tests are encountered.falseNo
haltonskippedBooleanStop the build process if any skipped tests are encountered.falseNo
haltonwarningBooleanStop the build process if any warnings are encountered.falseNo
haltonriskyBooleanStop the build process if any risky tests are encountered.falseNo
failurepropertyStringName of property to set (to true) on failure.n/aNo
errorpropertyStringName of property to set (to true) on error.n/aNo
incompletepropertyStringName of property to set (to true) on incomplete tests.n/aNo
skippedpropertyStringName of property to set (to true) on skipped tests.n/aNo
warningpropertyStringName of property to set (to true) on warnings.n/aNo
riskypropertyStringName of property to set (to true) on risky tests.n/aNo
usecustomerrorhandlerBooleanUse a custom Phing/PHPUnit error handler to process PHP errors.trueNo
processisolationBooleanEnable process isolation when executing tests.falseNo
configurationStringPath to a PHPUnit configuration file (such as phpunit.xml). Supported elements are: bootstrap, processIsolation, stopOnFailure, stopOnError, stopOnIncomplete and stopOnSkipped. Values provided overwrite other attributes!n/aNo
groupsStringOnly run tests from the specified group(s).n/aNo
excludeGroupsStringExclude tests from the specified group(s).n/aNo
pharlocationStringLocation of the PHPUnit PHAR package.n/aNo

### C.68.1 Supported Nested Tags

• formatter

The results of the tests can be printed in different formats. Output will always be sent to a file, unless you set the usefile attribute to false. The name of the file is predetermined by the formatter and can be changed by the outfile attribute.

There are six predefined formatters. xml, clover, and crap4j print the test results in the JUnit, Clover, and Crap4J XML formats respectively. The clover-html formatter prints code coverage details to a set of HTML files. The plain formatter emits a short statistics line for all test cases. The summary formatter print the same statistics as the plain formatter but only to the log output. Custom formatters that implement Phing\Task\Ext\Formatter\PHPUnitResultFormatter can be specified.

Table C.91: Attributes

NameTypeDescriptionDefaultRequired
typeStringUse a predefined formatter (either xml, plain, clover, clover-html, crap4j, or summary). n/aOne of these is required.
classnameStringName of a custom formatter class.n/a
usefileBooleanBoolean that determines whether output should be sent to a file.trueNo
todirStringDirectory to write the file to.n/aNo
outfileStringFilename of the result.Depends on formatterNo

• batchtest

Define a number of tests based on pattern matching. batchtest collects the included files from any number of nested <fileset>s. It then generates a lists of classes that are (in)directly defined by each PHP file.

Table C.92: Attributes

NameTypeDescriptionDefaultRequired
excludeStringA list of classes to exclude from the pattern matching. For example, when you have two baseclasses BaseWebTest and BaseMathTest, which are included a number of testcases (and thus added to the list of testclasses), you can exclude those classes from the list by typing exclude="BaseWebTest BaseMathTest".n/aNo
classpathStringUsed to define more paths on which - besides the PHP include_path - to look for the test files.n/aNo
nameStringThe name that is used to create a testsuite from this batchtest.Phing BatchtestNo

### C.68.2 Example

<phpunit>
<formatter todir="reports" type="xml"/>
<batchtest>
<fileset dir="tests">
<include name="**/*Test*.php"/>
<exclude name="**/Abstract*.php"/>
</fileset>
</batchtest>
</phpunit>

Runs all matching testcases in the directory tests, writing XML results to the directory reports.

<phpunit codecoverage="true" haltonfailure="true" haltonerror="true">
<formatter type="plain" usefile="false"/>
<batchtest>
<fileset dir="tests">
<include name="**/*Test*.php"/>
</fileset>
</batchtest>
</phpunit>

Runs all matching testcases in the directory tests, gathers code coverage information, writing plain text results to the console. The build process is aborted if a test fails.

<phpunit bootstrap="src/autoload.php">
<formatter type="plain" usefile="false"/>
<batchtest>
<fileset dir="tests">
<include name="**/*Test*.php"/>
</fileset>
</batchtest>
</phpunit>

Runs all matching testcases in the directory tests, writing plain text results to the console. Additionally, before executing the tests, the bootstrap file src/autoload.php is loaded.

Important note: using a mechanism such as an "AllTests.php" file to execute testcases will bypass the Phing hooks used for reporting and counting, and could possibly lead to strange results. Instead, use one of more fileset's to provide a list of testcases to execute.

### C.68.3 Supported Nested Tags

• fileset

## C.69 PHPUnitReport

This task transforms PHPUnit xml reports to HTML using XSLT.

Table C.93: Attributes

NameTypeDescriptionDefaultRequired
infileStringThe filename of the XML results file to use.testsuites.xmlNo
formatStringThe format of the generated report. Must be noframes or frames.noframesNo
styledirStringThe directory where the stylesheets are located. They must conform to the following conventions: frames format: the stylesheet must be named phpunit-frames.xsl. noframes format: the stylesheet must be named phpunit-noframes.xsl. If unspecified, the task will look for the stylesheet(s) in the following directories: the PHP include path, the Phing home directory and the PEAR data directory (if applicable). n/aNo
todirStringAn existing directory where the files resulting from the transformation should be written to. Yes
usesorttableBooleanWhether to use the sorttable JavaScript library (see http://www.kryogenix.org/code/browser/sorttable/)falseNo

### C.69.1 Example

<phpunitreport infile="reports/testsuites.xml"
format="frames"
todir="reports/tests"
styledir="/home/phing/etc"/>

Generates a framed report in the directory reports/tests using the file reports/testsuites.xml as input.

Important note: testclasses that are not explicitly placed in a package (by using a '@package' tag in the class-level DocBlock) are listed under the "default" package.

Renders rST (reStructuredText) files into different output formats.

This task requires the python docutils installed. They contain rst2html, rst2latex, rst2man, rst2odt, rst2s5, rst2xml.

Table C.94: Attributes

NameTypeDescriptionDefaultRequired
fileStringrST input file to rendern/aYes (or fileset)
formatString

Output format:

• html

• latex

• man

• odt

• s5

• xml

htmlNo
destinationStringPath to store the rendered file to. Used as directory if it ends with a /.magically determined from input fileNo
uptodateBooleanOnly render if the input file is newer than the target filefalseNo
toolpathStringPath to the rst2* tooldetermined from formatNo
toolparamStringAdditional commandline parameters to the rst2* tooln/aNo
modeIntegerThe mode to create directories with.From umaskNo

### C.70.1 Features

• renders single files

• render nested filesets

• mappers to generate output file names based on the rst ones

• multiple output formats

• filter chains to e.g. replace variables after rendering

• custom parameters to the rst2* tool

• configurable rst tool path

• uptodate check

• automatically overwrites old files

• automatically creates target directories

### C.70.2 Examples

Render a single rST file to HTML

By default, HTML is generated. If no target file is specified, the input file name is taken, and its extension replaced with the correct one for the output format.

<?xml version="1.0" encoding="utf-8"?>
<project name="example" basedir="." default="single">
<target name="single" description="render a single rST file to HTML">

<rST file="path/to/file.rst" />

</target>
</project>

Render a single rST file to any supported format

The format attribute determines the output format:

<?xml version="1.0" encoding="utf-8"?>
<project name="example" basedir="." default="single">
<target name="single" description="render a single rST file to S5 HTML">

<rST file="path/to/file.rst" format="s5" />

</target>
</project>

Specifying the output file name

<?xml version="1.0" encoding="utf-8"?>
<project name="example" basedir="." default="single">
<target name="single" description="render a single rST file">

<rST file="path/to/file.rst" destination="path/to/output/file.html" />

</target>
</project>

Rendering multiple files

A nested fileset tag may be used to specify multiple files.

<?xml version="1.0" encoding="utf-8"?>
<project name="example" basedir="." default="multiple">
<target name="multiple" description="renders several rST files">

<rST>
<fileset dir=".">
<include name="docs/*.rst" />
</fileset>
</rST>

</target>
</project>

Rendering multiple files to another directory

A nested mapper may be used to determine the output file names.

<?xml version="1.0" encoding="utf-8"?>
<project name="example" basedir="." default="multiple">
<target name="multiple" description="renders several rST files">

<rST>
<fileset dir=".">
<include name="docs/*.rst" />
</fileset>
<mapper type="glob" from="*.rst" to="path/to/my/*.xhtml"/>
</rST>

</target>
</project>

Modifying files after rendering

You may have variables in your rST code that can be replaced after rendering, i.e. the version of your software.

<?xml version="1.0" encoding="utf-8"?>
<project name="example" basedir="." default="filterchain">
<target name="filterchain" description="renders several rST files">

<rST>
<fileset dir=".">
<include name="docs/*.rst" />
</fileset>
<filterchain>
<replacetokens begintoken="##" endtoken="##">
<token key="VERSION" value="1.23.0" />
</replacetokens>
</filterchain>
</rST>

</target>
</project>

Rendering changed files only

The uptodate attribute determines if only those files should be rendered that are newer than their output file.

<?xml version="1.0" encoding="utf-8"?>
<project name="example" basedir="." default="multiple">
<target name="multiple" description="renders several rST files">

<rST uptodate="true">
<fileset dir=".">
<include name="docs/*.rst" />
</fileset>
</rST>

</target>
</project>

Specify a custom CSS file

You may pass any additional parameters to the rst conversion tools with the toolparam attribute.

<?xml version="1.0" encoding="utf-8"?>
<project name="example" basedir="." default="single">
<target name="single" description="render a single rST file to S5 HTML">

<rST file="path/to/file.rst" toolparam="--stylesheet-path=custom.css" />

</target>
</project>

### C.70.3 Supported Nested Tags

• fileset

• mapper

• filterchain

Uploads an object to Amazon S3. This task requires the PEAR package Services_Amazon_S3

Table C.95: Attributes

NameTypeDescriptionDefaultRequired
keyStringAmazon S3 keyn/aYes (or defined before task call as: amazon.key)
secretStringAmazon S3 secretn/aYes (or defined before task call as: amazon.secret)
bucketStringBucket to store the object inn/aYes (or defined before task call as: amazon.bucket)
contentStringContent to store in the objectn/aYes (or source or fileset)
sourceStringWhere to read content for the object fromn/aYes (or content or fileset)
objectStringObject namen/aYes (unless fileset)
contentTypeStringContent type of the object, set to auto if you want to autodetect the content type based on the source file extensionbinary/octet-streamNo
fileNameOnlyBooleanWhether filenames should contain paths when uploaded to a bucketfalseNo

### C.71.1 Example

<s3put source="/path/to/file.txt" object="file.txt" bucket="mybucket"
key="AmazonKey" secret="AmazonSecret" />

You can also define "bucket, key, secret" outside of the task call:

<property name="amazon.key" value="my_key" />
<property name="amazon.secret" value="my_secret" />
<property name="amazon.bucket" value="mybucket" />

<s3put source="/path/to/file.txt" object="file.txt" />

You can also specify inline content instead of a file to upload:

<property name="amazon.key" value="my_key" />
<property name="amazon.secret" value="my_secret" />
<property name="amazon.bucket" value="mybucket" />

<s3put content="Some content here" object="file.txt" />

It also works with filesets:

<property name="amazon.key" value="my_key`