diff --git a/.gitignore b/.gitignore index eb0f0679..810a7b0a 100644 --- a/.gitignore +++ b/.gitignore @@ -4,9 +4,9 @@ .Trashes Thumbs.db Desktop.ini -composer.lock composer.phar phpunit.xml +phpword.ini /.buildpath /.idea /.project diff --git a/.scrutinizer.yml b/.scrutinizer.yml index 8efd68d3..6f982d8e 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -5,12 +5,20 @@ before_commands: - "composer install --prefer-source --dev" tools: + php_code_sniffer: + enabled: true + config: + standard: PSR2 + php_mess_detector: + enabled: true + config: + ruleset: phpmd.xml.dist external_code_coverage: enabled: true timeout: 900 - php_code_coverage: - enabled: false - test_command: phpunit -c phpunit.xml.dist - php_sim: true + php_cpd: true + # php_sim: # Temporarily disabled to allow focus on things other than duplicates + # min_mass: 40 php_pdepend: true php_analyzer: true + sensiolabs_security_checker: true diff --git a/.travis.yml b/.travis.yml index 8cc348f8..73dd68ec 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,55 +1,60 @@ language: php php: - - 5.3.3 - - 5.3 - - 5.4 - - 5.5 - - 5.6 - - hhvm + - 5.3.3 + - 5.3 + - 5.4 + - 5.5 + - 5.6 + - hhvm matrix: - allow_failures: - - php: 5.3.3 - - php: 5.6 - - php: hhvm + allow_failures: + - php: hhvm + +env: + global: + - secure: "Sq+6bVtnPsu0mWX8DWQ+9bGAjxMcGorksUiHc4YIXEJsuDfVmVlH8tTD547IeCjDAx9MxXerZ2Z4HSjxTB70VEnJPvZMHI/EZn4Ny31YLHEthdZbV5Gd1h0TGp8VOzPKGShvGrtGBX6MvMfgpK4zuieVWbSfdKeecm8ZNLMpUd4=" before_script: - ## Composer - # - curl -s http://getcomposer.org/installer | php - # - php composer.phar install --prefer-source - - composer self-update - - composer require dompdf/dompdf:0.6.* - - composer install --prefer-source - ## PHP_CodeSniffer - - pyrus install pear/PHP_CodeSniffer - - phpenv rehash - ## PHP Copy/Paste Detector - #- curl -o phpcpd.phar https://phar.phpunit.de/phpcpd.phar - ## PHP Mess Detector - #- pear config-set preferred_state beta - #- printf "\n" | pecl install imagick - #- pear channel-discover pear.phpmd.org - #- pear channel-discover pear.pdepend.org - #- pear install --alldeps phpmd/PHP_PMD - #- phpenv rehash - ## PHPLOC - #- curl -o phploc.phar https://phar.phpunit.de/phploc.phar + ## Packages + - sudo apt-get -qq update > /dev/null + - sudo apt-get -qq install graphviz > /dev/null + ## Composer + - composer self-update + - composer install --prefer-source --dev + ## PHP Copy/Paste Detector + - curl -o phpcpd.phar https://phar.phpunit.de/phpcpd.phar + ## PHP Mess Detector + - pear config-set preferred_state beta + - printf "\n" | pecl install imagick + - pear channel-discover pear.phpmd.org + - pear channel-discover pear.pdepend.org + - pear install --alldeps phpmd/PHP_PMD + - phpenv rehash + ## PHPLOC + #- curl -o phploc.phar https://phar.phpunit.de/phploc.phar + ## PHPDocumentor + - mkdir -p build/docs + - mkdir -p build/coverage script: - ## PHP_CodeSniffer - - phpcs --standard=PSR2 -n src/ --ignore=src/PhpWord/Shared/PCLZip - - phpcs --standard=PSR2 -n tests/ - ## PHP Copy/Paste Detector - #- php phpcpd.phar --verbose src/ - ## PHP Mess Detector - #- phpmd src/ text unusedcode,naming,design - ## PHPLOC - #- php phploc.phar src/ - ## PHPUnit - - phpunit -c ./ --coverage-text + ## PHP_CodeSniffer + - ./vendor/bin/phpcs src/ tests/ --standard=PSR2 -n --ignore=src/PhpWord/Shared/PCLZip + ## PHP Copy/Paste Detector + - php phpcpd.phar src/ tests/ --verbose + ## PHP Mess Detector + - phpmd src/,tests/ text ./phpmd.xml.dist --exclude pclzip.lib.php + ## PHPLOC + #- php phploc.phar src/ + ## PHPUnit + - phpunit -c ./ --coverage-text --coverage-html ./build/coverage + ## PHPDocumentor + - vendor/bin/phpdoc.php -q -d ./src -t ./build/docs --ignore "*/src/PhpWord/Shared/*/*" --template="responsive-twig" after_script: - ## Scrutinizer - - wget https://scrutinizer-ci.com/ocular.phar - - php ocular.phar code-coverage:upload --format=php-clover build/logs/clover.xml + ## PHPDocumentor + - bash .travis_shell_after_success.sh + ## Scrutinizer + - wget https://scrutinizer-ci.com/ocular.phar + - php ocular.phar code-coverage:upload --format=php-clover build/logs/clover.xml diff --git a/.travis_shell_after_success.sh b/.travis_shell_after_success.sh new file mode 100644 index 00000000..35c7a338 --- /dev/null +++ b/.travis_shell_after_success.sh @@ -0,0 +1,39 @@ +#!/bin/bash + +echo "--DEBUG--" +echo "TRAVIS_REPO_SLUG: $TRAVIS_REPO_SLUG" +echo "TRAVIS_PHP_VERSION: $TRAVIS_PHP_VERSION" +echo "TRAVIS_PULL_REQUEST: $TRAVIS_PULL_REQUEST" + +if [ "$TRAVIS_REPO_SLUG" == "PHPOffice/PHPWord" ] && [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_PHP_VERSION" == "5.5" ]; then + + echo -e "Publishing PHPDoc...\n" + + cp -R build/docs $HOME/docs-latest + cp -R build/coverage $HOME/coverage-latest + + cd $HOME + git config --global user.email "travis@travis-ci.org" + git config --global user.name "travis-ci" + git clone --quiet --branch=gh-pages https://${GH_TOKEN}@github.com/PHPOffice/PHPWord gh-pages > /dev/null + + cd gh-pages + echo "--DEBUG : Suppression" + git rm -rf ./docs/$TRAVIS_BRANCH + + echo "--DEBUG : Dossier" + mkdir -p docs/$TRAVIS_BRANCH + mkdir -p coverage/$TRAVIS_BRANCH + + echo "--DEBUG : Copie" + cp -Rf $HOME/docs-latest/* ./docs/$TRAVIS_BRANCH/ + cp -Rf $HOME/coverage-latest/* ./coverage/$TRAVIS_BRANCH/ + + echo "--DEBUG : Git" + git add -f . + git commit -m "PHPDocumentor (Travis Build: $TRAVIS_BUILD_NUMBER - Branch: $TRAVIS_BRANCH)" + git push -fq origin gh-pages > /dev/null + + echo -e "Published PHPDoc to gh-pages.\n" + +fi diff --git a/CHANGELOG.md b/CHANGELOG.md index 02439e1b..cd4d6f34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,73 @@ This is the changelog between releases of PHPWord. Releases are listed in reverse chronological order with the latest version listed on top, while additions/changes in each release are listed in chronological order. Changes in each release are divided into three parts: added or change features, bugfixes, and miscellaneous improvements. Each line contains short information about the change made, the person who made it, and the related issue number(s) in GitHub. +## 0.11.0 - 1 June 2014 + +This release marked the change of PHPWord license from LGPL 2.1 to LGPL 3. Four new elements were added: TextBox, ListItemRun, Field, and Line. Relative and absolute positioning for images and textboxes were added. Writer classes were refactored into parts, elements, and styles. ODT and RTF features were enhanced. Ability to add elements to PHPWord object via HTML were implemented. RTF and HTML reader were initiated. + +### Features + +- Image: Ability to define relative and absolute positioning - @basjan GH-217 +- Footer: Conform footer with header by adding firstPage, evenPage and by inheritance - @basjan @ivanlanin GH-219 +- Element: New `TextBox` element - @basjan @ivanlanin GH-228 GH-229 GH-231 +- HTML: Ability to add elements to PHPWord object via html - @basjan GH-231 +- Element: New `ListItemRun` element that can add a list item with inline formatting like a textrun - @basjan GH-235 +- Table: Ability to add table inside a cell (nested table) - @ivanlanin GH-149 +- RTF Writer: UTF8 support for RTF: Internal UTF8 text is converted to Unicode before writing - @ivanlanin GH-158 +- Table: Ability to define table width (in percent and twip) and position - @ivanlanin GH-237 +- RTF Writer: Ability to add links and page breaks in RTF - @ivanlanin GH-196 +- ListItemRun: Remove fontStyle parameter because ListItemRun is inherited from TextRun and TextRun doesn't have fontStyle - @ivanlanin +- Config: Ability to use a config file to store various common settings - @ivanlanin GH-200 +- ODT Writer: Enable inline font style in TextRun - @ivanlanin +- ODT Writer: Enable underline, strike/doublestrike, smallcaps/allcaps, superscript/subscript font style - @ivanlanin +- ODT Writer: Enable section and column - @ivanlanin +- PDF Writer: Add TCPDF and mPDF as optional PDF renderer library - @ivanlanin +- ODT Writer: Enable title element and custom document properties - @ivanlanin +- ODT Reader: Ability to read standard and custom document properties - @ivanlanin +- Word2007 Writer: Enable the missing custom document properties writer - @ivanlanin +- Image: Enable "image float left" - @ivanlanin GH-244 +- RTF Writer: Ability to write document properties - @ivanlanin +- RTF Writer: Ability to write image - @ivanlanin +- Element: New `Field` element - @basjan GH-251 +- RTF Reader: Basic RTF reader - @ivanlanin GH-72 GH-252 +- Element: New `Line` element - @basjan GH-253 +- Title: Ability to apply numbering in heading - @ivanlanin GH-193 +- HTML Reader: Basic HTML reader - @ivanlanin GH-80 GH-254 +- RTF Writer: Basic table writing - @ivanlanin GH-245 + +### Bugfixes + +- Header: All images added to the second header were assigned to the first header - @basjan GH-222 +- Conversion: Fix conversion from cm to pixel, pixel to cm, and pixel to point - @basjan GH-233 GH-234 +- PageBreak: Page break adds new line in the beginning of the new page - @ivanlanin GH-150 +- Image: `marginLeft` and `marginTop` cannot accept float value - @ivanlanin GH-248 +- Title: Orphan `w:fldChar` caused OpenOffice to crash when opening DOCX - @ivanlanin GH-236 + +### Deprecated + +- Static classes `Footnotes`, `Endnotes`, and `TOC` +- `Writer\Word2007\Part`: `Numbering::writeNumbering()`, `Settings::writeSettings()`, `WebSettings::writeWebSettings()`, `ContentTypes::writeContentTypes()`, `Styles::writeStyles()`, `Document::writeDocument()` all changed into `write()` +- `Writer\Word2007\Part\DocProps`: Split into `Writer\Word2007\Part\DocPropsCore` and `Writer\Word2007\Part\DocPropsApp` +- `Element\Title::getBookmarkId()` replaced by `Element\Title::getRelationId()` +- `Writer\HTML::writeDocument`: Replaced by `Writer\HTML::getContent` + +### Miscellaneous + +- License: Change the project license from LGPL 2.1 into LGPL 3.0 - GH-211 +- Word2007 Writer: New `Style\Image` class - @ivanlanin +- Refactor: Replace static classes `Footnotes`, `Endnotes`, and `TOC` with `Collections` - @ivanlanin GH-206 +- QA: Reactivate `phpcpd` and `phpmd` on Travis - @ivanlanin +- Refactor: PHPMD recommendation: Change all `get...` method that returns `boolean` into `is...` or `has...` - @ivanlanin +- Docs: Create gh-pages branch for API documentation - @Progi1984 GH-154 +- QA: Add `.scrutinizer.yml` and include `composer.lock` for preparation to Scrutinizer - @ivanlanin GH-186 +- Writer: Refactor writer parts using composite pattern - @ivanlanin +- Docs: Show code quality and test code coverage badge on README +- Style: Change behaviour of `set...` function of boolean properties; when none is defined, assumed true - @ivanlanin +- Shared: Unify PHP ZipArchive and PCLZip features into PhpWord ZipArchive - @ivanlanin +- Docs: Create VERSION file - @ivanlanin +- QA: Improve dan update requirement check in `samples` folder - @ivanlanin + + ## 0.10.1 - 21 May 2014 This is a bugfix release for `php-zip` requirement in Composer. @@ -32,7 +99,7 @@ This release marked heavy refactorings on internal code structure with the creat - Link: Ability to add link in header/footer - @ivanlanin GH-187 - Object: Ability to add object in header, footer, textrun, and footnote - @ivanlanin GH-187 - Media: Add `Media::resetElements()` to reset all media data - @juzi GH-19 -- General: Add `Style::resetStyles()`, `Footnote::resetElements()`, and `TOC::resetTitles()` - @ivanlanin GH-187 +- General: Add `Style::resetStyles()` - @ivanlanin GH-187 - DOCX Reader: Ability to read header, footer, footnotes, link, preservetext, textbreak, pagebreak, table, list, image, and title - @ivanlanin - Endnote: Ability to add endnotes - @ivanlanin - ListItem: Ability to create custom list and reset list number - @ivanlanin GH-10 GH-198 diff --git a/COPYING b/COPYING new file mode 100644 index 00000000..94a9ed02 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/COPYING.LESSER b/COPYING.LESSER new file mode 100644 index 00000000..65c5ca88 --- /dev/null +++ b/COPYING.LESSER @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..3f6a8c38 --- /dev/null +++ b/LICENSE @@ -0,0 +1,15 @@ +PHPWord, a pure PHP library for reading and writing word processing documents. + +Copyright (c) 2010-2014 PHPWord. + +PHPWord is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License version 3 as published by +the Free Software Foundation. + +PHPWord is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License version 3 for more details. + +You should have received a copy of the GNU Lesser General Public License version 3 +along with PHPWord. If not, see . diff --git a/LICENSE.md b/LICENSE.md deleted file mode 100644 index 57b74d4c..00000000 --- a/LICENSE.md +++ /dev/null @@ -1,345 +0,0 @@ -GNU LESSER GENERAL PUBLIC LICENSE - - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - -NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - -END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/README.md b/README.md index 5a8db0ef..ecbe1354 100644 --- a/README.md +++ b/README.md @@ -1,46 +1,50 @@ # ![PHPWord](https://rawgit.com/PHPOffice/PHPWord/develop/docs/images/phpword.svg "PHPWord") -[![Build Status](https://travis-ci.org/PHPOffice/PHPWord.svg?branch=master)](https://travis-ci.org/PHPOffice/PHPWord) [![Latest Stable Version](https://poser.pugx.org/phpoffice/phpword/v/stable.png)](https://packagist.org/packages/phpoffice/phpword) +[![Build Status](https://travis-ci.org/PHPOffice/PHPWord.svg?branch=master)](https://travis-ci.org/PHPOffice/PHPWord) +[![Code Quality](https://scrutinizer-ci.com/g/PHPOffice/PHPWord/badges/quality-score.png?s=b5997ce59ac2816b4514f3a38de9900f6d492c1d)](https://scrutinizer-ci.com/g/PHPOffice/PHPWord/) +[![Code Coverage](https://scrutinizer-ci.com/g/PHPOffice/PHPWord/badges/coverage.png?s=742a98745725c562955440edc8d2c39d7ff5ae25)](https://scrutinizer-ci.com/g/PHPOffice/PHPWord/) [![Total Downloads](https://poser.pugx.org/phpoffice/phpword/downloads.png)](https://packagist.org/packages/phpoffice/phpword) -[![Latest Unstable Version](https://poser.pugx.org/phpoffice/phpword/v/unstable.png)](https://packagist.org/packages/phpoffice/phpword) [![License](https://poser.pugx.org/phpoffice/phpword/license.png)](https://packagist.org/packages/phpoffice/phpword) +PHPWord is a library written in pure PHP that provides a set of classes to write to and read from different document file formats. The current version of PHPWord supports Microsoft [Office Open XML](http://en.wikipedia.org/wiki/Office_Open_XML) (OOXML or OpenXML), OASIS [Open Document Format for Office Applications](http://en.wikipedia.org/wiki/OpenDocument) (OpenDocument or ODF), [Rich Text Format](http://en.wikipedia.org/wiki/Rich_Text_Format) (RTF), HTML, and PDF. -PHPWord is a library written in pure PHP that provides a set of classes to write to and read from different document file formats. The current version of PHPWord supports Microsoft [Office Open XML](http://en.wikipedia.org/wiki/Office_Open_XML) (OOXML or OpenXML), OASIS [Open Document Format for Office Applications](http://en.wikipedia.org/wiki/OpenDocument) (OpenDocument or ODF), and [Rich Text Format](http://en.wikipedia.org/wiki/Rich_Text_Format) (RTF). +PHPWord is an open source project licensed under the terms of [LGPL version 3](https://github.com/PHPOffice/PHPWord/blob/develop/COPYING.LESSER). PHPWord is aimed to be a high quality software product by incorporating [continuous integration](https://travis-ci.org/PHPOffice/PHPWord) and [unit testing](http://phpoffice.github.io/PHPWord/coverage/develop/). You can learn more about PHPWord by reading the [Developers' Documentation](http://phpword.readthedocs.org/) and the [API Documentation](http://phpoffice.github.io/PHPWord/docs/develop/). + +## Features With PHPWord, you can create DOCX, ODT, or RTF documents dynamically using your PHP 5.3+ scripts. Below are some of the things that you can do with PHPWord library: -* Set document properties, e.g. title, subject, and creator. -* Create document sections with different settings, e.g. portrait/landscape, page size, and page numbering -* Create header and footer for each sections -* Set default font type, font size, and paragraph style -* Use UTF-8 and East Asia fonts/characters -* Define custom font styles (e.g. bold, italic, color) and paragraph styles (e.g. centered, multicolumns, spacing) either as named style or inline in text -* Insert paragraphs, either as a simple text or complex one (a text run) that contains other elements -* Insert titles (headers) and table of contents -* Insert text breaks and page breaks -* Insert and format images, either local, remote, or as page watermarks -* Insert binary OLE Objects such as Excel or Visio -* Insert and format table with customized properties for each rows (e.g. repeat as header row) and cells (e.g. background color, rowspan, colspan) -* Insert list items as bulleted, numbered, or multilevel -* Insert hyperlinks -* Insert footnotes and endnotes -* Create document from templates -* Use XSL 1.0 style sheets to transform main document part of OOXML template -* ... and many more features on progress - -__Want to contribute?__ [Fork us](https://github.com/PHPOffice/PHPWord/fork) or [submit](https://github.com/PHPOffice/PHPWord/issues) your bug reports or feature requests to us. +- Set document properties, e.g. title, subject, and creator. +- Create document sections with different settings, e.g. portrait/landscape, page size, and page numbering +- Create header and footer for each sections +- Set default font type, font size, and paragraph style +- Use UTF-8 and East Asia fonts/characters +- Define custom font styles (e.g. bold, italic, color) and paragraph styles (e.g. centered, multicolumns, spacing) either as named style or inline in text +- Insert paragraphs, either as a simple text or complex one (a text run) that contains other elements +- Insert titles (headers) and table of contents +- Insert text breaks and page breaks +- Insert and format images, either local, remote, or as page watermarks +- Insert binary OLE Objects such as Excel or Visio +- Insert and format table with customized properties for each rows (e.g. repeat as header row) and cells (e.g. background color, rowspan, colspan) +- Insert list items as bulleted, numbered, or multilevel +- Insert hyperlinks +- Insert footnotes and endnotes +- Create document from templates +- Use XSL 1.0 style sheets to transform main document part of OOXML template +- ... and many more features on progress ## Requirements -* PHP 5.3+ -* PHP [Zip](http://php.net/manual/en/book.zip.php) extension -* PHP [XML Parser](http://www.php.net/manual/en/xml.installation.php) extension -### Optional PHP extensions -* PHP [GD](http://php.net/manual/en/book.image.php) extension -* PHP [XMLWriter](http://php.net/manual/en/book.xmlwriter.php) extension -* PHP [XSL](http://php.net/manual/en/book.xsl.php) extension +PHPWord requires the following: + +- PHP 5.3+ +- [Zip extension](http://php.net/manual/en/book.zip.php) +- [XML Parser extension](http://www.php.net/manual/en/xml.installation.php) +- [GD extension](http://php.net/manual/en/book.image.php) (optional, used to add images) +- [XMLWriter extension](http://php.net/manual/en/book.xmlwriter.php) (optional, used to write DOCX and ODT) +- [XSL extension](http://php.net/manual/en/book.xsl.php) (optional, used to apply XSL style sheet to template ) +- [dompdf](https://github.com/dompdf/dompdf) (optional, used to write PDF) ## Installation @@ -63,7 +67,7 @@ require_once 'path/to/PhpWord/src/PhpWord/Autoloader.php'; \PhpOffice\PhpWord\Autoloader::register(); ``` -## Basic usage +## Usages The following is a basic example of the PHPWord library. More examples are provided in the [samples folder](samples/). @@ -107,6 +111,11 @@ $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'RTF'); $objWriter->save('helloWorld.rtf'); ``` -## Documentation +## Contributing -__Want to know more?__ Read the full documentation of PHPWord on [Read The Docs](http://phpword.readthedocs.org/). +We welcome everyone to contribute to PHPWord. Below are some of the things that you can do to contribute: + +- Read [our contributing guide](https://github.com/PHPOffice/PHPWord/blob/master/CONTRIBUTING.md) +- [Fork us](https://github.com/PHPOffice/PHPWord/fork) and [request a pull](https://github.com/PHPOffice/PHPWord/pulls) to the [develop](https://github.com/PHPOffice/PHPWord/tree/develop) branch +- Submit [bug reports or feature requests](https://github.com/PHPOffice/PHPWord/issues) to GitHub +- Follow [@PHPWord](https://twitter.com/PHPWord) and [@PHPOffice](https://twitter.com/PHPOffice) on Twitter diff --git a/VERSION b/VERSION new file mode 100644 index 00000000..142464bf --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.11.0 \ No newline at end of file diff --git a/composer.json b/composer.json index e9daa890..2f9a0915 100644 --- a/composer.json +++ b/composer.json @@ -1,14 +1,14 @@ { "name": "phpoffice/phpword", - "description": "PHPWord - Read, Create, and Write DOCX, ODT, and RTF documents in PHP", + "description": "PHPWord - A pure PHP library for reading and writing word processing documents (DOCX, ODT, RTF, HTML, PDF)", "keywords": [ "PHP", "PhpOffice", "office", "PhpWord", "word", "template", "reader", "writer", "docx", "OOXML", "OpenXML", "Office Open XML", "ISO IEC 29500", "WordprocessingML", - "RTF", "Rich Text Format", "doc", "odt", "OpenDocument" + "RTF", "Rich Text Format", "doc", "odt", "OpenDocument", "PDF", "HTML" ], "homepage": "http://phpoffice.github.io", "type": "library", - "license": "LGPL-2.1+", + "license": "LGPL-3.0", "authors": [ { "name": "Mark Baker" @@ -36,7 +36,12 @@ "ext-xml": "*" }, "require-dev": { - "phpunit/phpunit": "3.7.*" + "phpunit/phpunit": "3.7.*", + "phpdocumentor/phpdocumentor":"2.*", + "squizlabs/php_codesniffer": "1.*", + "dompdf/dompdf":"0.6.*", + "tecnick.com/tcpdf": "6.*", + "mpdf/mpdf": "5.*" }, "suggest": { "ext-zip": "Used to write DOCX and ODT", diff --git a/composer.lock b/composer.lock new file mode 100644 index 00000000..172e564e --- /dev/null +++ b/composer.lock @@ -0,0 +1,3283 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file" + ], + "hash": "91993ff980d11a416fcf3a7309a4044f", + "packages": [ + + ], + "packages-dev": [ + { + "name": "cilex/cilex", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/Cilex/Cilex.git", + "reference": "7acd965a609a56d0345e8b6071c261fbdb926cb5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Cilex/Cilex/zipball/7acd965a609a56d0345e8b6071c261fbdb926cb5", + "reference": "7acd965a609a56d0345e8b6071c261fbdb926cb5", + "shasum": "" + }, + "require": { + "cilex/console-service-provider": "1.*", + "php": ">=5.3.3", + "pimple/pimple": "~1.0", + "symfony/finder": "~2.1", + "symfony/process": "~2.1" + }, + "require-dev": { + "phpunit/phpunit": "3.7.*", + "symfony/validator": "~2.1" + }, + "suggest": { + "monolog/monolog": ">=1.0.0", + "symfony/validator": ">=1.0.0", + "symfony/yaml": ">=1.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "psr-0": { + "Cilex": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike van Riel", + "email": "mike.vanriel@naenius.com" + } + ], + "description": "The PHP micro-framework for Command line tools based on the Symfony2 Components", + "homepage": "http://cilex.github.com", + "keywords": [ + "cli", + "microframework" + ], + "time": "2014-03-29 14:03:13" + }, + { + "name": "cilex/console-service-provider", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/Cilex/console-service-provider.git", + "reference": "25ee3d1875243d38e1a3448ff94bdf944f70d24e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Cilex/console-service-provider/zipball/25ee3d1875243d38e1a3448ff94bdf944f70d24e", + "reference": "25ee3d1875243d38e1a3448ff94bdf944f70d24e", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "pimple/pimple": "1.*@dev", + "symfony/console": "~2.1" + }, + "require-dev": { + "cilex/cilex": "1.*@dev", + "silex/silex": "1.*@dev" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "psr-0": { + "Cilex\\Provider\\Console": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Beau Simensen", + "email": "beau@dflydev.com", + "homepage": "http://beausimensen.com" + }, + { + "name": "Mike van Riel", + "email": "mike.vanriel@naenius.com" + } + ], + "description": "Console Service Provider", + "keywords": [ + "cilex", + "console", + "pimple", + "service-provider", + "silex" + ], + "time": "2012-12-19 10:50:58" + }, + { + "name": "doctrine/annotations", + "version": "v1.1.2", + "source": { + "type": "git", + "url": "https://github.com/doctrine/annotations.git", + "reference": "40db0c96985aab2822edbc4848b3bd2429e02670" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/annotations/zipball/40db0c96985aab2822edbc4848b3bd2429e02670", + "reference": "40db0c96985aab2822edbc4848b3bd2429e02670", + "shasum": "" + }, + "require": { + "doctrine/lexer": "1.*", + "php": ">=5.3.2" + }, + "require-dev": { + "doctrine/cache": "1.*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-0": { + "Doctrine\\Common\\Annotations\\": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jonathan H. Wage", + "email": "jonwage@gmail.com", + "homepage": "http://www.jwage.com/", + "role": "Creator" + }, + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com", + "homepage": "http://www.instaclick.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "http://jmsyst.com", + "role": "Developer of wrapped JMSSerializerBundle" + } + ], + "description": "Docblock Annotations Parser", + "homepage": "http://www.doctrine-project.org", + "keywords": [ + "annotations", + "docblock", + "parser" + ], + "time": "2013-06-16 21:33:03" + }, + { + "name": "doctrine/lexer", + "version": "v1.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/lexer.git", + "reference": "2f708a85bb3aab5d99dab8be435abd73e0b18acb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/lexer/zipball/2f708a85bb3aab5d99dab8be435abd73e0b18acb", + "reference": "2f708a85bb3aab5d99dab8be435abd73e0b18acb", + "shasum": "" + }, + "require": { + "php": ">=5.3.2" + }, + "type": "library", + "autoload": { + "psr-0": { + "Doctrine\\Common\\Lexer\\": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com", + "homepage": "http://www.instaclick.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "http://jmsyst.com", + "role": "Developer of wrapped JMSSerializerBundle" + } + ], + "description": "Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.", + "homepage": "http://www.doctrine-project.org", + "keywords": [ + "lexer", + "parser" + ], + "time": "2013-01-12 18:59:04" + }, + { + "name": "dompdf/dompdf", + "version": "v0.6.1", + "source": { + "type": "git", + "url": "https://github.com/dompdf/dompdf.git", + "reference": "cf7d8a0a27270418850cc7d7ea532159e5eeb3eb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/dompdf/dompdf/zipball/cf7d8a0a27270418850cc7d7ea532159e5eeb3eb", + "reference": "cf7d8a0a27270418850cc7d7ea532159e5eeb3eb", + "shasum": "" + }, + "require": { + "phenx/php-font-lib": "0.2.*" + }, + "type": "library", + "autoload": { + "classmap": [ + "include/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL" + ], + "authors": [ + { + "name": "Fabien Ménager", + "email": "fabien.menager@gmail.com" + }, + { + "name": "Brian Sweeney", + "email": "eclecticgeek@gmail.com" + } + ], + "description": "DOMPDF is a CSS 2.1 compliant HTML to PDF converter", + "homepage": "https://github.com/dompdf/dompdf", + "time": "2014-03-11 01:59:52" + }, + { + "name": "erusev/parsedown", + "version": "0.9.4", + "source": { + "type": "git", + "url": "https://github.com/erusev/parsedown.git", + "reference": "d29ff18299210b52a75a631a70963e7c8b35b04f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/erusev/parsedown/zipball/d29ff18299210b52a75a631a70963e7c8b35b04f", + "reference": "d29ff18299210b52a75a631a70963e7c8b35b04f", + "shasum": "" + }, + "type": "library", + "autoload": { + "psr-0": { + "Parsedown": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Emanuil Rusev", + "email": "hello@erusev.com", + "homepage": "http://erusev.com" + } + ], + "description": "Parser for Markdown.", + "homepage": "http://parsedown.org", + "keywords": [ + "markdown", + "parser" + ], + "time": "2014-02-06 12:16:14" + }, + { + "name": "jms/metadata", + "version": "1.5.0", + "source": { + "type": "git", + "url": "https://github.com/schmittjoh/metadata.git", + "reference": "88ffa28bc987e4c26229fc84a2e541b6ed4e1459" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/schmittjoh/metadata/zipball/88ffa28bc987e4c26229fc84a2e541b6ed4e1459", + "reference": "88ffa28bc987e4c26229fc84a2e541b6ed4e1459", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "doctrine/cache": "~1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.5.x-dev" + } + }, + "autoload": { + "psr-0": { + "Metadata\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache" + ], + "authors": [ + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "http://jmsyst.com", + "role": "Developer of wrapped JMSSerializerBundle" + } + ], + "description": "Class/method/property metadata management in PHP", + "keywords": [ + "annotations", + "metadata", + "xml", + "yaml" + ], + "time": "2013-11-05 23:02:36" + }, + { + "name": "jms/parser-lib", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/schmittjoh/parser-lib.git", + "reference": "c509473bc1b4866415627af0e1c6cc8ac97fa51d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/schmittjoh/parser-lib/zipball/c509473bc1b4866415627af0e1c6cc8ac97fa51d", + "reference": "c509473bc1b4866415627af0e1c6cc8ac97fa51d", + "shasum": "" + }, + "require": { + "phpoption/phpoption": ">=0.9,<2.0-dev" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "psr-0": { + "JMS\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache2" + ], + "description": "A library for easily creating recursive-descent parsers.", + "time": "2012-11-18 18:08:43" + }, + { + "name": "jms/serializer", + "version": "0.16.0", + "source": { + "type": "git", + "url": "https://github.com/schmittjoh/serializer.git", + "reference": "c8a171357ca92b6706e395c757f334902d430ea9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/schmittjoh/serializer/zipball/c8a171357ca92b6706e395c757f334902d430ea9", + "reference": "c8a171357ca92b6706e395c757f334902d430ea9", + "shasum": "" + }, + "require": { + "doctrine/annotations": "1.*", + "jms/metadata": "~1.1", + "jms/parser-lib": "1.*", + "php": ">=5.3.2", + "phpcollection/phpcollection": "~0.1" + }, + "require-dev": { + "doctrine/orm": "~2.1", + "doctrine/phpcr-odm": "~1.0.1", + "jackalope/jackalope-doctrine-dbal": "1.0.*", + "propel/propel1": "~1.7", + "symfony/filesystem": "2.*", + "symfony/form": "~2.1", + "symfony/translation": "~2.0", + "symfony/validator": "~2.0", + "symfony/yaml": "2.*", + "twig/twig": ">=1.8,<2.0-dev" + }, + "suggest": { + "symfony/yaml": "Required if you'd like to serialize data to YAML format." + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "0.15-dev" + } + }, + "autoload": { + "psr-0": { + "JMS\\Serializer": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache2" + ], + "authors": [ + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "http://jmsyst.com", + "role": "Developer of wrapped JMSSerializerBundle" + } + ], + "description": "Library for (de-)serializing data of any complexity; supports XML, JSON, and YAML.", + "homepage": "http://jmsyst.com/libs/serializer", + "keywords": [ + "deserialization", + "jaxb", + "json", + "serialization", + "xml" + ], + "time": "2014-03-18 08:39:00" + }, + { + "name": "knplabs/knp-menu", + "version": "v1.1.2", + "source": { + "type": "git", + "url": "https://github.com/KnpLabs/KnpMenu.git", + "reference": "f8e867268f63f561c1adadd6cbb5d8524f921873" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/KnpLabs/KnpMenu/zipball/f8e867268f63f561c1adadd6cbb5d8524f921873", + "reference": "f8e867268f63f561c1adadd6cbb5d8524f921873", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "pimple/pimple": "*", + "silex/silex": "1.0.*", + "twig/twig": ">=1.2,<2.0-dev" + }, + "suggest": { + "pimple/pimple": "for the built-in implementations of the menu provider and renderer provider", + "silex/silex": "for the integration with your silex application", + "twig/twig": "for the TwigRenderer and the integration with your templates" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev" + } + }, + "autoload": { + "psr-0": { + "Knp\\Menu\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christophe Coevoet", + "email": "stof@notk.org" + }, + { + "name": "KnpLabs", + "homepage": "http://knplabs.com" + }, + { + "name": "Symfony Community", + "homepage": "https://github.com/KnpLabs/KnpMenu/contributors" + } + ], + "description": "An object oriented menu library", + "homepage": "http://knplabs.com", + "keywords": [ + "menu", + "tree" + ], + "time": "2012-06-10 16:20:40" + }, + { + "name": "monolog/monolog", + "version": "1.9.1", + "source": { + "type": "git", + "url": "https://github.com/Seldaek/monolog.git", + "reference": "65026b610f8c19e61d7242f600530677b0466aac" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/65026b610f8c19e61d7242f600530677b0466aac", + "reference": "65026b610f8c19e61d7242f600530677b0466aac", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "psr/log": "~1.0" + }, + "require-dev": { + "aws/aws-sdk-php": "~2.4, >2.4.8", + "doctrine/couchdb": "~1.0@dev", + "graylog2/gelf-php": "~1.0", + "phpunit/phpunit": "~3.7.0", + "raven/raven": "~0.5", + "ruflin/elastica": "0.90.*" + }, + "suggest": { + "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", + "doctrine/couchdb": "Allow sending log messages to a CouchDB server", + "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", + "ext-mongo": "Allow sending log messages to a MongoDB server", + "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", + "raven/raven": "Allow sending log messages to a Sentry server", + "rollbar/rollbar": "Allow sending log messages to Rollbar", + "ruflin/elastica": "Allow sending log messages to an Elastic Search server" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.9.x-dev" + } + }, + "autoload": { + "psr-4": { + "Monolog\\": "src/Monolog" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be", + "role": "Developer" + } + ], + "description": "Sends your logs to files, sockets, inboxes, databases and various web services", + "homepage": "http://github.com/Seldaek/monolog", + "keywords": [ + "log", + "logging", + "psr-3" + ], + "time": "2014-04-24 13:29:03" + }, + { + "name": "mpdf/mpdf", + "version": "v5.7.2", + "source": { + "type": "git", + "url": "https://github.com/finwe/mpdf.git", + "reference": "1627f9e7d2ef0f635a886f611079216ed2929717" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/finwe/mpdf/zipball/1627f9e7d2ef0f635a886f611079216ed2929717", + "reference": "1627f9e7d2ef0f635a886f611079216ed2929717", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": ">=4.3.10" + }, + "type": "library", + "autoload": { + "classmap": [ + "mpdf.php", + "classes" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "GPL-1.0+" + ], + "authors": [ + { + "name": "Ian Back" + } + ], + "description": "A PHP class to generate PDF files from HTML with Unicode/UTF-8 and CJK support", + "homepage": "http://www.mpdf1.com/mpdf/index.php", + "keywords": [ + "pdf", + "php", + "utf-8" + ], + "time": "2014-05-16 07:18:10" + }, + { + "name": "nikic/php-parser", + "version": "v0.9.4", + "source": { + "type": "git", + "url": "https://github.com/nikic/PHP-Parser.git", + "reference": "1e5e280ae88a27effa2ae4aa2bd088494ed8594f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/1e5e280ae88a27effa2ae4aa2bd088494ed8594f", + "reference": "1e5e280ae88a27effa2ae4aa2bd088494ed8594f", + "shasum": "" + }, + "require": { + "php": ">=5.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "0.9-dev" + } + }, + "autoload": { + "psr-0": { + "PHPParser": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov" + } + ], + "description": "A PHP parser written in PHP", + "keywords": [ + "parser", + "php" + ], + "time": "2013-08-25 17:11:40" + }, + { + "name": "phenx/php-font-lib", + "version": "0.2.2", + "source": { + "type": "git", + "url": "https://github.com/PhenX/php-font-lib.git", + "reference": "c30c7fc00a6b0d863e9bb4c5d5dd015298b2dc82" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PhenX/php-font-lib/zipball/c30c7fc00a6b0d863e9bb4c5d5dd015298b2dc82", + "reference": "c30c7fc00a6b0d863e9bb4c5d5dd015298b2dc82", + "shasum": "" + }, + "type": "library", + "autoload": { + "classmap": [ + "classes/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL" + ], + "authors": [ + { + "name": "Fabien Ménager", + "email": "fabien.menager@gmail.com" + } + ], + "description": "A library to read, parse, export and make subsets of different types of font files.", + "homepage": "https://github.com/PhenX/php-font-lib", + "time": "2014-02-01 15:22:28" + }, + { + "name": "phpcollection/phpcollection", + "version": "0.4.0", + "source": { + "type": "git", + "url": "https://github.com/schmittjoh/php-collection.git", + "reference": "b8bf55a0a929ca43b01232b36719f176f86c7e83" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/schmittjoh/php-collection/zipball/b8bf55a0a929ca43b01232b36719f176f86c7e83", + "reference": "b8bf55a0a929ca43b01232b36719f176f86c7e83", + "shasum": "" + }, + "require": { + "phpoption/phpoption": "1.*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "0.3-dev" + } + }, + "autoload": { + "psr-0": { + "PhpCollection": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache2" + ], + "authors": [ + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "http://jmsyst.com", + "role": "Developer of wrapped JMSSerializerBundle" + } + ], + "description": "General-Purpose Collection Library for PHP", + "keywords": [ + "collection", + "list", + "map", + "sequence", + "set" + ], + "time": "2014-03-11 13:46:42" + }, + { + "name": "phpdocumentor/fileset", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/Fileset.git", + "reference": "bfa78d8fa9763dfce6d0e5d3730c1d8ab25d34b0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/Fileset/zipball/bfa78d8fa9763dfce6d0e5d3730c1d8ab25d34b0", + "reference": "bfa78d8fa9763dfce6d0e5d3730c1d8ab25d34b0", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "symfony/finder": "~2.1" + }, + "require-dev": { + "phpunit/phpunit": "~3.7" + }, + "type": "library", + "autoload": { + "psr-0": { + "phpDocumentor": [ + "src/", + "tests/unit/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Fileset component for collecting a set of files given directories and file paths", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "files", + "fileset", + "phpdoc" + ], + "time": "2013-08-06 21:07:42" + }, + { + "name": "phpdocumentor/graphviz", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/GraphViz.git", + "reference": "13595130b9bc185109f40f1b70f0b231f490f5fc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/GraphViz/zipball/13595130b9bc185109f40f1b70f0b231f490f5fc", + "reference": "13595130b9bc185109f40f1b70f0b231f490f5fc", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "phpunit/phpunit": "~3.7" + }, + "type": "library", + "autoload": { + "psr-0": { + "phpDocumentor": [ + "src/", + "tests/unit" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike van Riel", + "email": "mike.vanriel@naenius.com" + } + ], + "time": "2014-02-26 17:45:01" + }, + { + "name": "phpdocumentor/phpdocumentor", + "version": "v2.5.0", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/phpDocumentor2.git", + "reference": "bf9fa40f6d00412410025b2e16eb16c315eb0216" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/phpDocumentor2/zipball/bf9fa40f6d00412410025b2e16eb16c315eb0216", + "reference": "bf9fa40f6d00412410025b2e16eb16c315eb0216", + "shasum": "" + }, + "require": { + "cilex/cilex": "~1.0", + "dompdf/dompdf": "~0.6", + "erusev/parsedown": "~0.7", + "jms/serializer": "~0.12", + "knplabs/knp-menu": "~1.1", + "monolog/monolog": "~1.6", + "php": ">=5.3.3", + "phpdocumentor/fileset": "~1.0", + "phpdocumentor/graphviz": "~1.0", + "phpdocumentor/reflection": "~1.0", + "phpdocumentor/reflection-docblock": "~2.0", + "phpdocumentor/template-abstract": "~1.2", + "phpdocumentor/template-checkstyle": "~1.2", + "phpdocumentor/template-clean": "~1.0", + "phpdocumentor/template-new-black": "~1.3", + "phpdocumentor/template-old-ocean": "~1.3", + "phpdocumentor/template-responsive": "~1.3", + "phpdocumentor/template-responsive-twig": "~1.2", + "phpdocumentor/template-xml": "~1.0", + "phpdocumentor/template-zend": "~1.3", + "symfony/config": "~2.3", + "symfony/console": "~2.3", + "symfony/event-dispatcher": "~2.1", + "symfony/process": "~2.0", + "symfony/stopwatch": "~2.3", + "symfony/validator": "~2.2", + "twig/twig": "~1.3", + "zendframework/zend-cache": "2.1.*", + "zendframework/zend-config": "2.1.*", + "zendframework/zend-filter": "2.1.*", + "zendframework/zend-i18n": "2.1.*", + "zendframework/zend-serializer": "2.1.*", + "zendframework/zend-servicemanager": "2.1.*", + "zendframework/zend-stdlib": "2.1.*", + "zetacomponents/document": ">=1.3.1" + }, + "require-dev": { + "behat/behat": "~2.4", + "mikey179/vfsstream": "~1.2", + "mockery/mockery": ">=0.8.0", + "phpunit/phpunit": "~3.7", + "squizlabs/php_codesniffer": "~1.4", + "symfony/expression-language": "~2.4" + }, + "suggest": { + "ext-twig": "Enabling the twig extension improves the generation of twig based templates.", + "ext-xslcache": "Enabling the XSLCache extension improves the generation of xml based templates." + }, + "bin": [ + "bin/phpdoc.php", + "bin/phpdoc" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-develop": "2.5-dev" + } + }, + "autoload": { + "psr-0": { + "phpDocumentor": [ + "src/", + "tests/unit/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Documentation Generator for PHP", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "api", + "application", + "dga", + "documentation", + "phpdoc" + ], + "time": "2014-05-17 12:25:35" + }, + { + "name": "phpdocumentor/reflection", + "version": "1.0.5", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/Reflection.git", + "reference": "df82db631acd60739c8796b3c6d5e4da970808f3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/Reflection/zipball/df82db631acd60739c8796b3c6d5e4da970808f3", + "reference": "df82db631acd60739c8796b3c6d5e4da970808f3", + "shasum": "" + }, + "require": { + "nikic/php-parser": "0.9.4", + "php": ">=5.3.3", + "phpdocumentor/reflection-docblock": "2.*", + "psr/log": "~1.0" + }, + "require-dev": { + "behat/behat": "~2.4", + "mockery/mockery": ">=0.7.0", + "phpunit/phpunit": "~3.7" + }, + "type": "library", + "autoload": { + "psr-0": { + "phpDocumentor": [ + "src/", + "tests/unit/", + "tests/mocks/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Reflection library to do Static Analysis for PHP Projects", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "phpDocumentor", + "phpdoc", + "reflection", + "static analysis" + ], + "time": "2014-03-28 11:20:22" + }, + { + "name": "phpdocumentor/reflection-docblock", + "version": "2.0.2", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git", + "reference": "0bca477a34baea39add016af90046f002a175619" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/0bca477a34baea39add016af90046f002a175619", + "reference": "0bca477a34baea39add016af90046f002a175619", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "phpunit/phpunit": "3.7.*@stable" + }, + "suggest": { + "dflydev/markdown": "1.0.*", + "erusev/parsedown": "~0.7" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-0": { + "phpDocumentor": [ + "src/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike van Riel", + "email": "mike.vanriel@naenius.com" + } + ], + "time": "2014-03-28 09:21:30" + }, + { + "name": "phpdocumentor/template-abstract", + "version": "1.2.1", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.abstract.git", + "reference": "43fa2db351d7a150803397721e778f9dd8a20b47" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.abstract/zipball/43fa2db351d7a150803397721e778f9dd8a20b47", + "reference": "43fa2db351d7a150803397721e778f9dd8a20b47", + "shasum": "" + }, + "require": { + "ext-xsl": "*", + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Simple bright template for phpDocumentor", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "template" + ], + "time": "2013-08-02 06:11:13" + }, + { + "name": "phpdocumentor/template-checkstyle", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.checkstyle.git", + "reference": "22a45684e737c8c3ec3f1a12edb7743b7a82ac8b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.checkstyle/zipball/22a45684e737c8c3ec3f1a12edb7743b7a82ac8b", + "reference": "22a45684e737c8c3ec3f1a12edb7743b7a82ac8b", + "shasum": "" + }, + "require": { + "ext-xsl": "*", + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Checkstyle XML output template for phpDocumentor2", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "template" + ], + "time": "2013-08-01 19:43:19" + }, + { + "name": "phpdocumentor/template-clean", + "version": "1.0.4", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.clean.git", + "reference": "78f2048c5ecd62f0b79dbac093687d78a66d1806" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.clean/zipball/78f2048c5ecd62f0b79dbac093687d78a66d1806", + "reference": "78f2048c5ecd62f0b79dbac093687d78a66d1806", + "shasum": "" + }, + "require": { + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A clean, responsive modern template for phpDocumentor for Twig aimed at usability", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "responsive", + "template" + ], + "time": "2014-03-29 08:22:15" + }, + { + "name": "phpdocumentor/template-new-black", + "version": "1.3.1", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.new_black.git", + "reference": "be38beba2b2674be292f32f88efe8a60c658a139" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.new_black/zipball/be38beba2b2674be292f32f88efe8a60c658a139", + "reference": "be38beba2b2674be292f32f88efe8a60c658a139", + "shasum": "" + }, + "require": { + "ext-xsl": "*", + "phpdocumentor/template-abstract": "1.*", + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Web 2.0 template with dark sidebar for phpDocumentor", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "template" + ], + "time": "2013-08-02 06:16:30" + }, + { + "name": "phpdocumentor/template-old-ocean", + "version": "1.3.1", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.old_ocean.git", + "reference": "3a0e2bcced4045a694d53b4607aad04e99d78489" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.old_ocean/zipball/3a0e2bcced4045a694d53b4607aad04e99d78489", + "reference": "3a0e2bcced4045a694d53b4607aad04e99d78489", + "shasum": "" + }, + "require": { + "ext-xsl": "*", + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Blue template with high contrast for the foreground", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "template" + ], + "time": "2013-08-02 06:21:07" + }, + { + "name": "phpdocumentor/template-responsive", + "version": "1.3.3", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.responsive.git", + "reference": "26f895a2ed3148e1686ae4d802f65a3ef04c04e1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.responsive/zipball/26f895a2ed3148e1686ae4d802f65a3ef04c04e1", + "reference": "26f895a2ed3148e1686ae4d802f65a3ef04c04e1", + "shasum": "" + }, + "require": { + "ext-xsl": "*", + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Responsive modern template for phpDocumentor", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "template" + ], + "time": "2014-03-29 08:55:54" + }, + { + "name": "phpdocumentor/template-responsive-twig", + "version": "1.2.3", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.responsive-twig.git", + "reference": "cd6d82be6a4626d865fd01d40aad170cea08db0a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.responsive-twig/zipball/cd6d82be6a4626d865fd01d40aad170cea08db0a", + "reference": "cd6d82be6a4626d865fd01d40aad170cea08db0a", + "shasum": "" + }, + "require": { + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Responsive modern template for phpDocumentor for Twig", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "template" + ], + "time": "2014-03-30 21:02:00" + }, + { + "name": "phpdocumentor/template-xml", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/mvriel/template.xml.git", + "reference": "a372713be8ee99b16497e2580592e474ff51190c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/mvriel/template.xml/zipball/a372713be8ee99b16497e2580592e474ff51190c", + "reference": "a372713be8ee99b16497e2580592e474ff51190c", + "shasum": "" + }, + "require": { + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Generates an XML representation of the project's structure", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "template" + ], + "time": "2013-08-01 20:23:32" + }, + { + "name": "phpdocumentor/template-zend", + "version": "1.3.2", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.zend.git", + "reference": "75913288bfd73d3bf4c1b1179c3963f3431e7a9d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.zend/zipball/75913288bfd73d3bf4c1b1179c3963f3431e7a9d", + "reference": "75913288bfd73d3bf4c1b1179c3963f3431e7a9d", + "shasum": "" + }, + "require": { + "ext-xsl": "*", + "phpdocumentor/template-abstract": "1.*", + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Official Zend Framework Template for phpDocumentor2", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "ZendFramework", + "documentation", + "phpdoc", + "template", + "zend", + "zf" + ], + "time": "2013-12-05 08:51:57" + }, + { + "name": "phpdocumentor/unified-asset-installer", + "version": "1.1.2", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/UnifiedAssetInstaller.git", + "reference": "241fb036268cd9da7d76da3db66e3eda66259c52" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/UnifiedAssetInstaller/zipball/241fb036268cd9da7d76da3db66e3eda66259c52", + "reference": "241fb036268cd9da7d76da3db66e3eda66259c52", + "shasum": "" + }, + "require": { + "composer-plugin-api": "1.0.0" + }, + "require-dev": { + "composer/composer": "~1.0@dev", + "phpunit/phpunit": "~3.7" + }, + "type": "composer-installer", + "extra": { + "class": "\\phpDocumentor\\Composer\\UnifiedAssetInstaller" + }, + "autoload": { + "psr-0": { + "phpDocumentor\\Composer": [ + "src/", + "test/unit/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Asset installer for phpDocumentor", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "assets", + "installer", + "plugins", + "templates" + ], + "time": "2013-09-09 06:13:02" + }, + { + "name": "phpoption/phpoption", + "version": "1.4.0", + "source": { + "type": "git", + "url": "https://github.com/schmittjoh/php-option.git", + "reference": "5d099bcf0393908bf4ad69cc47dafb785d51f7f5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/5d099bcf0393908bf4ad69cc47dafb785d51f7f5", + "reference": "5d099bcf0393908bf4ad69cc47dafb785d51f7f5", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "psr-0": { + "PhpOption\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache2" + ], + "authors": [ + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "http://jmsyst.com", + "role": "Developer of wrapped JMSSerializerBundle" + } + ], + "description": "Option Type for PHP", + "keywords": [ + "language", + "option", + "php", + "type" + ], + "time": "2014-01-09 22:37:17" + }, + { + "name": "phpunit/php-code-coverage", + "version": "1.2.17", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-code-coverage.git", + "reference": "6ef2bf3a1c47eca07ea95f0d8a902a6340390b34" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/6ef2bf3a1c47eca07ea95f0d8a902a6340390b34", + "reference": "6ef2bf3a1c47eca07ea95f0d8a902a6340390b34", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "phpunit/php-file-iterator": ">=1.3.0@stable", + "phpunit/php-text-template": ">=1.2.0@stable", + "phpunit/php-token-stream": ">=1.1.3@stable" + }, + "require-dev": { + "phpunit/phpunit": "3.7.*@dev" + }, + "suggest": { + "ext-dom": "*", + "ext-xdebug": ">=2.0.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.2.x-dev" + } + }, + "autoload": { + "classmap": [ + "PHP/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "" + ], + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.", + "homepage": "https://github.com/sebastianbergmann/php-code-coverage", + "keywords": [ + "coverage", + "testing", + "xunit" + ], + "time": "2014-03-28 10:53:45" + }, + { + "name": "phpunit/php-file-iterator", + "version": "1.3.4", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-file-iterator.git", + "reference": "acd690379117b042d1c8af1fafd61bde001bf6bb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/acd690379117b042d1c8af1fafd61bde001bf6bb", + "reference": "acd690379117b042d1c8af1fafd61bde001bf6bb", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "autoload": { + "classmap": [ + "File/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "" + ], + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "FilterIterator implementation that filters files based on a list of suffixes.", + "homepage": "https://github.com/sebastianbergmann/php-file-iterator/", + "keywords": [ + "filesystem", + "iterator" + ], + "time": "2013-10-10 15:34:57" + }, + { + "name": "phpunit/php-text-template", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-text-template.git", + "reference": "206dfefc0ffe9cebf65c413e3d0e809c82fbf00a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/206dfefc0ffe9cebf65c413e3d0e809c82fbf00a", + "reference": "206dfefc0ffe9cebf65c413e3d0e809c82fbf00a", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "autoload": { + "classmap": [ + "Text/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "" + ], + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "Simple template engine.", + "homepage": "https://github.com/sebastianbergmann/php-text-template/", + "keywords": [ + "template" + ], + "time": "2014-01-30 17:20:04" + }, + { + "name": "phpunit/php-timer", + "version": "1.0.5", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-timer.git", + "reference": "19689d4354b295ee3d8c54b4f42c3efb69cbc17c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/19689d4354b295ee3d8c54b4f42c3efb69cbc17c", + "reference": "19689d4354b295ee3d8c54b4f42c3efb69cbc17c", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "autoload": { + "classmap": [ + "PHP/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "" + ], + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "Utility class for timing", + "homepage": "https://github.com/sebastianbergmann/php-timer/", + "keywords": [ + "timer" + ], + "time": "2013-08-02 07:42:54" + }, + { + "name": "phpunit/php-token-stream", + "version": "1.2.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-token-stream.git", + "reference": "ad4e1e23ae01b483c16f600ff1bebec184588e32" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/ad4e1e23ae01b483c16f600ff1bebec184588e32", + "reference": "ad4e1e23ae01b483c16f600ff1bebec184588e32", + "shasum": "" + }, + "require": { + "ext-tokenizer": "*", + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.2-dev" + } + }, + "autoload": { + "classmap": [ + "PHP/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "" + ], + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "Wrapper around PHP's tokenizer extension.", + "homepage": "https://github.com/sebastianbergmann/php-token-stream/", + "keywords": [ + "tokenizer" + ], + "time": "2014-03-03 05:10:30" + }, + { + "name": "phpunit/phpunit", + "version": "3.7.37", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpunit.git", + "reference": "ae6cefd7cc84586a5ef27e04bae11ee940ec63dc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/ae6cefd7cc84586a5ef27e04bae11ee940ec63dc", + "reference": "ae6cefd7cc84586a5ef27e04bae11ee940ec63dc", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-dom": "*", + "ext-json": "*", + "ext-pcre": "*", + "ext-reflection": "*", + "ext-spl": "*", + "php": ">=5.3.3", + "phpunit/php-code-coverage": "~1.2", + "phpunit/php-file-iterator": "~1.3", + "phpunit/php-text-template": "~1.1", + "phpunit/php-timer": "~1.0", + "phpunit/phpunit-mock-objects": "~1.2", + "symfony/yaml": "~2.0" + }, + "require-dev": { + "pear-pear.php.net/pear": "1.9.4" + }, + "suggest": { + "phpunit/php-invoker": "~1.1" + }, + "bin": [ + "composer/bin/phpunit" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.7.x-dev" + } + }, + "autoload": { + "classmap": [ + "PHPUnit/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "", + "../../symfony/yaml/" + ], + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "The PHP Unit Testing framework.", + "homepage": "http://www.phpunit.de/", + "keywords": [ + "phpunit", + "testing", + "xunit" + ], + "time": "2014-04-30 12:24:19" + }, + { + "name": "phpunit/phpunit-mock-objects", + "version": "1.2.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpunit-mock-objects.git", + "reference": "5794e3c5c5ba0fb037b11d8151add2a07fa82875" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/5794e3c5c5ba0fb037b11d8151add2a07fa82875", + "reference": "5794e3c5c5ba0fb037b11d8151add2a07fa82875", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "phpunit/php-text-template": ">=1.1.1@stable" + }, + "suggest": { + "ext-soap": "*" + }, + "type": "library", + "autoload": { + "classmap": [ + "PHPUnit/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "" + ], + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "Mock Object library for PHPUnit", + "homepage": "https://github.com/sebastianbergmann/phpunit-mock-objects/", + "keywords": [ + "mock", + "xunit" + ], + "time": "2013-01-13 10:24:48" + }, + { + "name": "pimple/pimple", + "version": "v1.1.1", + "source": { + "type": "git", + "url": "https://github.com/fabpot/Pimple.git", + "reference": "2019c145fe393923f3441b23f29bbdfaa5c58c4d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/fabpot/Pimple/zipball/2019c145fe393923f3441b23f29bbdfaa5c58c4d", + "reference": "2019c145fe393923f3441b23f29bbdfaa5c58c4d", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev" + } + }, + "autoload": { + "psr-0": { + "Pimple": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + } + ], + "description": "Pimple is a simple Dependency Injection Container for PHP 5.3", + "homepage": "http://pimple.sensiolabs.org", + "keywords": [ + "container", + "dependency injection" + ], + "time": "2013-11-22 08:30:29" + }, + { + "name": "psr/log", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "fe0936ee26643249e916849d48e3a51d5f5e278b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/fe0936ee26643249e916849d48e3a51d5f5e278b", + "reference": "fe0936ee26643249e916849d48e3a51d5f5e278b", + "shasum": "" + }, + "type": "library", + "autoload": { + "psr-0": { + "Psr\\Log\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "time": "2012-12-21 11:40:51" + }, + { + "name": "squizlabs/php_codesniffer", + "version": "1.5.3", + "source": { + "type": "git", + "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", + "reference": "396178ada8499ec492363587f037125bf7b07fcc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/396178ada8499ec492363587f037125bf7b07fcc", + "reference": "396178ada8499ec492363587f037125bf7b07fcc", + "shasum": "" + }, + "require": { + "ext-tokenizer": "*", + "php": ">=5.1.2" + }, + "suggest": { + "phpunit/php-timer": "dev-master" + }, + "bin": [ + "scripts/phpcs" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-phpcs-fixer": "2.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "CodeSniffer.php", + "CodeSniffer/CLI.php", + "CodeSniffer/Exception.php", + "CodeSniffer/File.php", + "CodeSniffer/Report.php", + "CodeSniffer/Reporting.php", + "CodeSniffer/Sniff.php", + "CodeSniffer/Tokens.php", + "CodeSniffer/Reports/", + "CodeSniffer/CommentParser/", + "CodeSniffer/Tokenizers/", + "CodeSniffer/DocGenerators/", + "CodeSniffer/Standards/AbstractPatternSniff.php", + "CodeSniffer/Standards/AbstractScopeSniff.php", + "CodeSniffer/Standards/AbstractVariableSniff.php", + "CodeSniffer/Standards/IncorrectPatternException.php", + "CodeSniffer/Standards/Generic/Sniffs/", + "CodeSniffer/Standards/MySource/Sniffs/", + "CodeSniffer/Standards/PEAR/Sniffs/", + "CodeSniffer/Standards/PSR1/Sniffs/", + "CodeSniffer/Standards/PSR2/Sniffs/", + "CodeSniffer/Standards/Squiz/Sniffs/", + "CodeSniffer/Standards/Zend/Sniffs/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "lead" + } + ], + "description": "PHP_CodeSniffer tokenises PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "homepage": "http://www.squizlabs.com/php-codesniffer", + "keywords": [ + "phpcs", + "standards" + ], + "time": "2014-05-01 03:07:07" + }, + { + "name": "symfony/config", + "version": "v2.4.4", + "target-dir": "Symfony/Component/Config", + "source": { + "type": "git", + "url": "https://github.com/symfony/Config.git", + "reference": "2effc67af6f21a0d267210b72d0b0b691d113528" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Config/zipball/2effc67af6f21a0d267210b72d0b0b691d113528", + "reference": "2effc67af6f21a0d267210b72d0b0b691d113528", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "symfony/filesystem": "~2.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Config\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Config Component", + "homepage": "http://symfony.com", + "time": "2014-04-22 08:11:06" + }, + { + "name": "symfony/console", + "version": "v2.4.4", + "target-dir": "Symfony/Component/Console", + "source": { + "type": "git", + "url": "https://github.com/symfony/Console.git", + "reference": "2e452005b1e1d003d23702d227e23614679eb5ca" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Console/zipball/2e452005b1e1d003d23702d227e23614679eb5ca", + "reference": "2e452005b1e1d003d23702d227e23614679eb5ca", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "symfony/event-dispatcher": "~2.1" + }, + "suggest": { + "symfony/event-dispatcher": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Console\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Console Component", + "homepage": "http://symfony.com", + "time": "2014-04-27 13:34:57" + }, + { + "name": "symfony/event-dispatcher", + "version": "v2.4.4", + "target-dir": "Symfony/Component/EventDispatcher", + "source": { + "type": "git", + "url": "https://github.com/symfony/EventDispatcher.git", + "reference": "e539602e5455aa086c0e81e604745af7789e4d8a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/EventDispatcher/zipball/e539602e5455aa086c0e81e604745af7789e4d8a", + "reference": "e539602e5455aa086c0e81e604745af7789e4d8a", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "symfony/dependency-injection": "~2.0" + }, + "suggest": { + "symfony/dependency-injection": "", + "symfony/http-kernel": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\EventDispatcher\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony EventDispatcher Component", + "homepage": "http://symfony.com", + "time": "2014-04-16 10:34:31" + }, + { + "name": "symfony/filesystem", + "version": "v2.4.4", + "target-dir": "Symfony/Component/Filesystem", + "source": { + "type": "git", + "url": "https://github.com/symfony/Filesystem.git", + "reference": "a3af8294bcce4a7c1b2892363b0c9d8109affad4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Filesystem/zipball/a3af8294bcce4a7c1b2892363b0c9d8109affad4", + "reference": "a3af8294bcce4a7c1b2892363b0c9d8109affad4", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Filesystem\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Filesystem Component", + "homepage": "http://symfony.com", + "time": "2014-04-16 10:34:31" + }, + { + "name": "symfony/finder", + "version": "v2.4.4", + "target-dir": "Symfony/Component/Finder", + "source": { + "type": "git", + "url": "https://github.com/symfony/Finder.git", + "reference": "25e1e7d5e7376f8a92ae3b1d714d956edf33a730" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Finder/zipball/25e1e7d5e7376f8a92ae3b1d714d956edf33a730", + "reference": "25e1e7d5e7376f8a92ae3b1d714d956edf33a730", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Finder\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Finder Component", + "homepage": "http://symfony.com", + "time": "2014-04-27 13:34:57" + }, + { + "name": "symfony/process", + "version": "v2.4.4", + "target-dir": "Symfony/Component/Process", + "source": { + "type": "git", + "url": "https://github.com/symfony/Process.git", + "reference": "8721f1476d5d38a43c7d6ccb6435b351cf8f3bb7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Process/zipball/8721f1476d5d38a43c7d6ccb6435b351cf8f3bb7", + "reference": "8721f1476d5d38a43c7d6ccb6435b351cf8f3bb7", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Process\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Process Component", + "homepage": "http://symfony.com", + "time": "2014-04-27 13:34:57" + }, + { + "name": "symfony/property-access", + "version": "v2.4.4", + "target-dir": "Symfony/Component/PropertyAccess", + "source": { + "type": "git", + "url": "https://github.com/symfony/PropertyAccess.git", + "reference": "0456222bc00c40c1365065b603f7c397fb9a7134" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/PropertyAccess/zipball/0456222bc00c40c1365065b603f7c397fb9a7134", + "reference": "0456222bc00c40c1365065b603f7c397fb9a7134", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\PropertyAccess\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony PropertyAccess Component", + "homepage": "http://symfony.com", + "keywords": [ + "access", + "array", + "extraction", + "index", + "injection", + "object", + "property", + "property path", + "reflection" + ], + "time": "2014-04-18 20:37:09" + }, + { + "name": "symfony/stopwatch", + "version": "v2.4.4", + "target-dir": "Symfony/Component/Stopwatch", + "source": { + "type": "git", + "url": "https://github.com/symfony/Stopwatch.git", + "reference": "343bcc0360f2c22f371884b8f6a9fee8d1aa431a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Stopwatch/zipball/343bcc0360f2c22f371884b8f6a9fee8d1aa431a", + "reference": "343bcc0360f2c22f371884b8f6a9fee8d1aa431a", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Stopwatch\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Stopwatch Component", + "homepage": "http://symfony.com", + "time": "2014-04-18 20:37:09" + }, + { + "name": "symfony/translation", + "version": "v2.4.4", + "target-dir": "Symfony/Component/Translation", + "source": { + "type": "git", + "url": "https://github.com/symfony/Translation.git", + "reference": "d2c73ffa4a5ba1fa0c5d93f43b68331dffe898c5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Translation/zipball/d2c73ffa4a5ba1fa0c5d93f43b68331dffe898c5", + "reference": "d2c73ffa4a5ba1fa0c5d93f43b68331dffe898c5", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "symfony/config": "~2.0", + "symfony/yaml": "~2.2" + }, + "suggest": { + "symfony/config": "", + "symfony/yaml": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Translation\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Translation Component", + "homepage": "http://symfony.com", + "time": "2014-04-18 21:02:05" + }, + { + "name": "symfony/validator", + "version": "v2.4.4", + "target-dir": "Symfony/Component/Validator", + "source": { + "type": "git", + "url": "https://github.com/symfony/Validator.git", + "reference": "5bbcdcc520bc7fb3826abb44020880f14c9c03a7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Validator/zipball/5bbcdcc520bc7fb3826abb44020880f14c9c03a7", + "reference": "5bbcdcc520bc7fb3826abb44020880f14c9c03a7", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "symfony/property-access": "~2.2", + "symfony/translation": "~2.0" + }, + "require-dev": { + "doctrine/annotations": "~1.0", + "doctrine/cache": "~1.0", + "symfony/config": "~2.2", + "symfony/http-foundation": "~2.1", + "symfony/intl": "~2.3", + "symfony/yaml": "~2.0" + }, + "suggest": { + "doctrine/annotations": "For using the annotation mapping. You will also need doctrine/cache.", + "doctrine/cache": "For using the default cached annotation reader", + "symfony/config": "", + "symfony/http-foundation": "", + "symfony/intl": "", + "symfony/yaml": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Validator\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Validator Component", + "homepage": "http://symfony.com", + "time": "2014-04-27 13:34:57" + }, + { + "name": "symfony/yaml", + "version": "v2.4.4", + "target-dir": "Symfony/Component/Yaml", + "source": { + "type": "git", + "url": "https://github.com/symfony/Yaml.git", + "reference": "65539ecde838f9c0d18b006b2101e3deb4b5c9ff" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Yaml/zipball/65539ecde838f9c0d18b006b2101e3deb4b5c9ff", + "reference": "65539ecde838f9c0d18b006b2101e3deb4b5c9ff", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.4-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Yaml\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Yaml Component", + "homepage": "http://symfony.com", + "time": "2014-04-18 20:37:09" + }, + { + "name": "tecnick.com/tcpdf", + "version": "6.0.078", + "source": { + "type": "git", + "url": "git://git.code.sf.net/p/tcpdf/code", + "reference": "e1cbda79b99f3cdc8fdf26b39eb4870d2cd9fbac" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "fonts", + "config", + "include", + "tcpdf.php", + "tcpdf_parser.php", + "tcpdf_import.php", + "tcpdf_barcodes_1d.php", + "tcpdf_barcodes_2d.php", + "include/tcpdf_colors.php", + "include/tcpdf_filters.php", + "include/tcpdf_font_data.php", + "include/tcpdf_fonts.php", + "include/tcpdf_images.php", + "include/tcpdf_static.php", + "include/barcodes/datamatrix.php", + "include/barcodes/pdf417.php", + "include/barcodes/qrcode.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPLv3" + ], + "authors": [ + { + "name": "Nicola Asuni", + "email": "info@tecnick.com", + "homepage": "http://nicolaasuni.tecnick.com" + } + ], + "description": "TCPDF is a PHP class for generating PDF documents.", + "homepage": "http://www.tcpdf.org/", + "keywords": [ + "PDFD32000-2008", + "TCPDF", + "barcodes", + "datamatrix", + "pdf", + "pdf417", + "qrcode" + ], + "time": "2014-05-12 19:50:13" + }, + { + "name": "twig/twig", + "version": "v1.15.1", + "source": { + "type": "git", + "url": "https://github.com/fabpot/Twig.git", + "reference": "1fb5784662f438d7d96a541e305e28b812e2eeed" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/fabpot/Twig/zipball/1fb5784662f438d7d96a541e305e28b812e2eeed", + "reference": "1fb5784662f438d7d96a541e305e28b812e2eeed", + "shasum": "" + }, + "require": { + "php": ">=5.2.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.15-dev" + } + }, + "autoload": { + "psr-0": { + "Twig_": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Armin Ronacher2", + "email": "armin.ronacher@active-4.com", + "role": "Project Founder" + }, + { + "name": "Twig Team", + "homepage": "https://github.com/fabpot/Twig/graphs/contributors", + "role": "Contributors" + } + ], + "description": "Twig, the flexible, fast, and secure template language for PHP", + "homepage": "http://twig.sensiolabs.org", + "keywords": [ + "templating" + ], + "time": "2014-02-13 10:19:29" + }, + { + "name": "zendframework/zend-cache", + "version": "2.1.6", + "target-dir": "Zend/Cache", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendCache.git", + "reference": "560355160f06cdc3ef549a7eef843af3bead7e39" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendCache/zipball/560355160f06cdc3ef549a7eef843af3bead7e39", + "reference": "560355160f06cdc3ef549a7eef843af3bead7e39", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-eventmanager": "self.version", + "zendframework/zend-servicemanager": "self.version", + "zendframework/zend-stdlib": "self.version" + }, + "require-dev": { + "zendframework/zend-serializer": "self.version" + }, + "suggest": { + "ext-apc": "APC >= 3.1.6 to use the APC storage adapter", + "ext-dba": "DBA, to use the DBA storage adapter", + "ext-memcached": "Memcached >= 1.0.0 to use the Memcached storage adapter", + "ext-wincache": "WinCache, to use the WinCache storage adapter", + "zendframework/zend-serializer": "Zend\\Serializer component", + "zendframework/zend-session": "Zend\\Session component" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\Cache\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "provides a generic way to cache any data", + "keywords": [ + "cache", + "zf2" + ], + "time": "2014-03-03 23:00:17" + }, + { + "name": "zendframework/zend-config", + "version": "2.1.6", + "target-dir": "Zend/Config", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendConfig.git", + "reference": "a31c3980cf7ec88418a931e9cf4ba21079f47a08" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendConfig/zipball/a31c3980cf7ec88418a931e9cf4ba21079f47a08", + "reference": "a31c3980cf7ec88418a931e9cf4ba21079f47a08", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-stdlib": "self.version" + }, + "suggest": { + "zendframework/zend-json": "Zend\\Json to use the Json reader or writer classes", + "zendframework/zend-servicemanager": "Zend\\ServiceManager for use with the Config Factory to retrieve reader and writer instances" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\Config\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "provides a nested object property based user interface for accessing this configuration data within application code", + "keywords": [ + "config", + "zf2" + ], + "time": "2014-01-02 18:00:10" + }, + { + "name": "zendframework/zend-eventmanager", + "version": "2.1.6", + "target-dir": "Zend/EventManager", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendEventManager.git", + "reference": "89368704bb37303fba64c3ddd6bce0506aa7187c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendEventManager/zipball/89368704bb37303fba64c3ddd6bce0506aa7187c", + "reference": "89368704bb37303fba64c3ddd6bce0506aa7187c", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-stdlib": "self.version" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\EventManager\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "keywords": [ + "eventmanager", + "zf2" + ], + "time": "2014-01-04 13:00:14" + }, + { + "name": "zendframework/zend-filter", + "version": "2.1.6", + "target-dir": "Zend/Filter", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendFilter.git", + "reference": "8ceece474b29d079e86976dbd3efffe6064b3d72" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendFilter/zipball/8ceece474b29d079e86976dbd3efffe6064b3d72", + "reference": "8ceece474b29d079e86976dbd3efffe6064b3d72", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-stdlib": "self.version" + }, + "require-dev": { + "zendframework/zend-crypt": "self.version" + }, + "suggest": { + "zendframework/zend-crypt": "Zend\\Crypt component", + "zendframework/zend-i18n": "Zend\\I18n component", + "zendframework/zend-uri": "Zend\\Uri component for UriNormalize filter", + "zendframework/zend-validator": "Zend\\Validator component" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\Filter\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "provides a set of commonly needed data filters", + "keywords": [ + "filter", + "zf2" + ], + "time": "2014-03-03 21:00:06" + }, + { + "name": "zendframework/zend-i18n", + "version": "2.1.6", + "target-dir": "Zend/I18n", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendI18n.git", + "reference": "10f56e0869761d62699782e4dd04eb77262cc353" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendI18n/zipball/10f56e0869761d62699782e4dd04eb77262cc353", + "reference": "10f56e0869761d62699782e4dd04eb77262cc353", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-stdlib": "self.version" + }, + "suggest": { + "ext-intl": "Required for most features of Zend\\I18n; included in default builds of PHP", + "zendframework/zend-eventmanager": "You should install this package to use the events in the translator", + "zendframework/zend-filter": "You should install this package to use the provided filters", + "zendframework/zend-resources": "Translation resources", + "zendframework/zend-validator": "You should install this package to use the provided validators", + "zendframework/zend-view": "You should install this package to use the provided view helpers" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\I18n\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "keywords": [ + "i18n", + "zf2" + ], + "time": "2014-01-04 13:00:19" + }, + { + "name": "zendframework/zend-json", + "version": "2.1.6", + "target-dir": "Zend/Json", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendJson.git", + "reference": "dd8a8239a7c08c7449a6ea219da3e2369bd90d92" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendJson/zipball/dd8a8239a7c08c7449a6ea219da3e2369bd90d92", + "reference": "dd8a8239a7c08c7449a6ea219da3e2369bd90d92", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-stdlib": "self.version" + }, + "suggest": { + "zendframework/zend-server": "Zend\\Server component" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\Json\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "provides convenience methods for serializing native PHP to JSON and decoding JSON to native PHP", + "keywords": [ + "json", + "zf2" + ], + "time": "2014-03-06 18:00:05" + }, + { + "name": "zendframework/zend-math", + "version": "2.1.6", + "target-dir": "Zend/Math", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendMath.git", + "reference": "b982ee2edafd4075b22372596ab2e2fdd0f6424e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendMath/zipball/b982ee2edafd4075b22372596ab2e2fdd0f6424e", + "reference": "b982ee2edafd4075b22372596ab2e2fdd0f6424e", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "ext-bcmath": "If using the bcmath functionality", + "ext-gmp": "If using the gmp functionality", + "ircmaxell/random-lib": "Fallback random byte generator for Zend\\Math\\Rand if OpenSSL/Mcrypt extensions are unavailable", + "zendframework/zend-servicemanager": ">= current version, if using the BigInteger::factory functionality" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\Math\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "keywords": [ + "math", + "zf2" + ], + "time": "2014-03-05 18:00:06" + }, + { + "name": "zendframework/zend-serializer", + "version": "2.1.6", + "target-dir": "Zend/Serializer", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendSerializer.git", + "reference": "d76b931d3ffa842a496c9fa319bbe285b5ddfade" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendSerializer/zipball/d76b931d3ffa842a496c9fa319bbe285b5ddfade", + "reference": "d76b931d3ffa842a496c9fa319bbe285b5ddfade", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-json": "self.version", + "zendframework/zend-math": "self.version", + "zendframework/zend-stdlib": "self.version" + }, + "suggest": { + "zendframework/zend-servicemanager": "To support plugin manager support" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\Serializer\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "provides an adapter based interface to simply generate storable representation of PHP types by different facilities, and recover", + "keywords": [ + "serializer", + "zf2" + ], + "time": "2014-01-02 18:00:26" + }, + { + "name": "zendframework/zend-servicemanager", + "version": "2.1.6", + "target-dir": "Zend/ServiceManager", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendServiceManager.git", + "reference": "de182a20dfdcf978c49570514103c7477ef16e4f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendServiceManager/zipball/de182a20dfdcf978c49570514103c7477ef16e4f", + "reference": "de182a20dfdcf978c49570514103c7477ef16e4f", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "zendframework/zend-di": "Zend\\Di component" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\ServiceManager\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "keywords": [ + "servicemanager", + "zf2" + ], + "time": "2014-03-03 21:00:04" + }, + { + "name": "zendframework/zend-stdlib", + "version": "2.1.6", + "target-dir": "Zend/Stdlib", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendStdlib.git", + "reference": "e646729f2274f4552b6a92e38d8e458efe08ebc5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendStdlib/zipball/e646729f2274f4552b6a92e38d8e458efe08ebc5", + "reference": "e646729f2274f4552b6a92e38d8e458efe08ebc5", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "zendframework/zend-eventmanager": "To support aggregate hydrator usage", + "zendframework/zend-servicemanager": "To support hydrator plugin manager usage" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\Stdlib\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "keywords": [ + "stdlib", + "zf2" + ], + "time": "2014-01-04 13:00:28" + }, + { + "name": "zetacomponents/base", + "version": "1.8", + "source": { + "type": "git", + "url": "https://github.com/zetacomponents/Base.git", + "reference": "52ca69c1de55f3fa4f595779e5bc831da7ee176c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zetacomponents/Base/zipball/52ca69c1de55f3fa4f595779e5bc831da7ee176c", + "reference": "52ca69c1de55f3fa4f595779e5bc831da7ee176c", + "shasum": "" + }, + "type": "library", + "autoload": { + "classmap": [ + "src" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "apache2" + ], + "authors": [ + { + "name": "Sergey Alexeev" + }, + { + "name": "Sebastian Bergmann" + }, + { + "name": "Jan Borsodi" + }, + { + "name": "Raymond Bosman" + }, + { + "name": "Frederik Holljen" + }, + { + "name": "Kore Nordmann" + }, + { + "name": "Derick Rethans" + }, + { + "name": "Vadym Savchuk" + }, + { + "name": "Tobias Schlitt" + }, + { + "name": "Alexandru Stanoi" + } + ], + "description": "The Base package provides the basic infrastructure that all packages rely on. Therefore every component relies on this package.", + "homepage": "https://github.com/zetacomponents", + "time": "2009-12-21 12:14:16" + }, + { + "name": "zetacomponents/document", + "version": "1.3.1", + "source": { + "type": "git", + "url": "https://github.com/zetacomponents/Document.git", + "reference": "688abfde573cf3fe0730f82538fbd7aa9fc95bc8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zetacomponents/Document/zipball/688abfde573cf3fe0730f82538fbd7aa9fc95bc8", + "reference": "688abfde573cf3fe0730f82538fbd7aa9fc95bc8", + "shasum": "" + }, + "require": { + "zetacomponents/base": "*" + }, + "require-dev": { + "zetacomponents/unit-test": "dev-master" + }, + "type": "library", + "autoload": { + "classmap": [ + "src" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "Sebastian Bergmann" + }, + { + "name": "Kore Nordmann" + }, + { + "name": "Derick Rethans" + }, + { + "name": "Tobias Schlitt" + }, + { + "name": "Alexandru Stanoi" + } + ], + "description": "The Document components provides a general conversion framework for different semantic document markup languages like XHTML, Docbook, RST and similar.", + "homepage": "https://github.com/zetacomponents", + "time": "2013-12-19 11:40:00" + } + ], + "aliases": [ + + ], + "minimum-stability": "stable", + "stability-flags": [ + + ], + "platform": { + "php": ">=5.3.3", + "ext-xml": "*", + "ext-zip": "*" + }, + "platform-dev": [ + + ] +} diff --git a/docs/elements.rst b/docs/elements.rst index f2bf7791..7d076742 100644 --- a/docs/elements.rst +++ b/docs/elements.rst @@ -17,7 +17,7 @@ column shows the containers while the rows lists the elements. +-------+-----------------+-----------+----------+----------+---------+------------+------------+ | 4 | Title | v | ? | ? | ? | ? | ? | +-------+-----------------+-----------+----------+----------+---------+------------+------------+ -| 5 | Preserve Text | ? | v | v | v\* | ? | ? | +| 5 | Preserve Text | ? | v | v | v\* | - | - | +-------+-----------------+-----------+----------+----------+---------+------------+------------+ | 6 | Text Break | v | v | v | v | v | v | +-------+-----------------+-----------+----------+----------+---------+------------+------------+ @@ -25,7 +25,7 @@ column shows the containers while the rows lists the elements. +-------+-----------------+-----------+----------+----------+---------+------------+------------+ | 8 | List | v | v | v | v | - | - | +-------+-----------------+-----------+----------+----------+---------+------------+------------+ -| 9 | Table | v | v | v | ? | - | - | +| 9 | Table | v | v | v | v | - | - | +-------+-----------------+-----------+----------+----------+---------+------------+------------+ | 10 | Image | v | v | v | v | v | v | +-------+-----------------+-----------+----------+----------+---------+------------+------------+ @@ -39,7 +39,13 @@ column shows the containers while the rows lists the elements. +-------+-----------------+-----------+----------+----------+---------+------------+------------+ | 15 | Endnote | v | - | - | v\*\* | v\*\* | - | +-------+-----------------+-----------+----------+----------+---------+------------+------------+ -| 16 | CheckBox | v | v | v | v | ? | ? | +| 16 | CheckBox | v | v | v | v | - | - | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 17 | TextBox | v | v | v | v | - | - | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 18 | Field | v | v | v | v | v | v | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 19 | Line | v | v | v | v | v | v | +-------+-----------------+-----------+----------+----------+---------+------------+------------+ Legend: @@ -473,3 +479,18 @@ Checkbox elements can be added to sections or table cells by using - ``$text`` Text following the check box - ``$fontStyle`` See "Font style" section. - ``$paragraphStyle`` See "Paragraph style" section. + +Textboxes +--------- + +To be completed + +Fields +------ + +To be completed + +Line +------ + +To be completed diff --git a/docs/intro.rst b/docs/intro.rst index 3e74519e..aca5b241 100644 --- a/docs/intro.rst +++ b/docs/intro.rst @@ -12,18 +12,14 @@ Applications `__ (OpenDocument or ODF), and `Rich Text Format `__ (RTF). -No Windows operating system is needed for usage because the resulting -DOCX, ODT, or RTF files can be opened by all major `word processing -softwares `__. - -PHPWord is an open source project licensed under LGPL. PHPWord is `unit -tested `__ to make sure that -the released versions are stable. - -**Want to contribute?** `Fork -us `__ or -`submit `__ your bug -reports or feature requests to us. +PHPWord is an open source project licensed under the terms of `LGPL +version 3 `__. +PHPWord is aimed to be a high quality software product by incorporating +`continuous integration `__ and +`unit testing `__. +You can learn more about PHPWord by reading this Developers' +Documentation and the `API +Documentation `__. Features -------- @@ -65,31 +61,29 @@ Writers +---------------------------+----------------------+--------+-------+-------+--------+-------+ | Features | | DOCX | ODT | RTF | HTML | PDF | +===========================+======================+========+=======+=======+========+=======+ -| **Document Properties** | Standard | ✓ | | | | | +| **Document Properties** | Standard | ✓ | ✓ | ✓ | ✓ | ✓ | +---------------------------+----------------------+--------+-------+-------+--------+-------+ -| | Extended | ✓ | | | | | -+---------------------------+----------------------+--------+-------+-------+--------+-------+ -| | UserDefined | ✓ | | | | | +| | Custom | ✓ | ✓ | | | | +---------------------------+----------------------+--------+-------+-------+--------+-------+ | **Element Type** | Text | ✓ | ✓ | ✓ | ✓ | ✓ | +---------------------------+----------------------+--------+-------+-------+--------+-------+ | | Text Run | ✓ | ✓ | ✓ | ✓ | ✓ | +---------------------------+----------------------+--------+-------+-------+--------+-------+ -| | Title | ✓ | | | ✓ | ✓ | +| | Title | ✓ | ✓ | | ✓ | ✓ | +---------------------------+----------------------+--------+-------+-------+--------+-------+ -| | Link | ✓ | ✓ | | ✓ | ✓ | +| | Link | ✓ | ✓ | ✓ | ✓ | ✓ | +---------------------------+----------------------+--------+-------+-------+--------+-------+ | | Preserve Text | ✓ | | | | | +---------------------------+----------------------+--------+-------+-------+--------+-------+ | | Text Break | ✓ | ✓ | ✓ | ✓ | ✓ | +---------------------------+----------------------+--------+-------+-------+--------+-------+ -| | Page Break | ✓ | | | | | +| | Page Break | ✓ | | ✓ | | | +---------------------------+----------------------+--------+-------+-------+--------+-------+ | | List | ✓ | | | | | +---------------------------+----------------------+--------+-------+-------+--------+-------+ -| | Table | ✓ | ✓ | | ✓ | ✓ | +| | Table | ✓ | ✓ | ✓ | ✓ | ✓ | +---------------------------+----------------------+--------+-------+-------+--------+-------+ -| | Image | ✓ | ✓ | | ✓ | | +| | Image | ✓ | ✓ | ✓ | ✓ | | +---------------------------+----------------------+--------+-------+-------+--------+-------+ | | Object | ✓ | | | | | +---------------------------+----------------------+--------+-------+-------+--------+-------+ @@ -123,60 +117,75 @@ Writers Readers ~~~~~~~ -+---------------------------+----------------------+--------+-------+-------+ -| Features | | DOCX | ODT | RTF | -+===========================+======================+========+=======+=======+ -| **Document Properties** | Standard | ✓ | | | -+---------------------------+----------------------+--------+-------+-------+ -| | Extended | ✓ | | | -+---------------------------+----------------------+--------+-------+-------+ -| | UserDefined | ✓ | | | -+---------------------------+----------------------+--------+-------+-------+ -| **Element Type** | Text | ✓ | ✓ | | -+---------------------------+----------------------+--------+-------+-------+ -| | Text Run | ✓ | | | -+---------------------------+----------------------+--------+-------+-------+ -| | Title | ✓ | ✓ | | -+---------------------------+----------------------+--------+-------+-------+ -| | Link | ✓ | | | -+---------------------------+----------------------+--------+-------+-------+ -| | Preserve Text | ✓ | | | -+---------------------------+----------------------+--------+-------+-------+ -| | Text Break | ✓ | | | -+---------------------------+----------------------+--------+-------+-------+ -| | Page Break | ✓ | | | -+---------------------------+----------------------+--------+-------+-------+ -| | List | ✓ | ✓ | | -+---------------------------+----------------------+--------+-------+-------+ -| | Table | ✓ | | | -+---------------------------+----------------------+--------+-------+-------+ -| | Image | ✓ | | | -+---------------------------+----------------------+--------+-------+-------+ -| | Object | | | | -+---------------------------+----------------------+--------+-------+-------+ -| | Watermark | | | | -+---------------------------+----------------------+--------+-------+-------+ -| | Table of Contents | | | | -+---------------------------+----------------------+--------+-------+-------+ -| | Header | ✓ | | | -+---------------------------+----------------------+--------+-------+-------+ -| | Footer | ✓ | | | -+---------------------------+----------------------+--------+-------+-------+ -| | Footnote | ✓ | | | -+---------------------------+----------------------+--------+-------+-------+ -| | Endnote | ✓ | | | -+---------------------------+----------------------+--------+-------+-------+ -| **Graphs** | 2D basic graphs | | | | -+---------------------------+----------------------+--------+-------+-------+ -| | 2D advanced graphs | | | | -+---------------------------+----------------------+--------+-------+-------+ -| | 3D graphs | | | | -+---------------------------+----------------------+--------+-------+-------+ -| **Math** | OMML support | | | | -+---------------------------+----------------------+--------+-------+-------+ -| | MathML support | | | | -+---------------------------+----------------------+--------+-------+-------+ -| **Bonus** | Encryption | | | | -+---------------------------+----------------------+--------+-------+-------+ -| | Protection | | | | -+---------------------------+----------------------+--------+-------+-------+ ++---------------------------+----------------------+--------+-------+-------+-------+ +| Features | | DOCX | ODT | RTF | HTML | ++===========================+======================+========+=======+=======+=======+ +| **Document Properties** | Standard | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Custom | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| **Element Type** | Text | ✓ | ✓ | ✓ | ✓ | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Text Run | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Title | ✓ | ✓ | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Link | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Preserve Text | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Text Break | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Page Break | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | List | ✓ | ✓ | | ✓ | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Table | ✓ | | | ✓ | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Image | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Object | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Watermark | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Table of Contents | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Header | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Footer | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Footnote | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Endnote | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| **Graphs** | 2D basic graphs | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | 2D advanced graphs | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | 3D graphs | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| **Math** | OMML support | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | MathML support | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| **Bonus** | Encryption | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Protection | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ + +Contributing +------------ + +We welcome everyone to contribute to PHPWord. Below are some of the +things that you can do to contribute: + +- Read `our contributing + guide `__ +- `Fork us `__ and `request + a pull `__ to the + `develop `__ + branch +- Submit `bug reports or feature + requests `__ to GitHub +- Follow `@PHPWord `__ and + `@PHPOffice `__ on Twitter diff --git a/docs/recipes.rst b/docs/recipes.rst index 033452b3..d5678a52 100644 --- a/docs/recipes.rst +++ b/docs/recipes.rst @@ -2,3 +2,66 @@ Recipes ======= + +Create float left image +----------------------- + +Use absolute positioning relative to margin horizontally and to line +vertically. + +.. code-block:: php + + $imageStyle = array( + 'width' => 40, + 'height' => 40, + 'wrappingStyle' => 'square', + 'positioning' => 'absolute', + 'posHorizontalRel' => 'margin', + 'posVerticalRel' => 'line', + ); + $textrun->addImage('resources/_earth.jpg', $imageStyle); + $textrun->addText($lipsumText); + +Download the produced file automatically +---------------------------------------- + +Use ``php://output`` as the filename. + +.. code-block:: php + + $phpWord = new \PhpOffice\PhpWord\PhpWord(); + $section = $phpWord->createSection(); + $section->addText('Hello World!'); + $file = 'HelloWorld.docx'; + header("Content-Description: File Transfer"); + header('Content-Disposition: attachment; filename="' . $file . '"'); + header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); + header('Content-Transfer-Encoding: binary'); + header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); + header('Expires: 0'); + $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); + $xmlWriter->save("php://output"); + +Create numbered headings +------------------------ + +Define a numbering style and title styles, and match the two styles (with ``pStyle`` and ``numStyle``) like below. + +.. code-block:: php + + $phpWord->addNumberingStyle( + 'hNum', + array('type' => 'multilevel', 'levels' => array( + array('pStyle' => 'Heading1', 'format' => 'decimal', 'text' => '%1'), + array('pStyle' => 'Heading2', 'format' => 'decimal', 'text' => '%1.%2'), + array('pStyle' => 'Heading3', 'format' => 'decimal', 'text' => '%1.%2.%3'), + ) + ) + ); + $phpWord->addTitleStyle(1, array('size' => 16), array('numStyle' => 'hNum', 'numLevel' => 0)); + $phpWord->addTitleStyle(2, array('size' => 14), array('numStyle' => 'hNum', 'numLevel' => 1)); + $phpWord->addTitleStyle(3, array('size' => 12), array('numStyle' => 'hNum', 'numLevel' => 2)); + + $section->addTitle('Heading 1', 1); + $section->addTitle('Heading 2', 2); + $section->addTitle('Heading 3', 3); diff --git a/docs/references.rst b/docs/references.rst index 4f19a817..20aa1ed0 100644 --- a/docs/references.rst +++ b/docs/references.rst @@ -3,11 +3,21 @@ References ========== +ISO/IEC 29500, Third edition, 2012-09-01 +--------------------- + +- `Part 1: Fundamentals and Markup Language Reference + `__ +- `Part 2: Open Packaging Conventions + `__ +- `Part 3: Markup Compatibility and Extensibility + `__ +- `Part 4: Transitional Migration Features + `__ + Formal specifications --------------------- -- `Office Open XML (OOXML) (ECMA-376) - Schema `__ - `Oasis OpenDocument Standard Version 1.2 `__ - `Rich Text Format (RTF) Specification, version diff --git a/docs/src/documentation.md b/docs/src/documentation.md index bcf38a04..84522c1b 100644 --- a/docs/src/documentation.md +++ b/docs/src/documentation.md @@ -33,6 +33,9 @@ Don't forget to change `code::` directive to `code-block::` in the resulting rst - [Table of contents](#table-of-contents) - [Footnotes & endnotes](#footnotes-endnotes) - [Checkboxes](#checkboxes) + - [Textboxes](#textboxes) + - [Fields](#fields) + - [Lines](#lines) - [Templates](#templates) - [Writers & readers](#writers-readers) - [OOXML](#ooxml) @@ -40,6 +43,7 @@ Don't forget to change `code::` directive to `code-block::` in the resulting rst - [RTF](#rtf) - [HTML](#html) - [PDF](#pdf) +- [Recipes](#recipes) - [Frequently asked questions](#frequently-asked-questions) - [References](#references) @@ -47,11 +51,7 @@ Don't forget to change `code::` directive to `code-block::` in the resulting rst PHPWord is a library written in pure PHP that provides a set of classes to write to and read from different document file formats. The current version of PHPWord supports Microsoft [Office Open XML](http://en.wikipedia.org/wiki/Office_Open_XML) (OOXML or OpenXML), OASIS [Open Document Format for Office Applications](http://en.wikipedia.org/wiki/OpenDocument) (OpenDocument or ODF), and [Rich Text Format](http://en.wikipedia.org/wiki/Rich_Text_Format) (RTF). -No Windows operating system is needed for usage because the resulting DOCX, ODT, or RTF files can be opened by all major [word processing softwares](http://en.wikipedia.org/wiki/List_of_word_processors). - -PHPWord is an open source project licensed under LGPL. PHPWord is [unit tested](https://travis-ci.org/PHPOffice/PHPWord) to make sure that the released versions are stable. - -**Want to contribute?** [Fork us](https://github.com/PHPOffice/PHPWord/fork) or [submit](https://github.com/PHPOffice/PHPWord/issues) your bug reports or feature requests to us. +PHPWord is an open source project licensed under the terms of [LGPL version 3](https://github.com/PHPOffice/PHPWord/blob/develop/COPYING.LESSER). PHPWord is aimed to be a high quality software product by incorporating [continuous integration](https://travis-ci.org/PHPOffice/PHPWord) and [unit testing](http://phpoffice.github.io/PHPWord/coverage/develop/). You can learn more about PHPWord by reading this Developers' Documentation and the [API Documentation](http://phpoffice.github.io/PHPWord/docs/develop/). ## Features @@ -82,19 +82,18 @@ Below are the supported features for each file formats. | Features | | DOCX | ODT | RTF | HTML | PDF | |-------------------------|--------------------|------|-----|-----|------|-----| -| **Document Properties** | Standard | ✓ | | | | | -| | Extended | ✓ | | | | | -| | UserDefined | ✓ | | | | | +| **Document Properties** | Standard | ✓ | ✓ | ✓ | ✓ | | +| | Custom | ✓ | ✓ | | | | | **Element Type** | Text | ✓ | ✓ | ✓ | ✓ | ✓ | | | Text Run | ✓ | ✓ | ✓ | ✓ | ✓ | -| | Title | ✓ | | | ✓ | ✓ | -| | Link | ✓ | ✓ | | ✓ | ✓ | +| | Title | ✓ | ✓ | | ✓ | ✓ | +| | Link | ✓ | ✓ | ✓ | ✓ | ✓ | | | Preserve Text | ✓ | | | | | | | Text Break | ✓ | ✓ | ✓ | ✓ | ✓ | -| | Page Break | ✓ | | | | | +| | Page Break | ✓ | | ✓ | | | | | List | ✓ | | | | | -| | Table | ✓ | ✓ | | ✓ | ✓ | -| | Image | ✓ | ✓ | | ✓ | | +| | Table | ✓ | ✓ | ✓ | ✓ | ✓ | +| | Image | ✓ | ✓ | ✓ | ✓ | | | | Object | ✓ | | | | | | | Watermark | ✓ | | | | | | | Table of Contents | ✓ | | | | | @@ -112,35 +111,43 @@ Below are the supported features for each file formats. ### Readers -| Features | | DOCX | ODT | RTF | -|-------------------------|--------------------|------|-----|-----| -| **Document Properties** | Standard | ✓ | | | -| | Extended | ✓ | | | -| | UserDefined | ✓ | | | -| **Element Type** | Text | ✓ | ✓ | | -| | Text Run | ✓ | | | -| | Title | ✓ | ✓ | | -| | Link | ✓ | | | -| | Preserve Text | ✓ | | | -| | Text Break | ✓ | | | -| | Page Break | ✓ | | | -| | List | ✓ | ✓ | | -| | Table | ✓ | | | -| | Image | ✓ | | | -| | Object | | | | -| | Watermark | | | | -| | Table of Contents | | | | -| | Header | ✓ | | | -| | Footer | ✓ | | | -| | Footnote | ✓ | | | -| | Endnote | ✓ | | | -| **Graphs** | 2D basic graphs | | | | -| | 2D advanced graphs | | | | -| | 3D graphs | | | | -| **Math** | OMML support | | | | -| | MathML support | | | | -| **Bonus** | Encryption | | | | -| | Protection | | | | +| Features | | DOCX | ODT | RTF | HTML| +|-------------------------|--------------------|------|-----|-----|-----| +| **Document Properties** | Standard | ✓ | | | | +| | Custom | ✓ | | | | +| **Element Type** | Text | ✓ | ✓ | ✓ | ✓ | +| | Text Run | ✓ | | | | +| | Title | ✓ | ✓ | | | +| | Link | ✓ | | | | +| | Preserve Text | ✓ | | | | +| | Text Break | ✓ | | | | +| | Page Break | ✓ | | | | +| | List | ✓ | ✓ | | ✓ | +| | Table | ✓ | | | ✓ | +| | Image | ✓ | | | | +| | Object | | | | | +| | Watermark | | | | | +| | Table of Contents | | | | | +| | Header | ✓ | | | | +| | Footer | ✓ | | | | +| | Footnote | ✓ | | | | +| | Endnote | ✓ | | | | +| **Graphs** | 2D basic graphs | | | | | +| | 2D advanced graphs | | | | | +| | 3D graphs | | | | | +| **Math** | OMML support | | | | | +| | MathML support | | | | | +| **Bonus** | Encryption | | | | | +| | Protection | | | | | + +## Contributing + +We welcome everyone to contribute to PHPWord. Below are some of the things that you can do to contribute: + +- Read [our contributing guide](https://github.com/PHPOffice/PHPWord/blob/master/CONTRIBUTING.md) +- [Fork us](https://github.com/PHPOffice/PHPWord/fork) and [request a pull](https://github.com/PHPOffice/PHPWord/pulls) to the [develop](https://github.com/PHPOffice/PHPWord/tree/develop) branch +- Submit [bug reports or feature requests](https://github.com/PHPOffice/PHPWord/issues) to GitHub +- Follow [@PHPWord](https://twitter.com/PHPWord) and [@PHPOffice](https://twitter.com/PHPOffice) on Twitter # Installing/configuring @@ -443,18 +450,21 @@ Below are the matrix of element availability in each container. The column shows | 2 | Text Run | v | v | v | v | - | - | | 3 | Link | v | v | v | v | v | v | | 4 | Title | v | ? | ? | ? | ? | ? | -| 5 | Preserve Text | ? | v | v | v* | ? | ? | +| 5 | Preserve Text | ? | v | v | v* | - | - | | 6 | Text Break | v | v | v | v | v | v | | 7 | Page Break | v | - | - | - | - | - | | 8 | List | v | v | v | v | - | - | -| 9 | Table | v | v | v | ? | - | - | +| 9 | Table | v | v | v | v | - | - | | 10 | Image | v | v | v | v | v | v | | 11 | Watermark | - | v | - | - | - | - | | 12 | Object | v | v | v | v | v | v | | 13 | TOC | v | - | - | - | - | - | | 14 | Footnote | v | - | - | v** | v** | - | | 15 | Endnote | v | - | - | v** | v** | - | -| 16 | CheckBox | v | v | v | v | ? | ? | +| 16 | CheckBox | v | v | v | v | - | - | +| 17 | TextBox | v | v | v | v | - | - | +| 18 | Field | v | v | v | v | v | v | +| 19 | Line | v | v | v | v | v | v | Legend: @@ -487,7 +497,7 @@ $section->addText('I am simple paragraph', $fontStyle, $paragraphStyle); $textrun = $section->addTextRun(); $textrun->addText('I am bold', array('bold' => true)); $textrun->addText('I am italic', array('italic' => true)); -$textrun->addText('I am colored, array('color' => 'AACC00')); +$textrun->addText('I am colored', array('color' => 'AACC00')); ``` Defined style examples: @@ -828,6 +838,18 @@ $section->addCheckBox($name, $text, [$fontStyle], [$paragraphStyle]) - `$fontStyle` See "Font style" section. - `$paragraphStyle` See "Paragraph style" section. +## Textboxes + +To be completed. + +## Fields + +To be completed. + +## Lines + +To be completed. + # Templates You can create a docx template with included search-patterns that can be replaced by any value you wish. Only single-line values can be replaced. To load a template file, use the `loadTemplate` method. After loading the docx template, you can use the `setValue` method to change the value of a search pattern. The search-pattern model is: `${search-pattern}`. It is not possible to add new PHPWord elements to a loaded template file. @@ -926,6 +948,67 @@ To be completed. To be completed. +# Recipes + +## Create float left image + +Use absolute positioning relative to margin horizontally and to line vertically. + +```php +$imageStyle = array( + 'width' => 40, + 'height' => 40 + 'wrappingStyle' => 'square', + 'positioning' => 'absolute', + 'posHorizontalRel' => 'margin', + 'posVerticalRel' => 'line', +); +$textrun->addImage('resources/_earth.jpg', $imageStyle); +$textrun->addText($lipsumText); +``` + +## Download the produced file automatically + +Use `php://output` as the filename. + +```php +$phpWord = new \PhpOffice\PhpWord\PhpWord(); +$section = $phpWord->createSection(); +$section->addText('Hello World!'); +$file = 'HelloWorld.docx'; +header("Content-Description: File Transfer"); +header('Content-Disposition: attachment; filename="' . $file . '"'); +header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); +header('Content-Transfer-Encoding: binary'); +header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); +header('Expires: 0'); +$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); +$xmlWriter->save("php://output"); +``` + +## Create numbered headings + +Define a numbering style and title styles, and match the two styles (with `pStyle` and `numStyle`) like below. + +```php +$phpWord->addNumberingStyle( + 'hNum', + array('type' => 'multilevel', 'levels' => array( + array('pStyle' => 'Heading1', 'format' => 'decimal', 'text' => '%1'), + array('pStyle' => 'Heading2', 'format' => 'decimal', 'text' => '%1.%2'), + array('pStyle' => 'Heading3', 'format' => 'decimal', 'text' => '%1.%2.%3'), + ) + ) +); +$phpWord->addTitleStyle(1, array('size' => 16), array('numStyle' => 'hNum', 'numLevel' => 0)); +$phpWord->addTitleStyle(2, array('size' => 14), array('numStyle' => 'hNum', 'numLevel' => 1)); +$phpWord->addTitleStyle(3, array('size' => 12), array('numStyle' => 'hNum', 'numLevel' => 2)); + +$section->addTitle('Heading 1', 1); +$section->addTitle('Heading 2', 2); +$section->addTitle('Heading 3', 3); +``` + # Frequently asked questions ## Is this the same with PHPWord that I found in CodePlex? @@ -938,13 +1021,18 @@ PHPWord requires PHP 5.3+ since 0.8, while PHPWord 0.6.3 from CodePlex can run w # References +## ISO/IEC 29500, Third edition, 2012-09-01 + +- [Part 1: Fundamentals and Markup Language Reference](http://standards.iso.org/ittf/PubliclyAvailableStandards/c061750_ISO_IEC_29500-1_2012.zip) +- [Part 2: Open Packaging Conventions](http://standards.iso.org/ittf/PubliclyAvailableStandards/c061796_ISO_IEC_29500-2_2012.zip) +- [Part 3: Markup Compatibility and Extensibility](http://standards.iso.org/ittf/PubliclyAvailableStandards/c061797_ISO_IEC_29500-3_2012.zip) +- [Part 4: Transitional Migration Features](http://standards.iso.org/ittf/PubliclyAvailableStandards/c061798_ISO_IEC_29500-4_2012.zip) + ## Formal specifications -- [Office Open XML (OOXML) (ECMA-376) Schema](http://www.schemacentral.com/sc/ooxml/ss.html) -- [Oasis OpenDocument Standard Version 1.2](http://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os.html) -- [Rich Text Format (RTF) Specification, version 1.9.1](http://www.microsoft.com/en-us/download/details.aspx?id=10725) +- [Oasis OpenDocument Standard Version 1.2](http://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os.html) +- [Rich Text Format (RTF) Specification, version 1.9.1](http://www.microsoft.com/en-us/download/details.aspx?id=10725) ## Other resources -- [DocumentFormat.OpenXml.Wordprocessing Namespace on MSDN](http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing%28v=office.14%29.aspx) - +- [DocumentFormat.OpenXml.Wordprocessing Namespace on MSDN](http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing%28v=office.14%29.aspx) diff --git a/phpmd.xml b/phpmd.xml deleted file mode 100644 index c1ebb770..00000000 --- a/phpmd.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/phpmd.xml.dist b/phpmd.xml.dist new file mode 100644 index 00000000..f0b62b2d --- /dev/null +++ b/phpmd.xml.dist @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/phpunit.xml.dist b/phpunit.xml.dist index c7e59676..015dd2ed 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -10,7 +10,7 @@ syntaxCheck="false"> - ./tests/PhpWord/ + ./tests/PhpWord @@ -22,6 +22,7 @@ + \ No newline at end of file diff --git a/phpword.ini.dist b/phpword.ini.dist new file mode 100644 index 00000000..4a51ee11 --- /dev/null +++ b/phpword.ini.dist @@ -0,0 +1,14 @@ +; Default config file for PHPWord +; Copy this file into phpword.ini and use Settings::loadConfig to load + +[General] + +compatibility = true +zipClass = ZipArchive +pdfRendererName = DomPDF +pdfRendererPath = + +[Font] + +defaultFontName = Arial +defaultFontSize = 10 diff --git a/samples/Sample_01_SimpleText.php b/samples/Sample_01_SimpleText.php index 7202ed7e..311f3350 100644 --- a/samples/Sample_01_SimpleText.php +++ b/samples/Sample_01_SimpleText.php @@ -22,7 +22,8 @@ $section->addTextBreak(2); $section->addText('I am styled by a font style definition.', 'rStyle'); $section->addText('I am styled by a paragraph style definition.', null, 'pStyle'); $section->addText('I am styled by both font and paragraph style.', 'rStyle', 'pStyle'); -$section->addTextBreak(); + +$section->addPageBreak(); // Inline font style $fontStyle['name'] = 'Times New Roman'; @@ -36,10 +37,11 @@ $fontStyle['color'] = 'FF0000'; $fontStyle['fgColor'] = 'yellow'; $fontStyle['smallCaps'] = true; $section->addText('I am inline styled.', $fontStyle); + $section->addTextBreak(); // Link -$section->addLink('http://www.google.com', null, 'NLink'); +$section->addLink('http://www.google.com', 'Google'); $section->addTextBreak(); // Image diff --git a/samples/Sample_05_Multicolumn.php b/samples/Sample_05_Multicolumn.php index a3083824..f4737060 100644 --- a/samples/Sample_05_Multicolumn.php +++ b/samples/Sample_05_Multicolumn.php @@ -18,7 +18,7 @@ $section = $phpWord->addSection(array( 'colsNum' => 2, 'colsSpace' => 1440, 'breakType' => 'continuous')); -$section->addText('Three columns, one inch (1440 twips) spacing. ' . $filler); +$section->addText('Two columns, one inch (1440 twips) spacing. ' . $filler); // Normal $section = $phpWord->addSection(array('breakType' => 'continuous')); diff --git a/samples/Sample_09_Tables.php b/samples/Sample_09_Tables.php index 5b4b1300..882653bc 100644 --- a/samples/Sample_09_Tables.php +++ b/samples/Sample_09_Tables.php @@ -51,7 +51,7 @@ for($i = 1; $i <= 8; $i++) { // 3. colspan (gridSpan) and rowspan (vMerge) -$section->addTextBreak(1); +$section->addPageBreak(); $section->addText("Table with colspan and rowspan", $header); $styleTable = array('borderSize' => 6, 'borderColor' => '999999'); @@ -84,6 +84,17 @@ $table->addCell(2000, $cellVCentered)->addText('C', null, $cellHCentered); $table->addCell(2000, $cellVCentered)->addText('D', null, $cellHCentered); $table->addCell(null, $cellRowContinue); +// 4. Nested table + +$section->addTextBreak(2); +$section->addText('Nested table in a centered and 50% width table.', $header); + +$table = $section->addTable(array('width' => 50 * 50, 'unit' => 'pct', 'align' => 'center')); +$cell = $table->addRow()->addCell(); +$cell->addText('This cell contains nested table.'); +$innerCell = $cell->addTable(array('align' => 'center'))->addRow()->addCell(); +$innerCell->addText('Inside nested table'); + // Save file echo write($phpWord, basename(__FILE__, '.php'), $writers); if (!CLI) { diff --git a/samples/Sample_11_ReadWord2007.php b/samples/Sample_11_ReadWord2007.php index 09d9cab0..c0b54c7a 100644 --- a/samples/Sample_11_ReadWord2007.php +++ b/samples/Sample_11_ReadWord2007.php @@ -3,7 +3,8 @@ include_once 'Sample_Header.php'; // Read contents $name = basename(__FILE__, '.php'); -$source = "resources/{$name}.docx"; +$source = __DIR__ . "/resources/{$name}.docx"; + echo date('H:i:s'), " Reading contents from `{$source}`", EOL; $phpWord = \PhpOffice\PhpWord\IOFactory::load($source); diff --git a/samples/Sample_12_HeaderFooter.php b/samples/Sample_12_HeaderFooter.php index 8e053286..0fd56edc 100644 --- a/samples/Sample_12_HeaderFooter.php +++ b/samples/Sample_12_HeaderFooter.php @@ -25,6 +25,7 @@ $table->addCell(4500)->addImage( // Add header for all other pages $subsequent = $section->addHeader(); $subsequent->addText("Subsequent pages in Section 1 will Have this!"); +$subsequent->addImage('resources/_mars.jpg', array('width' => 80, 'height' => 80)); // Add footer $footer = $section->addFooter(); diff --git a/samples/Sample_13_Images.php b/samples/Sample_13_Images.php index 65e38bf5..dd0c8801 100644 --- a/samples/Sample_13_Images.php +++ b/samples/Sample_13_Images.php @@ -26,11 +26,45 @@ $wrappingStyles = array('inline', 'behind', 'infront', 'square', 'tight'); foreach ($wrappingStyles as $wrappingStyle) { $section->addTextBreak(5); $section->addText('Wrapping style ' . $wrappingStyle); - $section->addImage('resources/_earth.jpg', array('marginTop' => -1, 'marginLeft' => 1, + $section->addImage('resources/_earth.jpg', array('positioning' => 'relative', 'marginTop' => -1, 'marginLeft' => 1, 'width' => 80, 'height' => 80, 'wrappingStyle' => $wrappingStyle)); $section->addText($text); } +//Absolute positioning +$section->addTextBreak(3); +$section->addText('Absolute positioning: see top right corner of page'); +$section->addImage( + 'resources/_mars.jpg', + array( + 'width' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(3), + 'height' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(3), + 'positioning' => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE, + 'posHorizontal' => \PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_RIGHT, + 'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE, + 'posVerticalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE, + 'marginLeft' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(15.5), + 'marginTop' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(1.55) + ) +); + +//Relative positioning +$section->addTextBreak(3); +$section->addText('Relative positioning: Horizontal position center relative to column,'); +$section->addText('Vertical position top relative to line'); +$section->addImage( + 'resources/_mars.jpg', + array( + 'width' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(3), + 'height' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(3), + 'positioning' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE, + 'posHorizontal' => \PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_CENTER, + 'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_COLUMN, + 'posVertical' => \PhpOffice\PhpWord\Style\Image::POSITION_VERTICAL_TOP, + 'posVerticalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_LINE + ) +); + // Save file echo write($phpWord, basename(__FILE__, '.php'), $writers); if (!CLI) { diff --git a/samples/Sample_14_ListItem.php b/samples/Sample_14_ListItem.php index cd22df8e..3a3d34ab 100644 --- a/samples/Sample_14_ListItem.php +++ b/samples/Sample_14_ListItem.php @@ -18,7 +18,7 @@ $phpWord->addNumberingStyle( array('format' => 'decimal', 'text' => '%1.', 'left' => 360, 'hanging' => 360, 'tabPos' => 360), array('format' => 'upperLetter', 'text' => '%2.', 'left' => 720, 'hanging' => 360, 'tabPos' => 720), ) - ) + ) ); $predefinedMultilevel = array('listType' => \PhpOffice\PhpWord\Style\ListItem::TYPE_NUMBER_NESTED); @@ -54,6 +54,37 @@ $section->addListItem('List Item 6', 1, 'myOwnStyle', $predefinedMultilevel, 'P- $section->addListItem('List Item 7', 0, 'myOwnStyle', $predefinedMultilevel, 'P-Style'); $section->addTextBreak(2); +$section->addText('List with inline formatting.'); +$listItemRun = $section->addListItemRun(); +$listItemRun->addText('List item 1'); +$listItemRun->addText(' in bold', array('bold'=>true)); +$listItemRun = $section->addListItemRun(); +$listItemRun->addText('List item 2'); +$listItemRun->addText(' in italic', array('italic'=>true)); +$listItemRun = $section->addListItemRun(); +$listItemRun->addText('List item 3'); +$listItemRun->addText(' underlined', array('underline'=>'dash')); +$section->addTextBreak(2); + +// Numbered heading + +$phpWord->addNumberingStyle( + 'headingNumbering', + array('type' => 'multilevel', 'levels' => array( + array('pStyle' => 'Heading1', 'format' => 'decimal', 'text' => '%1'), + array('pStyle' => 'Heading2', 'format' => 'decimal', 'text' => '%1.%2'), + array('pStyle' => 'Heading3', 'format' => 'decimal', 'text' => '%1.%2.%3'), + ) + ) +); +$phpWord->addTitleStyle(1, array('size' => 16), array('numStyle' => 'headingNumbering', 'numLevel' => 0)); +$phpWord->addTitleStyle(2, array('size' => 14), array('numStyle' => 'headingNumbering', 'numLevel' => 1)); +$phpWord->addTitleStyle(3, array('size' => 12), array('numStyle' => 'headingNumbering', 'numLevel' => 2)); + +$section->addTitle('Heading 1', 1); +$section->addTitle('Heading 2', 2); +$section->addTitle('Heading 3', 3); + // Save file echo write($phpWord, basename(__FILE__, '.php'), $writers); if (!CLI) { diff --git a/samples/Sample_24_ReadODText.php b/samples/Sample_24_ReadODText.php index bb5332e6..42df23ae 100644 --- a/samples/Sample_24_ReadODText.php +++ b/samples/Sample_24_ReadODText.php @@ -3,7 +3,8 @@ include_once 'Sample_Header.php'; // Read contents $name = basename(__FILE__, '.php'); -$source = "resources/{$name}.odt"; +$source = __DIR__ . "/resources/{$name}.odt"; + echo date('H:i:s'), " Reading contents from `{$source}`", EOL; $phpWord = \PhpOffice\PhpWord\IOFactory::load($source, 'ODText'); diff --git a/samples/Sample_25_TextBox.php b/samples/Sample_25_TextBox.php new file mode 100644 index 00000000..0a659ddb --- /dev/null +++ b/samples/Sample_25_TextBox.php @@ -0,0 +1,39 @@ +addSection(); + +// In section +$textbox = $section->addTextBox(array('align' => 'center', 'width' => 400, 'height' => 150, 'borderSize' => 1, 'borderColor' => '#FF0000')); +$textbox->addText('Text box content in section.'); +$textbox->addText('Another line.'); +$cell = $textbox->addTable()->addRow()->addCell(); +$cell->addText('Table inside textbox'); + +// Inside table +$section->addTextBreak(2); +$cell = $section->addTable()->addRow()->addCell(300); +$textbox = $cell->addTextBox(array('borderSize' => 1, 'borderColor' => '#0000FF', 'innerMargin' => 100)); +$textbox->addText('Textbox inside table'); + +// Inside header with textrun +$header = $section->addHeader(); +$textbox = $header->addTextBox(array('width' => 600, 'borderSize' => 1, 'borderColor' => '#00FF00')); +$textrun = $textbox->addTextRun(); +$textrun->addText('TextBox in header. TextBox can contain a TextRun '); +$textrun->addText('with bold text', array('bold' => true)); +$textrun->addText(', '); +$textrun->addLink('http://www.google.com', 'link'); +$textrun->addText(', and image '); +$textrun->addImage('resources/_earth.jpg', array('width' => 18, 'height' => 18)); +$textrun->addText('.'); + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_26_Html.php b/samples/Sample_26_Html.php new file mode 100644 index 00000000..92b3aa49 --- /dev/null +++ b/samples/Sample_26_Html.php @@ -0,0 +1,23 @@ +addSection(); +$html = '

Adding element via HTML

'; +$html .= '

Some well formed HTML snippet needs to be used

'; +$html .= '

With for example some1 inline formatting1

'; +$html .= '

Unordered (bulleted) list:

'; +$html .= '
  • Item 1
  • Item 2
    • Item 2.1
    • Item 2.1
'; +$html .= '

Ordered (numbered) list:

'; +$html .= '
  1. Item 1
  2. Item 2
'; + +\PhpOffice\PhpWord\Shared\Html::addHtml($section, $html); + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} \ No newline at end of file diff --git a/samples/Sample_27_Field.php b/samples/Sample_27_Field.php new file mode 100644 index 00000000..fd750372 --- /dev/null +++ b/samples/Sample_27_Field.php @@ -0,0 +1,31 @@ +addSection(); + +// Add Field elements +// See Element/Field.php for all options +$section->addText('Date field:'); +$section->addField('DATE', array('dateformat'=>'dddd d MMMM yyyy H:mm:ss'), array('PreserveFormat')); + +$section->addText('Page field:'); +$section->addField('PAGE', array('format'=>'ArabicDash')); + +$section->addText('Number of pages field:'); +$section->addField('NUMPAGES', array('format'=>'Arabic', 'numformat'=>'0,00'), array('PreserveFormat')); + +$textrun = $section->addTextRun(array('align' => 'center')); +$textrun->addText('This is the date of lunar calendar '); +$textrun->addField('DATE', array('dateformat'=>'d-M-yyyy H:mm:ss'), array('PreserveFormat', 'LunarCalendar')); +$textrun->addText(' written in a textrun.'); + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_28_ReadRTF.php b/samples/Sample_28_ReadRTF.php new file mode 100644 index 00000000..76ac3d48 --- /dev/null +++ b/samples/Sample_28_ReadRTF.php @@ -0,0 +1,15 @@ +addSection(); + +// Add Line elements +// See Element/Line.php for all options +$section->addText('Horizontal Line (Inline style):'); +$section->addLine( + array( + 'width' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(4), + 'height' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(0), + 'positioning' => 'absolute' + ) +); +$section->addText('Vertical Line (Inline style):'); +$section->addLine( + array( + 'width' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(0), + 'height' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(1), + 'positioning' => 'absolute' + ) +); +// Two text break +$section->addTextBreak(1); + +$section->addText('Positioned Line (red):'); +$section->addLine( + array( + 'width' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(4), + 'height' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(1), + 'positioning' => 'absolute', + 'posHorizontalRel' => 'page', + 'posVerticalRel' => 'page', + 'marginLeft' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(10), + 'marginTop' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(8), + 'wrappingStyle' => \PhpOffice\PhpWord\Style\Image::WRAPPING_STYLE_SQUARE, + 'color' => 'red' + ) +); + +$section->addText('Horizontal Formatted Line'); +$section->addLine( + array( + 'width' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(15), + 'height' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(0), + 'positioning' => 'absolute', + 'beginArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_BLOCK, + 'endArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_OVAL, + 'dash' => \PhpOffice\PhpWord\Style\Line::DASH_STYLE_LONG_DASH_DOT_DOT, + 'weight' => 10 + ) +); + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_30_ReadHTML.php b/samples/Sample_30_ReadHTML.php new file mode 100644 index 00000000..029f8c8c --- /dev/null +++ b/samples/Sample_30_ReadHTML.php @@ -0,0 +1,15 @@ +'); define('SCRIPT_FILENAME', basename($_SERVER['SCRIPT_FILENAME'], '.php')); define('IS_INDEX', SCRIPT_FILENAME == 'index'); -require_once '../src/PhpWord/Autoloader.php'; -\PhpOffice\PhpWord\Autoloader::register(); +require_once __DIR__ . '/../src/PhpWord/Autoloader.php'; +Autoloader::register(); +Settings::loadConfig(); // Set writers $writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf', 'HTML' => 'html', 'PDF' => 'pdf'); // Set PDF renderer -$rendererName = \PhpOffice\PhpWord\Settings::PDF_RENDERER_DOMPDF; -$rendererLibraryPath = ''; // DomPDF library path - -if (!\PhpOffice\PhpWord\Settings::setPdfRenderer($rendererName, $rendererLibraryPath)) { +if (Settings::getPdfRendererPath() === null) { $writers['PDF'] = null; } @@ -60,9 +62,9 @@ function write($phpWord, $filename, $writers) foreach ($writers as $writer => $extension) { $result .= date('H:i:s') . " Write to {$writer} format"; if (!is_null($extension)) { - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$filename}.{$extension}"); - rename("{$filename}.{$extension}", "results/{$filename}.{$extension}"); + $xmlWriter = IOFactory::createWriter($phpWord, $writer); + $xmlWriter->save(__DIR__ . "/{$filename}.{$extension}"); + rename(__DIR__ . "/{$filename}.{$extension}", __DIR__ . "/results/{$filename}.{$extension}"); } else { $result .= ' ... NOT DONE!'; } diff --git a/samples/index.php b/samples/index.php index 71e8518a..420c5420 100644 --- a/samples/index.php +++ b/samples/index.php @@ -1,5 +1,13 @@ array('PHP 5.3.0', version_compare(phpversion(), '5.3.0', '>=')), + 'xml' => array('PHP extension XML', extension_loaded('xml')), + 'zip' => array('PHP extension ZipArchive (optional)', extension_loaded('zip')), + 'gd' => array('PHP extension GD (optional)', extension_loaded('gd')), + 'xmlw' => array('PHP extension XMLWriter (optional)', extension_loaded('xmlwriter')), + 'xsl' => array('PHP extension XSL (optional)', extension_loaded('xsl')), +); if (!CLI) { ?>
@@ -10,21 +18,23 @@ if (!CLI) { Read the Docs

- array('PHP 5.3.0', version_compare(phpversion(), '5.3.0', '>=')), - 'zip' => array('PHP extension ZipArchive', extension_loaded('zip')), - 'xml' => array('PHP extension XML', extension_loaded('xml')), - 'gd' => array('PHP extension GD (optional)', extension_loaded('gd')), -); -echo "

Requirements

"; -echo "
    "; -foreach ($requirements as $key => $value) { - $status = $value[1] ? 'passed' : 'failed'; - echo "
  • {$value[0]} ... {$status}
  • "; -} -echo "
"; +Requirement check:"; + echo "
    "; + foreach ($requirements as $key => $value) { + list($label, $result) = $value; + $status = $result ? 'passed' : 'failed'; + echo "
  • {$label} ... {$status}
  • "; + } + echo "
"; include_once 'Sample_Footer.php'; +} else { + echo 'Requirement check:' . PHP_EOL; + foreach ($requirements as $key => $value) { + list($label, $result) = $value; + $status = $result ? '32m passed' : '31m failed'; + echo "{$label} ... \033[{$status}\033[0m" . PHP_EOL; + } } diff --git a/samples/resources/Sample_11_ReadWord2007.docx b/samples/resources/Sample_11_ReadWord2007.docx index 2143c628..c9a50f48 100644 Binary files a/samples/resources/Sample_11_ReadWord2007.docx and b/samples/resources/Sample_11_ReadWord2007.docx differ diff --git a/samples/resources/Sample_24_ReadODText.odt b/samples/resources/Sample_24_ReadODText.odt index 9e18e619..d37c4e66 100644 Binary files a/samples/resources/Sample_24_ReadODText.odt and b/samples/resources/Sample_24_ReadODText.odt differ diff --git a/samples/resources/Sample_28_ReadRTF.rtf b/samples/resources/Sample_28_ReadRTF.rtf new file mode 100644 index 00000000..6f9ac0f8 --- /dev/null +++ b/samples/resources/Sample_28_ReadRTF.rtf @@ -0,0 +1,21 @@ +{\rtf1 +\ansi\ansicpg1252 +\deff0 +{\fonttbl{\f0\fnil\fcharset0 Arial;}{\f1\fnil\fcharset0 Times New Roman;}} +{\colortbl;\red255\green0\blue0;\red14\green0\blue0} +{\*\generator PhpWord;} + +{\info{\title }{\subject }{\category }{\keywords }{\comment }{\author }{\operator }{\creatim \yr2014\mo05\dy27\hr23\min36\sec45}{\revtim \yr2014\mo05\dy27\hr23\min36\sec45}{\company }{\manager }} +\deftab720\viewkind1\uc1\pard\nowidctlpar\lang1036\kerning1\fs20 +{Welcome to PhpWord}\par +\pard\nowidctlpar{\cf0\f0 Hello World!}\par +\par +\par +\pard\nowidctlpar{\cf0\f0\fs32\b\i I am styled by a font style definition.}\par +\pard\nowidctlpar{\cf0\f0 I am styled by a paragraph style definition.}\par +\pard\nowidctlpar\qc\sa100{\cf0\f0\fs32\b\i I am styled by both font and paragraph style.}\par +\pard\nowidctlpar{\cf1\f1\fs40\b\i\ul\strike\super I am inline styled.}\par +\par +{\field {\*\fldinst {HYPERLINK "http://www.google.com"}}{\fldrslt {Google}}}\par +\par +} \ No newline at end of file diff --git a/samples/resources/Sample_30_ReadHTML.html b/samples/resources/Sample_30_ReadHTML.html new file mode 100644 index 00000000..5593298b --- /dev/null +++ b/samples/resources/Sample_30_ReadHTML.html @@ -0,0 +1,15 @@ + + + +PHPWord + + +

Adding element via HTML

+

Some well formed HTML snippet needs to be used

+

With for example some1 inline formatting1

+

Unordered (bulleted) list:

+
  • Item 1
  • Item 2
    • Item 2.1
    • Item 2.1
+

Ordered (numbered) list:

+
  1. Item 1
  2. Item 2
+ + diff --git a/src/PhpWord/Autoloader.php b/src/PhpWord/Autoloader.php index 5bb331ab..c467f836 100644 --- a/src/PhpWord/Autoloader.php +++ b/src/PhpWord/Autoloader.php @@ -1,10 +1,18 @@ items; + } + + /** + * Get item by index + * + * @param int $index + * @return mixed + */ + public function getItem($index) + { + if (array_key_exists($index, $this->items)) { + return $this->items[$index]; + } else { + return null; + } + } + + /** + * Set item + * + * @param int $index + * @param mixed $item + */ + public function setItem($index, $item) + { + if (array_key_exists($index, $this->items)) { + $this->items[$index] = $item; + } + } + + /** + * Add new item + * + * @param mixed $item + * @return int + */ + public function addItem($item) + { + $index = $this->countItems() + 1; + $this->items[$index] = $item; + + return $index; + } + + /** + * Get item count + * + * @return int + */ + public function countItems() + { + return count($this->items); + } +} diff --git a/src/PhpWord/Collection/Endnotes.php b/src/PhpWord/Collection/Endnotes.php new file mode 100644 index 00000000..c16486ae --- /dev/null +++ b/src/PhpWord/Collection/Endnotes.php @@ -0,0 +1,27 @@ +isCustomPropertySet($propertyName)) { return $this->customProperties[$propertyName]['value']; + } else { + return null; } - } /** @@ -422,8 +431,9 @@ class DocumentProperties { if ($this->isCustomPropertySet($propertyName)) { return $this->customProperties[$propertyName]['type']; + } else { + return null; } - } /** @@ -478,49 +488,23 @@ class DocumentProperties */ public static function convertProperty($propertyValue, $propertyType) { - switch ($propertyType) { - case 'empty': // Empty + $conversion = self::getConversion($propertyType); + + switch ($conversion) { + case 'empty': // Empty return ''; - case 'null': // Null + case 'null': // Null return null; - case 'i1': // 1-Byte Signed Integer - case 'i2': // 2-Byte Signed Integer - case 'i4': // 4-Byte Signed Integer - case 'i8': // 8-Byte Signed Integer - case 'int': // Integer + case 'int': // Signed integer return (int) $propertyValue; - case 'ui1': // 1-Byte Unsigned Integer - case 'ui2': // 2-Byte Unsigned Integer - case 'ui4': // 4-Byte Unsigned Integer - case 'ui8': // 8-Byte Unsigned Integer - case 'uint': // Unsigned Integer + case 'uint': // Unsigned integer return abs((int) $propertyValue); - case 'r4': // 4-Byte Real Number - case 'r8': // 8-Byte Real Number - case 'decimal': // Decimal + case 'float': // Float return (float) $propertyValue; - case 'date': // Date and Time - case 'filetime': // File Time + case 'date': // Date return strtotime($propertyValue); - case 'bool': // Boolean + case 'bool': // Boolean return ($propertyValue == 'true') ? true : false; - case 'lpstr': // LPSTR - case 'lpwstr': // LPWSTR - case 'bstr': // Basic String - case 'cy': // Currency - case 'error': // Error Status Code - case 'vector': // Vector - case 'array': // Array - case 'blob': // Binary Blob - case 'oblob': // Binary Blob Object - case 'stream': // Binary Stream - case 'ostream': // Binary Stream Object - case 'storage': // Binary Storage - case 'ostorage': // Binary Storage Object - case 'vstream': // Binary Versioned Stream - case 'clsid': // Class ID - case 'cf': // Clipboard Data - return $propertyValue; } return $propertyValue; @@ -559,10 +543,36 @@ class DocumentProperties */ private function setValue($value, $default) { - if (is_null($value) || $value == '') { + if ($value === null || $value == '') { $value = $default; } return $value; } + + /** + * Get conversion model depending on property type + * + * @param string $propertyType + * @return string + */ + private static function getConversion($propertyType) + { + $conversions = array( + 'empty' => array('empty'), + 'null' => array('null'), + 'int' => array('i1', 'i2', 'i4', 'i8', 'int'), + 'uint' => array('ui1', 'ui2', 'ui4', 'ui8', 'uint'), + 'float' => array('r4', 'r8', 'decimal'), + 'bool' => array('bool'), + 'date' => array('date', 'filetime'), + ); + foreach ($conversions as $conversion => $types) { + if (in_array($propertyType, $types)) { + return $conversion; + } + } + + return 'string'; + } } diff --git a/src/PhpWord/Element/AbstractContainer.php b/src/PhpWord/Element/AbstractContainer.php index 8af70d42..4bbe5ddf 100644 --- a/src/PhpWord/Element/AbstractContainer.php +++ b/src/PhpWord/Element/AbstractContainer.php @@ -1,25 +1,45 @@ addElement($element, $fontStyle, $paragraphStyle); + } + + // All other elements + } else { + array_unshift($args, $element); // Prepend element name to the beginning of args array + return call_user_func_array(array($this, 'addElement'), $args); + } + } + + return null; + } + + /** + * Add element + * + * Each element has different number of parameters passed + * + * @param string $elementName + * @return \PhpOffice\PhpWord\Element\AbstractElement + */ + protected function addElement($elementName) + { + $elementClass = __NAMESPACE__ . '\\' . $elementName; + $this->checkValidity($elementName); + + // Get arguments + $args = func_get_args(); + $withoutP = in_array($this->container, array('TextRun', 'Footnote', 'Endnote', 'ListItemRun', 'Field')); + if ($withoutP && ($elementName == 'Text' || $elementName == 'PreserveText')) { + $args[3] = null; // Remove paragraph style for texts in textrun + } + $source = ''; + if (count($args) > 1) { + $source = $args[1]; + } + + // Create element using reflection + $reflection = new \ReflectionClass($elementClass); + $elementArgs = $args; + array_shift($elementArgs); // Shift the $elementName off the beginning of array + + /** @var \PhpOffice\PhpWord\Element\AbstractElement $element Type hint */ + $element = $reflection->newInstanceArgs($elementArgs); + + // Set nested level and relation Id + $this->setElementNestedLevel($element); + $this->setElementRelationId($element, $elementName, $source); + + // Set other properties and add element into collection + $element->setDocPart($this->getDocPart(), $this->getDocPartId()); $element->setElementIndex($this->countElements() + 1); $element->setElementId(); + $element->setPhpWord($this->phpWord); + $this->elements[] = $element; + + return $element; } /** @@ -54,7 +165,7 @@ abstract class AbstractContainer extends AbstractElement /** * Count elements * - * @return integer + * @return int */ public function countElements() { @@ -62,331 +173,97 @@ abstract class AbstractContainer extends AbstractElement } /** - * Add text element - * - * @param string $text - * @param mixed $fontStyle - * @param mixed $paragraphStyle - * @return Text + * Set element nested level based on container; add one when it's inside a cell */ - public function addText($text, $fontStyle = null, $paragraphStyle = null) + private function setElementNestedLevel(AbstractElement $element) { - $this->checkValidity('text'); - - // Reset paragraph style for footnote and textrun. They have their own - if (in_array($this->container, array('textrun', 'footnote', 'endnote'))) { - $paragraphStyle = null; - } - - $text = String::toUTF8($text); - $textObject = new Text($text, $fontStyle, $paragraphStyle); - $textObject->setDocPart($this->getDocPart(), $this->getDocPartId()); - $this->addElement($textObject); - - return $textObject; - } - - /** - * Add textrun element - * - * @param mixed $paragraphStyle - * @return TextRun - */ - public function addTextRun($paragraphStyle = null) - { - $this->checkValidity('textrun'); - - $textRun = new TextRun($paragraphStyle); - $textRun->setDocPart($this->getDocPart(), $this->getDocPartId()); - $this->addElement($textRun); - - return $textRun; - } - - /** - * Add link element - * - * @param string $linkSrc - * @param string $linkName - * @param mixed $fontStyle - * @param mixed $paragraphStyle - * @return Link - */ - public function addLink($linkSrc, $linkName = null, $fontStyle = null, $paragraphStyle = null) - { - $this->checkValidity('link'); - $elementDocPart = $this->checkElementDocPart(); - - $link = new Link(String::toUTF8($linkSrc), String::toUTF8($linkName), $fontStyle, $paragraphStyle); - $link->setDocPart($this->getDocPart(), $this->getDocPartId()); - $rId = Media::addElement($elementDocPart, 'link', $linkSrc); - $link->setRelationId($rId); - $this->addElement($link); - - return $link; - } - - /** - * Add a Title Element - * - * @param string $text - * @param int $depth - * @return Title - * @todo Enable title element in other containers - */ - public function addTitle($text, $depth = 1) - { - $this->checkValidity('title'); - - $styles = Style::getStyles(); - if (array_key_exists('Heading_' . $depth, $styles)) { - $style = 'Heading' . $depth; + if ($this->container == 'Cell') { + $element->setNestedLevel($this->getNestedLevel() + 1); } else { - $style = null; - } - $text = String::toUTF8($text); - $title = new Title($text, $depth, $style); - $title->setDocPart($this->getDocPart(), $this->getDocPartId()); - $data = Titles::addTitle($text, $depth); - $anchor = $data[0]; - $bookmarkId = $data[1]; - $title->setAnchor($anchor); - $title->setBookmarkId($bookmarkId); - $this->addElement($title); - - return $title; - } - - /** - * Add preserve text element - * - * @param string $text - * @param mixed $fontStyle - * @param mixed $paragraphStyle - * @return PreserveText - */ - public function addPreserveText($text, $fontStyle = null, $paragraphStyle = null) - { - $this->checkValidity('preservetext'); - - $preserveText = new PreserveText(String::toUTF8($text), $fontStyle, $paragraphStyle); - $preserveText->setDocPart($this->getDocPart(), $this->getDocPartId()); - $this->addElement($preserveText); - - return $preserveText; - } - - /** - * Add text break element - * - * @param int $count - * @param mixed $fontStyle - * @param mixed $paragraphStyle - */ - public function addTextBreak($count = 1, $fontStyle = null, $paragraphStyle = null) - { - $this->checkValidity('textbreak'); - - for ($i = 1; $i <= $count; $i++) { - $textBreak = new TextBreak($fontStyle, $paragraphStyle); - $textBreak->setDocPart($this->getDocPart(), $this->getDocPartId()); - $this->addElement($textBreak); + $element->setNestedLevel($this->getNestedLevel()); } } /** - * Add listitem element + * Set relation Id * - * @param string $text - * @param int $depth - * @param mixed $fontStyle - * @param mixed $styleList - * @param mixed $paragraphStyle - * @return ListItem + * @param string $elementName + * @param string $source */ - public function addListItem($text, $depth = 0, $fontStyle = null, $styleList = null, $paragraphStyle = null) + private function setElementRelationId(AbstractElement $element, $elementName, $source) { - $this->checkValidity('listitem'); + $mediaContainer = $this->getMediaContainer(); + $hasMediaRelation = in_array($elementName, array('Link', 'Image', 'Object')); + $hasOtherRelation = in_array($elementName, array('Footnote', 'Endnote', 'Title')); - $listItem = new ListItem(String::toUTF8($text), $depth, $fontStyle, $styleList, $paragraphStyle); - $listItem->setDocPart($this->getDocPart(), $this->getDocPartId()); - $this->addElement($listItem); - - return $listItem; - } - - /** - * Add table element - * - * @param mixed $style - * @return Table - */ - public function addTable($style = null) - { - $this->checkValidity('table'); - - $table = new Table($this->getDocPart(), $this->getDocPartId(), $style); - $this->addElement($table); - - return $table; - } - - /** - * Add image element - * - * @param string $src - * @param mixed $style Image style - * @param boolean $isWatermark - * @return Image - */ - public function addImage($src, $style = null, $isWatermark = false) - { - $this->checkValidity('image'); - $elementDocPart = $this->checkElementDocPart(); - - $image = new Image($src, $style, $isWatermark); - $image->setDocPart($this->getDocPart(), $this->getDocPartId()); - $rId = Media::addElement($elementDocPart, 'image', $src, $image); - $image->setRelationId($rId); - $this->addElement($image); - - return $image; - } - - /** - * Add OLE-object element - * - * All exceptions should be handled by \PhpOffice\PhpWord\Element\Object - * - * @param string $src - * @param mixed $style - * @return Object - * @throws \PhpOffice\PhpWord\Exception\Exception - * @todo Enable OLE object element in header and footer - */ - public function addObject($src, $style = null) - { - $this->checkValidity('object'); - $elementDocPart = $this->checkElementDocPart(); - - $object = new Object($src, $style); - $object->setDocPart($this->getDocPart(), $this->getDocPartId()); - if (!is_null($object->getSource())) { - $inf = pathinfo($src); - $ext = $inf['extension']; - if (strlen($ext) == 4 && strtolower(substr($ext, -1)) == 'x') { - $ext = substr($ext, 0, -1); - } - $icon = realpath(__DIR__ . "/../resources/{$ext}.png"); - $rId = Media::addElement($elementDocPart, 'object', $src); - $object->setRelationId($rId); - $rIdimg = Media::addElement($elementDocPart, 'image', $icon, new Image($icon)); - $object->setImageRelationId($rIdimg); - $this->addElement($object); - - return $object; - } else { - throw new InvalidObjectException(); + // Set relation Id for media elements (link, image, object; legacy of OOXML) + // Only Image that needs to be passed to Media class + if ($hasMediaRelation) { + /** @var \PhpOffice\PhpWord\Element\Image $element Type hint */ + $image = ($elementName == 'Image') ? $element : null; + $rId = Media::addElement($mediaContainer, strtolower($elementName), $source, $image); + $element->setRelationId($rId); } - } - /** - * Add footnote element - * - * @param mixed $paragraphStyle - * @return Footnote - */ - public function addFootnote($paragraphStyle = null) - { - $this->checkValidity('footnote'); + // Set relation Id for icon of object element + if ($elementName == 'Object') { + /** @var \PhpOffice\PhpWord\Element\Object $element Type hint */ + $rIdIcon = Media::addElement($mediaContainer, 'image', $element->getIcon(), new Image($element->getIcon())); + $element->setImageRelationId($rIdIcon); + } - $footnote = new Footnote($paragraphStyle); - $rId = Footnotes::addElement($footnote); - - $footnote->setDocPart('footnote', $this->getDocPartId()); - $footnote->setRelationId($rId); - $this->addElement($footnote); - - return $footnote; - } - - /** - * Add endnote element - * - * @param mixed $paragraphStyle - * @return Endnote - */ - public function addEndnote($paragraphStyle = null) - { - $this->checkValidity('endnote'); - - $endnote = new Endnote($paragraphStyle); - $rId = Endnotes::addElement($endnote); - - $endnote->setDocPart('endnote', $this->getDocPartId()); - $endnote->setRelationId($rId); - $this->addElement($endnote); - - return $endnote; - } - - /** - * Add a CheckBox Element - * - * @param string $name - * @param string $text - * @param mixed $fontStyle - * @param mixed $paragraphStyle - * @return CheckBox - */ - public function addCheckBox($name, $text, $fontStyle = null, $paragraphStyle = null) - { - $this->checkValidity('checkbox'); - - $checkBox = new CheckBox(String::toUTF8($name), String::toUTF8($text), $fontStyle, $paragraphStyle); - $checkBox->setDocPart($this->getDocPart(), $this->getDocPartId()); - $this->addElement($checkBox); - - return $checkBox; + // Set relation Id for elements that will be registered in the Collection subnamespaces + if ($hasOtherRelation && $this->phpWord instanceof PhpWord) { + $addMethod = "add{$elementName}"; + $rId = $this->phpWord->$addMethod($element); + $element->setRelationId($rId); + } } /** * Check if a method is allowed for the current container * * @param string $method - * @return boolean + * @return bool + * @throws \BadMethodCallException */ private function checkValidity($method) { // Valid containers for each element - $allContainers = array('section', 'header', 'footer', 'cell', 'textrun', 'footnote', 'endnote'); + $allContainers = array( + 'Section', 'Header', 'Footer', 'Footnote', 'Endnote', + 'Cell', 'TextRun', 'TextBox', 'ListItemRun', + ); $validContainers = array( - 'text' => $allContainers, - 'link' => $allContainers, - 'textbreak' => $allContainers, - 'image' => $allContainers, - 'object' => $allContainers, - 'textrun' => array('section', 'header', 'footer', 'cell'), - 'listitem' => array('section', 'header', 'footer', 'cell'), - 'checkbox' => array('section', 'header', 'footer', 'cell'), - 'table' => array('section', 'header', 'footer'), - 'footnote' => array('section', 'textrun', 'cell'), - 'endnote' => array('section', 'textrun', 'cell'), - 'preservetext' => array('header', 'footer', 'cell'), - 'title' => array('section'), + 'Text' => $allContainers, + 'Link' => $allContainers, + 'TextBreak' => $allContainers, + 'Image' => $allContainers, + 'Object' => $allContainers, + 'Field' => $allContainers, + 'Line' => $allContainers, + 'TextRun' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'), + 'ListItem' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'), + 'ListItemRun' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'), + 'Table' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'), + 'CheckBox' => array('Section', 'Header', 'Footer', 'Cell'), + 'TextBox' => array('Section', 'Header', 'Footer', 'Cell'), + 'Footnote' => array('Section', 'TextRun', 'Cell'), + 'Endnote' => array('Section', 'TextRun', 'Cell'), + 'PreserveText' => array('Header', 'Footer', 'Cell'), ); // Special condition, e.g. preservetext can only exists in cell when // the cell is located in header or footer $validSubcontainers = array( - 'preservetext' => array(array('cell'), array('header', 'footer')), - 'footnote' => array(array('cell', 'textrun'), array('section')), - 'endnote' => array(array('cell', 'textrun'), array('section')), + 'PreserveText' => array(array('Cell'), array('Header', 'Footer')), + 'Footnote' => array(array('Cell', 'TextRun'), array('Section')), + 'Endnote' => array(array('Cell', 'TextRun'), array('Section')), ); // Check if a method is valid for current container if (array_key_exists($method, $validContainers)) { if (!in_array($this->container, $validContainers[$method])) { - throw new \BadMethodCallException(); + throw new \BadMethodCallException("Cannot add $method in $this->container."); } } // Check if a method is valid for current container, located in other container @@ -396,7 +273,7 @@ abstract class AbstractContainer extends AbstractElement $allowedDocParts = $rules[1]; foreach ($containers as $container) { if ($this->container == $container && !in_array($this->getDocPart(), $allowedDocParts)) { - throw new \BadMethodCallException(); + throw new \BadMethodCallException("Cannot add $method in $this->container."); } } } @@ -405,16 +282,21 @@ abstract class AbstractContainer extends AbstractElement } /** - * Return element location in document: section, headerx, or footerx + * Return media element (image, object, link) container name + * + * @return string section|headerx|footerx|footnote|endnote */ - private function checkElementDocPart() + private function getMediaContainer() { - $isCellTextrun = in_array($this->container, array('cell', 'textrun')); - $docPart = $isCellTextrun ? $this->getDocPart() : $this->container; - $docPartId = $isCellTextrun ? $this->getDocPartId() : $this->sectionId; - $inHeaderFooter = ($docPart == 'header' || $docPart == 'footer'); + $partName = $this->container; + if (in_array($partName, array('Cell', 'TextRun', 'TextBox', 'ListItemRun'))) { + $partName = $this->getDocPart(); + } + if ($partName == 'Header' || $partName == 'Footer') { + $partName .= $this->getDocPartId(); + } - return $inHeaderFooter ? $docPart . $docPartId : $docPart; + return strtolower($partName); } /** @@ -422,6 +304,7 @@ abstract class AbstractContainer extends AbstractElement * * @param string $src * @param mixed $style + * @return \PhpOffice\PhpWord\Element\Image * @deprecated 0.9.0 * @codeCoverageIgnore */ @@ -434,6 +317,7 @@ abstract class AbstractContainer extends AbstractElement * Create textrun element * * @param mixed $paragraphStyle + * @return \PhpOffice\PhpWord\Element\TextRun * @deprecated 0.10.0 * @codeCoverageIgnore */ @@ -446,6 +330,7 @@ abstract class AbstractContainer extends AbstractElement * Create footnote element * * @param mixed $paragraphStyle + * @return \PhpOffice\PhpWord\Element\Footnote * @deprecated 0.10.0 * @codeCoverageIgnore */ diff --git a/src/PhpWord/Element/AbstractElement.php b/src/PhpWord/Element/AbstractElement.php index 6e993748..ca45ef23 100644 --- a/src/PhpWord/Element/AbstractElement.php +++ b/src/PhpWord/Element/AbstractElement.php @@ -1,14 +1,23 @@ phpWord; + } + + /** + * Set PhpWord as reference + * + * @param \PhpOffice\PhpWord\PhpWord + */ + public function setPhpWord(PhpWord &$phpWord = null) + { + $this->phpWord = &$phpWord; + } + /** * Get section number * - * @return integer + * @return int */ public function getSectionId() { @@ -89,7 +127,7 @@ abstract class AbstractElement * Set doc part * * @param string $docPart - * @param integer $docPartId + * @param int $docPartId */ public function setDocPart($docPart, $docPartId = 1) { @@ -110,7 +148,7 @@ abstract class AbstractElement /** * Get doc part Id * - * @return integer + * @return int */ public function getDocPartId() { @@ -168,21 +206,41 @@ abstract class AbstractElement /** * Set relation Id * - * @param int $rId + * @param int $value */ - public function setRelationId($rId) + public function setRelationId($value) { - $this->relationId = $rId; + $this->relationId = $value; } /** - * Check if element is located in section doc part (as opposed to header/footer) + * Get nested level * - * @return boolean + * @return int + */ + public function getNestedLevel() + { + return $this->nestedLevel; + } + + /** + * Set nested level + * + * @param int $value + */ + public function setNestedLevel($value) + { + $this->nestedLevel = $value; + } + + /** + * Check if element is located in Section doc part (as opposed to Header/Footer) + * + * @return bool */ public function isInSection() { - return ($this->docPart == 'section'); + return ($this->docPart == 'Section'); } /** @@ -190,14 +248,13 @@ abstract class AbstractElement * * @param mixed $styleObject Style object * @param mixed $styleValue Style value - * @param boolean $returnObject Always return object + * @param bool $returnObject Always return object + * @return mixed */ protected function setStyle($styleObject, $styleValue = null, $returnObject = false) { if (!is_null($styleValue) && is_array($styleValue)) { - foreach ($styleValue as $key => $value) { - $styleObject->setStyleValue($key, $value); - } + $styleObject->setStyleByArray($styleValue); $style = $styleObject; } else { $style = $returnObject ? $styleObject : $styleValue; diff --git a/src/PhpWord/Element/Cell.php b/src/PhpWord/Element/Cell.php index e3d3dd06..ea49bc7b 100644 --- a/src/PhpWord/Element/Cell.php +++ b/src/PhpWord/Element/Cell.php @@ -1,10 +1,18 @@ container = 'cell'; - $this->setDocPart($docPart, $docPartId); $this->width = $width; - $this->cellStyle = $this->setStyle(new CellStyle(), $style, true); + $this->style = $this->setStyle(new CellStyle(), $style, true); } /** @@ -53,7 +62,7 @@ class Cell extends AbstractContainer */ public function getStyle() { - return $this->cellStyle; + return $this->style; } /** diff --git a/src/PhpWord/Element/CheckBox.php b/src/PhpWord/Element/CheckBox.php index f273c128..a5620580 100644 --- a/src/PhpWord/Element/CheckBox.php +++ b/src/PhpWord/Element/CheckBox.php @@ -1,14 +1,24 @@ name = $name; + $this->name = String::toUTF8($name); return $this; } diff --git a/src/PhpWord/Element/Endnote.php b/src/PhpWord/Element/Endnote.php index 07d21969..20278898 100644 --- a/src/PhpWord/Element/Endnote.php +++ b/src/PhpWord/Element/Endnote.php @@ -1,10 +1,18 @@ container = 'endnote'; $this->paragraphStyle = $this->setStyle(new Paragraph(), $paragraphStyle); } } diff --git a/src/PhpWord/Element/Field.php b/src/PhpWord/Element/Field.php new file mode 100644 index 00000000..50f0522f --- /dev/null +++ b/src/PhpWord/Element/Field.php @@ -0,0 +1,181 @@ +array( + 'properties'=>array( + 'format' => array('Arabic', 'ArabicDash', 'alphabetic', 'ALPHABETIC', 'roman', 'ROMAN'), + ), + 'options'=>array('PreserveFormat') + ), + 'NUMPAGES'=>array( + 'properties'=>array( + 'format' => array('Arabic', 'ArabicDash', 'alphabetic', 'ALPHABETIC', 'roman', 'ROMAN'), + 'numformat' => array('0', '0,00', '#.##0', '#.##0,00', '€ #.##0,00(€ #.##0,00)', '0%', '0,00%') + ), + 'options'=>array('PreserveFormat') + ), + 'DATE'=>array( + 'properties'=> array( + 'dateformat' =>array('d-M-yyyy', 'dddd d MMMM yyyy', 'd MMMM yyyy', 'd-M-yy', 'yyyy-MM-dd', + 'd-MMM-yy', 'd/M/yyyy', 'd MMM. yy', 'd/M/yy', 'MMM-yy', 'd-M-yyy H:mm', 'd-M-yyyy H:mm:ss', + 'h:mm am/pm', 'h:mm:ss am/pm', 'HH:mm', 'HH:mm:ss') + ), + 'options'=>array('PreserveFormat', 'LunarCalendar', 'SakaEraCalendar', 'LastUsedFormat') + ) + ); + + /** + * Field type + * + * @var string + */ + protected $type; + + /** + * Field properties + * + * @var array + */ + protected $properties = array(); + + /** + * Field options + * + * @var array + */ + protected $options = array(); + + /** + * Create a new Field Element + * + * @param string $type + * @param array $properties + * @param array $options + */ + public function __construct($type = null, $properties = array(), $options = array()) + { + $this->setType($type); + $this->setProperties($properties); + $this->setOptions($options); + } + + /** + * Set Field type + * + * @param string $type + * @return string + * @throws \InvalidArgumentException + */ + public function setType($type = null) + { + if (isset($type)) { + if (array_key_exists($type, $this->fieldsArray)) { + $this->type = $type; + } else { + throw new \InvalidArgumentException("Invalid type"); + } + } + return $this->type; + } + + /** + * Get Field type + * + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * Set Field properties + * + * @param array $properties + * @return self + * @throws \InvalidArgumentException + */ + public function setProperties($properties = array()) + { + if (is_array($properties)) { + foreach (array_keys($properties) as $propkey) { + if (!(array_key_exists($propkey, $this->fieldsArray[$this->type]['properties']))) { + throw new \InvalidArgumentException("Invalid property"); + } + } + $this->properties = array_merge($this->properties, $properties); + } + return $this->properties; + } + + /** + * Get Field properties + * + * @return array + */ + public function getProperties() + { + return $this->properties; + } + + /** + * Set Field options + * + * @param array $options + * @return self + * @throws \InvalidArgumentException + */ + public function setOptions($options = array()) + { + if (is_array($options)) { + foreach (array_keys($options) as $optionkey) { + if (!(array_key_exists($optionkey, $this->fieldsArray[$this->type]['options']))) { + throw new \InvalidArgumentException("Invalid option"); + } + } + $this->options = array_merge($this->options, $options); + } + return $this->options; + } + + /** + * Get Field properties + * + * @return array + */ + public function getOptions() + { + return $this->options; + } +} diff --git a/src/PhpWord/Element/Footer.php b/src/PhpWord/Element/Footer.php index 50ec8236..142ccfda 100644 --- a/src/PhpWord/Element/Footer.php +++ b/src/PhpWord/Element/Footer.php @@ -1,10 +1,18 @@ container = 'footer'; $this->sectionId = $sectionId; $this->setType($type); - $this->setDocPart($this->container, ($sectionId - 1) * 3 + $footerId); + $this->setDocPart($this->container, ($sectionId - 1) * 3 + $containerId); } /** @@ -48,6 +66,9 @@ class Footer extends AbstractContainer */ public function setType($value = self::AUTO) { + if (!in_array($value, array(self::AUTO, self::FIRST, self::EVEN))) { + $value = self::AUTO; + } $this->type = $value; } @@ -61,4 +82,34 @@ class Footer extends AbstractContainer { return $this->type; } + + /** + * Reset type to default + * + * @return string + */ + public function resetType() + { + return $this->type = self::AUTO; + } + + /** + * First page only header + * + * @return string + */ + public function firstPage() + { + return $this->type = self::FIRST; + } + + /** + * Even numbered pages only + * + * @return string + */ + public function evenPage() + { + return $this->type = self::EVEN; + } } diff --git a/src/PhpWord/Element/Footnote.php b/src/PhpWord/Element/Footnote.php index bb8d6170..76311c6b 100644 --- a/src/PhpWord/Element/Footnote.php +++ b/src/PhpWord/Element/Footnote.php @@ -1,10 +1,18 @@ container = 'footnote'; $this->paragraphStyle = $this->setStyle(new Paragraph(), $paragraphStyle); } diff --git a/src/PhpWord/Element/Header.php b/src/PhpWord/Element/Header.php index 2c963d84..feaa86e8 100644 --- a/src/PhpWord/Element/Header.php +++ b/src/PhpWord/Element/Header.php @@ -1,52 +1,31 @@ container = 'header'; - $this->sectionId = $sectionId; - $this->setType($type); - $this->setDocPart($this->container, ($sectionId - 1) * 3 + $headerId); - } + protected $container = 'Header'; /** * Add a Watermark Element @@ -59,58 +38,4 @@ class Header extends AbstractContainer { return $this->addImage($src, $style, true); } - - /** - * Set header type - * - * @param string $value - * @since 0.10.0 - */ - public function setType($value = self::AUTO) - { - if (!in_array($value, array(self::AUTO, self::FIRST, self::EVEN))) { - $value = self::AUTO; - } - $this->type = $value; - } - - /** - * Get header type - * - * @return string - */ - public function getType() - { - return $this->type; - } - - /** - * Reset type to default - * - * @return string - */ - public function resetType() - { - return $this->type = self::AUTO; - } - - /** - * First page only header - * - * @return string - */ - public function firstPage() - { - return $this->type = self::FIRST; - } - - /** - * Even numbered pages only - * - * @return string - */ - public function evenPage() - { - return $this->type = self::EVEN; - } } diff --git a/src/PhpWord/Element/Image.php b/src/PhpWord/Element/Image.php index 53becbbf..a1cb8250 100644 --- a/src/PhpWord/Element/Image.php +++ b/src/PhpWord/Element/Image.php @@ -1,17 +1,25 @@ source = $source; - $this->setIsWatermark($isWatermark); + $this->setIsWatermark($watermark); $this->style = $this->setStyle(new ImageStyle(), $style, true); $this->checkImage($source); @@ -166,19 +174,19 @@ class Image extends AbstractElement * * @return boolean */ - public function getIsWatermark() + public function isWatermark() { - return $this->isWatermark; + return $this->watermark; } /** * Set is watermark * - * @param boolean $pValue + * @param boolean $value */ - public function setIsWatermark($pValue) + public function setIsWatermark($value) { - $this->isWatermark = $pValue; + $this->watermark = $value; } /** @@ -226,9 +234,9 @@ class Image extends AbstractElement * * @return boolean */ - public function getIsMemImage() + public function isMemImage() { - return $this->isMemImage; + return $this->memoryImage; } /** @@ -271,10 +279,83 @@ class Image extends AbstractElement $this->mediaIndex = $value; } + /** + * Get image string data + * + * @param bool $base64 + * @return string|null + * @since 0.11.0 + */ + public function getImageStringData($base64 = false) + { + $source = $this->source; + $actualSource = null; + $imageBinary = null; + $imageData = null; + $isTemp = false; + + // Get actual source from archive image or other source + // Return null if not found + if ($this->sourceType == self::SOURCE_ARCHIVE) { + $source = substr($source, 6); + list($zipFilename, $imageFilename) = explode('#', $source); + + $zip = new ZipArchive(); + if ($zip->open($zipFilename) !== false) { + if ($zip->locateName($imageFilename)) { + $isTemp = true; + $zip->extractTo(sys_get_temp_dir(), $imageFilename); + $actualSource = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $imageFilename; + } + } + $zip->close(); + } else { + $actualSource = $source; + } + + // Can't find any case where $actualSource = null hasn't captured by + // preceding exceptions. Please uncomment when you find the case and + // put the case into Element\ImageTest. + // if ($actualSource === null) { + // return null; + // } + + // Read image binary data and convert to hex/base64 string + if ($this->sourceType == self::SOURCE_GD) { + $imageResource = call_user_func($this->imageCreateFunc, $actualSource); + ob_start(); + call_user_func($this->imageFunc, $imageResource); + $imageBinary = ob_get_contents(); + ob_end_clean(); + } else { + $fileHandle = fopen($actualSource, 'rb', false); + if ($fileHandle !== false) { + $imageBinary = fread($fileHandle, filesize($actualSource)); + fclose($fileHandle); + } + } + if ($imageBinary !== null) { + if ($base64) { + $imageData = chunk_split(base64_encode($imageBinary)); + } else { + $imageData = chunk_split(bin2hex($imageBinary)); + } + } + + // Delete temporary file if necessary + if ($isTemp === true) { + @unlink($actualSource); + } + + return $imageData; + } + /** * Check memory image, supported type, image functions, and proportional width/height * * @param string $source + * @throws \PhpOffice\PhpWord\Exception\InvalidImageException + * @throws \PhpOffice\PhpWord\Exception\UnsupportedImageTypeException */ private function checkImage($source) { @@ -314,14 +395,14 @@ class Image extends AbstractElement private function setSourceType($source) { if (stripos(strrev($source), strrev('.php')) === 0) { - $this->isMemImage = true; + $this->memoryImage = true; $this->sourceType = self::SOURCE_GD; } elseif (strpos($source, 'zip://') !== false) { - $this->isMemImage = false; + $this->memoryImage = false; $this->sourceType = self::SOURCE_ARCHIVE; } else { - $this->isMemImage = (filter_var($source, FILTER_VALIDATE_URL) !== false); - $this->sourceType = $this->isMemImage ? self::SOURCE_GD : self::SOURCE_LOCAL; + $this->memoryImage = (filter_var($source, FILTER_VALIDATE_URL) !== false); + $this->sourceType = $this->memoryImage ? self::SOURCE_GD : self::SOURCE_LOCAL; } } @@ -338,8 +419,7 @@ class Image extends AbstractElement list($zipFilename, $imageFilename) = explode('#', $source); $tempFilename = tempnam(sys_get_temp_dir(), 'PHPWordImage'); - $zipClass = Settings::getZipClass(); - $zip = new $zipClass(); + $zip = new ZipArchive(); if ($zip->open($zipFilename) !== false) { if ($zip->locateName($imageFilename)) { $imageContent = $zip->getFromName($imageFilename); @@ -409,4 +489,26 @@ class Image extends AbstractElement } } } + + /** + * Get is watermark + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getIsWatermark() + { + return $this->isWatermark(); + } + + /** + * Get is memory image + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getIsMemImage() + { + return $this->isMemImage(); + } } diff --git a/src/PhpWord/Element/Line.php b/src/PhpWord/Element/Line.php new file mode 100644 index 00000000..4acca8ed --- /dev/null +++ b/src/PhpWord/Element/Line.php @@ -0,0 +1,53 @@ +style = $this->setStyle(new LineStyle(), $style); + } + + /** + * Get line style + * + * @return \PhpOffice\PhpWord\Style\Line + */ + public function getStyle() + { + return $this->style; + } +} diff --git a/src/PhpWord/Element/Link.php b/src/PhpWord/Element/Link.php index 31b06c68..3ffe58d4 100644 --- a/src/PhpWord/Element/Link.php +++ b/src/PhpWord/Element/Link.php @@ -1,14 +1,23 @@ target = $target; - $this->text = is_null($text) ? $target : $text; + $this->target = String::toUTF8($target); + $this->text = is_null($text) ? $this->target : String::toUTF8($text); $this->fontStyle = $this->setStyle(new Font('text'), $fontStyle); $this->paragraphStyle = $this->setStyle(new Paragraph(), $paragraphStyle); diff --git a/src/PhpWord/Element/ListItem.php b/src/PhpWord/Element/ListItem.php index 66061537..59bd8391 100644 --- a/src/PhpWord/Element/ListItem.php +++ b/src/PhpWord/Element/ListItem.php @@ -1,14 +1,23 @@ textObject = new Text($text, $fontStyle, $paragraphStyle); + $this->textObject = new Text(String::toUTF8($text), $fontStyle, $paragraphStyle); $this->depth = $depth; // Version >= 0.10.0 will pass numbering style name. Older version will use old method @@ -61,7 +69,9 @@ class ListItem extends AbstractElement } /** - * Get ListItem style + * Get style + * + * @return \PhpOffice\PhpWord\Style\ListItem */ public function getStyle() { @@ -69,7 +79,9 @@ class ListItem extends AbstractElement } /** - * Get ListItem TextRun + * Get Text object + * + * @return \PhpOffice\PhpWord\Element\Text */ public function getTextObject() { @@ -77,10 +89,23 @@ class ListItem extends AbstractElement } /** - * Get ListItem depth + * Get depth + * + * @return int */ public function getDepth() { return $this->depth; } + + /** + * Get text + * + * @return string + * @since 0.11.0 + */ + public function getText() + { + return $this->textObject->getText(); + } } diff --git a/src/PhpWord/Element/ListItemRun.php b/src/PhpWord/Element/ListItemRun.php new file mode 100644 index 00000000..fb219f91 --- /dev/null +++ b/src/PhpWord/Element/ListItemRun.php @@ -0,0 +1,82 @@ +depth = $depth; + + // Version >= 0.10.0 will pass numbering style name. Older version will use old method + if (!is_null($listStyle) && is_string($listStyle)) { + $this->style = new ListItemStyle($listStyle); + } else { + $this->style = $this->setStyle(new ListItemStyle(), $listStyle, true); + } + $this->paragraphStyle = $this->setStyle(new Paragraph(), $paragraphStyle); + } + + /** + * Get ListItem style + */ + public function getStyle() + { + return $this->style; + } + + /** + * Get ListItem depth + */ + public function getDepth() + { + return $this->depth; + } +} diff --git a/src/PhpWord/Element/Object.php b/src/PhpWord/Element/Object.php index 7407688a..a63c1869 100644 --- a/src/PhpWord/Element/Object.php +++ b/src/PhpWord/Element/Object.php @@ -1,14 +1,23 @@ source = $src; + if (file_exists($source) && in_array($pathInfo['extension'], $supportedTypes)) { + $ext = $pathInfo['extension']; + if (strlen($ext) == 4 && strtolower(substr($ext, -1)) == 'x') { + $ext = substr($ext, 0, -1); + } + + $this->source = $source; $this->style = $this->setStyle(new ImageStyle(), $style, true); + $this->icon = realpath(__DIR__ . "/../resources/{$ext}.png"); + return $this; } else { - return false; + throw new InvalidObjectException(); } } /** - * Get Image style - * - * @return \PhpOffice\PhpWord\Style\Image - */ - public function getStyle() - { - return $this->style; - } - - /** - * Get Source + * Get object source * * @return string */ @@ -78,7 +92,27 @@ class Object extends AbstractElement } /** - * Get Image Relation ID + * Get object style + * + * @return \PhpOffice\PhpWord\Style\Image + */ + public function getStyle() + { + return $this->style; + } + + /** + * Get object icon + * + * @return string + */ + public function getIcon() + { + return $this->icon; + } + + /** + * Get image relation ID * * @return int */ diff --git a/src/PhpWord/Element/PageBreak.php b/src/PhpWord/Element/PageBreak.php index d2f85f20..a1e7e998 100644 --- a/src/PhpWord/Element/PageBreak.php +++ b/src/PhpWord/Element/PageBreak.php @@ -1,10 +1,18 @@ fontStyle = $this->setStyle(new Font('text'), $fontStyle); $this->paragraphStyle = $this->setStyle(new Paragraph(), $paragraphStyle); - $matches = preg_split('/({.*?})/', $text, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); + $this->text = String::toUTF8($text); + $matches = preg_split('/({.*?})/', $this->text, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); if (isset($matches[0])) { $this->text = $matches; } diff --git a/src/PhpWord/Element/Row.php b/src/PhpWord/Element/Row.php index dc4b8a44..d7dcea34 100644 --- a/src/PhpWord/Element/Row.php +++ b/src/PhpWord/Element/Row.php @@ -1,10 +1,18 @@ setDocPart($docPart, $docPartId); $this->height = $height; $this->style = $this->setStyle(new RowStyle(), $style, true); } @@ -59,18 +64,23 @@ class Row extends AbstractElement * * @param int $width * @param mixed $style + * @return \PhpOffice\PhpWord\Element\Cell */ public function addCell($width = null, $style = null) { - $cell = new Cell($this->getDocPart(), $this->getDocPartId(), $width, $style); + $cell = new Cell($width, $style); + $cell->setDocPart($this->getDocPart(), $this->getDocPartId()); + $cell->setPhpWord($this->phpWord); + $cell->setNestedLevel($this->getNestedLevel()); $this->cells[] = $cell; + return $cell; } /** * Get all cells * - * @return array + * @return \PhpOffice\PhpWord\Element\Cell[] */ public function getCells() { diff --git a/src/PhpWord/Element/Section.php b/src/PhpWord/Element/Section.php index 64e226ab..b7cee6a2 100644 --- a/src/PhpWord/Element/Section.php +++ b/src/PhpWord/Element/Section.php @@ -1,24 +1,35 @@ container = 'section'; $this->sectionId = $sectionCount; $this->setDocPart($this->container, $this->sectionId); $this->settings = new SectionSettings(); @@ -82,12 +92,24 @@ class Section extends AbstractContainer return $this->settings; } + /** + * Add a Title Element + * + * @param string $text + * @param int $depth + * @return \PhpOffice\PhpWord\Element\Title + */ + public function addTitle($text, $depth = 1) + { + return $this->addElement('Title', $text, $depth); + } + /** * Add a PageBreak Element */ public function addPageBreak() { - $this->elements[] = new PageBreak(); + return $this->addElement('PageBreak'); } /** @@ -101,9 +123,7 @@ class Section extends AbstractContainer */ public function addTOC($fontStyle = null, $tocStyle = null, $minDepth = 1, $maxDepth = 9) { - $toc = new TOC($fontStyle, $tocStyle, $minDepth, $maxDepth); - $this->elements[] = $toc; - return $toc; + return $this->addElement('TOC', $fontStyle, $tocStyle, $minDepth, $maxDepth); } /** @@ -179,14 +199,17 @@ class Section extends AbstractContainer */ private function addHeaderFooter($type = Header::AUTO, $header = true) { + $containerClass = substr(get_class($this), 0, strrpos(get_class($this), '\\')) . '\\' . + ($header ? 'Header' : 'Footer'); $collectionArray = $header ? 'headers' : 'footers'; - $containerClass = 'PhpOffice\\PhpWord\\Element\\'; - $containerClass .= ($header ? 'Header' : 'Footer'); $collection = &$this->$collectionArray; if (in_array($type, array(Header::AUTO, Header::FIRST, Header::EVEN))) { $index = count($collection); + /** @var \PhpOffice\PhpWord\Element\AbstractContainer $container Type hint */ $container = new $containerClass($this->sectionId, ++$index, $type); + $container->setPhpWord($this->phpWord); + $collection[$index] = $container; return $container; } else { diff --git a/src/PhpWord/Element/TOC.php b/src/PhpWord/Element/TOC.php index ac48a49d..9ac74554 100644 --- a/src/PhpWord/Element/TOC.php +++ b/src/PhpWord/Element/TOC.php @@ -1,15 +1,23 @@ TOCStyle = new TOCStyle(); if (!is_null($tocStyle) && is_array($tocStyle)) { - foreach ($tocStyle as $key => $value) { - $this->TOCStyle->setStyleValue($key, $value); - } + $this->TOCStyle->setStyleByArray($tocStyle); } - if (!is_null($fontStyle)) { - if (is_array($fontStyle)) { - $this->fontStyle = new Font(); - foreach ($fontStyle as $key => $value) { - $this->fontStyle->setStyleValue($key, $value); - } - } else { - $this->fontStyle = $fontStyle; - } + if (!is_null($fontStyle) && is_array($fontStyle)) { + $this->fontStyle = new Font(); + $this->fontStyle->setStyleByArray($fontStyle); + } else { + $this->fontStyle = $fontStyle; } $this->minDepth = $minDepth; @@ -87,16 +89,21 @@ class TOC extends AbstractElement */ public function getTitles() { - $titles = Titles::getTitles(); + if (!$this->phpWord instanceof PhpWord) { + return array(); + } + + $titles = $this->phpWord->getTitles()->getItems(); foreach ($titles as $i => $title) { - if ($this->minDepth > $title['depth']) { + /** @var \PhpOffice\PhpWord\Element\Title $title Type hint */ + $depth = $title->getDepth(); + if ($this->minDepth > $depth) { unset($titles[$i]); } - if (($this->maxDepth != 0) && ($this->maxDepth < $title['depth'])) { + if (($this->maxDepth != 0) && ($this->maxDepth < $depth)) { unset($titles[$i]); } } - $titles = array_merge(array(), $titles); return $titles; } diff --git a/src/PhpWord/Element/Table.php b/src/PhpWord/Element/Table.php index 1fa729e1..ace63460 100644 --- a/src/PhpWord/Element/Table.php +++ b/src/PhpWord/Element/Table.php @@ -1,10 +1,18 @@ setDocPart($docPart, $docPartId); $this->style = $this->setStyle(new TableStyle(), $style); } /** * Add a row * - * @param integer $height + * @param int $height * @param mixed $style + * @return \PhpOffice\PhpWord\Element\Row */ public function addRow($height = null, $style = null) { - $row = new Row($this->getDocPart(), $this->getDocPartId(), $height, $style); + $row = new Row($height, $style); + $row->setDocPart($this->getDocPart(), $this->getDocPartId()); + $row->setPhpWord($this->phpWord); + $row->setNestedLevel($this->getNestedLevel()); $this->rows[] = $row; + return $row; } /** * Add a cell * - * @param integer $width + * @param int $width * @param mixed $style - * @return Cell + * @return \PhpOffice\PhpWord\Element\Cell */ public function addCell($width = null, $style = null) { $index = count($this->rows) - 1; - $cell = $this->rows[$index]->addCell($width, $style); + $row = $this->rows[$index]; + $cell = $row->addCell($width, $style); + return $cell; } /** * Get all rows * - * @return array + * @return \PhpOffice\PhpWord\Element\Row[] */ public function getRows() { @@ -98,30 +109,30 @@ class Table extends AbstractElement return $this->style; } - /** - * Set table width - * - * @param integer $width - */ - public function setWidth($width) - { - $this->width = $width; - } - /** * Get table width * - * @return integer + * @return int */ public function getWidth() { return $this->width; } + /** + * Set table width + * + * @param int $width + */ + public function setWidth($width) + { + $this->width = $width; + } + /** * Get column count * - * @return integer + * @return int */ public function countColumns() { @@ -129,7 +140,9 @@ class Table extends AbstractElement if (is_array($this->rows)) { $rowCount = count($this->rows); for ($i = 0; $i < $rowCount; $i++) { - $cellCount = count($this->rows[$i]->getCells()); + /** @var \PhpOffice\PhpWord\Element\Row $row Type hint */ + $row = $this->rows[$i]; + $cellCount = count($row->getCells()); if ($columnCount < $cellCount) { $columnCount = $cellCount; } diff --git a/src/PhpWord/Element/Text.php b/src/PhpWord/Element/Text.php index 96e0e164..52fccb3f 100644 --- a/src/PhpWord/Element/Text.php +++ b/src/PhpWord/Element/Text.php @@ -1,14 +1,23 @@ setParagraphStyle($paragraphStyle); } elseif (is_array($style)) { $this->fontStyle = new Font('text', $paragraphStyle); - $this->fontStyle->setArrayStyle($style); + $this->fontStyle->setStyleByArray($style); } elseif (null === $style) { $this->fontStyle = new Font('text', $paragraphStyle); } else { @@ -97,7 +106,7 @@ class Text extends AbstractElement { if (is_array($style)) { $this->paragraphStyle = new Paragraph; - $this->paragraphStyle->setArrayStyle($style); + $this->paragraphStyle->setStyleByArray($style); } elseif ($style instanceof Paragraph) { $this->paragraphStyle = $style; } elseif (null === $style) { @@ -127,7 +136,7 @@ class Text extends AbstractElement */ public function setText($text) { - $this->text = $text; + $this->text = String::toUTF8($text); return $this; } diff --git a/src/PhpWord/Element/TextBox.php b/src/PhpWord/Element/TextBox.php new file mode 100644 index 00000000..06c95181 --- /dev/null +++ b/src/PhpWord/Element/TextBox.php @@ -0,0 +1,60 @@ +style = $this->setStyle(new TextBoxStyle(), $style); + } + + /** + * Get textbox style + * + * @return \PhpOffice\PhpWord\Style\TextBox + */ + public function getStyle() + { + return $this->style; + } +} diff --git a/src/PhpWord/Element/TextBreak.php b/src/PhpWord/Element/TextBreak.php index b80ff681..aa6ab582 100644 --- a/src/PhpWord/Element/TextBreak.php +++ b/src/PhpWord/Element/TextBreak.php @@ -1,10 +1,18 @@ setParagraphStyle($paragraphStyle); } elseif (is_array($style)) { $this->fontStyle = new Font('text', $paragraphStyle); - $this->fontStyle->setArrayStyle($style); + $this->fontStyle->setStyleByArray($style); } else { $this->fontStyle = $style; $this->setParagraphStyle($paragraphStyle); @@ -89,7 +97,7 @@ class TextBreak extends AbstractElement { if (is_array($style)) { $this->paragraphStyle = new Paragraph; - $this->paragraphStyle->setArrayStyle($style); + $this->paragraphStyle->setStyleByArray($style); } elseif ($style instanceof Paragraph) { $this->paragraphStyle = $style; } else { @@ -107,4 +115,14 @@ class TextBreak extends AbstractElement { return $this->paragraphStyle; } + + /** + * Has font/paragraph style defined + * + * @return bool + */ + public function hasStyle() + { + return !is_null($this->fontStyle) || !is_null($this->paragraphStyle); + } } diff --git a/src/PhpWord/Element/TextRun.php b/src/PhpWord/Element/TextRun.php index a8428d1e..75837104 100644 --- a/src/PhpWord/Element/TextRun.php +++ b/src/PhpWord/Element/TextRun.php @@ -1,10 +1,18 @@ container = 'textrun'; $this->paragraphStyle = $this->setStyle(new Paragraph(), $paragraphStyle); } diff --git a/src/PhpWord/Element/Title.php b/src/PhpWord/Element/Title.php index 93b48d62..d5206879 100644 --- a/src/PhpWord/Element/Title.php +++ b/src/PhpWord/Element/Title.php @@ -1,14 +1,25 @@ style = $style; + + $this->text = String::toUTF8($text); + $this->depth = $depth; + if (array_key_exists('Heading_' . $this->depth, Style::getStyles())) { + $this->style = 'Heading' . $this->depth; } - $this->text = $text; - $this->depth = $depth; - return $this; } - /** - * Set Anchor - * - * @param int $anchor - */ - public function setAnchor($anchor) - { - $this->anchor = $anchor; - } - - /** - * Get Anchor - * - * @return int - */ - public function getAnchor() - { - return $this->anchor; - } - - /** - * Set Bookmark ID - * - * @param int $bookmarkId - */ - public function setBookmarkId($bookmarkId) - { - $this->bookmarkId = $bookmarkId; - } - - /** - * Get Anchor - * - * @return int - */ - public function getBookmarkId() - { - return $this->bookmarkId; - } - /** * Get Title Text content * diff --git a/src/PhpWord/Endnotes.php b/src/PhpWord/Endnotes.php deleted file mode 100644 index 6587dfe9..00000000 --- a/src/PhpWord/Endnotes.php +++ /dev/null @@ -1,95 +0,0 @@ -load($filename); } + + /** + * Check if it's a concrete class (not abstract nor interface) + * + * @param string $class + * @return bool + */ + private static function isConcreteClass($class) + { + $reflection = new \ReflectionClass($class); + + return !$reflection->isAbstract() && !$reflection->isInterface(); + } } diff --git a/src/PhpWord/Media.php b/src/PhpWord/Media.php index 7d129b86..7f35841c 100644 --- a/src/PhpWord/Media.php +++ b/src/PhpWord/Media.php @@ -1,10 +1,18 @@ getIsMemImage(); + $isMemImage = $image->isMemImage(); $extension = $image->getImageExtension(); $mediaData['imageExtension'] = $extension; $mediaData['imageType'] = $image->getImageType(); @@ -131,37 +139,53 @@ class Media * Get media elements * * @param string $container section|headerx|footerx|footnote|endnote - * @param string $mediaType image|object|link + * @param string $type image|object|link * @return array * @since 0.10.0 */ - public static function getElements($container, $mediaType = null) + public static function getElements($container, $type = null) { - $mediaElements = array(); + $elements = array(); // If header/footer, search for headerx and footerx where x is number if ($container == 'header' || $container == 'footer') { foreach (self::$elements as $key => $val) { if (substr($key, 0, 6) == $container) { - $mediaElements[$key] = $val; + $elements[$key] = $val; } } + return $elements; } else { if (!array_key_exists($container, self::$elements)) { - return $mediaElements; + return $elements; } - foreach (self::$elements[$container] as $mediaKey => $mediaData) { - if (!is_null($mediaType)) { - if ($mediaType == $mediaData['type']) { - $mediaElements[$mediaKey] = $mediaData; - } - } else { - $mediaElements[$mediaKey] = $mediaData; + return self::getElementsByType($container, $type); + } + } + + /** + * Get elements by media type + * + * @param string $container section|footnote|endnote + * @param string $type image|object|link + * @return array + * @since 0.11.0 Splitted from `getElements` to reduce complexity + */ + private static function getElementsByType($container, $type = null) + { + $elements = array(); + + foreach (self::$elements[$container] as $key => $data) { + if ($type !== null) { + if ($type == $data['type']) { + $elements[$key] = $data; } + } else { + $elements[$key] = $data; } } - return $mediaElements; + return $elements; } /** diff --git a/src/PhpWord/PhpWord.php b/src/PhpWord/PhpWord.php index d4b13356..c54faa36 100644 --- a/src/PhpWord/PhpWord.php +++ b/src/PhpWord/PhpWord.php @@ -1,36 +1,43 @@ documentProperties = new DocumentProperties(); - $this->defaultFontName = self::DEFAULT_FONT_NAME; - $this->defaultFontSize = self::DEFAULT_FONT_SIZE; + $this->titles = new Titles(); + $this->footnotes = new Footnotes(); + $this->endnotes = new Endnotes(); } /** @@ -92,6 +108,16 @@ class PhpWord return $this; } + /** + * Get all sections + * + * @return \PhpOffice\PhpWord\Element\Section[] + */ + public function getSections() + { + return $this->sections; + } + /** * Create new section * @@ -101,11 +127,75 @@ class PhpWord public function addSection($settings = null) { $section = new Section(count($this->sections) + 1, $settings); + $section->setPhpWord($this); $this->sections[] = $section; return $section; } + /** + * Get titles + * + * @return \PhpOffice\PhpWord\Collection\Titles + */ + public function getTitles() + { + return $this->titles; + } + + /** + * Add new title + * + * @param \PhpOffice\PhpWord\Element\Title $title + * @return int + */ + public function addTitle($title) + { + return $this->titles->addItem($title); + } + + /** + * Get footnotes + * + * @return \PhpOffice\PhpWord\Collection\Footnotes + */ + public function getFootnotes() + { + return $this->footnotes; + } + + /** + * Add new footnote + * + * @param \PhpOffice\PhpWord\Element\Footnote $footnote + * @return int + */ + public function addFootnote($footnote) + { + return $this->footnotes->addItem($footnote); + } + + /** + * Get endnotes + * + * @return \PhpOffice\PhpWord\Collection\Endnotes + */ + public function getEndnotes() + { + return $this->endnotes; + } + + /** + * Add new endnote + * + * @param \PhpOffice\PhpWord\Element\Endnote $endnote + * @return int + */ + public function addEndnote($endnote) + { + return $this->endnotes->addItem($endnote); + } + /** * Get default font name * @@ -113,7 +203,7 @@ class PhpWord */ public function getDefaultFontName() { - return $this->defaultFontName; + return Settings::getDefaultFontName(); } /** @@ -123,7 +213,7 @@ class PhpWord */ public function setDefaultFontName($fontName) { - $this->defaultFontName = $fontName; + Settings::setDefaultFontName($fontName); } /** @@ -133,7 +223,7 @@ class PhpWord */ public function getDefaultFontSize() { - return $this->defaultFontSize; + return Settings::getDefaultFontSize(); } /** @@ -143,17 +233,18 @@ class PhpWord */ public function setDefaultFontSize($fontSize) { - $this->defaultFontSize = $fontSize; + Settings::setDefaultFontSize($fontSize); } /** * Set default paragraph style definition to styles.xml * * @param array $styles Paragraph style definition + * @return \PhpOffice\PhpWord\Style\Paragraph */ public function setDefaultParagraphStyle($styles) { - Style::setDefaultParagraphStyle($styles); + return Style::setDefaultParagraphStyle($styles); } /** @@ -161,10 +252,11 @@ class PhpWord * * @param string $styleName * @param array $styles + * @return \PhpOffice\PhpWord\Style\Paragraph */ public function addParagraphStyle($styleName, $styles) { - Style::addParagraphStyle($styleName, $styles); + return Style::addParagraphStyle($styleName, $styles); } /** @@ -173,10 +265,11 @@ class PhpWord * @param string $styleName * @param mixed $fontStyle * @param mixed $paragraphStyle + * @return \PhpOffice\PhpWord\Style\Font */ public function addFontStyle($styleName, $fontStyle, $paragraphStyle = null) { - Style::addFontStyle($styleName, $fontStyle, $paragraphStyle); + return Style::addFontStyle($styleName, $fontStyle, $paragraphStyle); } /** @@ -185,33 +278,11 @@ class PhpWord * @param string $styleName * @param mixed $styleTable * @param mixed $styleFirstRow + * @return \PhpOffice\PhpWord\Style\Table */ public function addTableStyle($styleName, $styleTable, $styleFirstRow = null) { - Style::addTableStyle($styleName, $styleTable, $styleFirstRow); - } - - /** - * Adds a heading style definition to styles.xml - * - * @param int $titleCount - * @param mixed $fontStyle - * @param mixed $paragraphStyle - */ - public function addTitleStyle($titleCount, $fontStyle, $paragraphStyle = null) - { - Style::addTitleStyle($titleCount, $fontStyle, $paragraphStyle); - } - - /** - * Adds a hyperlink style to styles.xml - * - * @param string $styleName - * @param mixed $styles - */ - public function addLinkStyle($styleName, $styles) - { - Style::addLinkStyle($styleName, $styles); + return Style::addTableStyle($styleName, $styleTable, $styleFirstRow); } /** @@ -219,20 +290,36 @@ class PhpWord * * @param string $styleName * @param mixed $styles + * @return \PhpOffice\PhpWord\Style\Numbering */ public function addNumberingStyle($styleName, $styles) { - Style::addNumberingStyle($styleName, $styles); + return Style::addNumberingStyle($styleName, $styles); } /** - * Get all sections + * Adds a hyperlink style to styles.xml * - * @return \PhpOffice\PhpWord\Element\Section[] + * @param string $styleName + * @param mixed $styles + * @return \PhpOffice\PhpWord\Style\Font */ - public function getSections() + public function addLinkStyle($styleName, $styles) { - return $this->sections; + return Style::addLinkStyle($styleName, $styles); + } + + /** + * Adds a heading style definition to styles.xml + * + * @param int $depth + * @param mixed $fontStyle + * @param mixed $paragraphStyle + * @return \PhpOffice\PhpWord\Style\Font + */ + public function addTitleStyle($depth, $fontStyle, $paragraphStyle = null) + { + return Style::addTitleStyle($depth, $fontStyle, $paragraphStyle); } /** diff --git a/src/PhpWord/Reader/AbstractReader.php b/src/PhpWord/Reader/AbstractReader.php index 424ff2cd..c08914e5 100644 --- a/src/PhpWord/Reader/AbstractReader.php +++ b/src/PhpWord/Reader/AbstractReader.php @@ -1,10 +1,18 @@ readDataOnly; return true; @@ -46,47 +55,47 @@ abstract class AbstractReader implements ReaderInterface /** * Set read data only * - * @param bool $pValue + * @param bool $value * @return self */ - public function setReadDataOnly($pValue = true) + public function setReadDataOnly($value = true) { - $this->readDataOnly = $pValue; + $this->readDataOnly = $value; return $this; } /** * Open file for reading * - * @param string $pFilename + * @param string $filename * @return resource * @throws \PhpOffice\PhpWord\Exception\Exception */ - protected function openFile($pFilename) + protected function openFile($filename) { // Check if file exists - if (!file_exists($pFilename) || !is_readable($pFilename)) { - throw new Exception("Could not open " . $pFilename . " for reading! File does not exist."); + if (!file_exists($filename) || !is_readable($filename)) { + throw new Exception("Could not open " . $filename . " for reading! File does not exist."); } // Open file - $this->fileHandle = fopen($pFilename, 'r'); + $this->fileHandle = fopen($filename, 'r'); if ($this->fileHandle === false) { - throw new Exception("Could not open file " . $pFilename . " for reading."); + throw new Exception("Could not open file " . $filename . " for reading."); } } /** * Can the current ReaderInterface read the file? * - * @param string $pFilename + * @param string $filename * @return bool */ - public function canRead($pFilename) + public function canRead($filename) { // Check if file exists try { - $this->openFile($pFilename); + $this->openFile($filename); } catch (Exception $e) { return false; } @@ -96,4 +105,15 @@ abstract class AbstractReader implements ReaderInterface return true; } + + /** + * Read data only? + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getReadDataOnly() + { + return $this->isReadDataOnly(); + } } diff --git a/src/PhpWord/Reader/HTML.php b/src/PhpWord/Reader/HTML.php new file mode 100644 index 00000000..a6582a3f --- /dev/null +++ b/src/PhpWord/Reader/HTML.php @@ -0,0 +1,50 @@ +canRead($docFile)) { + $section = $phpWord->addSection(); + HTMLParser::addHtml($section, file_get_contents($docFile), true); + } else { + throw new \Exception("Cannot read {$docFile}."); + } + + return $phpWord; + } +} diff --git a/src/PhpWord/Reader/ODText.php b/src/PhpWord/Reader/ODText.php index db4708b4..19efdc51 100644 --- a/src/PhpWord/Reader/ODText.php +++ b/src/PhpWord/Reader/ODText.php @@ -1,10 +1,18 @@ 'Content', + 'meta.xml' => 'Meta', ); foreach ($readerParts as $xmlFile => $partName) { @@ -54,6 +63,7 @@ class ODText extends AbstractReader implements ReaderInterface { $partClass = "PhpOffice\\PhpWord\\Reader\\ODText\\{$partName}"; if (class_exists($partClass)) { + /** @var \PhpOffice\PhpWord\Reader\ODText\AbstractPart $part Type hint */ $part = new $partClass($docFile, $xmlFile); $part->setRels($relationships); $part->read($phpWord); diff --git a/src/PhpWord/Reader/ODText/AbstractPart.php b/src/PhpWord/Reader/ODText/AbstractPart.php index 15c67190..95f70084 100644 --- a/src/PhpWord/Reader/ODText/AbstractPart.php +++ b/src/PhpWord/Reader/ODText/AbstractPart.php @@ -1,50 +1,30 @@ getDomFromZip($this->docFile, $this->xmlFile); + $docProps = $phpWord->getDocumentProperties(); + + $metaNode = $xmlReader->getElement('office:meta'); + + // Standard properties + $properties = array( + 'title' => 'dc:title', + 'subject' => 'dc:subject', + 'description' => 'dc:description', + 'keywords' => 'meta:keyword', + 'creator' => 'meta:initial-creator', + 'lastModifiedBy' => 'dc:creator', + // 'created' => 'meta:creation-date', + // 'modified' => 'dc:date', + ); + foreach ($properties as $property => $path) { + $method = "set{$property}"; + $propertyNode = $xmlReader->getElement($path, $metaNode); + if ($propertyNode !== null && method_exists($docProps, $method)) { + $docProps->$method($propertyNode->nodeValue); + } + } + + // Custom properties + $propertyNodes = $xmlReader->getElements('meta:user-defined', $metaNode); + foreach ($propertyNodes as $propertyNode) { + $property = $xmlReader->getAttribute('meta:name', $propertyNode); + + // Set category, company, and manager property + if (in_array($property, array('Category', 'Company', 'Manager'))) { + $method = "set{$property}"; + $docProps->$method($propertyNode->nodeValue); + + // Set other custom properties + } else { + $docProps->setCustomProperty($property, $propertyNode->nodeValue); + } + } + } +} diff --git a/src/PhpWord/Reader/RTF.php b/src/PhpWord/Reader/RTF.php new file mode 100644 index 00000000..9d5d813b --- /dev/null +++ b/src/PhpWord/Reader/RTF.php @@ -0,0 +1,51 @@ +canRead($docFile)) { + $doc = new Document(); + $doc->rtf = file_get_contents($docFile); + $doc->read($phpWord); + } else { + throw new \Exception("Cannot read {$docFile}."); + } + + return $phpWord; + } +} diff --git a/src/PhpWord/Reader/RTF/Document.php b/src/PhpWord/Reader/RTF/Document.php new file mode 100644 index 00000000..cb082fdc --- /dev/null +++ b/src/PhpWord/Reader/RTF/Document.php @@ -0,0 +1,393 @@ + 'markOpening', // { + 125 => 'markClosing', // } + 92 => 'markBackslash', // \ + 10 => 'markNewline', // LF + 13 => 'markNewline' // CR + ); + + $this->phpWord = $phpWord; + $this->section = $phpWord->addSection(); + $this->textrun = $this->section->addTextRun(); + $this->length = strlen($this->rtf); + + $this->flags['paragraph'] = true; // Set paragraph flag from the beginning + + // Walk each characters + while ($this->offset < $this->length) { + $char = $this->rtf[$this->offset]; + $ascii = ord($char); + + if (array_key_exists($ascii, $markers)) { // Marker found: {, }, \, LF, or CR + $markerFunction = $markers[$ascii]; + $this->$markerFunction(); + } else { + if ($this->isControl === false) { // Non control word: Push character + $this->pushText($char); + } else { + if (preg_match("/^[a-zA-Z0-9-]?$/", $char)) { // No delimiter: Buffer control + $this->control .= $char; + $this->isFirst = false; + } else { // Delimiter found: Parse buffered control + if ($this->isFirst) { + $this->isFirst = false; + } else { + if ($char == ' ') { // Discard space as a control word delimiter + $this->flushControl(true); + } + } + } + } + } + $this->offset++; + } + $this->flushText(); + } + + /** + * Mark opening braket `{` character + */ + private function markOpening() + { + $this->flush(true); + array_push($this->groups, $this->flags); + } + + /** + * Mark closing braket `}` character + */ + private function markClosing() + { + $this->flush(true); + $this->flags = array_pop($this->groups); + } + + /** + * Mark backslash `\` character + */ + private function markBackslash() + { + if ($this->isFirst) { + $this->setControl(false); + $this->text .= '\\'; + } else { + $this->flush(); + $this->setControl(true); + $this->control = ''; + } + } + + /** + * Mark newline character: Flush control word because it's not possible to span multiline + */ + private function markNewline() + { + if ($this->isControl) { + $this->flushControl(true); + } + } + + /** + * Flush control word or text + * + * @param bool $isControl + */ + private function flush($isControl = false) + { + if ($this->isControl) { + $this->flushControl($isControl); + } else { + $this->flushText(); + } + } + + /** + * Flush control word + * + * @param bool $isControl + */ + private function flushControl($isControl = false) + { + if (preg_match("/^([A-Za-z]+)(-?[0-9]*) ?$/", $this->control, $match) === 1) { + list(, $control, $parameter) = $match; + $this->parseControl($control, $parameter); + } + + if ($isControl === true) { + $this->setControl(false); + } + } + + /** + * Flush text in queue + */ + private function flushText() + { + if ($this->text != '') { + if (isset($this->flags['property'])) { // Set property + $this->flags['value'] = $this->text; + } else { // Set text + if ($this->flags['paragraph'] === true) { + $this->flags['paragraph'] = false; + $this->flags['text'] = $this->text; + } + } + + // Add text if it's not flagged as skipped + if (!isset($this->flags['skipped'])) { + $this->readText(); + } + + $this->text = ''; + } + } + + /** + * Reset control word and first char state + * + * @param bool $value + */ + private function setControl($value) + { + $this->isControl = $value; + $this->isFirst = $value; + } + + /** + * Push text into queue + * + * @param string $char + */ + private function pushText($char) + { + if ($char == '<') { + $this->text .= "<"; + } elseif ($char == '>') { + $this->text .= ">"; + } else { + $this->text .= $char; + } + } + + /** + * Parse control + * + * @param string $control + * @param string $parameter + */ + private function parseControl($control, $parameter) + { + $controls = array( + 'par' => array(self::PARA, 'paragraph', true), + 'b' => array(self::STYL, 'font', 'bold', true), + 'i' => array(self::STYL, 'font', 'italic', true), + 'u' => array(self::STYL, 'font', 'underline', true), + 'strike' => array(self::STYL, 'font', 'strikethrough',true), + 'fs' => array(self::STYL, 'font', 'size', $parameter), + 'qc' => array(self::STYL, 'paragraph', 'align', 'center'), + 'sa' => array(self::STYL, 'paragraph', 'spaceAfter', $parameter), + 'fonttbl' => array(self::SKIP, 'fonttbl', null), + 'colortbl' => array(self::SKIP, 'colortbl', null), + 'info' => array(self::SKIP, 'info', null), + 'generator' => array(self::SKIP, 'generator', null), + 'title' => array(self::SKIP, 'title', null), + 'subject' => array(self::SKIP, 'subject', null), + 'category' => array(self::SKIP, 'category', null), + 'keywords' => array(self::SKIP, 'keywords', null), + 'comment' => array(self::SKIP, 'comment', null), + 'shppict' => array(self::SKIP, 'pic', null), + 'fldinst' => array(self::SKIP, 'link', null), + ); + + if (array_key_exists($control, $controls)) { + list($function) = $controls[$control]; + if (method_exists($this, $function)) { + $directives = $controls[$control]; + array_shift($directives); // remove the function variable; we won't need it + $this->$function($directives); + } + } + } + + /** + * Read paragraph + * + * @param array $directives + */ + private function readParagraph($directives) + { + list($property, $value) = $directives; + $this->textrun = $this->section->addTextRun(); + $this->flags[$property] = $value; + } + + /** + * Read style + * + * @param array $directives + */ + private function readStyle($directives) + { + list($style, $property, $value) = $directives; + $this->flags['styles'][$style][$property] = $value; + } + + /** + * Read skip + * + * @param array $directives + */ + private function readSkip($directives) + { + list($property) = $directives; + $this->flags['property'] = $property; + $this->flags['skipped'] = true; + } + + /** + * Read text + */ + private function readText() + { + $text = $this->textrun->addText($this->text); + if (isset($this->flags['styles']['font'])) { + $text->getFontStyle()->setStyleByArray($this->flags['styles']['font']); + } + } +} diff --git a/src/PhpWord/Reader/ReaderInterface.php b/src/PhpWord/Reader/ReaderInterface.php index 2829d4ab..361c4137 100644 --- a/src/PhpWord/Reader/ReaderInterface.php +++ b/src/PhpWord/Reader/ReaderInterface.php @@ -1,31 +1,41 @@ setRels($relationships); $part->read($phpWord); @@ -101,8 +110,7 @@ class Word2007 extends AbstractReader implements ReaderInterface // word/_rels/*.xml.rels $wordRelsPath = 'word/_rels/'; - $zipClass = Settings::getZipClass(); - $zip = new $zipClass(); + $zip = new ZipArchive(); if ($zip->open($docFile) === true) { for ($i = 0; $i < $zip->numFiles; $i++) { $xmlFile = $zip->getNameIndex($i); diff --git a/src/PhpWord/Reader/Word2007/AbstractPart.php b/src/PhpWord/Reader/Word2007/AbstractPart.php index 57ad4815..a7261d6d 100644 --- a/src/PhpWord/Reader/Word2007/AbstractPart.php +++ b/src/PhpWord/Reader/Word2007/AbstractPart.php @@ -1,10 +1,18 @@ rels = $value; } + /** + * Read w:p + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $domNode + * @param mixed $parent + * @param string $docPart + * + * @todo Get font style for preserve text + */ + protected function readParagraph(XMLReader $xmlReader, \DOMElement $domNode, &$parent, $docPart = 'document') + { + // Paragraph style + $paragraphStyle = null; + $headingMatches = array(); + if ($xmlReader->elementExists('w:pPr', $domNode)) { + $paragraphStyle = $this->readParagraphStyle($xmlReader, $domNode); + if (is_array($paragraphStyle) && array_key_exists('styleName', $paragraphStyle)) { + preg_match('/Heading(\d)/', $paragraphStyle['styleName'], $headingMatches); + } + } + + // PreserveText + if ($xmlReader->elementExists('w:r/w:instrText', $domNode)) { + $ignoreText = false; + $textContent = ''; + $fontStyle = $this->readFontStyle($xmlReader, $domNode); + $nodes = $xmlReader->getElements('w:r', $domNode); + foreach ($nodes as $node) { + $instrText = $xmlReader->getValue('w:instrText', $node); + if ($xmlReader->elementExists('w:fldChar', $node)) { + $fldCharType = $xmlReader->getAttribute('w:fldCharType', $node, 'w:fldChar'); + if ($fldCharType == 'begin') { + $ignoreText = true; + } elseif ($fldCharType == 'end') { + $ignoreText = false; + } + } + if (!is_null($instrText)) { + $textContent .= '{' . $instrText . '}'; + } else { + if ($ignoreText === false) { + $textContent .= $xmlReader->getValue('w:t', $node); + } + } + } + $parent->addPreserveText($textContent, $fontStyle, $paragraphStyle); + + // List item + } elseif ($xmlReader->elementExists('w:pPr/w:numPr', $domNode)) { + $textContent = ''; + $numId = $xmlReader->getAttribute('w:val', $domNode, 'w:pPr/w:numPr/w:numId'); + $levelId = $xmlReader->getAttribute('w:val', $domNode, 'w:pPr/w:numPr/w:ilvl'); + $nodes = $xmlReader->getElements('w:r', $domNode); + foreach ($nodes as $node) { + $textContent .= $xmlReader->getValue('w:t', $node); + } + $parent->addListItem($textContent, $levelId, null, "PHPWordList{$numId}", $paragraphStyle); + + // Heading + } elseif (!empty($headingMatches)) { + $textContent = ''; + $nodes = $xmlReader->getElements('w:r', $domNode); + foreach ($nodes as $node) { + $textContent .= $xmlReader->getValue('w:t', $node); + } + $parent->addTitle($textContent, $headingMatches[1]); + + // Text and TextRun + } else { + $runCount = $xmlReader->countElements('w:r', $domNode); + $linkCount = $xmlReader->countElements('w:hyperlink', $domNode); + $runLinkCount = $runCount + $linkCount; + if ($runLinkCount == 0) { + $parent->addTextBreak(null, $paragraphStyle); + } else { + if ($runLinkCount > 1) { + $textrun = $parent->addTextRun($paragraphStyle); + $textParent = &$textrun; + } else { + $textParent = &$parent; + } + $nodes = $xmlReader->getElements('*', $domNode); + foreach ($nodes as $node) { + $this->readRun($xmlReader, $node, $textParent, $docPart, $paragraphStyle); + } + } + } + } + /** * Read w:r * @@ -128,144 +241,144 @@ abstract class AbstractPart } /** - * Read w:pPr + * Read w:tbl * - * @return string|array|null + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $domNode + * @param mixed $parent + * @param string $docPart */ - protected function readParagraphStyle(XMLReader $xmlReader, \DOMElement $domNode) + protected function readTable(XMLReader $xmlReader, \DOMElement $domNode, &$parent, $docPart = 'document') { - $style = null; - if ($xmlReader->elementExists('w:pPr', $domNode)) { - if ($xmlReader->elementExists('w:pPr/w:pStyle', $domNode)) { - $style = $xmlReader->getAttribute('w:val', $domNode, 'w:pPr/w:pStyle'); - } else { - $style = array(); - $mapping = array( - 'w:ind' => 'indent', 'w:spacing' => 'spacing', - 'w:jc' => 'align', 'w:basedOn' => 'basedOn', 'w:next' => 'next', - 'w:widowControl' => 'widowControl', 'w:keepNext' => 'keepNext', - 'w:keepLines' => 'keepLines', 'w:pageBreakBefore' => 'pageBreakBefore', + // Table style + $tblStyle = null; + if ($xmlReader->elementExists('w:tblPr', $domNode)) { + $tblStyle = $this->readTableStyle($xmlReader, $domNode); + } + + /** @var \PhpOffice\PhpWord\Element\Table $table Type hint */ + $table = $parent->addTable($tblStyle); + $tblNodes = $xmlReader->getElements('*', $domNode); + foreach ($tblNodes as $tblNode) { + if ($tblNode->nodeName == 'w:tblGrid') { // Column + // @todo Do something with table columns + + } elseif ($tblNode->nodeName == 'w:tr') { // Row + $rowHeight = $xmlReader->getAttribute('w:val', $tblNode, 'w:trPr/w:trHeight'); + $rowHRule = $xmlReader->getAttribute('w:hRule', $tblNode, 'w:trPr/w:trHeight'); + $rowHRule = $rowHRule == 'exact' ? true : false; + $rowStyle = array( + 'tblHeader' => $xmlReader->elementExists('w:trPr/w:tblHeader', $tblNode), + 'cantSplit' => $xmlReader->elementExists('w:trPr/w:cantSplit', $tblNode), + 'exactHeight' => $rowHRule, ); - $nodes = $xmlReader->getElements('w:pPr/*', $domNode); - foreach ($nodes as $node) { - if (!array_key_exists($node->nodeName, $mapping)) { - continue; - } - $property = $mapping[$node->nodeName]; - switch ($node->nodeName) { + $row = $table->addRow($rowHeight, $rowStyle); + $rowNodes = $xmlReader->getElements('*', $tblNode); + foreach ($rowNodes as $rowNode) { + if ($rowNode->nodeName == 'w:trPr') { // Row style + // @todo Do something with row style - case 'w:ind': - $style['indent'] = $xmlReader->getAttribute('w:left', $node); - $style['hanging'] = $xmlReader->getAttribute('w:hanging', $node); - break; + } elseif ($rowNode->nodeName == 'w:tc') { // Cell + $cellWidth = $xmlReader->getAttribute('w:w', $rowNode, 'w:tcPr/w:tcW'); + $cellStyle = null; + $cellStyleNode = $xmlReader->getElement('w:tcPr', $rowNode); + if (!is_null($cellStyleNode)) { + $cellStyle = $this->readCellStyle($xmlReader, $cellStyleNode); + } - case 'w:spacing': - $style['spaceAfter'] = $xmlReader->getAttribute('w:after', $node); - $style['spaceBefore'] = $xmlReader->getAttribute('w:before', $node); - // Commented. Need to adjust the number when return value is null - // $style['spacing'] = $xmlReader->getAttribute('w:line', $node); - break; - - case 'w:keepNext': - case 'w:keepLines': - case 'w:pageBreakBefore': - $style[$property] = true; - break; - - case 'w:widowControl': - $style[$property] = false; - break; - - case 'w:jc': - case 'w:basedOn': - case 'w:next': - $style[$property] = $xmlReader->getAttribute('w:val', $node); - break; + $cell = $row->addCell($cellWidth, $cellStyle); + $cellNodes = $xmlReader->getElements('*', $rowNode); + foreach ($cellNodes as $cellNode) { + if ($cellNode->nodeName == 'w:p') { // Paragraph + $this->readParagraph($xmlReader, $cellNode, $cell, $docPart); + } + } } } } } + } - return $style; + /** + * Read w:pPr + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $domNode + * @return array|null + */ + protected function readParagraphStyle(XMLReader $xmlReader, \DOMElement $domNode) + { + if (!$xmlReader->elementExists('w:pPr', $domNode)) { + return null; + } + + $styleNode = $xmlReader->getElement('w:pPr', $domNode); + $styleDefs = array( + 'styleName' => array(self::READ_VALUE, 'w:pStyle'), + 'align' => array(self::READ_VALUE, 'w:jc'), + 'basedOn' => array(self::READ_VALUE, 'w:basedOn'), + 'next' => array(self::READ_VALUE, 'w:next'), + 'indent' => array(self::READ_VALUE, 'w:ind', 'w:left'), + 'hanging' => array(self::READ_VALUE, 'w:ind', 'w:hanging'), + 'spaceAfter' => array(self::READ_VALUE, 'w:spacing', 'w:after'), + 'spaceBefore' => array(self::READ_VALUE, 'w:spacing', 'w:before'), + 'widowControl' => array(self::READ_FALSE, 'w:widowControl'), + 'keepNext' => array(self::READ_TRUE, 'w:keepNext'), + 'keepLines' => array(self::READ_TRUE, 'w:keepLines'), + 'pageBreakBefore' => array(self::READ_TRUE, 'w:pageBreakBefore'), + ); + + return $this->readStyleDefs($xmlReader, $styleNode, $styleDefs); } /** * Read w:rPr * - * @return string|array|null + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $domNode + * @return array */ protected function readFontStyle(XMLReader $xmlReader, \DOMElement $domNode) { - $style = null; + if (is_null($domNode)) { + return null; + } // Hyperlink has an extra w:r child if ($domNode->nodeName == 'w:hyperlink') { $domNode = $xmlReader->getElement('w:r', $domNode); } - if (is_null($domNode)) { - return $style; - } - if ($xmlReader->elementExists('w:rPr', $domNode)) { - if ($xmlReader->elementExists('w:rPr/w:rStyle', $domNode)) { - $style = $xmlReader->getAttribute('w:val', $domNode, 'w:rPr/w:rStyle'); - } else { - $style = array(); - $mapping = array( - 'w:b' => 'bold', 'w:i' => 'italic', 'w:color' => 'color', - 'w:strike' => 'strikethrough', 'w:u' => 'underline', - 'w:highlight' => 'fgColor', 'w:sz' => 'size', - 'w:rFonts' => 'name', 'w:vertAlign' => 'superScript', - ); - - $nodes = $xmlReader->getElements('w:rPr/*', $domNode); - foreach ($nodes as $node) { - if (!array_key_exists($node->nodeName, $mapping)) { - continue; - } - $property = $mapping[$node->nodeName]; - switch ($node->nodeName) { - - case 'w:rFonts': - $style['name'] = $xmlReader->getAttribute('w:ascii', $node); - $style['hint'] = $xmlReader->getAttribute('w:hint', $node); - break; - - case 'w:b': - case 'w:i': - case 'w:strike': - $style[$property] = true; - break; - - case 'w:u': - case 'w:highlight': - case 'w:color': - $style[$property] = $xmlReader->getAttribute('w:val', $node); - break; - - case 'w:sz': - $style[$property] = $xmlReader->getAttribute('w:val', $node) / 2; - break; - - case 'w:vertAlign': - $style[$property] = $xmlReader->getAttribute('w:val', $node); - if ($style[$property] == 'superscript') { - $style['superScript'] = true; - } else { - $style['superScript'] = false; - $style['subScript'] = true; - } - break; - } - } - } + if (!$xmlReader->elementExists('w:rPr', $domNode)) { + return null; } - return $style; + $styleNode = $xmlReader->getElement('w:rPr', $domNode); + $styleDefs = array( + 'styleName' => array(self::READ_VALUE, 'w:rStyle'), + 'name' => array(self::READ_VALUE, 'w:rFonts', 'w:ascii'), + 'hint' => array(self::READ_VALUE, 'w:rFonts', 'w:hint'), + 'size' => array(self::READ_SIZE, 'w:sz'), + 'color' => array(self::READ_VALUE, 'w:color'), + 'underline' => array(self::READ_VALUE, 'w:u'), + 'bold' => array(self::READ_TRUE, 'w:b'), + 'italic' => array(self::READ_TRUE, 'w:i'), + 'strikethrough' => array(self::READ_TRUE, 'w:strike'), + 'doubleStrikethrough' => array(self::READ_TRUE, 'w:dstrike'), + 'smallCaps' => array(self::READ_TRUE, 'w:smallCaps'), + 'allCaps' => array(self::READ_TRUE, 'w:caps'), + 'superScript' => array(self::READ_EQUAL, 'w:vertAlign', 'w:val', 'superscript'), + 'subScript' => array(self::READ_EQUAL, 'w:vertAlign', 'w:val', 'subscript'), + 'fgColor' => array(self::READ_VALUE, 'w:highlight'), + ); + + return $this->readStyleDefs($xmlReader, $styleNode, $styleDefs); } /** * Read w:tblPr * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $domNode * @return string|array|null * @todo Capture w:tblStylePr w:type="firstRow" */ @@ -279,39 +392,101 @@ abstract class AbstractPart if ($xmlReader->elementExists('w:tblPr/w:tblStyle', $domNode)) { $style = $xmlReader->getAttribute('w:val', $domNode, 'w:tblPr/w:tblStyle'); } else { - $style = array(); - $mapping = array( - 'w:tblCellMar' => 'cellMargin', - 'w:tblBorders' => 'border', - ); + $styleNode = $xmlReader->getElement('w:tblPr', $domNode); + $styleDefs = array(); + // $styleDefs['styleName'] = array(self::READ_VALUE, 'w:tblStyle'); + foreach ($margins as $side) { + $ucfSide = ucfirst($side); + $styleDefs["cellMargin$ucfSide"] = array(self::READ_VALUE, "w:tblCellMar/w:$side", 'w:w'); + } + foreach ($borders as $side) { + $ucfSide = ucfirst($side); + $styleDefs["border{$ucfSide}Size"] = array(self::READ_VALUE, "w:tblBorders/w:$side", 'w:sz'); + $styleDefs["border{$ucfSide}Color"] = array(self::READ_VALUE, "w:tblBorders/w:$side", 'w:color'); + } + $style = $this->readStyleDefs($xmlReader, $styleNode, $styleDefs); + } + } - $nodes = $xmlReader->getElements('w:tblPr/*', $domNode); - foreach ($nodes as $node) { - if (!array_key_exists($node->nodeName, $mapping)) { - continue; - } - // $property = $mapping[$node->nodeName]; - switch ($node->nodeName) { + return $style; + } - case 'w:tblCellMar': - foreach ($margins as $side) { - $ucfSide = ucfirst($side); - $style["cellMargin$ucfSide"] = $xmlReader->getAttribute('w:w', $node, "w:$side"); - } - break; + /** + * Read w:tcPr + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $domNode + * @return array + */ + private function readCellStyle(XMLReader $xmlReader, \DOMElement $domNode) + { + $styleDefs = array( + 'valign' => array(self::READ_VALUE, 'w:vAlign'), + 'textDirection' => array(self::READ_VALUE, 'w:textDirection'), + 'gridSpan' => array(self::READ_VALUE, 'w:gridSpan'), + 'vMerge' => array(self::READ_VALUE, 'w:vMerge'), + 'bgColor' => array(self::READ_VALUE, 'w:shd/w:fill'), + ); - case 'w:tblBorders': - foreach ($borders as $side) { - $ucfSide = ucfirst($side); - $style["border{$ucfSide}Size"] = $xmlReader->getAttribute('w:sz', $node, "w:$side"); - $style["border{$ucfSide}Color"] = $xmlReader->getAttribute('w:color', $node, "w:$side"); - } - break; - } + return $this->readStyleDefs($xmlReader, $domNode, $styleDefs); + } + + /** + * Read style definition + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $parentNode + * @param array $styleDefs + * @ignoreScrutinizerPatch + * @return array + */ + protected function readStyleDefs(XMLReader $xmlReader, \DOMElement $parentNode = null, $styleDefs = array()) + { + $styles = array(); + + foreach ($styleDefs as $styleProp => $styleVal) { + @list($method, $element, $attribute, $expected) = $styleVal; + + if ($xmlReader->elementExists($element, $parentNode)) { + $node = $xmlReader->getElement($element, $parentNode); + + // Use w:val as default if no attribute assigned + $attribute = ($attribute === null) ? 'w:val' : $attribute; + $attributeValue = $xmlReader->getAttribute($attribute, $node); + + $styleValue = $this->readStyleDef($method, $attributeValue, $expected); + if ($styleValue !== null) { + $styles[$styleProp] = $styleValue; } } } + return $styles; + } + + /** + * Return style definition based on conversion method + * + * @param string $method + * @ignoreScrutinizerPatch + * @param mixed $attributeValue + * @param mixed $expected + * @return mixed + */ + private function readStyleDef($method, $attributeValue, $expected) + { + $style = $attributeValue; + + if ($method == self::READ_SIZE) { + $style = $attributeValue / 2; + } elseif ($method == self::READ_TRUE) { + $style = true; + } elseif ($method == self::READ_FALSE) { + $style = false; + } elseif ($method == self::READ_EQUAL && $attributeValue == $expected) { + $style = true; + } + return $style; } diff --git a/src/PhpWord/Reader/Word2007/DocProps.php b/src/PhpWord/Reader/Word2007/DocProps.php deleted file mode 100644 index 2c76417a..00000000 --- a/src/PhpWord/Reader/Word2007/DocProps.php +++ /dev/null @@ -1,63 +0,0 @@ -getDomFromZip($this->docFile, $this->xmlFile); - - $docProps = $phpWord->getDocumentProperties(); - - $nodes = $xmlReader->getElements('*'); - if ($nodes->length > 0) { - foreach ($nodes as $node) { - if (!array_key_exists($node->nodeName, $this->mapping)) { - continue; - } - $method = $this->mapping[$node->nodeName]; - $value = $node->nodeValue == '' ? null : $node->nodeValue; - if (array_key_exists($node->nodeName, $this->callbacks)) { - $value = $this->callbacks[$node->nodeName]($value); - } - if (method_exists($docProps, $method)) { - $docProps->$method($value); - } - } - } - } -} diff --git a/src/PhpWord/Reader/Word2007/DocPropsApp.php b/src/PhpWord/Reader/Word2007/DocPropsApp.php index 7797528a..ddbe474f 100644 --- a/src/PhpWord/Reader/Word2007/DocPropsApp.php +++ b/src/PhpWord/Reader/Word2007/DocPropsApp.php @@ -1,18 +1,28 @@ 'setCompany', 'Manager' => 'setManager'); + + /** + * Callback functions + * + * @var array + */ + protected $callbacks = array(); } diff --git a/src/PhpWord/Reader/Word2007/DocPropsCore.php b/src/PhpWord/Reader/Word2007/DocPropsCore.php index fd943875..0b92b64d 100644 --- a/src/PhpWord/Reader/Word2007/DocPropsCore.php +++ b/src/PhpWord/Reader/Word2007/DocPropsCore.php @@ -1,18 +1,31 @@ 'strtotime', 'dcterms:modified' => 'strtotime'); + + /** + * Read core/extended document properties + * + * @param \PhpOffice\PhpWord\PhpWord $phpWord + */ + public function read(PhpWord &$phpWord) + { + $xmlReader = new XMLReader(); + $xmlReader->getDomFromZip($this->docFile, $this->xmlFile); + + $docProps = $phpWord->getDocumentProperties(); + + $nodes = $xmlReader->getElements('*'); + if ($nodes->length > 0) { + foreach ($nodes as $node) { + if (!array_key_exists($node->nodeName, $this->mapping)) { + continue; + } + $method = $this->mapping[$node->nodeName]; + $value = $node->nodeValue == '' ? null : $node->nodeValue; + if (array_key_exists($node->nodeName, $this->callbacks)) { + $value = $this->callbacks[$node->nodeName]($value); + } + if (method_exists($docProps, $method)) { + $docProps->$method($value); + } + } + } + } } diff --git a/src/PhpWord/Reader/Word2007/DocPropsCustom.php b/src/PhpWord/Reader/Word2007/DocPropsCustom.php index 6c67dc7a..efbbfaa5 100644 --- a/src/PhpWord/Reader/Word2007/DocPropsCustom.php +++ b/src/PhpWord/Reader/Word2007/DocPropsCustom.php @@ -1,10 +1,18 @@ phpWord = $phpWord; $xmlReader = new XMLReader(); $xmlReader->getDomFromZip($this->docFile, $this->xmlFile); + $readMethods = array('w:p' => 'readWPNode', 'w:tbl' => 'readTable', 'w:sectPr' => 'readWSectPrNode'); $nodes = $xmlReader->getElements('w:body/*'); if ($nodes->length > 0) { - $section = $phpWord->addSection(); + $section = $this->phpWord->addSection(); foreach ($nodes as $node) { - switch ($node->nodeName) { - - case 'w:p': // Paragraph - // Page break - // @todo - if ($xmlReader->getAttribute('w:type', $node, 'w:r/w:br') == 'page') { - $section->addPageBreak(); // PageBreak - } - - // Paragraph - $this->readParagraph($xmlReader, $node, $section, 'document'); - // Section properties - if ($xmlReader->elementExists('w:pPr/w:sectPr', $node)) { - $settingsNode = $xmlReader->getElement('w:pPr/w:sectPr', $node); - if (!is_null($settingsNode)) { - $settings = $this->readSectionStyle($xmlReader, $settingsNode); - $section->setSettings($settings); - if (!is_null($settings)) { - $this->readHeaderFooter($settings, $section); - } - } - $section = $phpWord->addSection(); - } - break; - - case 'w:tbl': // Table - $this->readTable($xmlReader, $node, $section, 'document'); - break; - - case 'w:sectPr': // Last section - $settings = $this->readSectionStyle($xmlReader, $node); - $section->setSettings($settings); - if (!is_null($settings)) { - $this->readHeaderFooter($settings, $section); - } - break; + if (array_key_exists($node->nodeName, $readMethods)) { + $readMethod = $readMethods[$node->nodeName]; + $this->$readMethod($xmlReader, $node, $section); } } } @@ -78,14 +66,16 @@ class Document extends AbstractPart * @param array $settings * @param \PhpOffice\PhpWord\Element\Section $section */ - private function readHeaderFooter($settings, &$section) + private function readHeaderFooter($settings, Section &$section) { + $readMethods = array('w:p' => 'readParagraph', 'w:tbl' => 'readTable'); + if (is_array($settings) && array_key_exists('hf', $settings)) { foreach ($settings['hf'] as $rId => $hfSetting) { if (array_key_exists($rId, $this->rels['document'])) { list($hfType, $xmlFile, $docPart) = array_values($this->rels['document'][$rId]); - $method = "add{$hfType}"; - $hfObject = $section->$method($hfSetting['type']); + $addMethod = "add{$hfType}"; + $hfObject = $section->$addMethod($hfSetting['type']); // Read header/footer content $xmlReader = new XMLReader(); @@ -93,160 +83,9 @@ class Document extends AbstractPart $nodes = $xmlReader->getElements('*'); if ($nodes->length > 0) { foreach ($nodes as $node) { - switch ($node->nodeName) { - - case 'w:p': // Paragraph - $this->readParagraph($xmlReader, $node, $hfObject, $docPart); - break; - - case 'w:tbl': // Table - $this->readTable($xmlReader, $node, $hfObject, $docPart); - break; - } - } - } - } - } - } - } - - /** - * Read w:p - * - * @param mixed $parent - * @param string $docPart - * - * @todo Get font style for preserve text - */ - private function readParagraph(XMLReader $xmlReader, \DOMElement $domNode, &$parent, $docPart) - { - // Paragraph style - $paragraphStyle = null; - $headingMatches = array(); - if ($xmlReader->elementExists('w:pPr', $domNode)) { - $paragraphStyle = $this->readParagraphStyle($xmlReader, $domNode); - if (is_string($paragraphStyle)) { - preg_match('/Heading(\d)/', $paragraphStyle, $headingMatches); - } - } - - // PreserveText - if ($xmlReader->elementExists('w:r/w:instrText', $domNode)) { - $ignoreText = false; - $textContent = ''; - $fontStyle = $this->readFontStyle($xmlReader, $domNode); - $nodes = $xmlReader->getElements('w:r', $domNode); - foreach ($nodes as $node) { - $instrText = $xmlReader->getValue('w:instrText', $node); - if ($xmlReader->elementExists('w:fldChar', $node)) { - $fldCharType = $xmlReader->getAttribute('w:fldCharType', $node, 'w:fldChar'); - if ($fldCharType == 'begin') { - $ignoreText = true; - } elseif ($fldCharType == 'end') { - $ignoreText = false; - } - } - if (!is_null($instrText)) { - $textContent .= '{' . $instrText . '}'; - } else { - if ($ignoreText === false) { - $textContent .= $xmlReader->getValue('w:t', $node); - } - } - } - $parent->addPreserveText($textContent, $fontStyle, $paragraphStyle); - - // List item - } elseif ($xmlReader->elementExists('w:pPr/w:numPr', $domNode)) { - $textContent = ''; - $numId = $xmlReader->getAttribute('w:val', $domNode, 'w:pPr/w:numPr/w:numId'); - $levelId = $xmlReader->getAttribute('w:val', $domNode, 'w:pPr/w:numPr/w:ilvl'); - $nodes = $xmlReader->getElements('w:r', $domNode); - foreach ($nodes as $node) { - $textContent .= $xmlReader->getValue('w:t', $node); - } - $parent->addListItem($textContent, $levelId, null, "PHPWordList{$numId}", $paragraphStyle); - - // Heading - } elseif (!empty($headingMatches)) { - $textContent = ''; - $nodes = $xmlReader->getElements('w:r', $domNode); - foreach ($nodes as $node) { - $textContent .= $xmlReader->getValue('w:t', $node); - } - $parent->addTitle($textContent, $headingMatches[1]); - - // Text and TextRun - } else { - $runCount = $xmlReader->countElements('w:r', $domNode); - $linkCount = $xmlReader->countElements('w:hyperlink', $domNode); - $runLinkCount = $runCount + $linkCount; - if ($runLinkCount == 0) { - $parent->addTextBreak(null, $paragraphStyle); - } else { - if ($runLinkCount > 1) { - $textrun = $parent->addTextRun($paragraphStyle); - $textParent = &$textrun; - } else { - $textParent = &$parent; - } - $nodes = $xmlReader->getElements('*', $domNode); - foreach ($nodes as $node) { - $this->readRun($xmlReader, $node, $textParent, $docPart, $paragraphStyle); - } - } - } - } - - /** - * Read w:tbl - * - * @param mixed $parent - * @param string $docPart - */ - private function readTable(XMLReader $xmlReader, \DOMElement $domNode, &$parent, $docPart) - { - // Table style - $tblStyle = null; - if ($xmlReader->elementExists('w:tblPr', $domNode)) { - $tblStyle = $this->readTableStyle($xmlReader, $domNode); - } - - $table = $parent->addTable($tblStyle); - $tblNodes = $xmlReader->getElements('*', $domNode); - foreach ($tblNodes as $tblNode) { - if ($tblNode->nodeName == 'w:tblGrid') { // Column - // @todo Do something with table columns - - } elseif ($tblNode->nodeName == 'w:tr') { // Row - $rowHeight = $xmlReader->getAttribute('w:val', $tblNode, 'w:trPr/w:trHeight'); - $rowHRule = $xmlReader->getAttribute('w:hRule', $tblNode, 'w:trPr/w:trHeight'); - $rowHRule = $rowHRule == 'exact' ? true : false; - $rowStyle = array( - 'tblHeader' => $xmlReader->elementExists('w:trPr/w:tblHeader', $tblNode), - 'cantSplit' => $xmlReader->elementExists('w:trPr/w:cantSplit', $tblNode), - 'exactHeight' => $rowHRule, - ); - - $row = $table->addRow($rowHeight, $rowStyle); - $rowNodes = $xmlReader->getElements('*', $tblNode); - foreach ($rowNodes as $rowNode) { - if ($rowNode->nodeName == 'w:trPr') { // Row style - // @todo Do something with row style - - } elseif ($rowNode->nodeName == 'w:tc') { // Cell - $cellWidth = $xmlReader->getAttribute('w:w', $rowNode, 'w:tcPr/w:tcW'); - $cellStyle = null; - $cellStyleNode = $xmlReader->getElement('w:tcPr', $rowNode); - if (!is_null($cellStyleNode)) { - $cellStyle = $this->readCellStyle($xmlReader, $cellStyleNode); - } - - $cell = $row->addCell($cellWidth, $cellStyle); - $cellNodes = $xmlReader->getElements('*', $rowNode); - foreach ($cellNodes as $cellNode) { - if ($cellNode->nodeName == 'w:p') { // Paragraph - $this->readParagraph($xmlReader, $cellNode, $cell, $docPart); + if (array_key_exists($node->nodeName, $readMethods)) { + $readMethod = $readMethods[$node->nodeName]; + $this->$readMethod($xmlReader, $node, $hfObject, $docPart); } } } @@ -258,93 +97,86 @@ class Document extends AbstractPart /** * Read w:sectPr * - * @return array|null + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $domNode + * @ignoreScrutinizerPatch + * @return array */ private function readSectionStyle(XMLReader $xmlReader, \DOMElement $domNode) { - $ret = null; - $mapping = array( - 'w:type' => 'breakType', 'w:pgSz' => 'pageSize', - 'w:pgMar' => 'pageMargin', 'w:cols' => 'columns', - 'w:headerReference' => 'header', 'w:footerReference' => 'footer', + $styleDefs = array( + 'breakType' => array(self::READ_VALUE, 'w:type'), + 'pageSizeW' => array(self::READ_VALUE, 'w:pgSz', 'w:w'), + 'pageSizeH' => array(self::READ_VALUE, 'w:pgSz', 'w:h'), + 'orientation' => array(self::READ_VALUE, 'w:pgSz', 'w:orient'), + 'colsNum' => array(self::READ_VALUE, 'w:cols', 'w:num'), + 'colsSpace' => array(self::READ_VALUE, 'w:cols', 'w:space'), + 'topMargin' => array(self::READ_VALUE, 'w:pgMar', 'w:top'), + 'leftMargin' => array(self::READ_VALUE, 'w:pgMar', 'w:left'), + 'bottomMargin' => array(self::READ_VALUE, 'w:pgMar', 'w:bottom'), + 'rightMargin' => array(self::READ_VALUE, 'w:pgMar', 'w:right'), + 'headerHeight' => array(self::READ_VALUE, 'w:pgMar', 'w:header'), + 'footerHeight' => array(self::READ_VALUE, 'w:pgMar', 'w:footer'), + 'gutter' => array(self::READ_VALUE, 'w:pgMar', 'w:gutter'), ); + $styles = $this->readStyleDefs($xmlReader, $domNode, $styleDefs); + + // Header and footer + // @todo Cleanup this part $nodes = $xmlReader->getElements('*', $domNode); foreach ($nodes as $node) { - if (!array_key_exists($node->nodeName, $mapping)) { - continue; - } - $property = $mapping[$node->nodeName]; - switch ($node->nodeName) { - - case 'w:type': - $ret['breakType'] = $xmlReader->getAttribute('w:val', $node); - break; - - case 'w:pgSz': - $ret['pageSizeW'] = $xmlReader->getAttribute('w:w', $node); - $ret['pageSizeH'] = $xmlReader->getAttribute('w:h', $node); - $ret['orientation'] = $xmlReader->getAttribute('w:orient', $node); - break; - - case 'w:pgMar': - $ret['topMargin'] = $xmlReader->getAttribute('w:top', $node); - $ret['leftMargin'] = $xmlReader->getAttribute('w:left', $node); - $ret['bottomMargin'] = $xmlReader->getAttribute('w:bottom', $node); - $ret['rightMargin'] = $xmlReader->getAttribute('w:right', $node); - $ret['headerHeight'] = $xmlReader->getAttribute('w:header', $node); - $ret['footerHeight'] = $xmlReader->getAttribute('w:footer', $node); - $ret['gutter'] = $xmlReader->getAttribute('w:gutter', $node); - break; - - case 'w:cols': - $ret['colsNum'] = $xmlReader->getAttribute('w:num', $node); - $ret['colsSpace'] = $xmlReader->getAttribute('w:space', $node); - break; - - case 'w:headerReference': - case 'w:footerReference': - $id = $xmlReader->getAttribute('r:id', $node); - $ret['hf'][$id] = array( - 'method' => $property, - 'type' => $xmlReader->getAttribute('w:type', $node), - ); - break; + if ($node->nodeName == 'w:headerReference' || $node->nodeName == 'w:footerReference') { + $id = $xmlReader->getAttribute('r:id', $node); + $styles['hf'][$id] = array( + 'method' => str_replace('w:', '', str_replace('Reference', '', $node->nodeName)), + 'type' => $xmlReader->getAttribute('w:type', $node), + ); } } - return $ret; + return $styles; } /** - * Read w:tcPr + * Read w:p node * - * @return array|null + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $node + * @param \PhpOffice\PhpWord\Element\Section $section + * + * @todo */ - private function readCellStyle(XMLReader $xmlReader, \DOMElement $domNode) + private function readWPNode(XMLReader $xmlReader, \DOMElement $node, Section &$section) { - $style = null; - $mapping = array( - 'w:shd' => 'bgColor', - 'w:vAlign' => 'valign', 'w:textDirection' => 'textDirection', - 'w:gridSpan' => 'gridSpan', 'w:vMerge' => 'vMerge', - ); - $nodes = $xmlReader->getElements('*', $domNode); - foreach ($nodes as $node) { - if (!array_key_exists($node->nodeName, $mapping)) { - continue; - } - $property = $mapping[$node->nodeName]; - switch ($node->nodeName) { - case 'w:shd': - $style['bgColor'] = $xmlReader->getAttribute('w:fill', $node); - break; - - default: - $style[$property] = $xmlReader->getAttribute('w:val', $node); - break; - } + // Page break + if ($xmlReader->getAttribute('w:type', $node, 'w:r/w:br') == 'page') { + $section->addPageBreak(); // PageBreak } - return $style; + // Paragraph + $this->readParagraph($xmlReader, $node, $section); + + // Section properties + if ($xmlReader->elementExists('w:pPr/w:sectPr', $node)) { + $sectPrNode = $xmlReader->getElement('w:pPr/w:sectPr', $node); + if ($sectPrNode !== null) { + $this->readWSectPrNode($xmlReader, $sectPrNode, $section); + } + $section = $this->phpWord->addSection(); + } + } + + /** + * Read w:sectPr node + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $node + * @param \PhpOffice\PhpWord\Element\Section $section + */ + private function readWSectPrNode(XMLReader $xmlReader, \DOMElement $node, Section &$section) + { + $settings = $this->readSectionStyle($xmlReader, $node); + $section->setSettings($settings); + $this->readHeaderFooter($settings, $section); } } diff --git a/src/PhpWord/Reader/Word2007/Endnotes.php b/src/PhpWord/Reader/Word2007/Endnotes.php index 235dab4b..c493c347 100644 --- a/src/PhpWord/Reader/Word2007/Endnotes.php +++ b/src/PhpWord/Reader/Word2007/Endnotes.php @@ -1,23 +1,40 @@ collection}"; + $collection = $phpWord->$getMethod()->getItems(); + + $xmlReader = new XMLReader(); + $xmlReader->getDomFromZip($this->docFile, $this->xmlFile); + $nodes = $xmlReader->getElements('*'); + if ($nodes->length > 0) { + foreach ($nodes as $node) { + $id = $xmlReader->getAttribute('w:id', $node); + $type = $xmlReader->getAttribute('w:type', $node); + + // Avoid w:type "separator" and "continuationSeparator" + // Only look for or without w:type attribute + if (is_null($type) && array_key_exists($id, $collection)) { + $element = $collection[$id]; + $pNodes = $xmlReader->getElements('w:p/*', $node); + foreach ($pNodes as $pNode) { + $this->readRun($xmlReader, $pNode, $element, $this->collection); + } + $addMethod = "add{$this->element}"; + $phpWord->$addMethod($element); + } + } + } + } } diff --git a/src/PhpWord/Reader/Word2007/Notes.php b/src/PhpWord/Reader/Word2007/Notes.php deleted file mode 100644 index bdb0b9e8..00000000 --- a/src/PhpWord/Reader/Word2007/Notes.php +++ /dev/null @@ -1,59 +0,0 @@ -type = ($this->type == 'endnotes') ? 'endnotes' : 'footnotes'; - $collectionClass = 'PhpOffice\\PhpWord\\' . ucfirst($this->type); - $collection = $collectionClass::getElements(); - - $xmlReader = new XMLReader(); - $xmlReader->getDomFromZip($this->docFile, $this->xmlFile); - $nodes = $xmlReader->getElements('*'); - if ($nodes->length > 0) { - foreach ($nodes as $node) { - $id = $xmlReader->getAttribute('w:id', $node); - $type = $xmlReader->getAttribute('w:type', $node); - - // Avoid w:type "separator" and "continuationSeparator" - // Only look for or without w:type attribute - if (is_null($type) && array_key_exists($id, $collection)) { - $element = $collection[$id]; - $pNodes = $xmlReader->getElements('w:p/*', $node); - foreach ($pNodes as $pNode) { - $this->readRun($xmlReader, $pNode, $element, $type); - } - $collectionClass::setElement($id, $element); - } - } - } - } -} diff --git a/src/PhpWord/Reader/Word2007/Numbering.php b/src/PhpWord/Reader/Word2007/Numbering.php index 5cd3f7ae..2dd3f521 100644 --- a/src/PhpWord/Reader/Word2007/Numbering.php +++ b/src/PhpWord/Reader/Word2007/Numbering.php @@ -1,10 +1,18 @@ 0) { + self::$defaultFontSize = $value; + return true; + } + + return false; + } + + /** + * Load setting from phpword.yml or phpword.yml.dist + * + * @param string $filename + * @return array + */ + public static function loadConfig($filename = null) + { + // Get config file + $configFile = null; + $configPath = __DIR__ . '/../../'; + if ($filename !== null) { + $files = array($filename); + } else { + $files = array("{$configPath}phpword.ini", "{$configPath}phpword.ini.dist"); + } + foreach ($files as $file) { + if (file_exists($file)) { + $configFile = realpath($file); + break; + } + } + + // Parse config file + $config = array(); + if ($configFile !== null) { + $config = @parse_ini_file($configFile); + if ($config === false) { + return $config; + } + } + + // Set config value + foreach ($config as $key => $value) { + $method = "set{$key}"; + if (method_exists(__CLASS__, $method)) { + self::$method($value); + } + } + + return $config; + } + + /** + * Return the compatibility option used by the XMLWriter + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public static function getCompatibility() + { + return self::hasCompatibility(); + } } diff --git a/src/PhpWord/Shared/Drawing.php b/src/PhpWord/Shared/Drawing.php index 58a6ee1a..5ee7e960 100644 --- a/src/PhpWord/Shared/Drawing.php +++ b/src/PhpWord/Shared/Drawing.php @@ -1,10 +1,18 @@ ' . $html . ''; + } + + // Load DOM + $dom = new \DOMDocument(); + $dom->preserveWhiteSpace = true; + $dom->loadXML($html); + $node = $dom->getElementsByTagName('body'); + + self::parseNode($node->item(0), $element); + } + + /** + * parse Inline style of a node + * + * @param \DOMNode $node Node to check on attributes and to compile a style array + * @param array $styles is supplied, the inline style attributes are added to the already existing style + * @return array + */ + protected static function parseInlineStyle($node, $styles = array()) + { + if ($node->nodeType == XML_ELEMENT_NODE) { + $attributes = $node->attributes; // get all the attributes(eg: id, class) + + foreach ($attributes as $attribute) { + switch ($attribute->name) { + case 'style': + $styles = self::parseStyle($attribute, $styles); + break; + } + } + } + + return $styles; + } + + /** + * Parse a node and add a corresponding element to the parent element + * + * @param \DOMNode $node node to parse + * @param \PhpOffice\PhpWord\Element\AbstractContainer $element object to add an element corresponding with the node + * @param array $styles Array with all styles + * @param array $data Array to transport data to a next level in the DOM tree, for example level of listitems + */ + protected static function parseNode($node, $element, $styles = array(), $data = array()) + { + // Populate styles array + $styleTypes = array('font', 'paragraph', 'list'); + foreach ($styleTypes as $styleType) { + if (!isset($styles[$styleType])) { + $styles[$styleType] = array(); + } + } + + // Node mapping table + $nodes = array( + // $method $node $element $styles $data $argument1 $argument2 + 'p' => array('Paragraph', $node, $element, $styles, null, null, null), + 'h1' => array('Heading', null, $element, $styles, null, 'Heading1', null), + 'h2' => array('Heading', null, $element, $styles, null, 'Heading2', null), + 'h3' => array('Heading', null, $element, $styles, null, 'Heading3', null), + 'h4' => array('Heading', null, $element, $styles, null, 'Heading4', null), + 'h5' => array('Heading', null, $element, $styles, null, 'Heading5', null), + 'h6' => array('Heading', null, $element, $styles, null, 'Heading6', null), + '#text' => array('Text', $node, $element, $styles, null, null, null), + 'strong' => array('Property', null, null, $styles, null, 'bold', true), + 'em' => array('Property', null, null, $styles, null, 'italic', true), + 'sup' => array('Property', null, null, $styles, null, 'superScript', true), + 'sub' => array('Property', null, null, $styles, null, 'subScript', true), + 'table' => array('Table', $node, $element, $styles, null, 'addTable', true), + 'tr' => array('Table', $node, $element, $styles, null, 'addRow', true), + 'td' => array('Table', $node, $element, $styles, null, 'addCell', true), + 'ul' => array('List', null, null, $styles, $data, 3, null), + 'ol' => array('List', null, null, $styles, $data, 7, null), + 'li' => array('ListItem', $node, $element, $styles, $data, null, null), + ); + + $newElement = null; + $keys = array('node', 'element', 'styles', 'data', 'argument1', 'argument2'); + + if (array_key_exists($node->nodeName, $nodes)) { + + // Execute method based on node mapping table and return $newElement or null + // Arguments are passed by reference + $arguments = array(); + $args = array(); + list($method, $args[0], $args[1], $args[2], $args[3], $args[4], $args[5]) = $nodes[$node->nodeName]; + for ($i = 0; $i <= 5; $i++) { + if ($args[$i] !== null) { + $arguments[$keys[$i]] = &$args[$i]; + } + } + $method = "parse{$method}"; + $newElement = call_user_func_array(array('PhpOffice\PhpWord\Shared\Html', $method), $arguments); + + // Retrieve back variables from arguments + foreach ($keys as $key) { + if (array_key_exists($key, $arguments)) { + $$key = $arguments[$key]; + } + } + } + + if ($newElement === null) { + $newElement = $element; + } + + self::parseChildNodes($node, $newElement, $styles, $data); + } + + /** + * Parse child nodes + * + * @param \DOMNode $node + * @param \PhpOffice\PhpWord\Element\AbstractContainer $element + * @param array $styles + * @param array $data + */ + private static function parseChildNodes($node, $element, $styles, $data) + { + if ($node->nodeName != 'li') { + $cNodes = $node->childNodes; + if (count($cNodes) > 0) { + foreach ($cNodes as $cNode) { + if ($element instanceof AbstractContainer) { + self::parseNode($cNode, $element, $styles, $data); + } + } + } + } + } + + /** + * Parse paragraph node + * + * @param \DOMNode $node + * @param \PhpOffice\PhpWord\Element\AbstractContainer $element + * @param array $styles + * @return \PhpOffice\PhpWord\Element\TextRun + */ + private static function parseParagraph($node, $element, &$styles) + { + $styles['paragraph'] = self::parseInlineStyle($node, $styles['paragraph']); + $newElement = $element->addTextRun($styles['paragraph']); + + return $newElement; + } + + /** + * Parse heading node + * + * @param \PhpOffice\PhpWord\Element\AbstractContainer $element + * @param array $styles + * @param string $argument1 Name of heading style + * @return \PhpOffice\PhpWord\Element\TextRun + * + * @todo Think of a clever way of defining header styles, now it is only based on the assumption, that + * Heading1 - Heading6 are already defined somewhere + */ + private static function parseHeading($element, &$styles, $argument1) + { + $styles['paragraph'] = $argument1; + $newElement = $element->addTextRun($styles['paragraph']); + + return $newElement; + } + + /** + * Parse text node + * + * @param \DOMNode $node + * @param \PhpOffice\PhpWord\Element\AbstractContainer $element + * @param array $styles + * @return null + */ + private static function parseText($node, $element, &$styles) + { + $styles['font'] = self::parseInlineStyle($node, $styles['font']); + if (method_exists($element, 'addText')) { + $element->addText($node->nodeValue, $styles['font'], $styles['paragraph']); + } + + return null; + } + + /** + * Parse property node + * + * @param array $styles + * @param string $argument1 Style name + * @param string $argument2 Style value + * @return null + */ + private static function parseProperty(&$styles, $argument1, $argument2) + { + $styles['font'][$argument1] = $argument2; + + return null; + } + + /** + * Parse table node + * + * @param \DOMNode $node + * @param \PhpOffice\PhpWord\Element\AbstractContainer $element + * @param array $styles + * @param string $argument1 Method name + * @return \PhpOffice\PhpWord\Element\AbstractContainer $element + * + * @todo As soon as TableItem, RowItem and CellItem support relative width and height + */ + private static function parseTable($node, $element, &$styles, $argument1) + { + $styles['paragraph'] = self::parseInlineStyle($node, $styles['paragraph']); + + $newElement = $element->$argument1(); + + // $attributes = $node->attributes; + // if ($attributes->getNamedItem('width') !== null) { + // $newElement->setWidth($attributes->getNamedItem('width')->value); + // } + + // if ($attributes->getNamedItem('height') !== null) { + // $newElement->setHeight($attributes->getNamedItem('height')->value); + // } + // if ($attributes->getNamedItem('width') !== null) { + // $newElement=$element->addCell($width=$attributes->getNamedItem('width')->value); + // } + + return $newElement; + } + + /** + * Parse list node + * + * @param array $styles + * @param array $data + * @param string $argument1 List type + * @return null + */ + private static function parseList(&$styles, &$data, $argument1) + { + if (isset($data['listdepth'])) { + $data['listdepth']++; + } else { + $data['listdepth'] = 0; + } + $styles['list']['listType'] = $argument1; + + return null; + } + + /** + * Parse list item node + * + * @param \DOMNode $node + * @param \PhpOffice\PhpWord\Element\AbstractContainer $element + * @param array $styles + * @param array $data + * @return null + * + * @todo This function is almost the same like `parseChildNodes`. Merged? + * @todo As soon as ListItem inherits from AbstractContainer or TextRun delete parsing part of childNodes + */ + private static function parseListItem($node, $element, &$styles, $data) + { + $cNodes = $node->childNodes; + if (count($cNodes) > 0) { + $text = ''; + foreach ($cNodes as $cNode) { + if ($cNode->nodeName == '#text') { + $text = $cNode->nodeValue; + } + } + $element->addListItem($text, $data['listdepth'], $styles['font'], $styles['list'], $styles['paragraph']); + } + + return null; + } + + /** + * Parse style + * + * @param \DOMAttr $attribute + * @param array $styles + * @return array + */ + private static function parseStyle($attribute, $styles) + { + $properties = explode(';', trim($attribute->value, " \t\n\r\0\x0B;")); + foreach ($properties as $property) { + list($cKey, $cValue) = explode(':', $property, 2); + $cValue = trim($cValue); + switch (trim($cKey)) { + case 'text-decoration': + switch ($cValue) { + case 'underline': + $styles['underline'] = 'single'; + break; + case 'line-through': + $styles['strikethrough'] = true; + break; + } + break; + case 'text-align': + $styles['align'] = $cValue; + break; + case 'color': + $styles['color'] = trim($cValue, "#"); + break; + case 'background-color': + $styles['bgColor'] = trim($cValue, "#"); + break; + } + } + + return $styles; + } +} diff --git a/src/PhpWord/Shared/String.php b/src/PhpWord/Shared/String.php index 95f75f13..1e4504cc 100644 --- a/src/PhpWord/Shared/String.php +++ b/src/PhpWord/Shared/String.php @@ -1,10 +1,18 @@ 127 ? '\uc0{\u' . $value . '}' : chr($value); + } + } + + return $entities; + } + /** * Return name without underscore for < 0.10.0 variable name compatibility * diff --git a/src/PhpWord/Shared/XMLReader.php b/src/PhpWord/Shared/XMLReader.php index b7f5549e..153152ee 100644 --- a/src/PhpWord/Shared/XMLReader.php +++ b/src/PhpWord/Shared/XMLReader.php @@ -1,16 +1,23 @@ open($zipFile); - if ($canOpen === false) { - throw new Exception('Cannot open archive file.'); - } - $contents = $zip->getFromName($xmlFile); + $zip = new ZipArchive(); + $zip->open($zipFile); + $content = $zip->getFromName($xmlFile); $zip->close(); - if ($contents === false) { + if ($content === false) { return false; } else { - $this->dom = new \DOMDocument(); - $this->dom->loadXML($contents); - return $this->dom; + return $this->getDomFromString($content); } } + /** + * Get DOMDocument from content string + * + * @param string $content + * @return \DOMDocument + */ + public function getDomFromString($content) + { + $this->dom = new \DOMDocument(); + $this->dom->loadXML($content); + + return $this->dom; + } + /** * Get elements * * @param string $path + * @param \DOMElement $contextNode * @return \DOMNodeList */ public function getElements($path, \DOMElement $contextNode = null) @@ -86,9 +103,10 @@ class XMLReader * Get element * * @param string $path + * @param \DOMElement $contextNode * @return \DOMElement|null */ - public function getElement($path, \DOMElement $contextNode) + public function getElement($path, \DOMElement $contextNode = null) { $elements = $this->getElements($path, $contextNode); if ($elements->length > 0) { @@ -102,19 +120,23 @@ class XMLReader * Get element attribute * * @param string $attribute + * @param \DOMElement $contextNode * @param string $path * @return string|null */ - public function getAttribute($attribute, \DOMElement $contextNode, $path = null) + public function getAttribute($attribute, \DOMElement $contextNode = null, $path = null) { - if (is_null($path)) { - $return = $contextNode->getAttribute($attribute); - } else { + $return = null; + if ($path !== null) { $elements = $this->getElements($path, $contextNode); if ($elements->length > 0) { - $return = $elements->item(0)->getAttribute($attribute); - } else { - $return = null; + /** @var \DOMElement $node Type hint */ + $node = $elements->item(0); + $return = $node->getAttribute($attribute); + } + } else { + if ($contextNode !== null) { + $return = $contextNode->getAttribute($attribute); } } @@ -125,9 +147,10 @@ class XMLReader * Get element value * * @param string $path + * @param \DOMElement $contextNode * @return string|null */ - public function getValue($path, \DOMElement $contextNode) + public function getValue($path, \DOMElement $contextNode = null) { $elements = $this->getElements($path, $contextNode); if ($elements->length > 0) { @@ -141,9 +164,10 @@ class XMLReader * Count elements * * @param string $path + * @param \DOMElement $contextNode * @return integer */ - public function countElements($path, \DOMElement $contextNode) + public function countElements($path, \DOMElement $contextNode = null) { $elements = $this->getElements($path, $contextNode); @@ -154,9 +178,10 @@ class XMLReader * Element exists * * @param string $path + * @param \DOMElement $contextNode * @return boolean */ - public function elementExists($path, \DOMElement $contextNode) + public function elementExists($path, \DOMElement $contextNode = null) { return $this->getElements($path, $contextNode)->length > 0; } diff --git a/src/PhpWord/Shared/XMLWriter.php b/src/PhpWord/Shared/XMLWriter.php index 53f5e893..cb00c70b 100644 --- a/src/PhpWord/Shared/XMLWriter.php +++ b/src/PhpWord/Shared/XMLWriter.php @@ -1,31 +1,34 @@ tempFile = @tempnam($tempFolder, 'xml'); - // Open storage + // Fallback to memory when temporary file cannot be used + // @codeCoverageIgnoreStart + // Can't find any test case. Uncomment when found. if ($this->xmlWriter->openUri($this->tempFile) === false) { - // Fallback to memory... $this->xmlWriter->openMemory(); } + // @codeCoverageIgnoreEnd } // Set xml Compatibility - $compatibility = Settings::getCompatibility(); + $compatibility = Settings::hasCompatibility(); if ($compatibility) { $this->xmlWriter->setIndent(false); $this->xmlWriter->setIndentString(''); @@ -102,9 +107,16 @@ class XMLWriter * * @param mixed $function * @param mixed $args + * @throws \BadMethodCallException */ public function __call($function, $args) { + // Catch exception + if (method_exists($this->xmlWriter, $function) === false) { + throw new \BadMethodCallException("Method '{$function}' does not exists."); + } + + // Run method try { @call_user_func_array(array($this->xmlWriter, $function), $args); } catch (\Exception $ex) { @@ -128,17 +140,37 @@ class XMLWriter } /** - * Fallback method for writeRaw, introduced in PHP 5.2 + * Write element if ... * - * @param string $text - * @return bool + * @param bool $condition + * @param string $element + * @param string $attribute + * @param mixed $value */ - public function writeRaw($text) + public function writeElementIf($condition, $element, $attribute = null, $value = null) { - if (isset($this->xmlWriter) && is_object($this->xmlWriter) && (method_exists($this->xmlWriter, 'writeRaw'))) { - return $this->xmlWriter->writeRaw($text); + if ($condition == true) { + if (is_null($attribute)) { + $this->xmlWriter->writeElement($element, $value); + } else { + $this->xmlWriter->startElement($element); + $this->xmlWriter->writeAttribute($attribute, $value); + $this->xmlWriter->endElement(); + } } + } - return $this->text($text); + /** + * Write attribute if ... + * + * @param bool $condition + * @param string $attribute + * @param mixed $value + */ + public function writeAttributeIf($condition, $attribute, $value) + { + if ($condition == true) { + $this->xmlWriter->writeAttribute($attribute, $value); + } } } diff --git a/src/PhpWord/Shared/ZipArchive.php b/src/PhpWord/Shared/ZipArchive.php index 2da7573c..cbfcb071 100644 --- a/src/PhpWord/Shared/ZipArchive.php +++ b/src/PhpWord/Shared/ZipArchive.php @@ -1,40 +1,59 @@ usePclzip = (Settings::getZipClass() != 'ZipArchive'); + if ($this->usePclzip) { + if (!defined('PCLZIP_TEMPORARY_DIR')) { + define('PCLZIP_TEMPORARY_DIR', sys_get_temp_dir() . '/'); + } + require_once 'PCLZip/pclzip.lib.php'; + } + } + + /** + * Catch function calls: pass to ZipArchive or PCLZip + * + * `call_user_func_array` can only used for public function, hence the `public` in all `pcl...` methods + * + * @param mixed $function + * @param mixed $args + * @return mixed + */ + public function __call($function, $args) + { + // Set object and function + $zipFunction = $function; + if (!$this->usePclzip) { + $zipObject = $this->zip; + } else { + $zipObject = $this; + $zipFunction = "pclzip{$zipFunction}"; + } + + // Run function + $result = false; + if (method_exists($zipObject, $zipFunction)) { + $result = @call_user_func_array(array($zipObject, $zipFunction), $args); + } + + return $result; + } + /** * Open a new zip archive * - * @param string $filename Filename for the zip archive - * @return boolean + * @param string $filename The file name of the ZIP archive to open + * @param int $flags The mode to use to open the archive + * @return bool */ - public function open($filename) + public function open($filename, $flags = null) { - $this->tempDir = sys_get_temp_dir(); - $this->zip = new \PclZip($filename); - $this->numFiles = count($this->zip->listContent()); + $result = true; + $this->filename = $filename; + + if (!$this->usePclzip) { + $zip = new \ZipArchive(); + $result = $zip->open($this->filename, $flags); + + // Scrutizer will report the property numFiles does not exist + // See https://github.com/scrutinizer-ci/php-analyzer/issues/190 + $this->numFiles = $zip->numFiles; + } else { + $zip = new \PclZip($this->filename); + $this->tempDir = sys_get_temp_dir(); + $this->numFiles = count($zip->listContent()); + } + $this->zip = $zip; + + return $result; + } + + /** + * Close the active archive + * + * @return bool + * @throws \PhpOffice\PhpWord\Exception\Exception + * @codeCoverageIgnore Can't find any test case. Uncomment when found. + */ + public function close() + { + if (!$this->usePclzip) { + if ($this->zip->close() === false) { + throw new Exception("Could not close zip file $this->filename."); + } + } return true; } /** - * Close this zip archive (emulate \ZipArchive) + * Extract the archive contents (emulate \ZipArchive) * - * @codeCoverageIgnore + * @param string $destination + * @param string|array $entries + * @return bool + * @since 0.10.0 */ - public function close() + public function extractTo($destination, $entries = null) { + if (!is_dir($destination)) { + return false; + } + + if (!$this->usePclzip) { + return $this->zip->extractTo($destination, $entries); + } else { + return $this->pclzipExtractTo($destination, $entries); + } + } + + /** + * Extract file from archive by given file name (emulate \ZipArchive) + * + * @param string $filename Filename for the file in zip archive + * @return string $contents File string contents + */ + public function getFromName($filename) + { + if (!$this->usePclzip) { + $contents = $this->zip->getFromName($filename); + if ($contents === false) { + $filename = substr($filename, 1); + $contents = $this->zip->getFromName($filename); + } + } else { + $contents = $this->pclzipGetFromName($filename); + } + + return $contents; } /** * Add a new file to the zip archive (emulate \ZipArchive) * - * @param string $filename Directory/Name of the file to add to the zip archive + * @param string $filename Directory/Name of the file to add to the zip archive * @param string $localname Directory/Name of the file added to the zip + * @return bool */ - public function addFile($filename, $localname = null) + public function pclzipAddFile($filename, $localname = null) { + /** @var \PclZip $zip Type hint */ + $zip = $this->zip; $filename = realpath($filename); $filenameParts = pathinfo($filename); $localnameParts = pathinfo($localname); @@ -94,13 +231,10 @@ class ZipArchive $filenameParts = pathinfo($temppath); } - $res = $this->zip->add( - $filename, - PCLZIP_OPT_REMOVE_PATH, - $filenameParts['dirname'], - PCLZIP_OPT_ADD_PATH, - $localnameParts["dirname"] - ); + $pathRemoved = $filenameParts['dirname']; + $pathAdded = $localnameParts['dirname']; + + $res = $zip->add($filename, PCLZIP_OPT_REMOVE_PATH, $pathRemoved, PCLZIP_OPT_ADD_PATH, $pathAdded); return ($res == 0) ? false : true; } @@ -109,10 +243,13 @@ class ZipArchive * Add a new file to the zip archive from a string of raw data (emulate \ZipArchive) * * @param string $localname Directory/Name of the file to add to the zip archive - * @param string $contents String of data to add to the zip archive + * @param string $contents String of data to add to the zip archive + * @return bool */ - public function addFromString($localname, $contents) + public function pclzipAddFromString($localname, $contents) { + /** @var \PclZip $zip Type hint */ + $zip = $this->zip; $filenameParts = pathinfo($localname); // Write $contents to a temp file @@ -121,13 +258,11 @@ class ZipArchive fclose($handle); // Add temp file to zip - $res = $this->zip->add( - $this->tempDir . '/' . $filenameParts["basename"], - PCLZIP_OPT_REMOVE_PATH, - $this->tempDir, - PCLZIP_OPT_ADD_PATH, - $filenameParts["dirname"] - ); + $filename = $this->tempDir . '/' . $filenameParts["basename"]; + $pathRemoved = $this->tempDir; + $pathAdded = $filenameParts['dirname']; + + $res = $zip->add($filename, PCLZIP_OPT_REMOVE_PATH, $pathRemoved, PCLZIP_OPT_ADD_PATH, $pathAdded); // Remove temp file @unlink($this->tempDir . '/' . $filenameParts["basename"]); @@ -135,15 +270,97 @@ class ZipArchive return ($res == 0) ? false : true; } + /** + * Extract the archive contents (emulate \ZipArchive) + * + * @param string $destination + * @param string|array $entries + * @return bool + * @since 0.10.0 + */ + public function pclzipExtractTo($destination, $entries = null) + { + /** @var \PclZip $zip Type hint */ + $zip = $this->zip; + + // Extract all files + if (is_null($entries)) { + $result = $zip->extract(PCLZIP_OPT_PATH, $destination); + return ($result > 0) ? true : false; + } + + // Extract by entries + if (!is_array($entries)) { + $entries = array($entries); + } + foreach ($entries as $entry) { + $entryIndex = $this->locateName($entry); + $result = $zip->extractByIndex($entryIndex, PCLZIP_OPT_PATH, $destination); + if ($result <= 0) { + return false; + } + } + + return true; + } + + /** + * Extract file from archive by given file name (emulate \ZipArchive) + * + * @param string $filename Filename for the file in zip archive + * @return string $contents File string contents + */ + public function pclzipGetFromName($filename) + { + /** @var \PclZip $zip Type hint */ + $zip = $this->zip; + $listIndex = $this->pclzipLocateName($filename); + $contents = false; + + if ($listIndex !== false) { + $extracted = $zip->extractByIndex($listIndex, PCLZIP_OPT_EXTRACT_AS_STRING); + } else { + $filename = substr($filename, 1); + $listIndex = $this->pclzipLocateName($filename); + $extracted = $zip->extractByIndex($listIndex, PCLZIP_OPT_EXTRACT_AS_STRING); + } + if ((is_array($extracted)) && ($extracted != 0)) { + $contents = $extracted[0]["content"]; + } + + return $contents; + } + + /** + * Returns the name of an entry using its index (emulate \ZipArchive) + * + * @param int $index + * @return string + * @since 0.10.0 + */ + public function pclzipGetNameIndex($index) + { + /** @var \PclZip $zip Type hint */ + $zip = $this->zip; + $list = $zip->listContent(); + if (isset($list[$index])) { + return $list[$index]['filename']; + } else { + return false; + } + } + /** * Returns the index of the entry in the archive (emulate \ZipArchive) * * @param string $filename Filename for the file in zip archive - * @return integer|false + * @return int */ - public function locateName($filename) + public function pclzipLocateName($filename) { - $list = $this->zip->listContent(); + /** @var \PclZip $zip Type hint */ + $zip = $this->zip; + $list = $zip->listContent(); $listCount = count($list); $listIndex = -1; for ($i = 0; $i < $listCount; ++$i) { @@ -156,81 +373,4 @@ class ZipArchive return ($listIndex > -1) ? $listIndex : false; } - - /** - * Extract file from archive by given file name (emulate \ZipArchive) - * - * @param string $filename Filename for the file in zip archive - * @return string|false $contents File string contents - */ - public function getFromName($filename) - { - $listIndex = $this->locateName($filename); - $contents = false; - - if ($listIndex !== false) { - $extracted = $this->zip->extractByIndex($listIndex, PCLZIP_OPT_EXTRACT_AS_STRING); - } else { - $filename = substr($filename, 1); - $listIndex = $this->locateName($filename); - $extracted = $this->zip->extractByIndex($listIndex, PCLZIP_OPT_EXTRACT_AS_STRING); - } - if ((is_array($extracted)) && ($extracted != 0)) { - $contents = $extracted[0]["content"]; - } - - return $contents; - } - - /** - * Returns the name of an entry using its index (emulate \ZipArchive) - * - * @param integer $index - * @return string|false - * @since 0.10.0 - */ - public function getNameIndex($index) - { - $list = $this->zip->listContent(); - if (isset($list[$index])) { - return $list[$index]['filename']; - } else { - return false; - } - } - - /** - * Extract the archive contents (emulate \ZipArchive) - * - * @param string $destination - * @param string|array $entries - * @return boolean - * @since 0.10.0 - */ - public function extractTo($destination, $entries = null) - { - if (!is_dir($destination)) { - return false; - } - - // Extract all files - if (is_null($entries)) { - $result = $this->zip->extract(PCLZIP_OPT_PATH, $destination); - return ($result > 0) ? true : false; - } - - // Extract by entries - if (!is_array($entries)) { - $entries = array($entries); - } - foreach ($entries as $entry) { - $entryIndex = $this->locateName($entry); - $result = $this->zip->extractByIndex($entryIndex, PCLZIP_OPT_PATH, $destination); - if ($result <= 0) { - return false; - } - } - - return true; - } } diff --git a/src/PhpWord/Style.php b/src/PhpWord/Style.php index 85743a22..d56c73fe 100644 --- a/src/PhpWord/Style.php +++ b/src/PhpWord/Style.php @@ -1,18 +1,27 @@ $value) { - $styleObject->setStyleValue($key, $value); + if (!array_key_exists($name, self::$styles)) { + if ($value !== null) { + if (is_array($value)) { + $style->setStyleByArray($value); + } elseif ($value instanceof AbstractStyle) { + if (get_class($style) == get_class($value)) { + $style = $value; + } } } - $styleObject->setStyleName($styleName); - $styleObject->setIndex(self::countStyles() + 1); // One based index - self::$styles[$styleName] = $styleObject; + $style->setStyleName($name); + $style->setIndex(self::countStyles() + 1); // One based index + self::$styles[$name] = $style; } + + return self::getStyle($name); } } diff --git a/src/PhpWord/Style/AbstractStyle.php b/src/PhpWord/Style/AbstractStyle.php index c498575a..13ef8f9b 100644 --- a/src/PhpWord/Style/AbstractStyle.php +++ b/src/PhpWord/Style/AbstractStyle.php @@ -1,10 +1,18 @@ isAuto; + } + + /** + * Set is automatic style flag + * + * @param bool $value + * @return self + */ + public function setAuto($value = true) + { + $this->isAuto = $this->setBoolVal($value, $this->isAuto); + + return $this; + } + /** * Set style value template method * @@ -94,6 +140,9 @@ abstract class AbstractStyle */ public function setStyleValue($key, $value) { + if (isset($this->aliases[$key])) { + $key = $this->aliases[$key]; + } $method = 'set' . String::removeUnderscorePrefix($key); if (method_exists($this, $method)) { $this->$method($value); @@ -105,12 +154,12 @@ abstract class AbstractStyle /** * Set style by using associative array * - * @param array $styles + * @param array $values * @return self */ - public function setStyleByArray($styles = array()) + public function setStyleByArray($values = array()) { - foreach ($styles as $key => $value) { + foreach ($values as $key => $value) { $this->setStyleValue($key, $value); } @@ -120,13 +169,13 @@ abstract class AbstractStyle /** * Set default for null and empty value * - * @param mixed $value - * @param mixed $default - * @return mixed + * @param string $value (was: mixed) + * @param string $default (was: mixed) + * @return string (was: mixed) */ protected function setNonEmptyVal($value, $default) { - if (is_null($value) || $value == '') { + if ($value === null || $value == '') { $value = $default; } @@ -134,13 +183,13 @@ abstract class AbstractStyle } /** - * Set boolean value + * Set bool value * - * @param mixed $value - * @param boolean|null $default - * @return boolean|null + * @param bool $value + * @param bool $default + * @return bool */ - protected function setBoolVal($value, $default = null) + protected function setBoolVal($value, $default) { if (!is_bool($value)) { $value = $default; @@ -153,8 +202,8 @@ abstract class AbstractStyle * Set numeric value * * @param mixed $value - * @param integer|float|null $default - * @return integer|float|null + * @param int|float|null $default + * @return int|float|null */ protected function setNumericVal($value, $default = null) { @@ -166,14 +215,17 @@ abstract class AbstractStyle } /** - * Set integer value + * Set integer value: Convert string that contains only numeric into integer * - * @param mixed $value - * @param integer|null $default - * @return integer|null + * @param int|null $value + * @param int|null $default + * @return int|null */ protected function setIntVal($value, $default = null) { + if (is_string($value) && (preg_match('/[^\d]/', $value) == 0)) { + $value = intval($value); + } if (!is_int($value)) { $value = $default; } @@ -182,7 +234,7 @@ abstract class AbstractStyle } /** - * Set float value + * Set float value: Convert string that contains only numeric into float * * @param mixed $value * @param float|null $default @@ -190,7 +242,10 @@ abstract class AbstractStyle */ protected function setFloatVal($value, $default = null) { - if (!is_float($value)) { + if (is_string($value) && (preg_match('/[^\d\.\,]/', $value) == 0)) { + $value = floatval($value); + } + if (!is_numeric($value)) { $value = $default; } @@ -203,13 +258,54 @@ abstract class AbstractStyle * @param mixed $value * @param array $enum * @param mixed $default + * @return mixed + * @throws \InvalidArgumentException */ - protected function setEnumVal($value, $enum, $default = null) + protected function setEnumVal($value = null, $enum = array(), $default = null) { - if (!in_array($value, $enum)) { + if ($value != null && trim($value) != '' && !empty($enum) && !in_array($value, $enum)) { + throw new \InvalidArgumentException('Invalid style value.'); + } elseif ($value === null || trim($value) == '') { $value = $default; } return $value; } + + /** + * Set object value + * + * @param mixed $value + * @param string $styleName + * @param mixed $style + * @return mixed + */ + protected function setObjectVal($value, $styleName, &$style) + { + $styleClass = substr(get_class($this), 0, strrpos(get_class($this), '\\')) . '\\' . $styleName; + if (is_array($value)) { + /** @var \PhpOffice\PhpWord\Style\AbstractStyle $style Type hint */ + if (!$style instanceof $styleClass) { + $style = new $styleClass(); + } + $style->setStyleByArray($value); + } else { + $style = $value; + } + + return $style; + } + + /** + * Set style using associative array + * + * @param array $style + * @return self + * @deprecated 0.11.0 + * @codeCoverageIgnore + */ + public function setArrayStyle(array $style = array()) + { + return $this->setStyleByArray($style); + } } diff --git a/src/PhpWord/Style/Alignment.php b/src/PhpWord/Style/Alignment.php new file mode 100644 index 00000000..3beabe37 --- /dev/null +++ b/src/PhpWord/Style/Alignment.php @@ -0,0 +1,78 @@ +setStyleByArray($style); + } + + /** + * Get alignment + * + * @return string + */ + public function getValue() + { + return $this->value; + } + + /** + * Set alignment + * + * @param string $value + * @return self + */ + public function setValue($value = null) + { + if (strtolower($value) == self::ALIGN_JUSTIFY) { + $value = self::ALIGN_BOTH; + } + $enum = array(self::ALIGN_LEFT, self::ALIGN_RIGHT, self::ALIGN_CENTER, self::ALIGN_BOTH, self::ALIGN_JUSTIFY); + $this->value = $this->setEnumVal($value, $enum, $this->value); + + return $this; + } +} diff --git a/src/PhpWord/Style/Border.php b/src/PhpWord/Style/Border.php index 13230863..84116d7a 100644 --- a/src/PhpWord/Style/Border.php +++ b/src/PhpWord/Style/Border.php @@ -1,10 +1,18 @@ setBorderTopSize($value); - $this->setBorderLeftSize($value); - $this->setBorderRightSize($value); - $this->setBorderBottomSize($value); - - return $this; - } - /** * Get border size * - * @return int[] + * @return integer[] */ public function getBorderSize() { @@ -102,17 +94,17 @@ class Border extends AbstractStyle } /** - * Set border color + * Set border size * - * @param string $value + * @param int|float $value * @return self */ - public function setBorderColor($value = null) + public function setBorderSize($value = null) { - $this->setBorderTopColor($value); - $this->setBorderLeftColor($value); - $this->setBorderRightColor($value); - $this->setBorderBottomColor($value); + $this->setBorderTopSize($value); + $this->setBorderLeftSize($value); + $this->setBorderRightSize($value); + $this->setBorderBottomSize($value); return $this; } @@ -133,14 +125,17 @@ class Border extends AbstractStyle } /** - * Set border top size + * Set border color * - * @param int|float $value + * @param string $value * @return self */ - public function setBorderTopSize($value = null) + public function setBorderColor($value = null) { - $this->borderTopSize = $value; + $this->setBorderTopColor($value); + $this->setBorderLeftColor($value); + $this->setBorderRightColor($value); + $this->setBorderBottomColor($value); return $this; } @@ -155,6 +150,29 @@ class Border extends AbstractStyle return $this->borderTopSize; } + /** + * Set border top size + * + * @param int|float $value + * @return self + */ + public function setBorderTopSize($value = null) + { + $this->borderTopSize = $this->setNumericVal($value, $this->borderTopSize); + + return $this; + } + + /** + * Get border top color + * + * @return string + */ + public function getBorderTopColor() + { + return $this->borderTopColor; + } + /** * Set border top color * @@ -169,13 +187,13 @@ class Border extends AbstractStyle } /** - * Get border top color + * Get border left size * - * @return string + * @return int|float */ - public function getBorderTopColor() + public function getBorderLeftSize() { - return $this->borderTopColor; + return $this->borderLeftSize; } /** @@ -186,19 +204,19 @@ class Border extends AbstractStyle */ public function setBorderLeftSize($value = null) { - $this->borderLeftSize = $value; + $this->borderLeftSize = $this->setNumericVal($value, $this->borderLeftSize); return $this; } /** - * Get border left size + * Get border left color * - * @return int|float + * @return string */ - public function getBorderLeftSize() + public function getBorderLeftColor() { - return $this->borderLeftSize; + return $this->borderLeftColor; } /** @@ -215,13 +233,13 @@ class Border extends AbstractStyle } /** - * Get border left color + * Get border right size * - * @return string + * @return int|float */ - public function getBorderLeftColor() + public function getBorderRightSize() { - return $this->borderLeftColor; + return $this->borderRightSize; } /** @@ -232,19 +250,19 @@ class Border extends AbstractStyle */ public function setBorderRightSize($value = null) { - $this->borderRightSize = $value; + $this->borderRightSize = $this->setNumericVal($value, $this->borderRightSize); return $this; } /** - * Get border right size + * Get border right color * - * @return int|float + * @return string */ - public function getBorderRightSize() + public function getBorderRightColor() { - return $this->borderRightSize; + return $this->borderRightColor; } /** @@ -261,13 +279,13 @@ class Border extends AbstractStyle } /** - * Get border right color + * Get border bottom size * - * @return string + * @return int|float */ - public function getBorderRightColor() + public function getBorderBottomSize() { - return $this->borderRightColor; + return $this->borderBottomSize; } /** @@ -278,19 +296,19 @@ class Border extends AbstractStyle */ public function setBorderBottomSize($value = null) { - $this->borderBottomSize = $value; + $this->borderBottomSize = $this->setNumericVal($value, $this->borderBottomSize); return $this; } /** - * Get border bottom size + * Get border bottom color * - * @return int|float + * @return string */ - public function getBorderBottomSize() + public function getBorderBottomColor() { - return $this->borderBottomSize; + return $this->borderBottomColor; } /** @@ -307,12 +325,14 @@ class Border extends AbstractStyle } /** - * Get border bottom color + * Check if any of the border is not null * - * @return string + * @return bool */ - public function getBorderBottomColor() + public function hasBorder() { - return $this->borderBottomColor; + $borders = $this->getBorderSize(); + + return $borders !== array_filter($borders, 'is_null'); } } diff --git a/src/PhpWord/Style/Cell.php b/src/PhpWord/Style/Cell.php index d7597e0e..2d1b88d0 100644 --- a/src/PhpWord/Style/Cell.php +++ b/src/PhpWord/Style/Cell.php @@ -1,21 +1,37 @@ valign; + return $this->vAlign; } /** * Set vertical align * * @param string $value + * @return self */ public function setVAlign($value = null) { - $this->valign = $value; + $enum = array(self::VALIGN_TOP, self::VALIGN_CENTER, self::VALIGN_BOTTOM, self::VALIGN_BOTH); + $this->vAlign = $this->setEnumVal($value, $enum, $this->vAlign); + + return $this; } /** @@ -99,10 +127,14 @@ class Cell extends Border * Set text direction * * @param string $value + * @return self */ public function setTextDirection($value = null) { - $this->textDirection = $value; + $enum = array(self::TEXT_DIR_BTLR, self::TEXT_DIR_TBRL); + $this->textDirection = $this->setEnumVal($value, $enum, $this->textDirection); + + return $this; } /** @@ -112,8 +144,10 @@ class Cell extends Border */ public function getBgColor() { - if (!is_null($this->shading)) { + if ($this->shading !== null) { return $this->shading->getFill(); + } else { + return null; } } @@ -128,16 +162,6 @@ class Cell extends Border return $this->setShading(array('fill' => $value)); } - /** - * Set grid span (colspan) - * - * @param int $value - */ - public function setGridSpan($value = null) - { - $this->gridSpan = $value; - } - /** * Get grid span (colspan) */ @@ -147,13 +171,16 @@ class Cell extends Border } /** - * Set vertical merge (rowspan) + * Set grid span (colspan) * - * @param string $value + * @param int $value + * @return self */ - public function setVMerge($value = null) + public function setGridSpan($value = null) { - $this->vMerge = $value; + $this->gridSpan = $this->setIntVal($value, $this->gridSpan); + + return $this; } /** @@ -164,6 +191,20 @@ class Cell extends Border return $this->vMerge; } + /** + * Set vertical merge (rowspan) + * + * @param string $value + * @return self + */ + public function setVMerge($value = null) + { + $enum = array(self::VMERGE_RESTART, self::VMERGE_CONTINUE); + $this->vMerge = $this->setEnumVal($value, $enum, $this->vMerge); + + return $this; + } + /** * Get shading * @@ -177,19 +218,12 @@ class Cell extends Border /** * Set shading * - * @param array $value + * @param mixed $value * @return self */ public function setShading($value = null) { - if (is_array($value)) { - if (!$this->shading instanceof Shading) { - $this->shading = new Shading(); - } - $this->shading->setStyleByArray($value); - } else { - $this->shading = null; - } + $this->setObjectVal($value, 'Shading', $this->shading); return $this; } diff --git a/src/PhpWord/Style/Font.php b/src/PhpWord/Style/Font.php index 86467d02..0775b8b3 100644 --- a/src/PhpWord/Style/Font.php +++ b/src/PhpWord/Style/Font.php @@ -1,18 +1,22 @@ 'lineHeight'); + /** * Font style type * @@ -70,26 +81,33 @@ class Font extends AbstractStyle */ private $type; - /** - * Paragraph style - * - * @var \PhpOffice\PhpWord\Style\Paragraph - */ - private $paragraphStyle; - /** * Font name * - * @var int|float + * @var string */ - private $name = PhpWord::DEFAULT_FONT_NAME; + private $name; + + /** + * Font Content Type + * + * @var string + */ + private $hint; /** * Font size * * @var int|float */ - private $size = PhpWord::DEFAULT_FONT_SIZE; + private $size; + + /** + * Font color + * + * @var string + */ + private $color; /** * Bold @@ -105,6 +123,13 @@ class Font extends AbstractStyle */ private $italic = false; + /** + * Undeline + * + * @var string + */ + private $underline = self::UNDERLINE_NONE; + /** * Superscript * @@ -119,13 +144,6 @@ class Font extends AbstractStyle */ private $subScript = false; - /** - * Undeline - * - * @var string - */ - private $underline = self::UNDERLINE_NONE; - /** * Strikethrough * @@ -140,40 +158,6 @@ class Font extends AbstractStyle */ private $doubleStrikethrough = false; - /** - * Font color - * - * @var string - */ - private $color = PhpWord::DEFAULT_FONT_COLOR; - - /** - * Foreground/highlight - * - * @var string - */ - private $fgColor = null; - - /** - * Text line height - * - * @var int - */ - - /** - * Text line height - * - * @var int - */ - private $lineHeight = 1.0; - - /** - * Font Content Type - * - * @var string - */ - private $hint = PhpWord::DEFAULT_FONT_CONTENT_TYPE; - /** * Small caps * @@ -190,6 +174,26 @@ class Font extends AbstractStyle */ private $allCaps = false; + /** + * Foreground/highlight + * + * @var string + */ + private $fgColor; + + /** + * Text line height + * + * @var int + */ + + /** + * Paragraph style + * + * @var \PhpOffice\PhpWord\Style\Paragraph + */ + private $paragraph; + /** * Shading * @@ -201,39 +205,22 @@ class Font extends AbstractStyle * Create new font style * * @param string $type Type of font - * @param array $paragraphStyle Paragraph styles definition + * @param array $paragraph Paragraph styles definition */ - public function __construct($type = 'text', $paragraphStyle = null) + public function __construct($type = 'text', $paragraph = null) { $this->type = $type; - - if ($paragraphStyle instanceof Paragraph) { - $this->paragraphStyle = $paragraphStyle; - } elseif (is_array($paragraphStyle)) { - $this->paragraphStyle = new Paragraph; - $this->paragraphStyle->setArrayStyle($paragraphStyle); - } else { - $this->paragraphStyle = $paragraphStyle; - } + $this->setParagraph($paragraph); } /** - * Set style using associative array + * Get style type * - * @param array $style - * @return $this + * @return string */ - public function setArrayStyle(array $style = array()) + public function getStyleType() { - foreach ($style as $key => $value) { - if ($key === 'line-height') { - $this->setLineHeight($value); - null; - } - $this->setStyleValue($key, $value); - } - - return $this; + return $this->type; } /** @@ -252,13 +239,35 @@ class Font extends AbstractStyle * @param string $value * @return self */ - public function setName($value = PhpWord::DEFAULT_FONT_NAME) + public function setName($value = null) { - $this->name = $this->setNonEmptyVal($value, PhpWord::DEFAULT_FONT_NAME); + $this->name = $value; return $this; } + /** + * Get Font Content Type + * + * @return string + */ + public function getHint() + { + return $this->hint; + } + + /** + * Set Font Content Type + * + * @param string $value + * @return self + */ + public function setHint($value = null) + { + $this->hint = $value; + + return $this; + } /** * Get font size @@ -276,9 +285,32 @@ class Font extends AbstractStyle * @param int|float $value * @return self */ - public function setSize($value = PhpWord::DEFAULT_FONT_SIZE) + public function setSize($value = null) { - $this->size = $this->setNumericVal($value, PhpWord::DEFAULT_FONT_SIZE); + $this->size = $this->setNumericVal($value, $this->size); + + return $this; + } + + /** + * Get font color + * + * @return string + */ + public function getColor() + { + return $this->color; + } + + /** + * Set font color + * + * @param string $value + * @return self + */ + public function setColor($value = null) + { + $this->color = $value; return $this; } @@ -288,7 +320,7 @@ class Font extends AbstractStyle * * @return bool */ - public function getBold() + public function isBold() { return $this->bold; } @@ -299,7 +331,7 @@ class Font extends AbstractStyle * @param bool $value * @return self */ - public function setBold($value = false) + public function setBold($value = true) { $this->bold = $this->setBoolVal($value, $this->bold); @@ -311,7 +343,7 @@ class Font extends AbstractStyle * * @return bool */ - public function getItalic() + public function isItalic() { return $this->italic; } @@ -322,65 +354,13 @@ class Font extends AbstractStyle * @param bool $value * @return self */ - public function setItalic($value = false) + public function setItalic($value = true) { $this->italic = $this->setBoolVal($value, $this->italic); return $this; } - /** - * Get superscript - * - * @return bool - */ - public function getSuperScript() - { - return $this->superScript; - } - - /** - * Set superscript - * - * @param bool $value - * @return self - */ - public function setSuperScript($value = false) - { - $this->superScript = $this->setBoolVal($value, $this->superScript); - if ($this->superScript) { - $this->subScript = false; - } - - return $this; - } - - /** - * Get subscript - * - * @return bool - */ - public function getSubScript() - { - return $this->subScript; - } - - /** - * Set subscript - * - * @param bool $value - * @return self - */ - public function setSubScript($value = false) - { - $this->subScript = $this->setBoolVal($value, $this->subScript); - if ($this->subScript) { - $this->superScript = false; - } - - return $this; - } - /** * Get underline * @@ -404,12 +384,54 @@ class Font extends AbstractStyle return $this; } + /** + * Get superscript + * + * @return bool + */ + public function isSuperScript() + { + return $this->superScript; + } + + /** + * Set superscript + * + * @param bool $value + * @return self + */ + public function setSuperScript($value = true) + { + return $this->setPairedProperty($this->superScript, $this->subScript, $value); + } + + /** + * Get subscript + * + * @return bool + */ + public function isSubScript() + { + return $this->subScript; + } + + /** + * Set subscript + * + * @param bool $value + * @return self + */ + public function setSubScript($value = true) + { + return $this->setPairedProperty($this->subScript, $this->superScript, $value); + } + /** * Get strikethrough * * @return bool */ - public function getStrikethrough() + public function isStrikethrough() { return $this->strikethrough; } @@ -420,14 +442,9 @@ class Font extends AbstractStyle * @param bool $value * @return self */ - public function setStrikethrough($value = false) + public function setStrikethrough($value = true) { - $this->strikethrough = $this->setBoolVal($value, $this->strikethrough); - if ($this->strikethrough) { - $this->doubleStrikethrough = false; - } - - return $this; + return $this->setPairedProperty($this->strikethrough, $this->doubleStrikethrough, $value); } /** @@ -435,7 +452,7 @@ class Font extends AbstractStyle * * @return bool */ - public function getDoubleStrikethrough() + public function isDoubleStrikethrough() { return $this->doubleStrikethrough; } @@ -446,37 +463,51 @@ class Font extends AbstractStyle * @param bool $value * @return self */ - public function setDoubleStrikethrough($value = false) + public function setDoubleStrikethrough($value = true) { - $this->doubleStrikethrough = $this->setBoolVal($value, $this->doubleStrikethrough); - if ($this->doubleStrikethrough) { - $this->strikethrough = false; - } - - return $this; + return $this->setPairedProperty($this->doubleStrikethrough, $this->strikethrough, $value); } /** - * Get font color + * Get small caps * - * @return string + * @return bool */ - public function getColor() + public function isSmallCaps() { - return $this->color; + return $this->smallCaps; } /** - * Set font color + * Set small caps * - * @param string $value + * @param bool $value * @return self */ - public function setColor($value = PhpWord::DEFAULT_FONT_COLOR) + public function setSmallCaps($value = true) { - $this->color = $this->setNonEmptyVal($value, PhpWord::DEFAULT_FONT_COLOR); + return $this->setPairedProperty($this->smallCaps, $this->allCaps, $value); + } - return $this; + /** + * Get all caps + * + * @return bool + */ + public function isAllCaps() + { + return $this->allCaps; + } + + /** + * Set all caps + * + * @param bool $value + * @return self + */ + public function setAllCaps($value = true) + { + return $this->setPairedProperty($this->allCaps, $this->smallCaps, $value); } /** @@ -509,8 +540,10 @@ class Font extends AbstractStyle */ public function getBgColor() { - if (!is_null($this->shading)) { + if ($this->shading !== null) { return $this->shading->getFill(); + } else { + return null; } } @@ -526,13 +559,26 @@ class Font extends AbstractStyle } /** - * Get style type + * Get line height * - * @return string + * @return int|float */ - public function getStyleType() + public function getLineHeight() { - return $this->type; + return $this->getParagraph()->getLineHeight(); + } + + /** + * Set lineheight + * + * @param int|float|string $value + * @return self + */ + public function setLineHeight($value) + { + $this->setParagraph(array('lineHeight' => $value)); + + return $this; } /** @@ -540,114 +586,20 @@ class Font extends AbstractStyle * * @return \PhpOffice\PhpWord\Style\Paragraph */ - public function getParagraphStyle() + public function getParagraph() { - return $this->paragraphStyle; + return $this->paragraph; } /** - * Set lineheight + * Set shading * - * @param int|float|string $lineHeight - * @return $this - * @throws \PhpOffice\PhpWord\Exception\InvalidStyleException - */ - public function setLineHeight($lineHeight) - { - if (is_string($lineHeight)) { - $lineHeight = floatval(preg_replace('/[^0-9\.\,]/', '', $lineHeight)); - } - - if ((!is_integer($lineHeight) && !is_float($lineHeight)) || !$lineHeight) { - throw new InvalidStyleException('Line height must be a valid number'); - } - - $this->lineHeight = $lineHeight; - $this->getParagraphStyle()->setLineHeight($lineHeight); - return $this; - } - - /** - * Get line height - * - * @return int|float - */ - public function getLineHeight() - { - return $this->lineHeight; - } - - /** - * Get Font Content Type - * - * @return string - */ - public function getHint() - { - return $this->hint; - } - - /** - * Set Font Content Type - * - * @param string $value + * @param mixed $value * @return self */ - public function setHint($value = PhpWord::DEFAULT_FONT_CONTENT_TYPE) + public function setParagraph($value = null) { - $this->hint = $this->setNonEmptyVal($value, PhpWord::DEFAULT_FONT_CONTENT_TYPE); - - return $this; - } - - /** - * Get small caps - * - * @return bool - */ - public function getSmallCaps() - { - return $this->smallCaps; - } - - /** - * Set small caps - * - * @param bool $value - * @return self - */ - public function setSmallCaps($value = false) - { - $this->smallCaps = $this->setBoolVal($value, $this->smallCaps); - if ($this->smallCaps) { - $this->allCaps = false; - } - - return $this; - } - - /** - * Get all caps - * - * @return bool - */ - public function getAllCaps() - { - return $this->allCaps; - } - - /** - * Set all caps - * - * @param bool $value - * @return self - */ - public function setAllCaps($value = false) - { - $this->allCaps = $this->setBoolVal($value, $this->allCaps); - if ($this->allCaps) { - $this->smallCaps = false; - } + $this->setObjectVal($value, 'Paragraph', $this->paragraph); return $this; } @@ -665,20 +617,97 @@ class Font extends AbstractStyle /** * Set shading * - * @param array $value + * @param mixed $value * @return self */ public function setShading($value = null) { - if (is_array($value)) { - if (!$this->shading instanceof Shading) { - $this->shading = new Shading(); - } - $this->shading->setStyleByArray($value); - } else { - $this->shading = null; + $this->setObjectVal($value, 'Shading', $this->shading); + + return $this; + } + + /** + * Set $property value and set $pairProperty = false when $value = true + * + * @param bool $property + * @param bool $pairProperty + * @param bool $value + * @return self + */ + private function setPairedProperty(&$property, &$pairProperty, $value) + { + $property = $this->setBoolVal($value, $property); + if ($value == true) { + $pairProperty = false; } return $this; } + + /** + * Get bold + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getBold() + { + return $this->isBold(); + } + + /** + * Get italic + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getItalic() + { + return $this->isItalic(); + } + + /** + * Get superscript + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getSuperScript() + { + return $this->isSuperScript(); + } + + /** + * Get subscript + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getSubScript() + { + return $this->isSubScript(); + } + + /** + * Get strikethrough + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getStrikethrough() + { + return $this->isStrikethrough(); + } + + /** + * Get paragraph style + * + * @deprecated 0.11.0 + * @codeCoverageIgnore + */ + public function getParagraphStyle() + { + return $this->getParagraph(); + } } diff --git a/src/PhpWord/Style/Image.php b/src/PhpWord/Style/Image.php index f21e6674..3798c1a2 100644 --- a/src/PhpWord/Style/Image.php +++ b/src/PhpWord/Style/Image.php @@ -1,12 +1,19 @@ width = null; - $this->height = null; - $this->align = null; - $this->marginTop = null; - $this->marginLeft = null; - $this->setWrappingStyle(self::WRAPPING_STYLE_INLINE); + $this->alignment = new Alignment(); } /** * Get width + * + * @return int */ public function getWidth() { @@ -86,15 +176,20 @@ class Image extends AbstractStyle /** * Set width * - * @param int $pValue + * @param int $value + * @return self */ - public function setWidth($pValue = null) + public function setWidth($value = null) { - $this->width = $pValue; + $this->width = $value; + + return $this; } /** * Get height + * + * @return int */ public function getHeight() { @@ -104,35 +199,43 @@ class Image extends AbstractStyle /** * Set height * - * @param int $pValue + * @param int $value + * @return self */ - public function setHeight($pValue = null) + public function setHeight($value = null) { - $this->height = $pValue; + $this->height = $value; + + return $this; } /** * Get alignment + * + * @return string */ public function getAlign() { - return $this->align; + return $this->alignment->getValue(); } /** * Set alignment * - * @param string $pValue + * @param string $value + * @return self */ - public function setAlign($pValue = null) + public function setAlign($value = null) { - $this->align = $pValue; + $this->alignment->setValue($value); + + return $this; } /** - * Get Margin Top + * Get margin top * - * @return int + * @return int|float */ public function getMarginTop() { @@ -140,21 +243,23 @@ class Image extends AbstractStyle } /** - * Set Margin Top + * Set margin top * - * @param int $pValue - * @return $this + * @ignoreScrutinizerPatch + * @param int|float $value + * @return self */ - public function setMarginTop($pValue = null) + public function setMarginTop($value = 0) { - $this->marginTop = $pValue; + $this->marginTop = $this->setNumericVal($value, 0); + return $this; } /** - * Get Margin Left + * Get margin left * - * @return int + * @return int|float */ public function getMarginLeft() { @@ -162,37 +267,16 @@ class Image extends AbstractStyle } /** - * Set Margin Left + * Set margin left * - * @param int $pValue - * @return $this + * @ignoreScrutinizerPatch + * @param int|float $value + * @return self */ - public function setMarginLeft($pValue = null) + public function setMarginLeft($value = 0) { - $this->marginLeft = $pValue; - return $this; - } + $this->marginLeft = $this->setNumericVal($value, 0); - /** - * Set wrapping style - * - * @param string $wrappingStyle - * @throws \InvalidArgumentException - * @return $this - */ - public function setWrappingStyle($wrappingStyle) - { - switch ($wrappingStyle) { - case self::WRAPPING_STYLE_BEHIND: - case self::WRAPPING_STYLE_INFRONT: - case self::WRAPPING_STYLE_INLINE: - case self::WRAPPING_STYLE_SQUARE: - case self::WRAPPING_STYLE_TIGHT: - $this->wrappingStyle = $wrappingStyle; - break; - default: - throw new \InvalidArgumentException('Wrapping style does not exists'); - } return $this; } @@ -205,4 +289,165 @@ class Image extends AbstractStyle { return $this->wrappingStyle; } + + /** + * Set wrapping style + * + * @param string $wrappingStyle + * @throws \InvalidArgumentException + * @return self + */ + public function setWrappingStyle($wrappingStyle) + { + $enum = array( + self::WRAPPING_STYLE_INLINE, + self::WRAPPING_STYLE_INFRONT, self::WRAPPING_STYLE_BEHIND, + self::WRAPPING_STYLE_SQUARE, self::WRAPPING_STYLE_TIGHT, + ); + $this->wrappingStyle = $this->setEnumVal($wrappingStyle, $enum, $this->wrappingStyle); + + return $this; + } + + /** + * Get positioning type + * + * @return string + */ + public function getPositioning() + { + return $this->positioning; + } + + /** + * Set positioning type + * + * @param string $positioning + * @throws \InvalidArgumentException + * @return self + */ + public function setPositioning($positioning) + { + $enum = array(self::POSITION_RELATIVE, self::POSITION_ABSOLUTE); + $this->positioning = $this->setEnumVal($positioning, $enum, $this->positioning); + + return $this; + } + + /** + * Get horizontal alignment + * + * @return string + */ + public function getPosHorizontal() + { + return $this->posHorizontal; + } + + /** + * Set horizontal alignment + * + * @param string $alignment + * @throws \InvalidArgumentException + * @return self + */ + public function setPosHorizontal($alignment) + { + $enum = array( + self::POSITION_HORIZONTAL_LEFT, self::POSITION_HORIZONTAL_CENTER, + self::POSITION_HORIZONTAL_RIGHT, self::POSITION_ABSOLUTE + ); + $this->posHorizontal = $this->setEnumVal($alignment, $enum, $this->posHorizontal); + + return $this; + } + + /** + * Get vertical alignment + * + * @return string + */ + public function getPosVertical() + { + return $this->posVertical; + } + + /** + * Set vertical alignment + * + * @param string $alignment + * @throws \InvalidArgumentException + * @return self + */ + public function setPosVertical($alignment) + { + $enum = array( + self::POSITION_VERTICAL_TOP, self::POSITION_VERTICAL_CENTER, + self::POSITION_VERTICAL_BOTTOM, self::POSITION_VERTICAL_INSIDE, + self::POSITION_VERTICAL_OUTSIDE, self::POSITION_ABSOLUTE + ); + $this->posVertical = $this->setEnumVal($alignment, $enum, $this->posVertical); + + return $this; + } + + /** + * Get horizontal relation + * + * @return string + */ + public function getPosHorizontalRel() + { + return $this->posHorizontalRel; + } + + /** + * Set horizontal relation + * + * @param string $relto + * @throws \InvalidArgumentException + * @return self + */ + public function setPosHorizontalRel($relto) + { + $enum = array( + self::POSITION_RELATIVE_TO_MARGIN, self::POSITION_RELATIVE_TO_PAGE, + self::POSITION_RELATIVE_TO_COLUMN, self::POSITION_RELATIVE_TO_CHAR, + self::POSITION_RELATIVE_TO_LMARGIN, self::POSITION_RELATIVE_TO_RMARGIN, + self::POSITION_RELATIVE_TO_IMARGIN, self::POSITION_RELATIVE_TO_OMARGIN, + ); + $this->posHorizontalRel = $this->setEnumVal($relto, $enum, $this->posHorizontalRel); + + return $this; + } + + /** + * Get vertical relation + * + * @return string + */ + public function getPosVerticalRel() + { + return $this->posVerticalRel; + } + + /** + * Set vertical relation + * + * @param string $relto + * @throws \InvalidArgumentException + * @return self + */ + public function setPosVerticalRel($relto) + { + $enum = array( + self::POSITION_RELATIVE_TO_MARGIN, self::POSITION_RELATIVE_TO_PAGE, + self::POSITION_RELATIVE_TO_TEXT, self::POSITION_RELATIVE_TO_LINE, + self::POSITION_RELATIVE_TO_TMARGIN, self::POSITION_RELATIVE_TO_BMARGIN, + self::POSITION_RELATIVE_TO_IMARGIN, self::POSITION_RELATIVE_TO_OMARGIN, + ); + $this->posVerticalRel = $this->setEnumVal($relto, $enum, $this->posVerticalRel); + + return $this; + } } diff --git a/src/PhpWord/Style/Indentation.php b/src/PhpWord/Style/Indentation.php index bda2c9ad..5854204a 100644 --- a/src/PhpWord/Style/Indentation.php +++ b/src/PhpWord/Style/Indentation.php @@ -1,10 +1,18 @@ flip; + } + + /** + * Set flip + * + * @param boolean $value + * @return self + */ + public function setFlip($value = false) + { + $this->flip = $this->setBoolVal($value, $this->flip); + + return $this; + } + + /** + * Get connectorType + * + * @return string + */ + public function getConnectorType() + { + return $this->connectorType; + } + + /** + * Set connectorType + * + * @param string $value + * @return self + */ + public function setConnectorType($value = null) + { + $enum = array( + self::CONNECTOR_TYPE_STRAIGHT + ); + $this->connectorType = $this->setEnumVal($value, $enum, $this->connectorType); + + return $this; + } + + /** + * Get weight + * + * @return int + */ + public function getWeight() + { + return $this->weight; + } + + /** + * Set weight + * + * @param int $value Weight in points + * @return self + */ + public function setWeight($value = null) + { + $this->weight = $this->setNumericVal($value, $this->weight); + + return $this; + } + + /** + * Get color + * + * @return string + */ + public function getColor() + { + return $this->color; + } + + /** + * Set color + * + * @param string $value + * @return self + */ + public function setColor($value = null) + { + $this->color = $value; + + return $this; + } + + /** + * Get beginArrow + * + * @return string + */ + public function getBeginArrow() + { + return $this->beginArrow; + } + + /** + * Set beginArrow + * + * @param string $value + * @return self + */ + public function setBeginArrow($value = null) + { + $enum = array( + self::ARROW_STYLE_BLOCK, self::ARROW_STYLE_CLASSIC, self::ARROW_STYLE_DIAMOND, + self::ARROW_STYLE_OPEN, self::ARROW_STYLE_OVAL + ); + $this->beginArrow = $this->setEnumVal($value, $enum, $this->beginArrow); + + return $this; + } + + /** + * Get endArrow + * + * @return string + */ + public function getEndArrow() + { + return $this->endArrow; + } + + /** + * Set endArrow + * + * @param string $value + * @return self + */ + public function setEndArrow($value = null) + { + $enum = array( + self::ARROW_STYLE_BLOCK, self::ARROW_STYLE_CLASSIC, self::ARROW_STYLE_DIAMOND, + self::ARROW_STYLE_OPEN, self::ARROW_STYLE_OVAL + ); + $this->endArrow = $this->setEnumVal($value, $enum, $this->endArrow); + + return $this; + } + + /** + * Get Dash + * + * @return string + */ + public function getDash() + { + return $this->dash; + } + + /** + * Set Dash + * + * @param string $value + * @return self + */ + public function setDash($value = null) + { + $enum = array( + self::DASH_STYLE_DASH, self::DASH_STYLE_DASH_DOT, self::DASH_STYLE_LONG_DASH, + self::DASH_STYLE_LONG_DASH_DOT, self::DASH_STYLE_LONG_DASH_DOT_DOT, self::DASH_STYLE_ROUND_DOT, + self::DASH_STYLE_SQUARE_DOT + ); + $this->dash = $this->setEnumVal($value, $enum, $this->dash); + + return $this; + } +} diff --git a/src/PhpWord/Style/LineNumbering.php b/src/PhpWord/Style/LineNumbering.php index 384d5d42..b93ce03f 100644 --- a/src/PhpWord/Style/LineNumbering.php +++ b/src/PhpWord/Style/LineNumbering.php @@ -1,10 +1,18 @@ setNumStyle($numStyle); } else { $this->setListType(); @@ -78,14 +86,19 @@ class ListItem extends AbstractStyle * Set legacy list type for version < 0.10.0 * * @param integer $value + * @return self */ public function setListType($value = self::TYPE_BULLET_FILLED) { - $enum = array(self::TYPE_SQUARE_FILLED, self::TYPE_BULLET_FILLED, + $enum = array( + self::TYPE_SQUARE_FILLED, self::TYPE_BULLET_FILLED, self::TYPE_BULLET_EMPTY, self::TYPE_NUMBER, - self::TYPE_NUMBER_NESTED, self::TYPE_ALPHANUM); + self::TYPE_NUMBER_NESTED, self::TYPE_ALPHANUM + ); $this->listType = $this->setEnumVal($value, $enum, $this->listType); $this->getListTypeStyle(); + + return $this; } /** @@ -102,6 +115,7 @@ class ListItem extends AbstractStyle * Set numbering style name * * @param string $value + * @return self */ public function setNumStyle($value) { @@ -111,6 +125,8 @@ class ListItem extends AbstractStyle $this->numId = $numStyleObject->getIndex(); $numStyleObject->setNumId($this->numId); } + + return $this; } /** @@ -133,7 +149,7 @@ class ListItem extends AbstractStyle { // Check if legacy style already registered in global Style collection $numStyle = "PHPWordList{$this->listType}"; - if (!is_null(Style::getStyle($numStyle))) { + if (Style::getStyle($numStyle) !== null) { $this->setNumStyle($numStyle); return; } diff --git a/src/PhpWord/Style/Numbering.php b/src/PhpWord/Style/Numbering.php index 8c2e4a69..726af2be 100644 --- a/src/PhpWord/Style/Numbering.php +++ b/src/PhpWord/Style/Numbering.php @@ -1,16 +1,22 @@ numId = $this->setIntVal($value, $this->numId); + return $this; } @@ -86,6 +93,7 @@ class Numbering extends AbstractStyle { $enum = array('singleLevel', 'multilevel', 'hybridMultilevel'); $this->type = $this->setEnumVal($value, $enum, $this->type); + return $this; } diff --git a/src/PhpWord/Style/NumberingLevel.php b/src/PhpWord/Style/NumberingLevel.php index dff7de22..32e61c89 100644 --- a/src/PhpWord/Style/NumberingLevel.php +++ b/src/PhpWord/Style/NumberingLevel.php @@ -1,10 +1,18 @@ pStyle; + } + + /** + * Set related paragraph style + * + * @param string $value + * @return self + */ + public function setPStyle($value) + { + $this->pStyle = $value; + return $this; + } + /** * Get suffix * @@ -369,10 +407,11 @@ class NumberingLevel extends AbstractStyle * @param string $value * @return self */ - public function setHint($value) + public function setHint($value = null) { $enum = array('default', 'eastAsia', 'cs'); $this->hint = $this->setEnumVal($value, $enum, $this->hint); + return $this; } } diff --git a/src/PhpWord/Style/Paragraph.php b/src/PhpWord/Style/Paragraph.php index b6f482bf..81673586 100644 --- a/src/PhpWord/Style/Paragraph.php +++ b/src/PhpWord/Style/Paragraph.php @@ -1,46 +1,65 @@ 'lineHeight'); /** * Parent style @@ -56,6 +75,34 @@ class Paragraph extends AbstractStyle */ private $next; + /** + * Alignment + * + * @var \PhpOffice\PhpWord\Style\Alignment + */ + private $alignment; + + /** + * Indentation + * + * @var \PhpOffice\PhpWord\Style\Indentation + */ + private $indentation; + + /** + * Spacing + * + * @var \PhpOffice\PhpWord\Style\Spacing + */ + private $spacing; + + /** + * Text line height + * + * @var int + */ + private $lineHeight; + /** * Allow first/last line to display on a separate page * @@ -85,35 +132,32 @@ class Paragraph extends AbstractStyle private $pageBreakBefore = false; /** - * Indentation + * Numbering style name * - * @var \PhpOffice\PhpWord\Style\Indentation + * @var string */ - private $indentation; + private $numStyle; /** - * Spacing + * Numbering level * - * @var \PhpOffice\PhpWord\Style\Spacing + * @var int */ - private $spacing; + private $numLevel = 0; /** - * Set style by array + * Set of Custom Tab Stops * - * @param array $style - * @return $this + * @var \PhpOffice\PhpWord\Style\Tab[] */ - public function setArrayStyle(array $style = array()) + private $tabs = array(); + + /** + * Create new instance + */ + public function __construct() { - foreach ($style as $key => $value) { - if ($key === 'line-height') { - null; - } - $this->setStyleValue($key, $value); - } - - return $this; + $this->alignment = new Alignment(); } /** @@ -121,6 +165,7 @@ class Paragraph extends AbstractStyle * * @param string $key * @param mixed $value + * @return self */ public function setStyleValue($key, $value) { @@ -129,39 +174,210 @@ class Paragraph extends AbstractStyle $value = $value * 720; } elseif ($key == 'spacing') { $value += 240; // because line height of 1 matches 240 twips - } elseif ($key === 'line-height') { - $this->setLineHeight($value); - return; - } - $method = 'set' . $key; - if (method_exists($this, $method)) { - $this->$method($value); } + + return parent::setStyleValue($key, $value); } /** - * Get Paragraph Alignment + * Get style values + * + * An experiment to retrieve all style values in one function. This will + * reduce function call and increase cohesion between functions. Should be + * implemented in all styles. + * + * @ignoreScrutinizerPatch + * @return array + */ + public function getStyleValues() + { + $styles = array( + 'name' => $this->getStyleName(), + 'basedOn' => $this->getBasedOn(), + 'next' => $this->getNext(), + 'alignment' => $this->getAlign(), + 'indentation' => $this->getIndentation(), + 'spacing' => $this->getSpace(), + 'pagination' => array( + 'widowControl' => $this->hasWidowControl(), + 'keepNext' => $this->isKeepNext(), + 'keepLines' => $this->isKeepLines(), + 'pageBreak' => $this->hasPageBreakBefore(), + ), + 'numbering' => array( + 'style' => $this->getNumStyle(), + 'level' => $this->getNumLevel(), + ), + 'tabs' => $this->getTabs(), + ); + + return $styles; + } + + /** + * Get alignment * * @return string */ public function getAlign() { - return $this->align; + return $this->alignment->getValue(); } /** - * Set Paragraph Alignment + * Set alignment * * @param string $value * @return self */ public function setAlign($value = null) { - if (strtolower($value) == 'justify') { - // justify becames both - $value = 'both'; + $this->alignment->setValue($value); + + return $this; + } + + /** + * Get parent style ID + * + * @return string + */ + public function getBasedOn() + { + return $this->basedOn; + } + + /** + * Set parent style ID + * + * @param string $value + * @return self + */ + public function setBasedOn($value = 'Normal') + { + $this->basedOn = $value; + + return $this; + } + + /** + * Get style for next paragraph + * + * @return string + */ + public function getNext() + { + return $this->next; + } + + /** + * Set style for next paragraph + * + * @param string $value + * @return self + */ + public function setNext($value = null) + { + $this->next = $value; + + return $this; + } + + /** + * Get shading + * + * @return \PhpOffice\PhpWord\Style\Indentation + */ + public function getIndentation() + { + return $this->indentation; + } + + /** + * Set shading + * + * @param mixed $value + * @return self + */ + public function setIndentation($value = null) + { + $this->setObjectVal($value, 'Indentation', $this->indentation); + + return $this; + } + + /** + * Get indentation + * + * @return int + */ + public function getIndent() + { + if ($this->indentation !== null) { + return $this->indentation->getLeft(); + } else { + return null; } - $this->align = $value; + } + + /** + * Set indentation + * + * @param int $value + * @return self + */ + public function setIndent($value = null) + { + return $this->setIndentation(array('left' => $value)); + } + + /** + * Get hanging + * + * @return int + */ + public function getHanging() + { + if ($this->indentation !== null) { + return $this->indentation->getHanging(); + } else { + return null; + } + } + + /** + * Set hanging + * + * @param int $value + * @return self + */ + public function setHanging($value = null) + { + return $this->setIndentation(array('hanging' => $value)); + } + + /** + * Get spacing + * + * @return \PhpOffice\PhpWord\Style\Spacing + * @todo Rename to getSpacing in 1.0 + */ + public function getSpace() + { + return $this->spacing; + } + + /** + * Set spacing + * + * @param mixed $value + * @return self + * @todo Rename to setSpacing in 1.0 + */ + public function setSpace($value = null) + { + $this->setObjectVal($value, 'Spacing', $this->spacing); + return $this; } @@ -172,8 +388,10 @@ class Paragraph extends AbstractStyle */ public function getSpaceBefore() { - if (!is_null($this->spacing)) { + if ($this->spacing !== null) { return $this->spacing->getBefore(); + } else { + return null; } } @@ -195,8 +413,10 @@ class Paragraph extends AbstractStyle */ public function getSpaceAfter() { - if (!is_null($this->spacing)) { + if ($this->spacing !== null) { return $this->spacing->getAfter(); + } else { + return null; } } @@ -218,8 +438,10 @@ class Paragraph extends AbstractStyle */ public function getSpacing() { - if (!is_null($this->spacing)) { + if ($this->spacing !== null) { return $this->spacing->getLine(); + } else { + return null; } } @@ -248,7 +470,7 @@ class Paragraph extends AbstractStyle * Set the line height * * @param int|float|string $lineHeight - * @return $this + * @return self * @throws \PhpOffice\PhpWord\Exception\InvalidStyleException */ public function setLineHeight($lineHeight) @@ -267,49 +489,141 @@ class Paragraph extends AbstractStyle } /** - * Get indentation + * Get allow first/last line to display on a separate page setting * - * @return int + * @return bool */ - public function getIndent() + public function hasWidowControl() { - if (!is_null($this->indentation)) { - return $this->indentation->getLeft(); - } + return $this->widowControl; } /** - * Set indentation + * Set keep paragraph with next paragraph setting + * + * @param bool $value + * @return self + */ + public function setWidowControl($value = true) + { + $this->widowControl = $this->setBoolVal($value, $this->widowControl); + + return $this; + } + + /** + * Get keep paragraph with next paragraph setting + * + * @return bool + */ + public function isKeepNext() + { + return $this->keepNext; + } + + /** + * Set keep paragraph with next paragraph setting + * + * @param bool $value + * @return self + */ + public function setKeepNext($value = true) + { + $this->keepNext = $this->setBoolVal($value, $this->keepNext); + + return $this; + } + + /** + * Get keep all lines on one page setting + * + * @return bool + */ + public function isKeepLines() + { + return $this->keepLines; + } + + /** + * Set keep all lines on one page setting + * + * @param bool $value + * @return self + */ + public function setKeepLines($value = true) + { + $this->keepLines = $this->setBoolVal($value, $this->keepLines); + + return $this; + } + + /** + * Get start paragraph on next page setting + * + * @return bool + */ + public function hasPageBreakBefore() + { + return $this->pageBreakBefore; + } + + /** + * Set start paragraph on next page setting + * + * @param bool $value + * @return self + */ + public function setPageBreakBefore($value = true) + { + $this->pageBreakBefore = $this->setBoolVal($value, $this->pageBreakBefore); + + return $this; + } + + /** + * Get numbering style name + * + * @return string + */ + public function getNumStyle() + { + return $this->numStyle; + } + + /** + * Set numbering style name + * + * @param string $value + * @return self + */ + public function setNumStyle($value) + { + $this->numStyle = $value; + + return $this; + } + + /** + * Get numbering level + * + * @return int + */ + public function getNumLevel() + { + return $this->numLevel; + } + + /** + * Set numbering level * * @param int $value * @return self */ - public function setIndent($value = null) + public function setNumLevel($value = 0) { - return $this->setIndentation(array('left' => $value)); - } + $this->numLevel = $this->setIntVal($value, $this->numLevel); - /** - * Get hanging - * - * @return int - */ - public function getHanging() - { - if (!is_null($this->indentation)) { - return $this->indentation->getHanging(); - } - } - - /** - * Set hanging - * - * @param int $value - * @return self - */ - public function setHanging($value = null) - { - return $this->setIndentation(array('hanging' => $value)); + return $this; } /** @@ -337,209 +651,47 @@ class Paragraph extends AbstractStyle return $this; } - /** - * Get parent style ID - * - * @return string - */ - public function getBasedOn() - { - return $this->basedOn; - } - - /** - * Set parent style ID - * - * @param string $value - * @return self - */ - public function setBasedOn($value = 'Normal') - { - $this->basedOn = $value; - return $this; - } - - /** - * Get style for next paragraph - * - * @return string - */ - public function getNext() - { - return $this->next; - } - - /** - * Set style for next paragraph - * - * @param string $value - * @return self - */ - public function setNext($value = null) - { - $this->next = $value; - return $this; - } - /** * Get allow first/last line to display on a separate page setting * - * @return bool + * @deprecated 0.10.0 + * @codeCoverageIgnore */ public function getWidowControl() { - return $this->widowControl; - } - - /** - * Set keep paragraph with next paragraph setting - * - * @param bool $value - * @return self - */ - public function setWidowControl($value = true) - { - if (!is_bool($value)) { - $value = true; - } - $this->widowControl = $value; - return $this; + return $this->hasWidowControl(); } /** * Get keep paragraph with next paragraph setting * - * @return bool + * @deprecated 0.10.0 + * @codeCoverageIgnore */ public function getKeepNext() { - return $this->keepNext; - } - - /** - * Set keep paragraph with next paragraph setting - * - * @param bool $value - * @return self - */ - public function setKeepNext($value = false) - { - if (!is_bool($value)) { - $value = false; - } - $this->keepNext = $value; - return $this; + return $this->isKeepNext(); } /** * Get keep all lines on one page setting * - * @return bool + * @deprecated 0.10.0 + * @codeCoverageIgnore */ public function getKeepLines() { - return $this->keepLines; - } - - /** - * Set keep all lines on one page setting - * - * @param bool $value - * @return self - */ - public function setKeepLines($value = false) - { - if (!is_bool($value)) { - $value = false; - } - $this->keepLines = $value; - return $this; + return $this->isKeepLines(); } /** * Get start paragraph on next page setting * - * @return bool + * @deprecated 0.10.0 + * @codeCoverageIgnore */ public function getPageBreakBefore() { - return $this->pageBreakBefore; - } - - /** - * Set start paragraph on next page setting - * - * @param bool $value - * @return self - */ - public function setPageBreakBefore($value = false) - { - if (!is_bool($value)) { - $value = false; - } - $this->pageBreakBefore = $value; - return $this; - } - - /** - * Get shading - * - * @return \PhpOffice\PhpWord\Style\Indentation - */ - public function getIndentation() - { - return $this->indentation; - } - - /** - * Set shading - * - * @param array $value - * @return self - */ - public function setIndentation($value = null) - { - if (is_array($value)) { - if (!$this->indentation instanceof Indentation) { - $this->indentation = new Indentation(); - } - $this->indentation->setStyleByArray($value); - } else { - $this->indentation = null; - } - - return $this; - } - - /** - * Get shading - * - * @return \PhpOffice\PhpWord\Style\Spacing - * @todo Rename to getSpacing in 1.0 - */ - public function getSpace() - { - return $this->spacing; - } - - /** - * Set shading - * - * @param array $value - * @return self - * @todo Rename to setSpacing in 1.0 - */ - public function setSpace($value = null) - { - if (is_array($value)) { - if (!$this->spacing instanceof Spacing) { - $this->spacing = new Spacing(); - } - $this->spacing->setStyleByArray($value); - } else { - $this->spacing = null; - } - - return $this; + return $this->hasPageBreakBefore(); } } diff --git a/src/PhpWord/Style/Row.php b/src/PhpWord/Style/Row.php index e2a07b85..45897aed 100644 --- a/src/PhpWord/Style/Row.php +++ b/src/PhpWord/Style/Row.php @@ -1,10 +1,18 @@ tblHeader = $this->setBoolVal($value, $this->tblHeader); - } - - /** - * Get tblHeader - * - * @return boolean - */ - public function getTblHeader() + public function isTblHeader() { return $this->tblHeader; } /** - * Set cantSplit + * Is tblHeader * - * @param boolean $value + * @param bool $value * @return self */ - public function setCantSplit($value = false) + public function setTblHeader($value = true) { - $this->cantSplit = $this->setBoolVal($value, $this->cantSplit); + $this->tblHeader = $this->setBoolVal($value, $this->tblHeader); + + return $this; } /** - * Get cantSplit + * Is cantSplit * - * @return boolean + * @return bool */ - public function getCantSplit() + public function isCantSplit() { return $this->cantSplit; } + /** + * Is cantSplit + * + * @param bool $value + * @return self + */ + public function setCantSplit($value = true) + { + $this->cantSplit = $this->setBoolVal($value, $this->cantSplit); + + return $this; + } + + /** + * Is exactHeight + * + * @return bool + */ + public function isExactHeight() + { + return $this->exactHeight; + } + /** * Set exactHeight * * @param bool $value * @return self */ - public function setExactHeight($value = false) + public function setExactHeight($value = true) { $this->exactHeight = $this->setBoolVal($value, $this->exactHeight); + return $this; } + /** + * Get tblHeader + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getTblHeader() + { + return $this->isTblHeader(); + } + + /** + * Get cantSplit + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getCantSplit() + { + return $this->isCantSplit(); + } + /** * Get exactHeight * - * @return boolean + * @deprecated 0.10.0 + * @codeCoverageIgnore */ public function getExactHeight() { - return $this->exactHeight; + return $this->isExactHeight(); } } diff --git a/src/PhpWord/Style/Section.php b/src/PhpWord/Style/Section.php index e109526f..fd59f1b4 100644 --- a/src/PhpWord/Style/Section.php +++ b/src/PhpWord/Style/Section.php @@ -1,16 +1,22 @@ orientation = $this->setEnumVal($value, $enum, $this->orientation); - $longSize = $this->pageSizeW >= $this->pageSizeH ? $this->pageSizeW : $this->pageSizeH; - $shortSize = $this->pageSizeW < $this->pageSizeH ? $this->pageSizeW : $this->pageSizeH; + + /** @var int|float $longSide Type hint */ + $longSide = $this->pageSizeW >= $this->pageSizeH ? $this->pageSizeW : $this->pageSizeH; + + /** @var int|float $shortSide Type hint */ + $shortSide = $this->pageSizeW < $this->pageSizeH ? $this->pageSizeW : $this->pageSizeH; if ($this->orientation == self::ORIENTATION_PORTRAIT) { - $this->pageSizeW = $shortSize; - $this->pageSizeH = $longSize; + $this->pageSizeW = $shortSide; + $this->pageSizeH = $longSide; } else { - $this->pageSizeW = $longSize; - $this->pageSizeH = $shortSize; + $this->pageSizeW = $longSide; + $this->pageSizeH = $shortSide; } return $this; @@ -255,7 +265,7 @@ class Section extends Border * @param int|float $value * @return self */ - public function setMarginTop($value = '') + public function setMarginTop($value = null) { $this->marginTop = $this->setNumericVal($value, self::DEFAULT_MARGIN); @@ -278,7 +288,7 @@ class Section extends Border * @param int|float $value * @return self */ - public function setMarginLeft($value = '') + public function setMarginLeft($value = null) { $this->marginLeft = $this->setNumericVal($value, self::DEFAULT_MARGIN); @@ -301,7 +311,7 @@ class Section extends Border * @param int|float $value * @return self */ - public function setMarginRight($value = '') + public function setMarginRight($value = null) { $this->marginRight = $this->setNumericVal($value, self::DEFAULT_MARGIN); @@ -324,7 +334,7 @@ class Section extends Border * @param int|float $value * @return self */ - public function setMarginBottom($value = '') + public function setMarginBottom($value = null) { $this->marginBottom = $this->setNumericVal($value, self::DEFAULT_MARGIN); @@ -347,7 +357,7 @@ class Section extends Border * @param int|float $value * @return self */ - public function setGutter($value = '') + public function setGutter($value = null) { $this->gutter = $this->setNumericVal($value, self::DEFAULT_GUTTER); @@ -370,7 +380,7 @@ class Section extends Border * @param int|float $value * @return self */ - public function setHeaderHeight($value = '') + public function setHeaderHeight($value = null) { $this->headerHeight = $this->setNumericVal($value, self::DEFAULT_HEADER_HEIGHT); @@ -393,7 +403,7 @@ class Section extends Border * @param int|float $value * @return self */ - public function setFooterHeight($value = '') + public function setFooterHeight($value = null) { $this->footerHeight = $this->setNumericVal($value, self::DEFAULT_FOOTER_HEIGHT); @@ -414,7 +424,7 @@ class Section extends Border * Set page numbering start * * @param null|int $pageNumberingStart - * @return $this + * @return self */ public function setPageNumberingStart($pageNumberingStart = null) { @@ -438,7 +448,7 @@ class Section extends Border * @param int $value * @return self */ - public function setColsNum($value = '') + public function setColsNum($value = null) { $this->colsNum = $this->setIntVal($value, self::DEFAULT_COLUMN_COUNT); @@ -461,7 +471,7 @@ class Section extends Border * @param int|float $value * @return self */ - public function setColsSpace($value = '') + public function setColsSpace($value = null) { $this->colsSpace = $this->setNumericVal($value, self::DEFAULT_COLUMN_SPACING); @@ -503,19 +513,12 @@ class Section extends Border /** * Set line numbering * - * @param array $value + * @param mixed $value * @return self */ public function setLineNumbering($value = null) { - if (is_array($value)) { - if (!$this->lineNumbering instanceof LineNumbering) { - $this->lineNumbering = new LineNumbering($value); - } - $this->lineNumbering->setStyleByArray($value); - } else { - $this->lineNumbering = null; - } + $this->setObjectVal($value, 'LineNumbering', $this->lineNumbering); return $this; } diff --git a/src/PhpWord/Style/Shading.php b/src/PhpWord/Style/Shading.php index fee66a08..5c9742c9 100644 --- a/src/PhpWord/Style/Shading.php +++ b/src/PhpWord/Style/Shading.php @@ -1,10 +1,18 @@ pattern = $value; + $enum = array( + self::PATTERN_CLEAR, self::PATTERN_SOLID, self::PATTERN_HSTRIPE, + self::PATTERN_VSTRIPE, self::PATTERN_DSTRIPE, self::PATTERN_HCROSS, self::PATTERN_DCROSS + ); + $this->pattern = $this->setEnumVal($value, $enum, $this->pattern); return $this; } diff --git a/src/PhpWord/Style/Spacing.php b/src/PhpWord/Style/Spacing.php index db173061..9c9f3a81 100644 --- a/src/PhpWord/Style/Spacing.php +++ b/src/PhpWord/Style/Spacing.php @@ -1,10 +1,18 @@ tabPos = 9062; - $this->tabLeader = self::TABLEADER_DOT; - $this->indent = 200; + parent::__construct(self::TAB_STOP_RIGHT, 9062, self::TAB_LEADER_DOT); } /** * Get Tab Position * - * @return int + * @return int|float */ public function getTabPos() { - return $this->tabPos; + return $this->getPosition(); } /** * Set Tab Position * - * @param int $pValue + * @param int|float $value + * @return self */ - public function setTabPos($pValue) + public function setTabPos($value) { - $this->tabPos = $pValue; + return $this->setPosition($value); } /** @@ -78,23 +76,24 @@ class TOC extends AbstractStyle */ public function getTabLeader() { - return $this->tabLeader; + return $this->getLeader(); } /** * Set Tab Leader * - * @param string $pValue + * @param string $value + * @return self */ - public function setTabLeader($pValue = self::TABLEADER_DOT) + public function setTabLeader($value = self::TAB_LEADER_DOT) { - $this->tabLeader = $pValue; + return $this->setLeader($value); } /** * Get Indent * - * @return int + * @return int|float */ public function getIndent() { @@ -104,10 +103,13 @@ class TOC extends AbstractStyle /** * Set Indent * - * @param string $pValue + * @param int|float $value + * @return self */ - public function setIndent($pValue) + public function setIndent($value) { - $this->indent = $pValue; + $this->indent = $this->setNumericVal($value, $this->indent); + + return $this; } } diff --git a/src/PhpWord/Style/Tab.php b/src/PhpWord/Style/Tab.php index dfcb3b95..900e1fbd 100644 --- a/src/PhpWord/Style/Tab.php +++ b/src/PhpWord/Style/Tab.php @@ -1,10 +1,18 @@ val = $this->setEnumVal($val, $stopTypes, $this->val); + $this->type = $this->setEnumVal($type, $stopTypes, $this->type); $this->position = $this->setNumericVal($position, $this->position); $this->leader = $this->setEnumVal($leader, $leaderTypes, $this->leader); } @@ -90,9 +98,27 @@ class Tab extends AbstractStyle * * @return string */ - public function getStopType() + public function getType() { - return $this->val; + return $this->type; + } + + /** + * Set stop type + * + * @param string $value + * @return self + */ + public function setType($value) + { + $enum = array( + self::TAB_STOP_CLEAR, self::TAB_STOP_LEFT, self::TAB_STOP_CENTER, + self::TAB_STOP_RIGHT, self::TAB_STOP_DECIMAL, self::TAB_STOP_BAR, + self::TAB_STOP_NUM, + ); + $this->type = $this->setEnumVal($value, $enum, $this->type); + + return $this; } /** @@ -105,13 +131,43 @@ class Tab extends AbstractStyle return $this->leader; } + /** + * Set leader + * + * @param string $value + * @return self + */ + public function setLeader($value) + { + $enum = array( + self::TAB_LEADER_NONE, self::TAB_LEADER_DOT, self::TAB_LEADER_HYPHEN, + self::TAB_LEADER_UNDERSCORE, self::TAB_LEADER_HEAVY, self::TAB_LEADER_MIDDLEDOT, + ); + $this->leader = $this->setEnumVal($value, $enum, $this->leader); + + return $this; + } + /** * Get position * - * @return integer + * @return int|float */ public function getPosition() { return $this->position; } + + /** + * Set position + * + * @param int|float $value + * @return self + */ + public function setPosition($value) + { + $this->position = $this->setNumericVal($value, $this->position); + + return $this; + } } diff --git a/src/PhpWord/Style/Table.php b/src/PhpWord/Style/Table.php index c4ec8b68..24f50667 100644 --- a/src/PhpWord/Style/Table.php +++ b/src/PhpWord/Style/Table.php @@ -1,55 +1,75 @@ firstRow = clone $this; + $this->alignment = new Alignment(); - unset($this->firstRow->firstRow); - unset($this->firstRow->cellMarginBottom); - unset($this->firstRow->cellMarginTop); - unset($this->firstRow->cellMarginLeft); - unset($this->firstRow->cellMarginRight); - unset($this->firstRow->borderInsideVColor); - unset($this->firstRow->borderInsideVSize); - unset($this->firstRow->borderInsideHColor); - unset($this->firstRow->borderInsideHSize); - foreach ($styleFirstRow as $key => $value) { - $this->firstRow->setStyleValue($key, $value); - } + // Clone first row from table style, but with certain properties disabled + if ($firstRowStyle !== null && is_array($firstRowStyle)) { + $this->firstRowStyle = clone $this; + $this->firstRowStyle->isFirstRow = true; + unset($this->firstRowStyle->firstRowStyle); + unset($this->firstRowStyle->borderInsideHSize); + unset($this->firstRowStyle->borderInsideHColor); + unset($this->firstRowStyle->borderInsideVSize); + unset($this->firstRowStyle->borderInsideVColor); + unset($this->firstRowStyle->cellMarginTop); + unset($this->firstRowStyle->cellMarginLeft); + unset($this->firstRowStyle->cellMarginRight); + unset($this->firstRowStyle->cellMarginBottom); + $this->firstRowStyle->setStyleByArray($firstRowStyle); } - if (!is_null($styleTable) && is_array($styleTable)) { - foreach ($styleTable as $key => $value) { - $this->setStyleValue($key, $value); - } + if ($tableStyle !== null && is_array($tableStyle)) { + $this->setStyleByArray($tableStyle); } } /** - * Get First Row Style + * Set first row * * @return \PhpOffice\PhpWord\Style\Table */ public function getFirstRow() { - return $this->firstRow; + return $this->firstRowStyle; } /** @@ -135,20 +169,41 @@ class Table extends Border */ public function getBgColor() { - if (!is_null($this->shading)) { + if ($this->shading !== null) { return $this->shading->getFill(); } + + return null; } /** * Set background * * @param string $value - * @return \PhpOffice\PhpWord\Style\Table + * @return self */ public function setBgColor($value = null) { $this->setShading(array('fill' => $value)); + + return $this; + } + + /** + * Get TLRBHV Border Size + * + * @return integer[] + */ + public function getBorderSize() + { + return array( + $this->getBorderTopSize(), + $this->getBorderLeftSize(), + $this->getBorderRightSize(), + $this->getBorderBottomSize(), + $this->getBorderInsideHSize(), + $this->getBorderInsideVSize(), + ); } /** @@ -169,41 +224,6 @@ class Table extends Border return $this; } - /** - * Get TLRBHV Border Size - * - * @return int[] - */ - public function getBorderSize() - { - return array( - $this->getBorderTopSize(), - $this->getBorderLeftSize(), - $this->getBorderRightSize(), - $this->getBorderBottomSize(), - $this->getBorderInsideHSize(), - $this->getBorderInsideVSize(), - ); - } - - /** - * Set TLRBHV Border Color - * - * @param string $value - * @return self - */ - public function setBorderColor($value = null) - { - $this->setBorderTopColor($value); - $this->setBorderLeftColor($value); - $this->setBorderRightColor($value); - $this->setBorderBottomColor($value); - $this->setBorderInsideHColor($value); - $this->setBorderInsideVColor($value); - - return $this; - } - /** * Get TLRBHV Border Color * @@ -222,93 +242,105 @@ class Table extends Border } /** - * Set border size inside horizontal + * Set TLRBHV Border Color * - * @param $value + * @param string $value + * @return self */ - public function setBorderInsideHSize($value = null) + public function setBorderColor($value = null) { - $this->borderInsideHSize = $value; + $this->setBorderTopColor($value); + $this->setBorderLeftColor($value); + $this->setBorderRightColor($value); + $this->setBorderBottomColor($value); + $this->setBorderInsideHColor($value); + $this->setBorderInsideVColor($value); + + return $this; } /** * Get border size inside horizontal * - * @return + * @return int */ public function getBorderInsideHSize() { - return (isset($this->borderInsideHSize)) ? $this->borderInsideHSize : null; + return $this->getTableOnlyProperty('borderInsideHSize'); } /** - * Set border size inside vertical + * Set border size inside horizontal * - * @param $value + * @param int $value + * @return self */ - public function setBorderInsideVSize($value = null) + public function setBorderInsideHSize($value = null) { - $this->borderInsideVSize = $value; - } - - /** - * Get border size inside vertical - * - * @return - */ - public function getBorderInsideVSize() - { - return (isset($this->borderInsideVSize)) ? $this->borderInsideVSize : null; - } - - /** - * Set border color inside horizontal - * - * @param $value - */ - public function setBorderInsideHColor($value = null) - { - $this->borderInsideHColor = $value; + return $this->setTableOnlyProperty('borderInsideHSize', $value); } /** * Get border color inside horizontal * - * @return + * @return string */ public function getBorderInsideHColor() { - return (isset($this->borderInsideHColor)) ? $this->borderInsideHColor : null; + return $this->getTableOnlyProperty('borderInsideHColor'); } /** - * Set border color inside vertical + * Set border color inside horizontal * - * @param $value + * @param string $value + * @return self */ - public function setBorderInsideVColor($value = null) + public function setBorderInsideHColor($value = null) { - $this->borderInsideVColor = $value; + return $this->setTableOnlyProperty('borderInsideHColor', $value, false); + } + + /** + * Get border size inside vertical + * + * @return int + */ + public function getBorderInsideVSize() + { + return $this->getTableOnlyProperty('borderInsideVSize'); + } + + /** + * Set border size inside vertical + * + * @param int $value + * @return self + */ + public function setBorderInsideVSize($value = null) + { + return $this->setTableOnlyProperty('borderInsideVSize', $value); } /** * Get border color inside vertical * - * @return + * @return string */ public function getBorderInsideVColor() { - return (isset($this->borderInsideVColor)) ? $this->borderInsideVColor : null; + return $this->getTableOnlyProperty('borderInsideVColor'); } /** - * Set cell margin top + * Set border color inside vertical * - * @param int $value + * @param string $value + * @return self */ - public function setCellMarginTop($value = null) + public function setBorderInsideVColor($value = null) { - $this->cellMarginTop = $value; + return $this->setTableOnlyProperty('borderInsideVColor', $value, false); } /** @@ -318,17 +350,18 @@ class Table extends Border */ public function getCellMarginTop() { - return $this->cellMarginTop; + return $this->getTableOnlyProperty('cellMarginTop'); } /** - * Set cell margin left + * Set cell margin top * * @param int $value + * @return self */ - public function setCellMarginLeft($value = null) + public function setCellMarginTop($value = null) { - $this->cellMarginLeft = $value; + return $this->setTableOnlyProperty('cellMarginTop', $value); } /** @@ -338,17 +371,18 @@ class Table extends Border */ public function getCellMarginLeft() { - return $this->cellMarginLeft; + return $this->getTableOnlyProperty('cellMarginLeft'); } /** - * Set cell margin right + * Set cell margin left * * @param int $value + * @return self */ - public function setCellMarginRight($value = null) + public function setCellMarginLeft($value = null) { - $this->cellMarginRight = $value; + return $this->setTableOnlyProperty('cellMarginLeft', $value); } /** @@ -358,17 +392,18 @@ class Table extends Border */ public function getCellMarginRight() { - return $this->cellMarginRight; + return $this->getTableOnlyProperty('cellMarginRight'); } /** - * Set cell margin bottom + * Set cell margin right * * @param int $value + * @return self */ - public function setCellMarginBottom($value = null) + public function setCellMarginRight($value = null) { - $this->cellMarginBottom = $value; + return $this->setTableOnlyProperty('cellMarginRight', $value); } /** @@ -378,13 +413,40 @@ class Table extends Border */ public function getCellMarginBottom() { - return $this->cellMarginBottom; + return $this->getTableOnlyProperty('cellMarginBottom'); + } + + /** + * Set cell margin bottom + * + * @param int $value + * @return self + */ + public function setCellMarginBottom($value = null) + { + return $this->setTableOnlyProperty('cellMarginBottom', $value); + } + + /** + * Get cell margin + * + * @return integer[] + */ + public function getCellMargin() + { + return array( + $this->cellMarginTop, + $this->cellMarginLeft, + $this->cellMarginRight, + $this->cellMarginBottom + ); } /** * Set TLRB cell margin * * @param int $value Margin in twips + * @return self */ public function setCellMargin($value = null) { @@ -392,16 +454,20 @@ class Table extends Border $this->setCellMarginLeft($value); $this->setCellMarginRight($value); $this->setCellMarginBottom($value); + + return $this; } /** - * Get cell margin + * Check if any of the margin is not null * - * @return int[] + * @return bool */ - public function getCellMargin() + public function hasMargin() { - return array($this->cellMarginTop, $this->cellMarginLeft, $this->cellMarginRight, $this->cellMarginBottom); + $margins = $this->getCellMargin(); + + return $margins !== array_filter($margins, 'is_null'); } /** @@ -417,18 +483,123 @@ class Table extends Border /** * Set shading * - * @param array $value + * @param mixed $value * @return self */ public function setShading($value = null) { - if (is_array($value)) { - if (!$this->shading instanceof Shading) { - $this->shading = new Shading(); + $this->setObjectVal($value, 'Shading', $this->shading); + + return $this; + } + + /** + * Get alignment + * + * @return string + */ + public function getAlign() + { + return $this->alignment->getValue(); + } + + /** + * Set alignment + * + * @param string $value + * @return self + */ + public function setAlign($value = null) + { + $this->alignment->setValue($value); + + return $this; + } + + /** + * Get width + * + * @return int|float + */ + public function getWidth() + { + return $this->width; + } + + /** + * Set width + * + * @param int|float $value + * @return self + */ + public function setWidth($value = null) + { + $this->width = $this->setNumericVal($value, $this->width); + + return $this; + } + + /** + * Get width unit + * + * @return string + */ + public function getUnit() + { + return $this->unit; + } + + /** + * Set width unit + * + * @param string $value + * @return self + */ + public function setUnit($value = null) + { + $enum = array(self::WIDTH_AUTO, self::WIDTH_PERCENT, self::WIDTH_TWIP); + $this->unit = $this->setEnumVal($value, $enum, $this->unit); + + return $this; + } + + /** + * Get table style only property by checking if it's a firstRow + * + * This is necessary since firstRow style is cloned from table style but + * without certain properties activated, e.g. margins + * + * @param string $property + * @return int|string|null + */ + private function getTableOnlyProperty($property) + { + if ($this->isFirstRow === false) { + return $this->$property; + } + + return null; + } + + /** + * Set table style only property by checking if it's a firstRow + * + * This is necessary since firstRow style is cloned from table style but + * without certain properties activated, e.g. margins + * + * @param string $property + * @param int|string $value + * @param bool $isNumeric + * @return self + */ + private function setTableOnlyProperty($property, $value, $isNumeric = true) + { + if ($this->isFirstRow === false) { + if ($isNumeric === true) { + $this->$property = $this->setNumericVal($value, $this->$property); + } else { + $this->$property = $value; } - $this->shading->setStyleByArray($value); - } else { - $this->shading = null; } return $this; diff --git a/src/PhpWord/Style/TextBox.php b/src/PhpWord/Style/TextBox.php new file mode 100644 index 00000000..9f0a1dde --- /dev/null +++ b/src/PhpWord/Style/TextBox.php @@ -0,0 +1,229 @@ +innerMarginTop = $value; + } + + /** + * Get margin top + * + * @return int + */ + public function getInnerMarginTop() + { + return $this->innerMarginTop; + } + + /** + * Set margin left + * + * @param int $value + */ + public function setInnerMarginLeft($value = null) + { + $this->innerMarginLeft = $value; + } + + /** + * Get margin left + * + * @return int + */ + public function getInnerMarginLeft() + { + return $this->innerMarginLeft; + } + + /** + * Set margin right + * + * @param int $value + */ + public function setInnerMarginRight($value = null) + { + $this->innerMarginRight = $value; + } + + /** + * Get margin right + * + * @return int + */ + public function getInnerMarginRight() + { + return $this->innerMarginRight; + } + + /** + * Set margin bottom + * + * @param int $value + */ + public function setInnerMarginBottom($value = null) + { + $this->innerMarginBottom = $value; + } + + /** + * Get margin bottom + * + * @return int + */ + public function getInnerMarginBottom() + { + return $this->innerMarginBottom; + } + + /** + * Set TLRB cell margin + * + * @param int $value Margin in twips + */ + public function setInnerMargin($value = null) + { + $this->setInnerMarginTop($value); + $this->setInnerMarginLeft($value); + $this->setInnerMarginRight($value); + $this->setInnerMarginBottom($value); + } + + /** + * Get cell margin + * + * @return integer[] + */ + public function getInnerMargin() + { + return array($this->innerMarginLeft, $this->innerMarginTop, $this->innerMarginRight, $this->innerMarginBottom); + } + + /** + * Has inner margin? + * + * @return bool + */ + public function hasInnerMargins() + { + $hasInnerMargins = false; + $margins = $this->getInnerMargin(); + for ($i = 0; $i < count($margins); $i++) { + if ($margins[$i] !== null) { + $hasInnerMargins = true; + } + } + + return $hasInnerMargins; + } + + /** + * Set border size + * + * @param int $value Size in points + */ + public function setBorderSize($value = null) + { + $this->borderSize = $value; + } + + /** + * Get border size + * + * @return int + */ + public function getBorderSize() + { + return $this->borderSize; + } + + /** + * Set border color + * + * @param string $value + */ + public function setBorderColor($value = null) + { + $this->borderColor = $value; + } + + /** + * Get border color + * + * @return string + */ + public function getBorderColor() + { + return $this->borderColor; + } +} diff --git a/src/PhpWord/TOC.php b/src/PhpWord/TOC.php deleted file mode 100644 index ea75c10d..00000000 --- a/src/PhpWord/TOC.php +++ /dev/null @@ -1,78 +0,0 @@ -tempFileName}."); } - $zipClass = Settings::getZipClass(); - $this->zipClass = new $zipClass(); + $this->zipClass = new ZipArchive(); $this->zipClass->open($this->tempFileName); // Find and load headers and footers @@ -184,7 +192,7 @@ class Template // Check if there's a cell spanning multiple rows. if (preg_match('##', $xmlRow)) { - $extraRowStart = $rowEnd; + // $extraRowStart = $rowEnd; $extraRowEnd = $rowEnd; while (true) { $extraRowStart = $this->findRowStart($extraRowEnd + 1); @@ -197,7 +205,8 @@ class Template // If tmpXmlRow doesn't contain continue, this row is no longer part of the spanned row. $tmpXmlRow = $this->getSlice($extraRowStart, $extraRowEnd); - if (!preg_match('##', $tmpXmlRow) && !preg_match('##', $tmpXmlRow)) { + if (!preg_match('##', $tmpXmlRow) && + !preg_match('##', $tmpXmlRow)) { break; } // This row was a spanned row, update $rowEnd and search for the next row. @@ -226,7 +235,11 @@ class Template public function cloneBlock($blockname, $clones = 1, $replace = true) { $xmlBlock = null; - preg_match('/(<\?xml.*)(\${' . $blockname . '}<\/w:.*?p>)(.*)()/is', $this->documentXML, $matches); + preg_match( + '/(<\?xml.*)(\${' . $blockname . '}<\/w:.*?p>)(.*)()/is', + $this->documentXML, + $matches + ); if (isset($matches[3])) { $xmlBlock = $matches[3]; @@ -236,7 +249,11 @@ class Template } if ($replace) { - $this->documentXML = str_replace($matches[2] . $matches[3] . $matches[4], implode('', $cloned), $this->documentXML); + $this->documentXML = str_replace( + $matches[2] . $matches[3] . $matches[4], + implode('', $cloned), + $this->documentXML + ); } } @@ -251,10 +268,18 @@ class Template */ public function replaceBlock($blockname, $replacement) { - preg_match('/(<\?xml.*)(\${' . $blockname . '}<\/w:.*?p>)(.*)()/is', $this->documentXML, $matches); + preg_match( + '/(<\?xml.*)(\${' . $blockname . '}<\/w:.*?p>)(.*)()/is', + $this->documentXML, + $matches + ); if (isset($matches[3])) { - $this->documentXML = str_replace($matches[2] . $matches[3] . $matches[4], $replacement, $this->documentXML); + $this->documentXML = str_replace( + $matches[2] . $matches[3] . $matches[4], + $replacement, + $this->documentXML + ); } } diff --git a/src/PhpWord/Writer/AbstractWriter.php b/src/PhpWord/Writer/AbstractWriter.php index 0d713bc5..346e9b66 100644 --- a/src/PhpWord/Writer/AbstractWriter.php +++ b/src/PhpWord/Writer/AbstractWriter.php @@ -1,17 +1,25 @@ writerParts[strtolower($pPartName)])) { - return $this->writerParts[strtolower($pPartName)]; + if ($partName != '' && isset($this->writerParts[strtolower($partName)])) { + return $this->writerParts[strtolower($partName)]; } else { return null; } @@ -121,9 +136,9 @@ abstract class AbstractWriter implements WriterInterface /** * Get use disk caching status * - * @return boolean + * @return bool */ - public function getUseDiskCaching() + public function isUseDiskCaching() { return $this->useDiskCaching; } @@ -131,19 +146,20 @@ abstract class AbstractWriter implements WriterInterface /** * Set use disk caching status * - * @param boolean $pValue - * @param string $pDirectory + * @param bool $value + * @param string $directory * @return self + * @throws \PhpOffice\PhpWord\Exception\Exception */ - public function setUseDiskCaching($pValue = false, $pDirectory = null) + public function setUseDiskCaching($value = false, $directory = null) { - $this->useDiskCaching = $pValue; + $this->useDiskCaching = $value; - if (!is_null($pDirectory)) { - if (is_dir($pDirectory)) { - $this->diskCachingDirectory = $pDirectory; + if (!is_null($directory)) { + if (is_dir($directory)) { + $this->diskCachingDirectory = $directory; } else { - throw new Exception("Directory does not exist: $pDirectory"); + throw new Exception("Directory does not exist: $directory"); } } @@ -203,9 +219,12 @@ abstract class AbstractWriter implements WriterInterface $this->originalFilename = $filename; if (strtolower($filename) == 'php://output' || strtolower($filename) == 'php://stdout') { $filename = @tempnam(sys_get_temp_dir(), 'phpword_'); + // @codeCoverageIgnoreStart + // Can't find any test case. Uncomment when found. if ($filename == '') { $filename = $this->originalFilename; } + // @codeCoverageIgnoreEnd } $this->tempFilename = $filename; @@ -218,9 +237,12 @@ abstract class AbstractWriter implements WriterInterface protected function cleanupTempFile() { if ($this->originalFilename != $this->tempFilename) { + // @codeCoverageIgnoreStart + // Can't find any test case. Uncomment when found. if (copy($this->tempFilename, $this->originalFilename) === false) { - throw new Exception("Could not copy temporary zip file {$this->tempFilename} to {$this->originalFilename}."); + throw new Exception("Could not copy temporary zip file."); } + // @codeCoverageIgnoreEnd @unlink($this->tempFilename); } @@ -241,42 +263,74 @@ abstract class AbstractWriter implements WriterInterface * Get ZipArchive object * * @param string $filename - * @return mixed ZipArchive object + * @return \PhpOffice\PhpWord\Shared\ZipArchive + * @throws \Exception */ protected function getZipArchive($filename) { - // Create new ZIP file and open it for writing - $zipClass = Settings::getZipClass(); - $objZip = new $zipClass(); - - // Retrieve OVERWRITE and CREATE constants from the instantiated zip class - // This method of accessing constant values from a dynamic class should work with all appropriate versions of PHP - $reflection = new \ReflectionObject($objZip); - $zipOverWrite = $reflection->getConstant('OVERWRITE'); - $zipCreate = $reflection->getConstant('CREATE'); - // Remove any existing file if (file_exists($filename)) { unlink($filename); } // Try opening the ZIP file - if ($objZip->open($filename, $zipOverWrite) !== true) { - if ($objZip->open($filename, $zipCreate) !== true) { - throw new Exception("Could not open " . $filename . " for writing."); + $zip = new ZipArchive(); + + // @codeCoverageIgnoreStart + // Can't find any test case. Uncomment when found. + if ($zip->open($filename, ZipArchive::OVERWRITE) !== true) { + if ($zip->open($filename, ZipArchive::CREATE) !== true) { + throw new \Exception("Could not open '{$filename}' for writing."); } } + // @codeCoverageIgnoreEnd - return $objZip; + return $zip; + } + + /** + * Open file for writing + * + * @param string $filename + * @return resource + * @throws \Exception + * @since 0.11.0 + */ + protected function openFile($filename) + { + $filename = $this->getTempFile($filename); + $fileHandle = fopen($filename, 'w'); + // @codeCoverageIgnoreStart + // Can't find any test case. Uncomment when found. + if ($fileHandle === false) { + throw new \Exception("Could not open '{$filename}' for writing."); + } + // @codeCoverageIgnoreEnd + + return $fileHandle; + } + + /** + * Write content to file + * + * @param resource $fileHandle + * @param string $content + * @since 0.11.0 + */ + protected function writeFile(&$fileHandle, $content) + { + fwrite($fileHandle, $content); + fclose($fileHandle); + $this->cleanupTempFile(); } /** * Add files to package * - * @param mixed $objZip + * @param \PhpOffice\PhpWord\Shared\ZipArchive $zip * @param mixed $elements */ - protected function addFilesToPackage($objZip, $elements) + protected function addFilesToPackage(ZipArchive $zip, $elements) { foreach ($elements as $element) { $type = $element['type']; // image|object|link @@ -294,10 +348,10 @@ abstract class AbstractWriter implements WriterInterface call_user_func($element['imageFunction'], $image); $imageContents = ob_get_contents(); ob_end_clean(); - $objZip->addFromString($target, $imageContents); + $zip->addFromString($target, $imageContents); imagedestroy($image); } else { - $this->addFileToPackage($objZip, $element['source'], $target); + $this->addFileToPackage($zip, $element['source'], $target); } } } @@ -307,11 +361,11 @@ abstract class AbstractWriter implements WriterInterface * * Get the actual source from an archive image * - * @param mixed $objZip + * @param \PhpOffice\PhpWord\Shared\ZipArchive $zipPackage * @param string $source * @param string $target */ - protected function addFileToPackage($objZip, $source, $target) + protected function addFileToPackage($zipPackage, $source, $target) { $isArchive = strpos($source, 'zip://') !== false; $actualSource = null; @@ -319,8 +373,7 @@ abstract class AbstractWriter implements WriterInterface $source = substr($source, 6); list($zipFilename, $imageFilename) = explode('#', $source); - $zipClass = \PhpOffice\PhpWord\Settings::getZipClass(); - $zip = new $zipClass(); + $zip = new ZipArchive; if ($zip->open($zipFilename) !== false) { if ($zip->locateName($imageFilename)) { $zip->extractTo($this->getTempDir(), $imageFilename); @@ -333,7 +386,7 @@ abstract class AbstractWriter implements WriterInterface } if (!is_null($actualSource)) { - $objZip->addFile($actualSource, $target); + $zipPackage->addFile($actualSource, $target); } } @@ -356,4 +409,15 @@ abstract class AbstractWriter implements WriterInterface rmdir($dir); } + + /** + * Get use disk caching status + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getUseDiskCaching() + { + return $this->isUseDiskCaching(); + } } diff --git a/src/PhpWord/Writer/HTML.php b/src/PhpWord/Writer/HTML.php index d4b8adb3..29173ff2 100644 --- a/src/PhpWord/Writer/HTML.php +++ b/src/PhpWord/Writer/HTML.php @@ -1,25 +1,23 @@ setPhpWord($phpWord); + + $this->parts = array('Head', 'Body'); + foreach ($this->parts as $partName) { + $partClass = 'PhpOffice\\PhpWord\\Writer\\HTML\\Part\\' . $partName; + if (class_exists($partClass)) { + /** @var \PhpOffice\PhpWord\Writer\HTML\Part\AbstractPart $part Type hint */ + $part = new $partClass(); + $part->setParentWriter($this); + $this->writerParts[strtolower($partName)] = $part; + } + } } /** * Save PhpWord to file * * @param string $filename - * @throws Exception + * @throws \PhpOffice\PhpWord\Exception\Exception */ public function save($filename = null) { - if (!is_null($this->getPhpWord())) { - $this->setTempDir(sys_get_temp_dir() . '/PHPWordWriter/'); - $hFile = fopen($filename, 'w'); - if ($hFile !== false) { - fwrite($hFile, $this->writeDocument()); - fclose($hFile); - } else { - throw new Exception("Can't open file"); - } - $this->clearTempDir(); - } else { - throw new Exception("No PHPWord assigned."); - } - } - - /** - * Get phpWord data - * - * @return string - */ - public function writeDocument() - { - $html = ''; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= $this->writeHTMLHead(); - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - $html .= $this->writeHTMLBody(); - $html .= $this->writeNotes(); - $html .= '' . PHP_EOL; - $html .= '' . PHP_EOL; - - return $html; - } - - /** - * Generate HTML header - * - * @return string - */ - private function writeHTMLHead() - { - $properties = $this->getPhpWord()->getDocumentProperties(); - $propertiesMapping = array( - 'creator' => 'author', - 'title' => '', - 'description' => '', - 'subject' => '', - 'keywords' => '', - 'category' => '', - 'company' => '', - 'manager' => '' - ); - $title = $properties->getTitle(); - $title = ($title != '') ? $title : 'PHPWord'; - - $html = ''; - $html .= '' . PHP_EOL; - $html .= '' . htmlspecialchars($title) . '' . PHP_EOL; - foreach ($propertiesMapping as $key => $value) { - $value = ($value == '') ? $key : $value; - $method = "get" . $key; - if ($properties->$method() != '') { - $html .= '' . PHP_EOL; - } - } - $html .= $this->writeStyles(); - - return $html; + $fileHandle = $this->openFile($filename); + $this->writeFile($fileHandle, $this->getContent()); } /** * Get content * * @return string + * @since 0.11.0 */ - private function writeHTMLBody() + public function getContent() { - $phpWord = $this->getPhpWord(); - $html = ''; + $content = ''; - $sections = $phpWord->getSections(); - $countSections = count($sections); + $content .= '' . PHP_EOL; + $content .= '' . PHP_EOL; + $content .= '' . PHP_EOL; + $content .= $this->getWriterPart('Head')->write(); + $content .= $this->getWriterPart('Body')->write(); + $content .= '' . PHP_EOL; - if ($countSections > 0) { - foreach ($sections as $section) { - $elements = $section->getElements(); - foreach ($elements as $element) { - if ($element instanceof AbstractElement) { - $elementWriter = new ElementWriter($this, $element, false); - $html .= $elementWriter->write(); - } - } - } - } - - return $html; - } - - /** - * Write footnote/endnote contents as textruns - */ - private function writeNotes() - { - $html = ''; - if (!empty($this->notes)) { - $html .= "
"; - foreach ($this->notes as $noteId => $noteMark) { - $noteAnchor = "note-{$noteId}"; - list($noteType, $noteTypeId) = explode('-', $noteMark); - $collectionObject = 'PhpOffice\\PhpWord\\' . ($noteType == 'endnote' ? 'Endnotes' : 'Footnotes'); - $collection = $collectionObject::getElements(); - if (array_key_exists($noteTypeId, $collection)) { - $element = $collection[$noteTypeId]; - $elmWriter = new TextRunWriter($this, $element, true); - $content = "{$noteId}" . $elmWriter->write(); - $html .= "

{$content}

" . PHP_EOL; - } - } - } - - return $html; - } - - /** - * Get styles - * - * @return string - */ - private function writeStyles() - { - $css = '' . PHP_EOL; - - return $css; + return $content; } /** @@ -272,4 +122,16 @@ class HTML extends AbstractWriter implements WriterInterface { $this->notes[$noteId] = $noteMark; } + + /** + * Write document + * + * @return string + * @deprecated 0.11.0 + * @codeCoverageIgnore + */ + public function writeDocument() + { + return $this->getContent(); + } } diff --git a/src/PhpWord/Writer/HTML/Element/AbstractElement.php b/src/PhpWord/Writer/HTML/Element/AbstractElement.php new file mode 100644 index 00000000..53b994df --- /dev/null +++ b/src/PhpWord/Writer/HTML/Element/AbstractElement.php @@ -0,0 +1,79 @@ +parentWriter = $parentWriter; + $this->element = $element; + $this->withoutP = $withoutP; + } + + /** + * Set without paragraph + * + * @param bool $value + */ + public function setWithoutP($value) + { + $this->withoutP = $value; + } +} diff --git a/src/PhpWord/Writer/HTML/Element/Container.php b/src/PhpWord/Writer/HTML/Element/Container.php new file mode 100644 index 00000000..147329dd --- /dev/null +++ b/src/PhpWord/Writer/HTML/Element/Container.php @@ -0,0 +1,64 @@ +element; + if (!$container instanceof ContainerElement) { + return ''; + } + $containerClass = substr(get_class($container), strrpos(get_class($container), '\\') + 1); + $withoutP = in_array($containerClass, array('TextRun', 'Footnote', 'Endnote')) ? true : false; + $content = ''; + + $elements = $container->getElements(); + foreach ($elements as $element) { + $elementClass = get_class($element); + $writerClass = str_replace('PhpOffice\\PhpWord\\Element', $this->namespace, $elementClass); + if (class_exists($writerClass)) { + /** @var \PhpOffice\PhpWord\Writer\HTML\Element\AbstractElement $writer Type hint */ + $writer = new $writerClass($this->parentWriter, $element, $withoutP); + $content .= $writer->write(); + } + } + + return $content; + } +} diff --git a/src/PhpWord/Writer/HTML/Element/Element.php b/src/PhpWord/Writer/HTML/Element/Element.php deleted file mode 100644 index 434760f9..00000000 --- a/src/PhpWord/Writer/HTML/Element/Element.php +++ /dev/null @@ -1,76 +0,0 @@ -parentWriter = $parentWriter; - $this->element = $element; - $this->withoutP = $withoutP; - } - - /** - * Write element - * - * @return string - */ - public function write() - { - $html = ''; - $elmName = str_replace('PhpOffice\\PhpWord\\Element\\', '', get_class($this->element)); - $elmWriterClass = 'PhpOffice\\PhpWord\\Writer\\HTML\\Element\\' . $elmName; - if (class_exists($elmWriterClass) === true) { - $elmWriter = new $elmWriterClass($this->parentWriter, $this->element, $this->withoutP); - $html = $elmWriter->write(); - } - - return $html; - } -} diff --git a/src/PhpWord/Writer/HTML/Element/Endnote.php b/src/PhpWord/Writer/HTML/Element/Endnote.php index 66efcf4d..3da8a8fb 100644 --- a/src/PhpWord/Writer/HTML/Element/Endnote.php +++ b/src/PhpWord/Writer/HTML/Element/Endnote.php @@ -1,10 +1,18 @@ element instanceof \PhpOffice\PhpWord\Element\Footnote) { + return ''; + } + /** @var \PhpOffice\PhpWord\Writer\HTML $parentWriter Type hint */ + $parentWriter = $this->parentWriter; + + $noteId = count($parentWriter->getNotes()) + 1; + $noteMark = $this->noteType . '-' . $this->element->getRelationId(); + $content = "{$noteId}"; + + $parentWriter->addNote($noteId, $noteMark); + + return $content; + } } diff --git a/src/PhpWord/Writer/HTML/Element/Image.php b/src/PhpWord/Writer/HTML/Element/Image.php index 660e6204..ab78990b 100644 --- a/src/PhpWord/Writer/HTML/Element/Image.php +++ b/src/PhpWord/Writer/HTML/Element/Image.php @@ -1,10 +1,18 @@ element instanceof ImageElement) { - return $html; + return ''; } - if (!$this->parentWriter->isPdf()) { - $imageData = $this->getBase64ImageData($this->element); - if (!is_null($imageData)) { + /** @var \PhpOffice\PhpWord\Writer\HTML $parentWriter Type hint */ + $parentWriter = $this->parentWriter; + + $content = ''; + if (!$parentWriter->isPdf()) { + $imageData = $this->element->getImageStringData(true); + if ($imageData !== null) { $styleWriter = new ImageStyleWriter($this->element->getStyle()); $style = $styleWriter->write(); + $imageData = 'data:' . $this->element->getImageType() . ';base64,' . $imageData; - $html = ""; - if (!$this->withoutP) { - $html = "

{$html}

" . PHP_EOL; - } + $content .= $this->writeOpening(); + $content .= ""; + $content .= $this->writeClosing(); } } - return $html; - } - - /** - * Get Base64 image data - * - * @return string|null - */ - private function getBase64ImageData(ImageElement $element) - { - $source = $element->getSource(); - $imageType = $element->getImageType(); - $imageData = null; - $imageBinary = null; - $actualSource = null; - - // Get actual source from archive image or other source - // Return null if not found - if ($element->getSourceType() == ImageElement::SOURCE_ARCHIVE) { - $source = substr($source, 6); - list($zipFilename, $imageFilename) = explode('#', $source); - - $zipClass = \PhpOffice\PhpWord\Settings::getZipClass(); - $zip = new $zipClass(); - if ($zip->open($zipFilename) !== false) { - if ($zip->locateName($imageFilename)) { - $zip->extractTo($this->parentWriter->getTempDir(), $imageFilename); - $actualSource = $this->parentWriter->getTempDir() . DIRECTORY_SEPARATOR . $imageFilename; - } - } - $zip->close(); - } else { - $actualSource = $source; - } - if (is_null($actualSource)) { - return null; - } - - // Read image binary data and convert into Base64 - if ($element->getSourceType() == ImageElement::SOURCE_GD) { - $imageResource = call_user_func($element->getImageCreateFunction(), $actualSource); - ob_start(); - call_user_func($element->getImageFunction(), $imageResource); - $imageBinary = ob_get_contents(); - ob_end_clean(); - } else { - if ($fileHandle = fopen($actualSource, 'rb', false)) { - $imageBinary = fread($fileHandle, filesize($actualSource)); - fclose($fileHandle); - } - } - if (!is_null($imageBinary)) { - $base64 = chunk_split(base64_encode($imageBinary)); - $imageData = 'data:' . $imageType . ';base64,' . $base64; - } - - return $imageData; + return $content; } } diff --git a/src/PhpWord/Writer/HTML/Element/Link.php b/src/PhpWord/Writer/HTML/Element/Link.php index 1680edfc..d1256eb0 100644 --- a/src/PhpWord/Writer/HTML/Element/Link.php +++ b/src/PhpWord/Writer/HTML/Element/Link.php @@ -1,10 +1,18 @@ element->getTarget()}\">{$this->element->getText()}" . PHP_EOL; - if (!$this->withoutP) { - $html = '

' . $html . '

' . PHP_EOL; + if (!$this->element instanceof \PhpOffice\PhpWord\Element\Link) { + return ''; } - return $html; + $content = ''; + $content .= $this->writeOpening(); + $content .= "element->getTarget()}\">{$this->element->getText()}"; + $content .= $this->writeClosing(); + + return $content; } } diff --git a/src/PhpWord/Writer/HTML/Element/ListItem.php b/src/PhpWord/Writer/HTML/Element/ListItem.php index f8aa6073..79a3b393 100644 --- a/src/PhpWord/Writer/HTML/Element/ListItem.php +++ b/src/PhpWord/Writer/HTML/Element/ListItem.php @@ -1,10 +1,18 @@ element->getTextObject()->getText()); - $html = '

' . $text . '

' . PHP_EOL; + if (!$this->element instanceof \PhpOffice\PhpWord\Element\ListItem) { + return ''; + } - return $html; + $text = htmlspecialchars($this->element->getTextObject()->getText()); + $content = '

' . $text . '

' . PHP_EOL; + + return $content; } } diff --git a/src/PhpWord/Writer/HTML/Element/Note.php b/src/PhpWord/Writer/HTML/Element/Note.php deleted file mode 100644 index cac84cbe..00000000 --- a/src/PhpWord/Writer/HTML/Element/Note.php +++ /dev/null @@ -1,34 +0,0 @@ -parentWriter->getNotes()) + 1; - $prefix = ($this->element instanceof \PhpOffice\PhpWord\Element\Endnote) ? 'endnote' : 'footnote'; - $noteMark = $prefix . '-' . $this->element->getRelationId(); - $this->parentWriter->addNote($noteId, $noteMark); - $html = "{$noteId}"; - - return $html; - } -} diff --git a/src/PhpWord/Writer/HTML/Element/PageBreak.php b/src/PhpWord/Writer/HTML/Element/PageBreak.php index b05e43ca..a3fb1f3b 100644 --- a/src/PhpWord/Writer/HTML/Element/PageBreak.php +++ b/src/PhpWord/Writer/HTML/Element/PageBreak.php @@ -1,10 +1,18 @@ element instanceof \PhpOffice\PhpWord\Element\Table) { + return ''; + } + + $content = ''; $rows = $this->element->getRows(); $rowCount = count($rows); if ($rowCount > 0) { - $html .= '' . PHP_EOL; + $content .= '
' . PHP_EOL; foreach ($rows as $row) { - // $height = $row->getHeight(); + /** @var $row \PhpOffice\PhpWord\Element\Row Type hint */ $rowStyle = $row->getStyle(); - $tblHeader = $rowStyle->getTblHeader(); - $html .= '' . PHP_EOL; + // $height = $row->getHeight(); + $tblHeader = $rowStyle->isTblHeader(); + $content .= '' . PHP_EOL; foreach ($row->getCells() as $cell) { + $writer = new Container($this->parentWriter, $cell); $cellTag = $tblHeader ? 'th' : 'td'; - $cellContents = $cell->getElements(); - $html .= "<{$cellTag}>" . PHP_EOL; - if (count($cellContents) > 0) { - foreach ($cellContents as $content) { - $writer = new Element($this->parentWriter, $content, false); - $html .= $writer->write(); - } - } else { - $writer = new Element($this->parentWriter, new \PhpOffice\PhpWord\Element\TextBreak(), false); - $html .= $writer->write(); - } - $html .= '' . PHP_EOL; + $content .= "<{$cellTag}>" . PHP_EOL; + $content .= $writer->write(); + $content .= '' . PHP_EOL; } - $html .= '' . PHP_EOL; + $content .= '' . PHP_EOL; } - $html .= '
' . PHP_EOL; + $content .= '' . PHP_EOL; } - return $html; + return $content; } } diff --git a/src/PhpWord/Writer/HTML/Element/Text.php b/src/PhpWord/Writer/HTML/Element/Text.php index 56839c34..52e7a6b5 100644 --- a/src/PhpWord/Writer/HTML/Element/Text.php +++ b/src/PhpWord/Writer/HTML/Element/Text.php @@ -1,10 +1,18 @@ element->getParagraphStyle(); + /** @var \PhpOffice\PhpWord\Element\Text $element Type hint */ + $element = $this->element; + $this->getFontStyle(); + + $content = ''; + $content .= $this->writeOpening(); + $content .= $this->openingText; + $content .= $this->openingTags; + $content .= htmlspecialchars($element->getText()); + $content .= $this->closingTags; + $content .= $this->closingText; + $content .= $this->writeClosing(); + + return $content; + } + + /** + * Set opening text + * + * @param string $value + */ + public function setOpeningText($value) + { + $this->openingText = $value; + } + + /** + * Set closing text + * + * @param string $value + */ + public function setClosingText($value) + { + $this->closingText = $value; + } + + /** + * Write opening + * + * @return string + */ + protected function writeOpening() + { + $content = ''; + if (!$this->withoutP) { + $style = ''; + if (method_exists($this->element, 'getParagraphStyle')) { + $style = $this->getParagraphStyle(); + } + $content .= ""; + } + + return $content; + } + + /** + * Write ending + * + * @return string + */ + protected function writeClosing() + { + $content = ''; + if (!$this->withoutP) { + $content .= $this->closingText; + $content .= "

" . PHP_EOL; + } + + return $content; + } + + /** + * Write paragraph style + * + * @return string + */ + private function getParagraphStyle() + { + /** @var \PhpOffice\PhpWord\Element\Text $element Type hint */ + $element = $this->element; + $style = ''; + if (!method_exists($element, 'getParagraphStyle')) { + return $style; + } + + $paragraphStyle = $element->getParagraphStyle(); $pStyleIsObject = ($paragraphStyle instanceof Paragraph); if ($pStyleIsObject) { $styleWriter = new ParagraphStyleWriter($paragraphStyle); - $paragraphStyle = $styleWriter->write(); + $style = $styleWriter->write(); } - // Font style - $fontStyle = $this->element->getFontStyle(); - $fontStyleIsObject = ($fontStyle instanceof Font); - if ($fontStyleIsObject) { - $styleWriter = new FontStyleWriter($fontStyle); - $fontStyle = $styleWriter->write(); - } - - if ($paragraphStyle && !$this->withoutP) { + if ($style) { $attribute = $pStyleIsObject ? 'style' : 'class'; - $html .= "

"; - } - if ($fontStyle) { - $attribute = $fontStyleIsObject ? 'style' : 'class'; - $html .= ""; - } - $html .= htmlspecialchars($this->element->getText()); - if ($fontStyle) { - $html .= ''; - } - if ($paragraphStyle && !$this->withoutP) { - $html .= '

' . PHP_EOL; + $style = " {$attribute}=\"{$style}\""; } - return $html; + return $style; + } + + /** + * Get font style + */ + private function getFontStyle() + { + /** @var \PhpOffice\PhpWord\Element\Text $element Type hint */ + $element = $this->element; + $style = ''; + $fontStyle = $element->getFontStyle(); + $fStyleIsObject = ($fontStyle instanceof Font); + if ($fStyleIsObject) { + $styleWriter = new FontStyleWriter($fontStyle); + $style = $styleWriter->write(); + } + if ($style) { + $attribute = $fStyleIsObject ? 'style' : 'class'; + $this->openingTags = ""; + $this->closingTags = ""; + } } } diff --git a/src/PhpWord/Writer/HTML/Element/TextBreak.php b/src/PhpWord/Writer/HTML/Element/TextBreak.php index ed8f9f71..30560e96 100644 --- a/src/PhpWord/Writer/HTML/Element/TextBreak.php +++ b/src/PhpWord/Writer/HTML/Element/TextBreak.php @@ -1,10 +1,18 @@ withoutP) { - $html = '
' . PHP_EOL; + $content = '
' . PHP_EOL; } else { - $html = '

 

' . PHP_EOL; + $content = '

 

' . PHP_EOL; } - return $html; + return $content; } } diff --git a/src/PhpWord/Writer/HTML/Element/TextRun.php b/src/PhpWord/Writer/HTML/Element/TextRun.php index 712c1b33..b6bfacea 100644 --- a/src/PhpWord/Writer/HTML/Element/TextRun.php +++ b/src/PhpWord/Writer/HTML/Element/TextRun.php @@ -1,23 +1,28 @@ element->getElements(); - if (count($elements) > 0) { - // Paragraph style - $paragraphStyle = $this->element->getParagraphStyle(); - $pStyleIsObject = ($paragraphStyle instanceof Paragraph); - if ($pStyleIsObject) { - $styleWriter = new ParagraphStyleWriter($paragraphStyle); - $paragraphStyle = $styleWriter->write(); - } - $tag = $this->withoutP ? 'span' : 'p'; - $attribute = $pStyleIsObject ? 'style' : 'class'; - $html .= "<{$tag} {$attribute}=\"{$paragraphStyle}\">"; - foreach ($elements as $element) { - $elementWriter = new Element($this->parentWriter, $element, true); - $html .= $elementWriter->write(); - } - $html .= ""; - $html .= PHP_EOL; - } + $content = ''; - return $html; + $content .= $this->writeOpening(); + $writer = new Container($this->parentWriter, $this->element); + $content .= $writer->write(); + $content .= $this->writeClosing(); + + return $content; } } diff --git a/src/PhpWord/Writer/HTML/Element/Title.php b/src/PhpWord/Writer/HTML/Element/Title.php index 1395afed..20747bf9 100644 --- a/src/PhpWord/Writer/HTML/Element/Title.php +++ b/src/PhpWord/Writer/HTML/Element/Title.php @@ -1,10 +1,18 @@ element instanceof \PhpOffice\PhpWord\Element\Title) { + return ''; + } + $tag = 'h' . $this->element->getDepth(); $text = htmlspecialchars($this->element->getText()); - $html = "<{$tag}>{$text}" . PHP_EOL; + $content = "<{$tag}>{$text}" . PHP_EOL; - return $html; + return $content; } } diff --git a/src/PhpWord/Writer/HTML/Part/AbstractPart.php b/src/PhpWord/Writer/HTML/Part/AbstractPart.php new file mode 100644 index 00000000..319aa20f --- /dev/null +++ b/src/PhpWord/Writer/HTML/Part/AbstractPart.php @@ -0,0 +1,68 @@ +parentWriter = $writer; + } + + /** + * Get parent writer + * + * @return \PhpOffice\PhpWord\Writer\AbstractWriter + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + public function getParentWriter() + { + if ($this->parentWriter !== null) { + return $this->parentWriter; + } else { + throw new Exception('No parent WriterInterface assigned.'); + } + } +} diff --git a/src/PhpWord/Writer/HTML/Part/Body.php b/src/PhpWord/Writer/HTML/Part/Body.php new file mode 100644 index 00000000..4fd61a83 --- /dev/null +++ b/src/PhpWord/Writer/HTML/Part/Body.php @@ -0,0 +1,89 @@ +getParentWriter()->getPhpWord(); + + $content = ''; + + $content .= '' . PHP_EOL; + $sections = $phpWord->getSections(); + foreach ($sections as $section) { + $writer = new Container($this->getParentWriter(), $section); + $content .= $writer->write(); + } + + $content .= $this->writeNotes(); + $content .= '' . PHP_EOL; + + return $content; + } + + /** + * Write footnote/endnote contents as textruns + * + * @return string + */ + private function writeNotes() + { + /** @var \PhpOffice\PhpWord\Writer\HTML $parentWriter Type hint */ + $parentWriter = $this->getParentWriter(); + $phpWord = $parentWriter->getPhpWord(); + $notes = $parentWriter->getNotes(); + + $content = ''; + + if (!empty($notes)) { + $content .= "
" . PHP_EOL; + foreach ($notes as $noteId => $noteMark) { + list($noteType, $noteTypeId) = explode('-', $noteMark); + $method = 'get' . ($noteType == 'endnote' ? 'Endnotes' : 'Footnotes'); + $collection = $phpWord->$method()->getItems(); + + if (array_key_exists($noteTypeId, $collection)) { + $element = $collection[$noteTypeId]; + $noteAnchor = ""; + $noteAnchor .= "{$noteId}"; + + $writer = new TextRunWriter($this->getParentWriter(), $element); + $writer->setOpeningText($noteAnchor); + $content .= $writer->write(); + } + } + } + + return $content; + } +} diff --git a/src/PhpWord/Writer/HTML/Part/Head.php b/src/PhpWord/Writer/HTML/Part/Head.php new file mode 100644 index 00000000..edbc8dcf --- /dev/null +++ b/src/PhpWord/Writer/HTML/Part/Head.php @@ -0,0 +1,128 @@ +getParentWriter()->getPhpWord()->getDocumentProperties(); + $propertiesMapping = array( + 'creator' => 'author', + 'title' => '', + 'description' => '', + 'subject' => '', + 'keywords' => '', + 'category' => '', + 'company' => '', + 'manager' => '' + ); + $title = $docProps->getTitle(); + $title = ($title != '') ? $title : 'PHPWord'; + + $content = ''; + + $content .= '' . PHP_EOL; + $content .= '' . PHP_EOL; + $content .= '' . htmlspecialchars($title) . '' . PHP_EOL; + foreach ($propertiesMapping as $key => $value) { + $value = ($value == '') ? $key : $value; + $method = "get" . $key; + if ($docProps->$method() != '') { + $content .= '' . PHP_EOL; + } + } + $content .= $this->writeStyles(); + $content .= '' . PHP_EOL; + + return $content; + } + /** + * Get styles + * + * @return string + */ + private function writeStyles() + { + $css = '' . PHP_EOL; + + return $css; + } +} diff --git a/src/PhpWord/Writer/HTML/Style/AbstractStyle.php b/src/PhpWord/Writer/HTML/Style/AbstractStyle.php index eeb0a767..cd37174a 100644 --- a/src/PhpWord/Writer/HTML/Style/AbstractStyle.php +++ b/src/PhpWord/Writer/HTML/Style/AbstractStyle.php @@ -1,14 +1,24 @@ style = $style; } + /** + * Get style + * + * @return array|\PhpOffice\PhpWord\Style\AbstractStyle $style + */ + public function getStyle() + { + if (!$this->style instanceof Style && !is_array($this->style)) { + return ''; + } + + return $this->style; + } + /** * Takes array where of CSS properties / values and converts to CSS string * @@ -59,4 +83,16 @@ abstract class AbstractStyle return $string; } + + /** + * Get value if ... + * + * @param bool|null $condition + * @param string $value + * @return string + */ + protected function getValueIf($condition, $value) + { + return $condition == true ? $value : ''; + } } diff --git a/src/PhpWord/Writer/HTML/Style/Font.php b/src/PhpWord/Writer/HTML/Style/Font.php index 73ae14c1..18f28287 100644 --- a/src/PhpWord/Writer/HTML/Style/Font.php +++ b/src/PhpWord/Writer/HTML/Style/Font.php @@ -1,15 +1,23 @@ style instanceof \PhpOffice\PhpWord\Style\Font)) { - return; + $style = $this->getStyle(); + if (!$style instanceof FontStyle) { + return ''; } - $css = array(); - if (PhpWord::DEFAULT_FONT_NAME != $this->style->getName()) { - $css['font-family'] = "'" . $this->style->getName() . "'"; - } - if (PhpWord::DEFAULT_FONT_SIZE != $this->style->getSize()) { - $css['font-size'] = $this->style->getSize() . 'pt'; - } - if (PhpWord::DEFAULT_FONT_COLOR != $this->style->getColor()) { - $css['color'] = '#' . $this->style->getColor(); - } - $css['background'] = $this->style->getFgColor(); - if ($this->style->getBold()) { - $css['font-weight'] = 'bold'; - } - if ($this->style->getItalic()) { - $css['font-style'] = 'italic'; - } - if ($this->style->getSuperScript()) { - $css['vertical-align'] = 'super'; - } elseif ($this->style->getSubScript()) { - $css['vertical-align'] = 'sub'; - } + + $font = $style->getName(); + $size = $style->getSize(); + $color = $style->getColor(); + $fgColor = $style->getFgColor(); + $underline = $style->getUnderline() != FontStyle::UNDERLINE_NONE; + $lineThrough = $style->isStrikethrough() || $style->isDoubleStrikethrough(); + + $css['font-family'] = $this->getValueIf($font !== null, "'{$font}'"); + $css['font-size'] = $this->getValueIf($size !== null, "{$size}pt"); + $css['color'] = $this->getValueIf($color !== null, "#{$color}"); + $css['background'] = $this->getValueIf($fgColor != '', $fgColor); + $css['font-weight'] = $this->getValueIf($style->isBold(), 'bold'); + $css['font-style'] = $this->getValueIf($style->isItalic(), 'italic'); + $css['vertical-align'] = $this->getValueIf($style->isSuperScript(), 'italic'); + $css['vertical-align'] = $this->getValueIf($style->isSuperScript(), 'super'); + $css['vertical-align'] = $this->getValueIf($style->isSubScript(), 'sub'); $css['text-decoration'] = ''; - if ($this->style->getUnderline() != FontStyle::UNDERLINE_NONE) { - $css['text-decoration'] .= 'underline '; - } - if ($this->style->getStrikethrough()) { - $css['text-decoration'] .= 'line-through '; - } + $css['text-decoration'] .= $this->getValueIf($underline, 'underline '); + $css['text-decoration'] .= $this->getValueIf($lineThrough, 'line-through '); return $this->assembleCss($css); } diff --git a/src/PhpWord/Writer/HTML/Style/Generic.php b/src/PhpWord/Writer/HTML/Style/Generic.php index 841f20d8..df94d492 100644 --- a/src/PhpWord/Writer/HTML/Style/Generic.php +++ b/src/PhpWord/Writer/HTML/Style/Generic.php @@ -1,10 +1,18 @@ getStyle(); $css = array(); - if (is_array($this->style) && !empty($this->style)) { - $css = $this->style; + if (is_array($style) && !empty($style)) { + $css = $style; } return $this->assembleCss($css); diff --git a/src/PhpWord/Writer/HTML/Style/Image.php b/src/PhpWord/Writer/HTML/Style/Image.php index fb59b60d..13be3665 100644 --- a/src/PhpWord/Writer/HTML/Style/Image.php +++ b/src/PhpWord/Writer/HTML/Style/Image.php @@ -1,10 +1,18 @@ style instanceof \PhpOffice\PhpWord\Style\Image)) { - return; + $style = $this->getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Image) { + return ''; } - $css = array(); - if ($this->style->getWidth()) { - $css['width'] = $this->style->getWidth() . 'px'; - } - if ($this->style->getWidth()) { - $css['height'] = $this->style->getHeight() . 'px'; - } + + $width = $style->getWidth(); + $height = $style->getHeight(); + $css['width'] = $this->getValueIf(is_numeric($width), $width . 'px'); + $css['height'] = $this->getValueIf(is_numeric($height), $height . 'px'); return $this->assembleCss($css); } diff --git a/src/PhpWord/Writer/HTML/Style/Paragraph.php b/src/PhpWord/Writer/HTML/Style/Paragraph.php index dd025ee2..8b326a5c 100644 --- a/src/PhpWord/Writer/HTML/Style/Paragraph.php +++ b/src/PhpWord/Writer/HTML/Style/Paragraph.php @@ -1,10 +1,18 @@ style instanceof \PhpOffice\PhpWord\Style\Paragraph)) { - return; + $style = $this->getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Paragraph) { + return ''; } - $css = array(); - if ($this->style->getAlign()) { - $css['text-align'] = $this->style->getAlign(); + + // Alignment + $align = $style->getAlign(); + $css['text-align'] = $this->getValueIf(!is_null($align), $align); + + // Spacing + $spacing = $style->getSpace(); + if (!is_null($spacing)) { + $before = $spacing->getBefore(); + $after = $spacing->getAfter(); + $css['margin-top'] = $this->getValueIf(!is_null($before), ($before / 20) . 'pt'); + $css['margin-bottom'] = $this->getValueIf(!is_null($after), ($after / 20) . 'pt'); } return $this->assembleCss($css); diff --git a/src/PhpWord/Writer/ODText.php b/src/PhpWord/Writer/ODText.php index 0eb6c545..f9c8d5d4 100644 --- a/src/PhpWord/Writer/ODText.php +++ b/src/PhpWord/Writer/ODText.php @@ -1,17 +1,24 @@ setPhpWord($phpWord); // Create parts - $parts = array('Content', 'Manifest', 'Meta', 'Mimetype', 'Styles'); - foreach ($parts as $part) { - $partName = strtolower($part); - $partClass = 'PhpOffice\\PhpWord\\Writer\\ODText\\Part\\' . $part; + $this->parts = array( + 'Mimetype' => 'mimetype', + 'Content' => 'content.xml', + 'Meta' => 'meta.xml', + 'Styles' => 'styles.xml', + 'Manifest' => 'META-INF/manifest.xml', + ); + foreach (array_keys($this->parts) as $partName) { + $partClass = get_class($this) . '\\Part\\' . $partName; if (class_exists($partClass)) { + /** @var $partObject \PhpOffice\PhpWord\Writer\ODText\Part\AbstractPart Type hint */ $partObject = new $partClass(); $partObject->setParentWriter($this); - $this->writerParts[$partName] = $partObject; + $this->writerParts[strtolower($partName)] = $partObject; } } @@ -50,35 +63,27 @@ class ODText extends AbstractWriter implements WriterInterface * Save PhpWord to file * * @param string $filename - * @throws \PhpOffice\PhpWord\Exception\Exception */ public function save($filename = null) { - if (!is_null($this->phpWord)) { - $filename = $this->getTempFile($filename); - $objZip = $this->getZipArchive($filename); + $filename = $this->getTempFile($filename); + $zip = $this->getZipArchive($filename); - // Add section media files - $sectionMedia = Media::getElements('section'); - if (!empty($sectionMedia)) { - $this->addFilesToPackage($objZip, $sectionMedia); - } - - // Add parts - $objZip->addFromString('mimetype', $this->getWriterPart('mimetype')->writeMimetype()); - $objZip->addFromString('content.xml', $this->getWriterPart('content')->writeContent($this->phpWord)); - $objZip->addFromString('meta.xml', $this->getWriterPart('meta')->writeMeta($this->phpWord)); - $objZip->addFromString('styles.xml', $this->getWriterPart('styles')->writeStyles($this->phpWord)); - $objZip->addFromString('META-INF/manifest.xml', $this->getWriterPart('manifest')->writeManifest()); - - // Close file - if ($objZip->close() === false) { - throw new Exception("Could not close zip file $filename."); - } - - $this->cleanupTempFile(); - } else { - throw new Exception("PhpWord object unassigned."); + // Add section media files + $sectionMedia = Media::getElements('section'); + if (!empty($sectionMedia)) { + $this->addFilesToPackage($zip, $sectionMedia); } + + // Write parts + foreach ($this->parts as $partName => $fileName) { + if ($fileName != '') { + $zip->addFromString($fileName, $this->getWriterPart($partName)->write()); + } + } + + // Close zip archive and cleanup temp file + $zip->close(); + $this->cleanupTempFile(); } } diff --git a/src/PhpWord/Writer/ODText/Element/AbstractElement.php b/src/PhpWord/Writer/ODText/Element/AbstractElement.php new file mode 100644 index 00000000..9fb24364 --- /dev/null +++ b/src/PhpWord/Writer/ODText/Element/AbstractElement.php @@ -0,0 +1,29 @@ +xmlWriter = $xmlWriter; - $this->parentWriter = $parentWriter; - $this->element = $element; - $this->withoutP = $withoutP; - } - - /** - * Write element - * - * @return string - */ - public function write() - { - $elmName = str_replace('PhpOffice\\PhpWord\\Element\\', '', get_class($this->element)); - $elmWriterClass = 'PhpOffice\\PhpWord\\Writer\\ODText\\Element\\' . $elmName; - if (class_exists($elmWriterClass) === true) { - $elmWriter = new $elmWriterClass($this->xmlWriter, $this->parentWriter, $this->element, $this->withoutP); - $elmWriter->write(); - } - } -} diff --git a/src/PhpWord/Writer/ODText/Element/Image.php b/src/PhpWord/Writer/ODText/Element/Image.php index d096a03b..3229b59c 100644 --- a/src/PhpWord/Writer/ODText/Element/Image.php +++ b/src/PhpWord/Writer/ODText/Element/Image.php @@ -1,10 +1,18 @@ element->getMediaIndex(); - $target = 'Pictures/' . $this->element->getTarget(); - $style = $this->element->getStyle(); + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Image) { + return; + } + + $mediaIndex = $element->getMediaIndex(); + $target = 'Pictures/' . $element->getTarget(); + $style = $element->getStyle(); $width = Drawing::pixelsToCentimeters($style->getWidth()); $height = Drawing::pixelsToCentimeters($style->getHeight()); - $this->xmlWriter->startElement('text:p'); - $this->xmlWriter->writeAttribute('text:style-name', 'Standard'); + $xmlWriter->startElement('text:p'); + $xmlWriter->writeAttribute('text:style-name', 'Standard'); - $this->xmlWriter->startElement('draw:frame'); - $this->xmlWriter->writeAttribute('draw:style-name', 'fr' . $mediaIndex); - $this->xmlWriter->writeAttribute('draw:name', $this->element->getElementId()); - $this->xmlWriter->writeAttribute('text:anchor-type', 'as-char'); - $this->xmlWriter->writeAttribute('svg:width', $width . 'cm'); - $this->xmlWriter->writeAttribute('svg:height', $height . 'cm'); - $this->xmlWriter->writeAttribute('draw:z-index', $mediaIndex); + $xmlWriter->startElement('draw:frame'); + $xmlWriter->writeAttribute('draw:style-name', 'fr' . $mediaIndex); + $xmlWriter->writeAttribute('draw:name', $element->getElementId()); + $xmlWriter->writeAttribute('text:anchor-type', 'as-char'); + $xmlWriter->writeAttribute('svg:width', $width . 'cm'); + $xmlWriter->writeAttribute('svg:height', $height . 'cm'); + $xmlWriter->writeAttribute('draw:z-index', $mediaIndex); - $this->xmlWriter->startElement('draw:image'); - $this->xmlWriter->writeAttribute('xlink:href', $target); - $this->xmlWriter->writeAttribute('xlink:type', 'simple'); - $this->xmlWriter->writeAttribute('xlink:show', 'embed'); - $this->xmlWriter->writeAttribute('xlink:actuate', 'onLoad'); - $this->xmlWriter->endElement(); // draw:image + $xmlWriter->startElement('draw:image'); + $xmlWriter->writeAttribute('xlink:href', $target); + $xmlWriter->writeAttribute('xlink:type', 'simple'); + $xmlWriter->writeAttribute('xlink:show', 'embed'); + $xmlWriter->writeAttribute('xlink:actuate', 'onLoad'); + $xmlWriter->endElement(); // draw:image - $this->xmlWriter->endElement(); // draw:frame + $xmlWriter->endElement(); // draw:frame - $this->xmlWriter->endElement(); // text:p + $xmlWriter->endElement(); // text:p } } diff --git a/src/PhpWord/Writer/ODText/Element/Link.php b/src/PhpWord/Writer/ODText/Element/Link.php index 08235519..79d3aa24 100644 --- a/src/PhpWord/Writer/ODText/Element/Link.php +++ b/src/PhpWord/Writer/ODText/Element/Link.php @@ -1,10 +1,18 @@ withoutP) { - $this->xmlWriter->startElement('text:p'); // text:p + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Link) { + return; } - $this->xmlWriter->startElement('text:a'); - $this->xmlWriter->writeAttribute('xlink:type', 'simple'); - $this->xmlWriter->writeAttribute('xlink:href', $this->element->getTarget()); - $this->xmlWriter->writeRaw($this->element->getText()); - $this->xmlWriter->endElement(); // text:a + if (!$this->withoutP) { + $xmlWriter->startElement('text:p'); // text:p + } + + $xmlWriter->startElement('text:a'); + $xmlWriter->writeAttribute('xlink:type', 'simple'); + $xmlWriter->writeAttribute('xlink:href', $element->getTarget()); + $xmlWriter->writeRaw($element->getText()); + $xmlWriter->endElement(); // text:a if (!$this->withoutP) { - $this->xmlWriter->endElement(); // text:p + $xmlWriter->endElement(); // text:p } } } diff --git a/src/PhpWord/Writer/ODText/Element/Table.php b/src/PhpWord/Writer/ODText/Element/Table.php index 7972eb37..f26960b8 100644 --- a/src/PhpWord/Writer/ODText/Element/Table.php +++ b/src/PhpWord/Writer/ODText/Element/Table.php @@ -1,61 +1,67 @@ element->getRows(); + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Table) { + return; + } + $rows = $element->getRows(); $rowCount = count($rows); - $colCount = $this->element->countColumns(); - if ($rowCount > 0) { - $this->xmlWriter->startElement('table:table'); - $this->xmlWriter->writeAttribute('table:name', $this->element->getElementId()); - $this->xmlWriter->writeAttribute('table:style', $this->element->getElementId()); + $colCount = $element->countColumns(); - $this->xmlWriter->startElement('table:table-column'); - $this->xmlWriter->writeAttribute('table:number-columns-repeated', $colCount); - $this->xmlWriter->endElement(); // table:table-column + if ($rowCount > 0) { + $xmlWriter->startElement('table:table'); + $xmlWriter->writeAttribute('table:name', $element->getElementId()); + $xmlWriter->writeAttribute('table:style', $element->getElementId()); + + $xmlWriter->startElement('table:table-column'); + $xmlWriter->writeAttribute('table:number-columns-repeated', $colCount); + $xmlWriter->endElement(); // table:table-column foreach ($rows as $row) { - $this->xmlWriter->startElement('table:table-row'); + $xmlWriter->startElement('table:table-row'); + /** @var $row \PhpOffice\PhpWord\Element\Row Type hint */ foreach ($row->getCells() as $cell) { - $this->xmlWriter->startElement('table:table-cell'); - $this->xmlWriter->writeAttribute('office:value-type', 'string'); - $elements = $cell->getElements(); - if (count($elements) > 0) { - foreach ($elements as $element) { - $elementWriter = new ElementWriter($this->xmlWriter, $this->parentWriter, $element); - $elementWriter->write(); - } - } else { - $elementWriter = new ElementWriter($this->xmlWriter, $this->parentWriter, new TextBreakElement()); - $elementWriter->write(); - } - $this->xmlWriter->endElement(); // table:table-cell + $xmlWriter->startElement('table:table-cell'); + $xmlWriter->writeAttribute('office:value-type', 'string'); + + $containerWriter = new Container($xmlWriter, $cell); + $containerWriter->write(); + + $xmlWriter->endElement(); // table:table-cell } - $this->xmlWriter->endElement(); // table:table-row + $xmlWriter->endElement(); // table:table-row } - $this->xmlWriter->endElement(); // table:table + $xmlWriter->endElement(); // table:table } } } diff --git a/src/PhpWord/Writer/ODText/Element/Text.php b/src/PhpWord/Writer/ODText/Element/Text.php index 63ce7b68..4fc53bfe 100644 --- a/src/PhpWord/Writer/ODText/Element/Text.php +++ b/src/PhpWord/Writer/ODText/Element/Text.php @@ -1,63 +1,78 @@ element->getFontStyle(); - $paragraphStyle = $this->element->getParagraphStyle(); + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Text) { + return; + } + $fontStyle = $element->getFontStyle(); + $paragraphStyle = $element->getParagraphStyle(); // @todo Commented for TextRun. Should really checkout this value - // $SfIsObject = ($fontStyle instanceof Font) ? true : false; - $SfIsObject = false; + // $fStyleIsObject = ($fontStyle instanceof Font) ? true : false; + $fStyleIsObject = false; - if ($SfIsObject) { + if ($fStyleIsObject) { // Don't never be the case, because I browse all sections for cleaning all styles not declared - throw new Exception('PhpWord : $SfIsObject wouldn\'t be an object'); + throw new Exception('PhpWord : $fStyleIsObject wouldn\'t be an object'); } else { if (!$this->withoutP) { - $this->xmlWriter->startElement('text:p'); // text:p + $xmlWriter->startElement('text:p'); // text:p } if (empty($fontStyle)) { if (empty($paragraphStyle)) { - $this->xmlWriter->writeAttribute('text:style-name', 'P1'); + $xmlWriter->writeAttribute('text:style-name', 'P1'); } elseif (is_string($paragraphStyle)) { - $this->xmlWriter->writeAttribute('text:style-name', $paragraphStyle); + $xmlWriter->writeAttribute('text:style-name', $paragraphStyle); } - $this->xmlWriter->writeRaw($this->element->getText()); + $xmlWriter->writeRaw($element->getText()); } else { if (empty($paragraphStyle)) { - $this->xmlWriter->writeAttribute('text:style-name', 'Standard'); + $xmlWriter->writeAttribute('text:style-name', 'Standard'); } elseif (is_string($paragraphStyle)) { - $this->xmlWriter->writeAttribute('text:style-name', $paragraphStyle); + $xmlWriter->writeAttribute('text:style-name', $paragraphStyle); } // text:span - $this->xmlWriter->startElement('text:span'); + $xmlWriter->startElement('text:span'); if (is_string($fontStyle)) { - $this->xmlWriter->writeAttribute('text:style-name', $fontStyle); + $xmlWriter->writeAttribute('text:style-name', $fontStyle); } - $this->xmlWriter->writeRaw($this->element->getText()); - $this->xmlWriter->endElement(); + $xmlWriter->writeRaw($element->getText()); + $xmlWriter->endElement(); } if (!$this->withoutP) { - $this->xmlWriter->endElement(); // text:p + $xmlWriter->endElement(); // text:p } } } diff --git a/src/PhpWord/Writer/ODText/Element/TextBreak.php b/src/PhpWord/Writer/ODText/Element/TextBreak.php index ce342399..ef3186f4 100644 --- a/src/PhpWord/Writer/ODText/Element/TextBreak.php +++ b/src/PhpWord/Writer/ODText/Element/TextBreak.php @@ -1,10 +1,18 @@ xmlWriter->startElement('text:p'); - $this->xmlWriter->writeAttribute('text:style-name', 'Standard'); - $this->xmlWriter->endElement(); + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('text:p'); + $xmlWriter->writeAttribute('text:style-name', 'Standard'); + $xmlWriter->endElement(); } } diff --git a/src/PhpWord/Writer/ODText/Element/TextRun.php b/src/PhpWord/Writer/ODText/Element/TextRun.php index f97d9c8c..52240e8f 100644 --- a/src/PhpWord/Writer/ODText/Element/TextRun.php +++ b/src/PhpWord/Writer/ODText/Element/TextRun.php @@ -1,41 +1,42 @@ element->getElements(); - $this->xmlWriter->startElement('text:p'); - if (count($elements) > 0) { - foreach ($elements as $element) { - if ($element instanceof TextElement) { - $elementWriter = new Text($this->xmlWriter, $this->parentWriter, $element, true); - $elementWriter->write(); - } elseif ($element instanceof Link) { - $elementWriter = new Link($this->xmlWriter, $this->parentWriter, $element, true); - $elementWriter->write(); - } - } - } - $this->xmlWriter->endElement(); + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + + $xmlWriter->startElement('text:p'); + + $containerWriter = new Container($xmlWriter, $element); + $containerWriter->write(); + + $xmlWriter->endElement(); } } diff --git a/src/PhpWord/Writer/ODText/Element/Title.php b/src/PhpWord/Writer/ODText/Element/Title.php new file mode 100644 index 00000000..d45f5e12 --- /dev/null +++ b/src/PhpWord/Writer/ODText/Element/Title.php @@ -0,0 +1,43 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Title) { + return; + } + + $xmlWriter->startElement('text:h'); + $xmlWriter->writeAttribute('text:outline-level', $element->getDepth()); + $xmlWriter->writeRaw($element->getText()); + $xmlWriter->endElement(); // text:h + } +} diff --git a/src/PhpWord/Writer/ODText/Part/AbstractPart.php b/src/PhpWord/Writer/ODText/Part/AbstractPart.php index 4aa5d79f..31118ef9 100644 --- a/src/PhpWord/Writer/ODText/Part/AbstractPart.php +++ b/src/PhpWord/Writer/ODText/Part/AbstractPart.php @@ -1,24 +1,38 @@ startElement('office:font-face-decls'); - $arrFonts = array(); + $fontTable = array(); $styles = Style::getStyles(); $numFonts = 0; if (count($styles) > 0) { @@ -68,8 +82,8 @@ abstract class AbstractPart extends \PhpOffice\PhpWord\Writer\Word2007\Part\Abst if ($style instanceof Font) { $numFonts++; $name = $style->getName(); - if (!in_array($name, $arrFonts)) { - $arrFonts[] = $name; + if (!in_array($name, $fontTable)) { + $fontTable[] = $name; // style:font-face $xmlWriter->startElement('style:font-face'); @@ -80,10 +94,10 @@ abstract class AbstractPart extends \PhpOffice\PhpWord\Writer\Word2007\Part\Abst } } } - if (!in_array(PhpWord::DEFAULT_FONT_NAME, $arrFonts)) { + if (!in_array(Settings::getDefaultFontName(), $fontTable)) { $xmlWriter->startElement('style:font-face'); - $xmlWriter->writeAttribute('style:name', PhpWord::DEFAULT_FONT_NAME); - $xmlWriter->writeAttribute('svg:font-family', PhpWord::DEFAULT_FONT_NAME); + $xmlWriter->writeAttribute('style:name', Settings::getDefaultFontName()); + $xmlWriter->writeAttribute('svg:font-family', Settings::getDefaultFontName()); $xmlWriter->endElement(); } $xmlWriter->endElement(); diff --git a/src/PhpWord/Writer/ODText/Part/Content.php b/src/PhpWord/Writer/ODText/Part/Content.php index fbeb6982..f16937a0 100644 --- a/src/PhpWord/Writer/ODText/Part/Content.php +++ b/src/PhpWord/Writer/ODText/Part/Content.php @@ -1,42 +1,61 @@ array(), 'Image' => array(), 'Table' => array()); + + /** + * Write part + * + * @return string + */ + public function write() { - if (is_null($phpWord)) { - throw new Exception("No PhpWord assigned."); - } $xmlWriter = $this->getXmlWriter(); + $phpWord = $this->getParentWriter()->getPhpWord(); + + $this->getAutoStyles($phpWord); $xmlWriter->startDocument('1.0', 'UTF-8'); $xmlWriter->startElement('office:document-content'); @@ -47,14 +66,15 @@ class Content extends AbstractPart $xmlWriter->writeAttribute('xmlns:field', 'urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0'); $xmlWriter->writeAttribute('xmlns:formx', 'urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0'); - $this->getAutomaticStyles($phpWord); + // Font declarations and automatic styles $this->writeFontFaces($xmlWriter); // office:font-face-decls - $this->writeAutomaticStyles($xmlWriter, $phpWord); // office:automatic-styles + $this->writeAutoStyles($xmlWriter); // office:automatic-styles + // Body $xmlWriter->startElement('office:body'); $xmlWriter->startElement('office:text'); - // text:sequence-decls + // Sequence declarations $sequences = array('Illustration', 'Table', 'Text', 'Drawing'); $xmlWriter->startElement('text:sequence-decls'); foreach ($sequences as $sequence) { @@ -65,45 +85,63 @@ class Content extends AbstractPart } $xmlWriter->endElement(); // text:sequence-decl + // Sections $sections = $phpWord->getSections(); - $sectionCount = count($sections); - if ($sectionCount > 0) { - foreach ($sections as $section) { - $elements = $section->getElements(); - // $xmlWriter->startElement('text:section'); - foreach ($elements as $element) { - $elementWriter = new ElementWriter($xmlWriter, $this, $element, false); - $elementWriter->write(); - } - // $xmlWriter->endElement(); // text:section - } + foreach ($sections as $section) { + $name = 'Section' . $section->getSectionId(); + $xmlWriter->startElement('text:section'); + $xmlWriter->writeAttribute('text:name', $name); + $xmlWriter->writeAttribute('text:style-name', $name); + $containerWriter = new Container($xmlWriter, $section); + $containerWriter->write(); + $xmlWriter->endElement(); // text:section } + $xmlWriter->endElement(); // office:text $xmlWriter->endElement(); // office:body + $xmlWriter->endElement(); // office:document-content return $xmlWriter->getData(); } /** - * Write automatic styles + * Write automatic styles other than fonts and paragraphs + * + * @since 0.11.0 */ - private function writeAutomaticStyles(XMLWriter $xmlWriter, PhpWord $phpWord) + private function writeAutoStyles(XMLWriter $xmlWriter) { $xmlWriter->startElement('office:automatic-styles'); - // Font and paragraph + $this->writeTextStyles($xmlWriter); + foreach ($this->autoStyles as $element => $styles) { + $writerClass = 'PhpOffice\\PhpWord\\Writer\\ODText\\Style\\' . $element; + foreach ($styles as $style) { + + /** @var \PhpOffice\PhpWord\Writer\ODText\Style\AbstractStyle $styleWriter Type hint */ + $styleWriter = new $writerClass($xmlWriter, $style); + $styleWriter->write(); + } + } + + $xmlWriter->endElement(); // office:automatic-styles + } + + /** + * Write automatic styles + */ + private function writeTextStyles(XMLWriter $xmlWriter) + { $styles = Style::getStyles(); $paragraphStyleCount = 0; if (count($styles) > 0) { - foreach ($styles as $styleName => $style) { - if (preg_match('#^T[0-9]+$#', $styleName) != 0 - || preg_match('#^P[0-9]+$#', $styleName) != 0 - ) { - $styleClass = str_replace('Style', 'Writer\\ODText\\Style', get_class($style)); + foreach ($styles as $style) { + if ($style->isAuto() === true) { + $styleClass = str_replace('\\Style\\', '\\Writer\\ODText\\Style\\', get_class($style)); if (class_exists($styleClass)) { + /** @var \PhpOffice\PhpWord\Writer\ODText\Style\AbstractStyle $styleWriter Type hint */ $styleWriter = new $styleClass($xmlWriter, $style); - $styleWriter->setIsAuto(true); $styleWriter->write(); } if ($style instanceof Paragraph) { @@ -114,92 +152,90 @@ class Content extends AbstractPart if ($paragraphStyleCount == 0) { $style = new Paragraph(); $style->setStyleName('P1'); - $styleWriter = new \PhpOffice\PhpWord\Writer\ODText\Style\Paragraph($xmlWriter, $style); - $styleWriter->setIsAuto(true); + $style->setAuto(); + $styleWriter = new ParagraphStyleWriter($xmlWriter, $style); $styleWriter->write(); } } - - // Images - $images = Media::getElements('section'); - foreach ($images as $image) { - if ($image['type'] == 'image') { - $xmlWriter->startElement('style:style'); - $xmlWriter->writeAttribute('style:name', 'fr' . $image['rID']); - $xmlWriter->writeAttribute('style:family', 'graphic'); - $xmlWriter->writeAttribute('style:parent-style-name', 'Graphics'); - $xmlWriter->startElement('style:graphic-properties'); - $xmlWriter->writeAttribute('style:vertical-pos', 'top'); - $xmlWriter->writeAttribute('style:vertical-rel', 'baseline'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - } - - // Tables - $sections = $phpWord->getSections(); - $sectionCount = count($sections); - if ($sectionCount > 0) { - $sectionId = 0; - foreach ($sections as $section) { - $sectionId++; - $elements = $section->getElements(); - foreach ($elements as $element) { - if ($elements instanceof Table) { - $xmlWriter->startElement('style:style'); - $xmlWriter->writeAttribute('style:name', $element->getElementId()); - $xmlWriter->writeAttribute('style:family', 'table'); - $xmlWriter->startElement('style:table-properties'); - //$xmlWriter->writeAttribute('style:width', 'table'); - $xmlWriter->writeAttribute('style:rel-width', 100); - $xmlWriter->writeAttribute('table:align', 'center'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - } - } - } - - $xmlWriter->endElement(); // office:automatic-styles } /** - * Set automatic styles + * Get automatic styles */ - private function getAutomaticStyles(PhpWord $phpWord) + private function getAutoStyles(PhpWord $phpWord) { $sections = $phpWord->getSections(); - $sectionCount = count($sections); - if ($sectionCount > 0) { - $paragraphStyleCount = 0; - $fontStyleCount = 0; - foreach ($sections as $section) { - $elements = $section->getElements(); - foreach ($elements as $element) { - if ($element instanceof Text) { - $fontStyle = $element->getFontStyle(); - $paragraphStyle = $element->getParagraphStyle(); + $paragraphStyleCount = 0; + $fontStyleCount = 0; + foreach ($sections as $section) { + $style = $section->getSettings(); + $style->setStyleName("Section{$section->getSectionId()}"); + $this->autoStyles['Section'][] = $style; + $this->getContainerStyle($section, $paragraphStyleCount, $fontStyleCount); + } + } - // Font - if ($fontStyle instanceof Font) { - $fontStyleCount++; - $arrStyle = array( - 'color' => $fontStyle->getColor(), - 'name' => $fontStyle->getName() - ); - $phpWord->addFontStyle('T' . $fontStyleCount, $arrStyle); - $element->setFontStyle('T' . $fontStyleCount); - - // Paragraph - } elseif ($paragraphStyle instanceof Paragraph) { - $paragraphStyleCount++; - - $phpWord->addParagraphStyle('P' . $paragraphStyleCount, array()); - $element->setParagraphStyle('P' . $paragraphStyleCount); - } - } + /** + * Get all styles of each elements in container recursively + * + * Table style can be null or string of the style name + * + * @param \PhpOffice\PhpWord\Element\AbstractContainer $container + * @param int $paragraphStyleCount + * @param int $fontStyleCount + * @todo Simplify the logic + */ + private function getContainerStyle($container, &$paragraphStyleCount, &$fontStyleCount) + { + $elements = $container->getElements(); + foreach ($elements as $element) { + if ($element instanceof TextRun) { + $this->getContainerStyle($element, $paragraphStyleCount, $fontStyleCount); + } elseif ($element instanceof Text) { + $this->getElementStyle($element, $paragraphStyleCount, $fontStyleCount); + } elseif ($element instanceof Image) { + $style = $element->getStyle(); + $style->setStyleName('fr' . $element->getMediaIndex()); + $this->autoStyles['Image'][] = $style; + } elseif ($element instanceof Table) { + $style = $element->getStyle(); + if ($style === null) { + $style = new TableStyle(); + } elseif (is_string($style)) { + $style = Style::getStyle($style); } + $style->setStyleName($element->getElementId()); + $this->autoStyles['Table'][] = $style; } } } + + /** + * Get style of individual element + * + * @param \PhpOffice\PhpWord\Element\Text $element + * @param int $paragraphStyleCount + * @param int $fontStyleCount + */ + private function getElementStyle(&$element, &$paragraphStyleCount, &$fontStyleCount) + { + $fontStyle = $element->getFontStyle(); + $paragraphStyle = $element->getParagraphStyle(); + $phpWord = $this->getParentWriter()->getPhpWord(); + + // Font + if ($fontStyle instanceof Font) { + $fontStyleCount++; + $style = $phpWord->addFontStyle("T{$fontStyleCount}", $fontStyle); + $style->setAuto(); + $element->setFontStyle("T{$fontStyleCount}"); + + // Paragraph + } elseif ($paragraphStyle instanceof Paragraph) { + $paragraphStyleCount++; + $style = $phpWord->addParagraphStyle("P{$paragraphStyleCount}", array()); + $style->setAuto(); + $element->setParagraphStyle("P{$paragraphStyleCount}"); + } + } } diff --git a/src/PhpWord/Writer/ODText/Part/Manifest.php b/src/PhpWord/Writer/ODText/Part/Manifest.php index 4462e7ef..7c695e9b 100644 --- a/src/PhpWord/Writer/ODText/Part/Manifest.php +++ b/src/PhpWord/Writer/ODText/Part/Manifest.php @@ -1,10 +1,18 @@ getXmlWriter(); - // XML header $xmlWriter->startDocument('1.0', 'UTF-8'); - - // manifest:manifest $xmlWriter->startElement('manifest:manifest'); $xmlWriter->writeAttribute('manifest:version', '1.2'); $xmlWriter->writeAttribute('xmlns:manifest', 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0'); - // manifest:file-entry $xmlWriter->startElement('manifest:file-entry'); $xmlWriter->writeAttribute('manifest:media-type', 'application/vnd.oasis.opendocument.text'); - $xmlWriter->writeAttribute('manifest:version', '1.2'); $xmlWriter->writeAttribute('manifest:full-path', '/'); + $xmlWriter->writeAttribute('manifest:version', '1.2'); $xmlWriter->endElement(); - // manifest:file-entry - $xmlWriter->startElement('manifest:file-entry'); - $xmlWriter->writeAttribute('manifest:media-type', 'text/xml'); - $xmlWriter->writeAttribute('manifest:full-path', 'content.xml'); - $xmlWriter->endElement(); - // manifest:file-entry - $xmlWriter->startElement('manifest:file-entry'); - $xmlWriter->writeAttribute('manifest:media-type', 'text/xml'); - $xmlWriter->writeAttribute('manifest:full-path', 'meta.xml'); - $xmlWriter->endElement(); - // manifest:file-entry - $xmlWriter->startElement('manifest:file-entry'); - $xmlWriter->writeAttribute('manifest:media-type', 'text/xml'); - $xmlWriter->writeAttribute('manifest:full-path', 'styles.xml'); - $xmlWriter->endElement(); + + // Parts + foreach ($parts as $part) { + $xmlWriter->startElement('manifest:file-entry'); + $xmlWriter->writeAttribute('manifest:media-type', 'text/xml'); + $xmlWriter->writeAttribute('manifest:full-path', $part); + $xmlWriter->endElement(); + } // Media files $media = Media::getElements('section'); diff --git a/src/PhpWord/Writer/ODText/Part/Meta.php b/src/PhpWord/Writer/ODText/Part/Meta.php index 355e288b..c9e729ad 100644 --- a/src/PhpWord/Writer/ODText/Part/Meta.php +++ b/src/PhpWord/Writer/ODText/Part/Meta.php @@ -1,41 +1,43 @@ getParentWriter()->getPhpWord(); + $docProps = $phpWord->getDocumentProperties(); $xmlWriter = $this->getXmlWriter(); - // XML header $xmlWriter->startDocument('1.0', 'UTF-8'); - - // office:document-meta $xmlWriter->startElement('office:document-meta'); $xmlWriter->writeAttribute('office:version', '1.2'); $xmlWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); @@ -44,36 +46,60 @@ class Meta extends AbstractPart $xmlWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); $xmlWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); $xmlWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); - - // office:meta $xmlWriter->startElement('office:meta'); - // dc:creator - $xmlWriter->writeElement('dc:creator', $phpWord->getDocumentProperties()->getLastModifiedBy()); - // dc:date - $xmlWriter->writeElement('dc:date', gmdate('Y-m-d\TH:i:s.000', $phpWord->getDocumentProperties()->getModified())); - // dc:description - $xmlWriter->writeElement('dc:description', $phpWord->getDocumentProperties()->getDescription()); - // dc:subject - $xmlWriter->writeElement('dc:subject', $phpWord->getDocumentProperties()->getSubject()); - // dc:title - $xmlWriter->writeElement('dc:title', $phpWord->getDocumentProperties()->getTitle()); - // meta:creation-date - $xmlWriter->writeElement('meta:creation-date', gmdate('Y-m-d\TH:i:s.000', $phpWord->getDocumentProperties()->getCreated())); - // meta:initial-creator - $xmlWriter->writeElement('meta:initial-creator', $phpWord->getDocumentProperties()->getCreator()); - // meta:keyword - $xmlWriter->writeElement('meta:keyword', $phpWord->getDocumentProperties()->getKeywords()); + // Core properties + $xmlWriter->writeElement('dc:title', $docProps->getTitle()); + $xmlWriter->writeElement('dc:subject', $docProps->getSubject()); + $xmlWriter->writeElement('dc:description', $docProps->getDescription()); + $xmlWriter->writeElement('dc:creator', $docProps->getLastModifiedBy()); + $xmlWriter->writeElement('dc:date', gmdate($this->dateFormat, $docProps->getModified())); - // @todo : Where these properties are written ? - // $phpWord->getDocumentProperties()->getCategory() - // $phpWord->getDocumentProperties()->getCompany() + // Extended properties + $xmlWriter->writeElement('meta:generator', 'PHPWord'); + $xmlWriter->writeElement('meta:initial-creator', $docProps->getCreator()); + $xmlWriter->writeElement('meta:creation-date', gmdate($this->dateFormat, $docProps->getCreated())); + $xmlWriter->writeElement('meta:keyword', $docProps->getKeywords()); - $xmlWriter->endElement(); + // Category, company, and manager are put in meta namespace + $properties = array('Category', 'Company', 'Manager'); + foreach ($properties as $property) { + $method = "get{$property}"; + if ($docProps->$method() !== null) { + $this->writeCustomProperty($xmlWriter, $property, $docProps->$method()); + } + } - $xmlWriter->endElement(); + // Other custom properties + // @todo Check type. Currently all assumed as string + foreach ($docProps->getCustomProperties() as $property) { + $value = $docProps->getCustomPropertyValue($property); + $this->writeCustomProperty($xmlWriter, $property, $value); + } + + $xmlWriter->endElement(); // office:meta + $xmlWriter->endElement(); // office:document-meta - // Return return $xmlWriter->getData(); } + + /** + * Write individual property + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param string $property + * @param string $value + * + * @todo Handle other `$type`: double|date|dateTime|duration|boolean (4th arguments) + */ + private function writeCustomProperty(XMLWriter $xmlWriter, $property, $value) + { + $xmlWriter->startElement('meta:user-defined'); + $xmlWriter->writeAttribute('meta:name', $property); + // if ($type !== null) { + // $xmlWriter->writeAttribute('meta:value-type', $type); + // } + $xmlWriter->writeRaw($value); + $xmlWriter->endElement(); // meta:user-defined + } } diff --git a/src/PhpWord/Writer/ODText/Part/Mimetype.php b/src/PhpWord/Writer/ODText/Part/Mimetype.php index 3c3af1a5..1da4edb0 100644 --- a/src/PhpWord/Writer/ODText/Part/Mimetype.php +++ b/src/PhpWord/Writer/ODText/Part/Mimetype.php @@ -1,25 +1,33 @@ getXmlWriter(); // XML header $xmlWriter->startDocument('1.0', 'UTF-8'); - - // Styles:Styles $xmlWriter->startElement('office:document-styles'); $this->writeCommonRootAttributes($xmlWriter); - // office:font-face-decls + // Font declarations $this->writeFontFaces($xmlWriter); - // office:styles + // Office styles $xmlWriter->startElement('office:styles'); + $this->writeDefault($xmlWriter); + $this->writeNamed($xmlWriter); + $xmlWriter->endElement(); - // style:default-style + // Automatic styles + $xmlWriter->startElement('office:automatic-styles'); + $this->writePageLayout($xmlWriter); + $this->writeMaster($xmlWriter); + $xmlWriter->endElement(); + + $xmlWriter->endElement(); // office:document-styles + + return $xmlWriter->getData(); + } + + /** + * Write default styles + */ + private function writeDefault(XMLWriter $xmlWriter) + { $xmlWriter->startElement('style:default-style'); $xmlWriter->writeAttribute('style:family', 'paragraph'); - // style:paragraph-properties + // Paragraph $xmlWriter->startElement('style:paragraph-properties'); $xmlWriter->writeAttribute('fo:hyphenation-ladder-count', 'no-limit'); $xmlWriter->writeAttribute('style:text-autospace', 'ideograph-alpha'); @@ -58,54 +76,59 @@ class Styles extends AbstractPart $xmlWriter->writeAttribute('style:line-break', 'strict'); $xmlWriter->writeAttribute('style:tab-stop-distance', '1.249cm'); $xmlWriter->writeAttribute('style:writing-mode', 'page'); - $xmlWriter->endElement(); + $xmlWriter->endElement(); // style:paragraph-properties - // style:text-properties + // Font $xmlWriter->startElement('style:text-properties'); $xmlWriter->writeAttribute('style:use-window-font-color', 'true'); - $xmlWriter->writeAttribute('style:font-name', PhpWord::DEFAULT_FONT_NAME); - $xmlWriter->writeAttribute('fo:font-size', PhpWord::DEFAULT_FONT_SIZE . 'pt'); + $xmlWriter->writeAttribute('style:font-name', Settings::getDefaultFontName()); + $xmlWriter->writeAttribute('fo:font-size', Settings::getDefaultFontSize() . 'pt'); $xmlWriter->writeAttribute('fo:language', 'fr'); $xmlWriter->writeAttribute('fo:country', 'FR'); $xmlWriter->writeAttribute('style:letter-kerning', 'true'); - $xmlWriter->writeAttribute('style:font-name-asian', PhpWord::DEFAULT_FONT_NAME . '2'); - $xmlWriter->writeAttribute('style:font-size-asian', PhpWord::DEFAULT_FONT_SIZE . 'pt'); + $xmlWriter->writeAttribute('style:font-name-asian', Settings::getDefaultFontName() . '2'); + $xmlWriter->writeAttribute('style:font-size-asian', Settings::getDefaultFontSize() . 'pt'); $xmlWriter->writeAttribute('style:language-asian', 'zh'); $xmlWriter->writeAttribute('style:country-asian', 'CN'); - $xmlWriter->writeAttribute('style:font-name-complex', PhpWord::DEFAULT_FONT_NAME . '2'); - $xmlWriter->writeAttribute('style:font-size-complex', PhpWord::DEFAULT_FONT_SIZE . 'pt'); + $xmlWriter->writeAttribute('style:font-name-complex', Settings::getDefaultFontName() . '2'); + $xmlWriter->writeAttribute('style:font-size-complex', Settings::getDefaultFontSize() . 'pt'); $xmlWriter->writeAttribute('style:language-complex', 'hi'); $xmlWriter->writeAttribute('style:country-complex', 'IN'); $xmlWriter->writeAttribute('fo:hyphenate', 'false'); $xmlWriter->writeAttribute('fo:hyphenation-remain-char-count', '2'); $xmlWriter->writeAttribute('fo:hyphenation-push-char-count', '2'); - $xmlWriter->endElement(); + $xmlWriter->endElement(); // style:text-properties - $xmlWriter->endElement(); + $xmlWriter->endElement(); // style:default-style + } - // Write Style Definitions + /** + * Write named styles + */ + private function writeNamed(XMLWriter $xmlWriter) + { $styles = Style::getStyles(); if (count($styles) > 0) { - foreach ($styles as $styleName => $style) { - if (preg_match('#^T[0-9]+$#', $styleName) == 0 - && preg_match('#^P[0-9]+$#', $styleName) == 0 - ) { - $styleClass = str_replace('Style', 'Writer\\ODText\\Style', get_class($style)); + foreach ($styles as $style) { + if ($style->isAuto() === false) { + $styleClass = str_replace('\\Style\\', '\\Writer\\ODText\\Style\\', get_class($style)); if (class_exists($styleClass)) { + /** @var $styleWriter \PhpOffice\PhpWord\Writer\ODText\Style\AbstractStyle Type hint */ $styleWriter = new $styleClass($xmlWriter, $style); $styleWriter->write(); } } } } - $xmlWriter->endElement(); - - // office:automatic-styles - $xmlWriter->startElement('office:automatic-styles'); - // style:page-layout + } + /** + * Write page layout styles + */ + private function writePageLayout(XMLWriter $xmlWriter) + { $xmlWriter->startElement('style:page-layout'); $xmlWriter->writeAttribute('style:name', 'Mpm1'); - // style:page-layout-properties + $xmlWriter->startElement('style:page-layout-properties'); $xmlWriter->writeAttribute('fo:page-width', "21.001cm"); $xmlWriter->writeAttribute('fo:page-height', '29.7cm'); @@ -127,36 +150,38 @@ class Styles extends AbstractPart $xmlWriter->writeAttribute('style:layout-grid-base-width', '0.37cm'); $xmlWriter->writeAttribute('style:layout-grid-snap-to', 'true'); $xmlWriter->writeAttribute('style:footnote-max-height', '0cm'); - //style:footnote-sep + $xmlWriter->startElement('style:footnote-sep'); $xmlWriter->writeAttribute('style:width', '0.018cm'); $xmlWriter->writeAttribute('style:line-style', 'solid'); $xmlWriter->writeAttribute('style:adjustment', 'left'); $xmlWriter->writeAttribute('style:rel-width', '25%'); $xmlWriter->writeAttribute('style:color', '#000000'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - // style:header-style - $xmlWriter->startElement('style:header-style'); - $xmlWriter->endElement(); - // style:footer-style - $xmlWriter->startElement('style:footer-style'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - $xmlWriter->endElement(); + $xmlWriter->endElement(); //style:footnote-sep - // office:master-styles + $xmlWriter->endElement(); // style:page-layout-properties + + + $xmlWriter->startElement('style:header-style'); + $xmlWriter->endElement(); // style:header-style + + $xmlWriter->startElement('style:footer-style'); + $xmlWriter->endElement(); // style:footer-style + + $xmlWriter->endElement(); // style:page-layout + } + /** + * Write master style + */ + private function writeMaster(XMLWriter $xmlWriter) + { $xmlWriter->startElement('office:master-styles'); - // style:master-page + $xmlWriter->startElement('style:master-page'); $xmlWriter->writeAttribute('style:name', 'Standard'); $xmlWriter->writeAttribute('style:page-layout-name', 'Mpm1'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); + $xmlWriter->endElement(); // style:master-page - $xmlWriter->endElement(); - - // Return - return $xmlWriter->getData(); + $xmlWriter->endElement(); // office:master-styles } } diff --git a/src/PhpWord/Writer/ODText/Style/AbstractStyle.php b/src/PhpWord/Writer/ODText/Style/AbstractStyle.php index 30416b5d..18d6ce10 100644 --- a/src/PhpWord/Writer/ODText/Style/AbstractStyle.php +++ b/src/PhpWord/Writer/ODText/Style/AbstractStyle.php @@ -1,19 +1,29 @@ style instanceof \PhpOffice\PhpWord\Style\Font)) { + $style = $this->getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Font) { return; } + $xmlWriter = $this->getXmlWriter(); - $this->xmlWriter->startElement('style:style'); - $this->xmlWriter->writeAttribute('style:name', $this->style->getStyleName()); - $this->xmlWriter->writeAttribute('style:family', 'text'); - $this->xmlWriter->startElement('style:text-properties'); - if ($this->style->getName()) { - $this->xmlWriter->writeAttribute('style:font-name', $this->style->getName()); - $this->xmlWriter->writeAttribute('style:font-name-complex', $this->style->getName()); - } - if ($this->style->getSize()) { - $this->xmlWriter->writeAttribute('fo:font-size', ($this->style->getSize()) . 'pt'); - $this->xmlWriter->writeAttribute('style:font-size-asian', ($this->style->getSize()) . 'pt'); - $this->xmlWriter->writeAttribute('style:font-size-complex', ($this->style->getSize()) . 'pt'); - } - if ($this->style->getColor()) { - $this->xmlWriter->writeAttribute('fo:color', '#' . $this->style->getColor()); - } - if ($this->style->getItalic()) { - $this->xmlWriter->writeAttribute('fo:font-style', 'italic'); - $this->xmlWriter->writeAttribute('style:font-style-asian', 'italic'); - $this->xmlWriter->writeAttribute('style:font-style-complex', 'italic'); - } - if ($this->style->getBold()) { - $this->xmlWriter->writeAttribute('fo:font-weight', 'bold'); - $this->xmlWriter->writeAttribute('style:font-weight-asian', 'bold'); - } - $this->xmlWriter->endElement(); // style:text-properties - $this->xmlWriter->endElement(); // style:style - } + $xmlWriter->startElement('style:style'); + $xmlWriter->writeAttribute('style:name', $style->getStyleName()); + $xmlWriter->writeAttribute('style:family', 'text'); + $xmlWriter->startElement('style:text-properties'); - /** - * Set is automatic style - * - * @param bool $value - */ - public function setIsAuto($value) - { - $this->isAuto = $value; + // Name + $font = $style->getName(); + $xmlWriter->writeAttributeIf($font != '', 'style:font-name', $font); + $xmlWriter->writeAttributeIf($font != '', 'style:font-name-complex', $font); + $size = $style->getSize(); + + // Size + $xmlWriter->writeAttributeIf(is_numeric($size), 'fo:font-size', $size . 'pt'); + $xmlWriter->writeAttributeIf(is_numeric($size), 'style:font-size-asian', $size . 'pt'); + $xmlWriter->writeAttributeIf(is_numeric($size), 'style:font-size-complex', $size . 'pt'); + + // Color + $color = $style->getColor(); + $xmlWriter->writeAttributeIf($color != '', 'fo:color', '#' . $color); + + // Bold & italic + $xmlWriter->writeAttributeIf($style->isBold(), 'fo:font-weight', 'bold'); + $xmlWriter->writeAttributeIf($style->isBold(), 'style:font-weight-asian', 'bold'); + $xmlWriter->writeAttributeIf($style->isItalic(), 'fo:font-style', 'italic'); + $xmlWriter->writeAttributeIf($style->isItalic(), 'style:font-style-asian', 'italic'); + $xmlWriter->writeAttributeIf($style->isItalic(), 'style:font-style-complex', 'italic'); + + // Underline + // @todo Various mode of underline + $underline = $style->getUnderline(); + $xmlWriter->writeAttributeIf($underline != 'none', 'style:text-underline-style', 'solid'); + + // Strikethrough, double strikethrough + $xmlWriter->writeAttributeIf($style->isStrikethrough(), 'style:text-line-through-type', 'single'); + $xmlWriter->writeAttributeIf($style->isDoubleStrikethrough(), 'style:text-line-through-type', 'double'); + + // Small caps, all caps + $xmlWriter->writeAttributeIf($style->isSmallCaps(), 'fo:font-variant', 'small-caps'); + $xmlWriter->writeAttributeIf($style->isAllCaps(), 'fo:text-transform', 'uppercase'); + + // Superscript/subscript + $xmlWriter->writeAttributeIf($style->isSuperScript(), 'style:text-position', 'super'); + $xmlWriter->writeAttributeIf($style->isSubScript(), 'style:text-position', 'sub'); + + // @todo Foreground-Color + + // @todo Background color + + $xmlWriter->endElement(); // style:text-properties + $xmlWriter->endElement(); // style:style } } diff --git a/src/PhpWord/Writer/ODText/Style/Image.php b/src/PhpWord/Writer/ODText/Style/Image.php new file mode 100644 index 00000000..de97f474 --- /dev/null +++ b/src/PhpWord/Writer/ODText/Style/Image.php @@ -0,0 +1,49 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Image) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('style:style'); + $xmlWriter->writeAttribute('style:name', $style->getStyleName()); + $xmlWriter->writeAttribute('style:family', 'graphic'); + $xmlWriter->writeAttribute('style:parent-style-name', 'Graphics'); + $xmlWriter->startElement('style:graphic-properties'); + $xmlWriter->writeAttribute('style:vertical-pos', 'top'); + $xmlWriter->writeAttribute('style:vertical-rel', 'baseline'); + $xmlWriter->endElement(); // style:graphic-properties + $xmlWriter->endElement(); // style:style + } +} diff --git a/src/PhpWord/Writer/ODText/Style/Paragraph.php b/src/PhpWord/Writer/ODText/Style/Paragraph.php index 7bd490c3..133b8cdf 100644 --- a/src/PhpWord/Writer/ODText/Style/Paragraph.php +++ b/src/PhpWord/Writer/ODText/Style/Paragraph.php @@ -1,16 +1,22 @@ style instanceof \PhpOffice\PhpWord\Style\Paragraph)) { + $style = $this->getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Paragraph) { return; } + $xmlWriter = $this->getXmlWriter(); - $marginTop = is_null($this->style->getSpaceBefore()) ? '0' : round(17.6 / $this->style->getSpaceBefore(), 2); - $marginBottom = is_null($this->style->getSpaceAfter()) ? '0' : round(17.6 / $this->style->getSpaceAfter(), 2); + $marginTop = is_null($style->getSpaceBefore()) ? '0' : round(17.6 / $style->getSpaceBefore(), 2); + $marginBottom = is_null($style->getSpaceAfter()) ? '0' : round(17.6 / $style->getSpaceAfter(), 2); - $this->xmlWriter->startElement('style:style'); - $this->xmlWriter->writeAttribute('style:name', $this->style->getStyleName()); - $this->xmlWriter->writeAttribute('style:family', 'paragraph'); - if ($this->isAuto) { - $this->xmlWriter->writeAttribute('style:parent-style-name', 'Standard'); - $this->xmlWriter->writeAttribute('style:master-page-name', 'Standard'); + $xmlWriter->startElement('style:style'); + $xmlWriter->writeAttribute('style:name', $style->getStyleName()); + $xmlWriter->writeAttribute('style:family', 'paragraph'); + if ($style->isAuto()) { + $xmlWriter->writeAttribute('style:parent-style-name', 'Standard'); + $xmlWriter->writeAttribute('style:master-page-name', 'Standard'); } - $this->xmlWriter->startElement('style:paragraph-properties'); - if ($this->isAuto) { - $this->xmlWriter->writeAttribute('style:page-number', 'auto'); + $xmlWriter->startElement('style:paragraph-properties'); + if ($style->isAuto()) { + $xmlWriter->writeAttribute('style:page-number', 'auto'); } else { - $this->xmlWriter->writeAttribute('fo:margin-top', $marginTop . 'cm'); - $this->xmlWriter->writeAttribute('fo:margin-bottom', $marginBottom . 'cm'); - $this->xmlWriter->writeAttribute('fo:text-align', $this->style->getAlign()); + $xmlWriter->writeAttribute('fo:margin-top', $marginTop . 'cm'); + $xmlWriter->writeAttribute('fo:margin-bottom', $marginBottom . 'cm'); + $xmlWriter->writeAttribute('fo:text-align', $style->getAlign()); } - $this->xmlWriter->endElement(); //style:paragraph-properties + $xmlWriter->endElement(); //style:paragraph-properties - $this->xmlWriter->endElement(); //style:style - } - - /** - * Set is automatic style - * - * @param bool $value - */ - public function setIsAuto($value) - { - $this->isAuto = $value; + $xmlWriter->endElement(); //style:style } } diff --git a/src/PhpWord/Writer/ODText/Style/Section.php b/src/PhpWord/Writer/ODText/Style/Section.php new file mode 100644 index 00000000..3d910157 --- /dev/null +++ b/src/PhpWord/Writer/ODText/Style/Section.php @@ -0,0 +1,51 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Section) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('style:style'); + $xmlWriter->writeAttribute('style:name', $style->getStyleName()); + $xmlWriter->writeAttribute('style:family', "section"); + $xmlWriter->startElement('style:section-properties'); + + $xmlWriter->startElement('style:columns'); + $xmlWriter->writeAttribute('fo:column-count', $style->getColsNum()); + $xmlWriter->endElement(); // style:columns + + $xmlWriter->endElement(); // style:section-properties + $xmlWriter->endElement(); // style:style + } +} diff --git a/src/PhpWord/Writer/ODText/Style/Table.php b/src/PhpWord/Writer/ODText/Style/Table.php new file mode 100644 index 00000000..b32349af --- /dev/null +++ b/src/PhpWord/Writer/ODText/Style/Table.php @@ -0,0 +1,49 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Table) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('style:style'); + $xmlWriter->writeAttribute('style:name', $style->getStyleName()); + $xmlWriter->writeAttribute('style:family', 'table'); + $xmlWriter->startElement('style:table-properties'); + //$xmlWriter->writeAttribute('style:width', 'table'); + $xmlWriter->writeAttribute('style:rel-width', 100); + $xmlWriter->writeAttribute('table:align', 'center'); + $xmlWriter->endElement(); // style:table-properties + $xmlWriter->endElement(); // style:style + } +} diff --git a/src/PhpWord/Writer/PDF.php b/src/PhpWord/Writer/PDF.php index 7421e3e4..17865563 100644 --- a/src/PhpWord/Writer/PDF.php +++ b/src/PhpWord/Writer/PDF.php @@ -1,10 +1,18 @@ renderer = new $rendererName($phpWord); } @@ -57,9 +68,10 @@ class PDF */ public function __call($name, $arguments) { - if ($this->renderer === null) { - throw new Exception("PDF Rendering library has not been defined."); - } + // Note: Commented because all exceptions should already be catched by `__construct` + // if ($this->renderer === null) { + // throw new Exception("PDF Rendering library has not been defined."); + // } return call_user_func_array(array($this->renderer, $name), $arguments); } diff --git a/src/PhpWord/Writer/PDF/AbstractRenderer.php b/src/PhpWord/Writer/PDF/AbstractRenderer.php index 860a29dc..d4288c8a 100644 --- a/src/PhpWord/Writer/PDF/AbstractRenderer.php +++ b/src/PhpWord/Writer/PDF/AbstractRenderer.php @@ -1,22 +1,41 @@ includeFile; + if (file_exists($includeFile)) { + /** @noinspection PhpIncludeInspection Dynamic includes */ + require_once $includeFile; + } else { + // @codeCoverageIgnoreStart + // Can't find any test case. Uncomment when found. + throw new Exception('Unable to load PDF Rendering library'); + // @codeCoverageIgnoreEnd + } } /** @@ -82,10 +112,12 @@ abstract class AbstractRenderer extends \PhpOffice\PhpWord\Writer\HTML * 'arialunicid0-japanese' * * @param string $fontName + * @return self */ public function setFont($fontName) { $this->font = $fontName; + return $this; } @@ -102,12 +134,12 @@ abstract class AbstractRenderer extends \PhpOffice\PhpWord\Writer\HTML /** * Set Paper Size * - * @param int $pValue Paper size = PAPERSIZE_A4 + * @param int $value Paper size = PAPERSIZE_A4 * @return self */ - public function setPaperSize($pValue = 9) + public function setPaperSize($value = 9) { - $this->paperSize = $pValue; + $this->paperSize = $value; return $this; } @@ -124,27 +156,31 @@ abstract class AbstractRenderer extends \PhpOffice\PhpWord\Writer\HTML /** * Set Orientation * - * @param string $pValue Page orientation ORIENTATION_DEFAULT + * @param string $value Page orientation ORIENTATION_DEFAULT * @return self */ - public function setOrientation($pValue = 'default') + public function setOrientation($value = 'default') { - $this->orientation = $pValue; + $this->orientation = $value; return $this; } /** * Save PhpWord to PDF file, pre-save * - * @param string $pFilename Name of the file to save as + * @param string $filename Name of the file to save as * @return resource + * @throws \PhpOffice\PhpWord\Exception\Exception */ - protected function prepareForSave($pFilename = null) + protected function prepareForSave($filename = null) { - $fileHandle = fopen($pFilename, 'w'); + $fileHandle = fopen($filename, 'w'); + // @codeCoverageIgnoreStart + // Can't find any test case. Uncomment when found. if ($fileHandle === false) { - throw new Exception("Could not open file $pFilename for writing."); + throw new Exception("Could not open file $filename for writing."); } + // @codeCoverageIgnoreEnd $this->isPdf = true; return $fileHandle; diff --git a/src/PhpWord/Writer/PDF/DomPDF.php b/src/PhpWord/Writer/PDF/DomPDF.php index d4c7b5f8..a40e2cea 100644 --- a/src/PhpWord/Writer/PDF/DomPDF.php +++ b/src/PhpWord/Writer/PDF/DomPDF.php @@ -1,65 +1,56 @@ set_paper(strtolower($paperSize), $orientation); - - $pdf->load_html($this->writeDocument()); + $pdf->load_html($this->getContent()); $pdf->render(); // Write to file diff --git a/src/PhpWord/Writer/PDF/MPDF.php b/src/PhpWord/Writer/PDF/MPDF.php new file mode 100644 index 00000000..9d4e050c --- /dev/null +++ b/src/PhpWord/Writer/PDF/MPDF.php @@ -0,0 +1,71 @@ +_setPageSize($paperSize, $orientation); + $pdf->addPage($orientation); + + // Write document properties + $phpWord = $this->getPhpWord(); + $docProps = $phpWord->getDocumentProperties(); + $pdf->setTitle($docProps->getTitle()); + $pdf->setAuthor($docProps->getCreator()); + $pdf->setSubject($docProps->getSubject()); + $pdf->setKeywords($docProps->getKeywords()); + $pdf->setCreator($docProps->getCreator()); + + $pdf->writeHTML($this->getContent()); + + // Write to file + fwrite($fileHandle, $pdf->output($filename, 'S')); + + parent::restoreStateAfterSave($fileHandle); + } +} diff --git a/src/PhpWord/Writer/PDF/TCPDF.php b/src/PhpWord/Writer/PDF/TCPDF.php new file mode 100644 index 00000000..669a2cdd --- /dev/null +++ b/src/PhpWord/Writer/PDF/TCPDF.php @@ -0,0 +1,73 @@ +setFontSubsetting(false); + $pdf->setPrintHeader(false); + $pdf->setPrintFooter(false); + $pdf->addPage(); + $pdf->setFont($this->getFont()); + $pdf->writeHTML($this->getContent()); + + // Write document properties + $phpWord = $this->getPhpWord(); + $docProps = $phpWord->getDocumentProperties(); + $pdf->setTitle($docProps->getTitle()); + $pdf->setAuthor($docProps->getCreator()); + $pdf->setSubject($docProps->getSubject()); + $pdf->setKeywords($docProps->getKeywords()); + $pdf->setCreator($docProps->getCreator()); + + // Write to file + fwrite($fileHandle, $pdf->output($filename, 'S')); + + parent::restoreStateAfterSave($fileHandle); + } +} diff --git a/src/PhpWord/Writer/RTF.php b/src/PhpWord/Writer/RTF.php index dca6bc1f..d7fed942 100644 --- a/src/PhpWord/Writer/RTF.php +++ b/src/PhpWord/Writer/RTF.php @@ -1,21 +1,23 @@ setPhpWord($phpWord); - } - /** - * Save PhpWord to file - * - * @param string $pFilename - * @throws \PhpOffice\PhpWord\Exception\Exception - */ - public function save($pFilename = null) - { - if (!is_null($this->phpWord)) { - $pFilename = $this->getTempFile($pFilename); - - $hFile = fopen($pFilename, 'w'); - if ($hFile !== false) { - fwrite($hFile, $this->writeDocument()); - fclose($hFile); - } else { - throw new Exception("Can't open file"); + $this->parts = array('Header', 'Document'); + foreach ($this->parts as $partName) { + $partClass = get_class($this) . '\\Part\\' . $partName; + if (class_exists($partClass)) { + /** @var \PhpOffice\PhpWord\Writer\RTF\Part\AbstractPart $part Type hint */ + $part = new $partClass(); + $part->setParentWriter($this); + $this->writerParts[strtolower($partName)] = $part; } - $this->cleanupTempFile(); - } else { - throw new Exception("PhpWord object unassigned."); } } /** - * Get color table + * Save content to file + * + * @param string $filename + * @throws \PhpOffice\PhpWord\Exception\Exception */ - public function getColorTable() + public function save($filename = null) { - return $this->colorTable; + $fileHandle = $this->openFile($filename); + $this->writeFile($fileHandle, $this->getContent()); + } + + /** + * Get content + * + * @return string + * @since 0.11.0 + */ + private function getContent() + { + $content = ''; + + $content .= '{'; + $content .= '\rtf1' . PHP_EOL; + $content .= $this->getWriterPart('Header')->write(); + $content .= $this->getWriterPart('Document')->write(); + $content .= '}'; + + return $content; } /** @@ -92,7 +90,15 @@ class RTF extends AbstractWriter implements WriterInterface */ public function getFontTable() { - return $this->fontTable; + return $this->getWriterPart('Header')->getFontTable(); + } + + /** + * Get color table + */ + public function getColorTable() + { + return $this->getWriterPart('Header')->getColorTable(); } /** @@ -112,195 +118,4 @@ class RTF extends AbstractWriter implements WriterInterface { $this->lastParagraphStyle = $value; } - - /** - * Get all data - * - * @return string - */ - private function writeDocument() - { - $this->fontTable = $this->populateFontTable(); - $this->colorTable = $this->populateColorTable(); - - // Set the default character set - $sRTFContent = '{\rtf1'; - $sRTFContent .= '\ansi\ansicpg1252'; // Set the default font (the first one) - $sRTFContent .= '\deff0'; // Set the default tab size (720 twips) - $sRTFContent .= '\deftab720'; - $sRTFContent .= PHP_EOL; - - // Set the font tbl group - $sRTFContent .= '{\fonttbl'; - foreach ($this->fontTable as $idx => $font) { - $sRTFContent .= '{\f' . $idx . '\fnil\fcharset0 ' . $font . ';}'; - } - $sRTFContent .= '}' . PHP_EOL; - - // Set the color tbl group - $sRTFContent .= '{\colortbl '; - foreach ($this->colorTable as $idx => $color) { - $arrColor = Drawing::htmlToRGB($color); - $sRTFContent .= ';\red' . $arrColor[0] . '\green' . $arrColor[1] . '\blue' . $arrColor[2] . ''; - } - $sRTFContent .= ';}' . PHP_EOL; - - $sRTFContent .= '{\*\generator PhpWord;}' . PHP_EOL; // Set the generator - $sRTFContent .= '\viewkind4'; // Set the view mode of the document - $sRTFContent .= '\uc1'; // Set the numberof bytes that follows a unicode character - $sRTFContent .= '\pard'; // Resets to default paragraph properties. - $sRTFContent .= '\nowidctlpar'; // No widow/orphan control - $sRTFContent .= '\lang1036'; // Applies a language to a text run (1036 : French (France)) - $sRTFContent .= '\kerning1'; // Point size (in half-points) above which to kern character pairs - $sRTFContent .= '\fs' . (PhpWord::DEFAULT_FONT_SIZE * 2); // Set the font size in half-points - $sRTFContent .= PHP_EOL; - - // Body - $sRTFContent .= $this->writeContent(); - - $sRTFContent .= '}'; - - return $sRTFContent; - } - - /** - * Get content data - * - * @return string - */ - private function writeContent() - { - $phpWord = $this->phpWord; - $sRTFBody = ''; - - $sections = $phpWord->getSections(); - $countSections = count($sections); - $pSection = 0; - - if ($countSections > 0) { - foreach ($sections as $section) { - $pSection++; - $elements = $section->getElements(); - foreach ($elements as $element) { - $elementWriter = new ElementWriter($this, $element); - $sRTFBody .= $elementWriter->write(); - } - } - } - return $sRTFBody; - } - - /** - * Get all fonts - * - * @return array - */ - private function populateFontTable() - { - $phpWord = $this->phpWord; - - $arrFonts = array(); - // Default font : PhpWord::DEFAULT_FONT_NAME - $arrFonts[] = PhpWord::DEFAULT_FONT_NAME; - // PhpWord object : $this->phpWord - - // Browse styles - $styles = Style::getStyles(); - if (count($styles) > 0) { - foreach ($styles as $style) { - // Font - if ($style instanceof Font) { - if (in_array($style->getName(), $arrFonts) == false) { - $arrFonts[] = $style->getName(); - } - } - } - } - - // Search all fonts used - $sections = $phpWord->getSections(); - $countSections = count($sections); - if ($countSections > 0) { - $pSection = 0; - - foreach ($sections as $section) { - $pSection++; - $elements = $section->getElements(); - - foreach ($elements as $element) { - if ($element instanceof Text) { - $fontStyle = $element->getFontStyle(); - - if ($fontStyle instanceof Font) { - if (in_array($fontStyle->getName(), $arrFonts) == false) { - $arrFonts[] = $fontStyle->getName(); - } - } - } - } - } - } - - return $arrFonts; - } - - /** - * Get all colors - * - * @return array - */ - private function populateColorTable() - { - $phpWord = $this->phpWord; - - $arrColors = array(); - // PhpWord object : $this->phpWord - - // Browse styles - $styles = Style::getStyles(); - if (count($styles) > 0) { - foreach ($styles as $style) { - // Font - if ($style instanceof Font) { - $color = $style->getColor(); - $fgcolor = $style->getFgColor(); - if (in_array($color, $arrColors) == false && $color != PhpWord::DEFAULT_FONT_COLOR && !empty($color)) { - $arrColors[] = $color; - } - if (in_array($fgcolor, $arrColors) == false && $fgcolor != PhpWord::DEFAULT_FONT_COLOR && !empty($fgcolor)) { - $arrColors[] = $fgcolor; - } - } - } - } - - // Search all fonts used - $sections = $phpWord->getSections(); - $countSections = count($sections); - if ($countSections > 0) { - $pSection = 0; - - foreach ($sections as $section) { - $pSection++; - $elements = $section->getElements(); - - foreach ($elements as $element) { - if ($element instanceof Text) { - $fontStyle = $element->getFontStyle(); - - if ($fontStyle instanceof Font) { - if (in_array($fontStyle->getColor(), $arrColors) == false) { - $arrColors[] = $fontStyle->getColor(); - } - if (in_array($fontStyle->getFgColor(), $arrColors) == false) { - $arrColors[] = $fontStyle->getFgColor(); - } - } - } - } - } - } - - return $arrColors; - } } diff --git a/src/PhpWord/Writer/RTF/Element/AbstractElement.php b/src/PhpWord/Writer/RTF/Element/AbstractElement.php new file mode 100644 index 00000000..79e13947 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Element/AbstractElement.php @@ -0,0 +1,164 @@ +parentWriter; + + /** @var \PhpOffice\PhpWord\Element\Text $element Type hint */ + $element = $this->element; + + // Font style + if (method_exists($element, 'getFontStyle')) { + $this->fontStyle = $element->getFontStyle(); + if (is_string($this->fontStyle)) { + $this->fontStyle = Style::getStyle($this->fontStyle); + } + } + + // Paragraph style + if (method_exists($element, 'getParagraphStyle')) { + $this->paragraphStyle = $element->getParagraphStyle(); + if (is_string($this->paragraphStyle)) { + $this->paragraphStyle = Style::getStyle($this->paragraphStyle); + } + + if ($this->paragraphStyle !== null && !$this->withoutP) { + if ($parentWriter->getLastParagraphStyle() != $element->getParagraphStyle()) { + $parentWriter->setLastParagraphStyle($element->getParagraphStyle()); + } else { + $parentWriter->setLastParagraphStyle(); + $this->paragraphStyle = null; + } + } else { + $parentWriter->setLastParagraphStyle(); + $this->paragraphStyle = null; + } + } + } + + /** + * Write opening + * + * @return string + */ + protected function writeOpening() + { + if ($this->withoutP || !$this->paragraphStyle instanceof ParagraphStyle) { + return ''; + } + + $styleWriter = new ParagraphStyleWriter($this->paragraphStyle); + $styleWriter->setNestedLevel($this->element->getNestedLevel()); + return $styleWriter->write(); + } + + /** + * Write text + * + * @param string $text + * @return string + */ + protected function writeText($text) + { + return String::toUnicode($text); + } + + /** + * Write closing + * + * @return string + */ + protected function writeClosing() + { + if ($this->withoutP) { + return ''; + } + + return '\par' . PHP_EOL; + } + + /** + * Write font style + * + * @return string + */ + protected function writeFontStyle() + { + if (!$this->fontStyle instanceof FontStyle) { + return ''; + } + + /** @var \PhpOffice\PhpWord\Writer\RTF $parentWriter Type hint */ + $parentWriter = $this->parentWriter; + + // Create style writer and set color/name index + $styleWriter = new FontStyleWriter($this->fontStyle); + if ($this->fontStyle->getColor() != null) { + $colorIndex = array_search($this->fontStyle->getColor(), $parentWriter->getColorTable()); + if ($colorIndex !== false) { + $styleWriter->setColorIndex($colorIndex + 1); + } + } + if ($this->fontStyle->getName() != null) { + $fontIndex = array_search($this->fontStyle->getName(), $parentWriter->getFontTable()); + if ($fontIndex !== false) { + $styleWriter->setNameIndex($fontIndex); + } + } + + // Write style + $content = $styleWriter->write(); + + return $content; + } +} diff --git a/src/PhpWord/Writer/RTF/Element/Container.php b/src/PhpWord/Writer/RTF/Element/Container.php new file mode 100644 index 00000000..cb95b84b --- /dev/null +++ b/src/PhpWord/Writer/RTF/Element/Container.php @@ -0,0 +1,35 @@ +parentWriter = $parentWriter; - $this->element = $element; - $this->withoutP = $withoutP; - } - - /** - * Write element - * - * @return string - */ - public function write() - { - $rtfText = ''; - $elmName = str_replace('PhpOffice\\PhpWord\\Element\\', '', get_class($this->element)); - $elmWriterClass = 'PhpOffice\\PhpWord\\Writer\\RTF\\Element\\' . $elmName; - if (class_exists($elmWriterClass) === true) { - $elmWriter = new $elmWriterClass($this->parentWriter, $this->element, $this->withoutP); - $rtfText = $elmWriter->write(); - } - - return $rtfText; - } -} diff --git a/src/PhpWord/Writer/RTF/Element/Image.php b/src/PhpWord/Writer/RTF/Element/Image.php new file mode 100644 index 00000000..1daae2a0 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Element/Image.php @@ -0,0 +1,57 @@ +element instanceof ImageElement) { + return ''; + } + + $this->getStyles(); + $style = $this->element->getStyle(); + + $content = ''; + $content .= $this->writeOpening(); + $content .= '{\*\shppict {\pict'; + $content .= '\pngblip\picscalex100\picscaley100'; + $content .= '\picwgoal' . round(Font::pixelSizeToTwips($style->getWidth())); + $content .= '\pichgoal' . round(Font::pixelSizeToTwips($style->getHeight())); + $content .= PHP_EOL; + $content .= $this->element->getImageStringData(); + $content .= '}}'; + $content .= $this->writeClosing(); + + return $content; + } +} diff --git a/src/PhpWord/Writer/RTF/Element/Link.php b/src/PhpWord/Writer/RTF/Element/Link.php new file mode 100644 index 00000000..22b08588 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Element/Link.php @@ -0,0 +1,50 @@ +element instanceof \PhpOffice\PhpWord\Element\Link) { + return ''; + } + + $this->getStyles(); + + $content = ''; + $content .= $this->writeOpening(); + $content .= '{\field {\*\fldinst {HYPERLINK "' . $this->element->getTarget() . '"}}{\\fldrslt {'; + $content .= $this->writeFontStyle(); + $content .= $this->writeText($this->element->getText()); + $content .= '}}}'; + $content .= $this->writeClosing(); + + return $content; + } +} diff --git a/src/PhpWord/Writer/RTF/Element/ListItem.php b/src/PhpWord/Writer/RTF/Element/ListItem.php new file mode 100644 index 00000000..b795143c --- /dev/null +++ b/src/PhpWord/Writer/RTF/Element/ListItem.php @@ -0,0 +1,27 @@ +element instanceof TableElement) { + return ''; + } + $element = $this->element; + // No nesting table for now + if ($element->getNestedLevel() >= 1) { + return ''; + } + + $content = ''; + $rows = $element->getRows(); + $rowCount = count($rows); + + if ($rowCount > 0) { + $content .= '\pard' . PHP_EOL; + + for ($i = 0; $i < $rowCount; $i++) { + $content .= '\trowd '; + $content .= $this->writeRowDef($rows[$i]); + $content .= PHP_EOL; + $content .= $this->writeRow($rows[$i]); + $content .= '\row' . PHP_EOL; + } + } + + return $content; + } + + /** + * Write column + * + * @return string + */ + private function writeRowDef(RowElement $row) + { + $content = ''; + + $rightMargin = 0; + foreach ($row->getCells() as $cell) { + $width = $cell->getWidth(); + $vMerge = $this->getVMerge($cell->getStyle()->getVMerge()); + if ($width === null) { + $width = 720; // Arbitrary default width + } + $rightMargin += $width; + $content .= "{$vMerge}\cellx{$rightMargin} "; + } + + return $content; + } + + /** + * Write row + * + * @return string + */ + private function writeRow(RowElement $row) + { + $content = ''; + + // Write cells + foreach ($row->getCells() as $cell) { + $content .= $this->writeCell($cell); + } + + return $content; + } + + /** + * Write cell + * + * @return string + */ + private function writeCell(CellElement $cell) + { + $content = '\intbl' . PHP_EOL; + + // Write content + $writer = new Container($this->parentWriter, $cell); + $content .= $writer->write(); + + $content .= '\cell' . PHP_EOL; + + return $content; + } + + /** + * Get vertical merge style + * + * @param string $value + * @return string + * @todo Move to style + */ + private function getVMerge($value) + { + $style = ''; + if ($value == 'restart') { + $style = '\clvmgf'; + } elseif ($value == 'continue') { + $style = '\clvmrg'; + } + + return $style; + } +} diff --git a/src/PhpWord/Writer/RTF/Element/Text.php b/src/PhpWord/Writer/RTF/Element/Text.php index 2ee110e0..38ef4c94 100644 --- a/src/PhpWord/Writer/RTF/Element/Text.php +++ b/src/PhpWord/Writer/RTF/Element/Text.php @@ -1,111 +1,53 @@ element->getFontStyle(); - if (is_string($fontStyle)) { - $fontStyle = Style::getStyle($fontStyle); + /** @var \PhpOffice\PhpWord\Element\Text $element Type hint */ + $element = $this->element; + $elementClass = str_replace('\\Writer\\RTF', '', get_class($this)); + if (!$element instanceof $elementClass) { + return ''; } - $paragraphStyle = $this->element->getParagraphStyle(); - if (is_string($paragraphStyle)) { - $paragraphStyle = Style::getStyle($paragraphStyle); - } + $this->getStyles(); - if ($paragraphStyle && !$this->withoutP) { - if ($this->parentWriter->getLastParagraphStyle() != $this->element->getParagraphStyle()) { - $rtfText .= '\pard\nowidctlpar'; - if ($paragraphStyle->getSpaceAfter() != null) { - $rtfText .= '\sa' . $paragraphStyle->getSpaceAfter(); - } - if ($paragraphStyle->getAlign() != null) { - if ($paragraphStyle->getAlign() == 'center') { - $rtfText .= '\qc'; - } - } - $this->parentWriter->setLastParagraphStyle($this->element->getParagraphStyle()); - } else { - $this->parentWriter->setLastParagraphStyle(); - } - } else { - $this->parentWriter->setLastParagraphStyle(); - } + $content = ''; + $content .= $this->writeOpening(); + $content .= '{'; + $content .= $this->writeFontStyle(); + $content .= $this->writeText($element->getText()); + $content .= '}'; + $content .= $this->writeClosing(); - if ($fontStyle instanceof Font) { - if ($fontStyle->getColor() != null) { - $idxColor = array_search($fontStyle->getColor(), $this->parentWriter->getColorTable()); - if ($idxColor !== false) { - $rtfText .= '\cf' . ($idxColor + 1); - } - } else { - $rtfText .= '\cf0'; - } - if ($fontStyle->getName() != null) { - $idxFont = array_search($fontStyle->getName(), $this->parentWriter->getFontTable()); - if ($idxFont !== false) { - $rtfText .= '\f' . $idxFont; - } - } else { - $rtfText .= '\f0'; - } - if ($fontStyle->getBold()) { - $rtfText .= '\b'; - } - if ($fontStyle->getItalic()) { - $rtfText .= '\i'; - } - if ($fontStyle->getSize()) { - $rtfText .= '\fs' . ($fontStyle->getSize() * 2); - } - } - if ($this->parentWriter->getLastParagraphStyle() != '' || $fontStyle) { - $rtfText .= ' '; - } - $rtfText .= $this->element->getText(); - - if ($fontStyle instanceof Font) { - $rtfText .= '\cf0'; - $rtfText .= '\f0'; - - if ($fontStyle->getBold()) { - $rtfText .= '\b0'; - } - if ($fontStyle->getItalic()) { - $rtfText .= '\i0'; - } - if ($fontStyle->getSize()) { - $rtfText .= '\fs' . (PhpWord::DEFAULT_FONT_SIZE * 2); - } - } - - if (!$this->withoutP) { - $rtfText .= '\par' . PHP_EOL; - } - return $rtfText; + return $content; } } diff --git a/src/PhpWord/Writer/RTF/Element/TextBreak.php b/src/PhpWord/Writer/RTF/Element/TextBreak.php index 91ae706d..57dc6349 100644 --- a/src/PhpWord/Writer/RTF/Element/TextBreak.php +++ b/src/PhpWord/Writer/RTF/Element/TextBreak.php @@ -1,10 +1,18 @@ parentWriter->setLastParagraphStyle(); + /** @var \PhpOffice\PhpWord\Writer\RTF $parentWriter Type hint */ + $parentWriter = $this->parentWriter; + $parentWriter->setLastParagraphStyle(); - return '\par' . PHP_EOL; + return '\pard\par' . PHP_EOL; } } diff --git a/src/PhpWord/Writer/RTF/Element/TextRun.php b/src/PhpWord/Writer/RTF/Element/TextRun.php index 86c30f4b..e7563716 100644 --- a/src/PhpWord/Writer/RTF/Element/TextRun.php +++ b/src/PhpWord/Writer/RTF/Element/TextRun.php @@ -1,22 +1,28 @@ element->getElements(); - if (count($elements) > 0) { - $rtfText .= '\pard\nowidctlpar' . PHP_EOL; - foreach ($elements as $element) { - if ($element instanceof TextElement) { - $elementWriter = new Element($this->parentWriter, $element, true); - $rtfText .= '{'; - $rtfText .= $elementWriter->write(); - $rtfText .= '}' . PHP_EOL; - } - } - $rtfText .= '\par' . PHP_EOL; - } + $writer = new Container($this->parentWriter, $this->element); - return $rtfText; + $content = ''; + $content .= $this->writeOpening(); + $content .= '{'; + $content .= $writer->write(); + $content .= '}'; + $content .= $this->writeClosing(); + + return $content; } } diff --git a/src/PhpWord/Writer/RTF/Element/Title.php b/src/PhpWord/Writer/RTF/Element/Title.php index 61a40032..b9645a68 100644 --- a/src/PhpWord/Writer/RTF/Element/Title.php +++ b/src/PhpWord/Writer/RTF/Element/Title.php @@ -1,33 +1,27 @@ element->getText(); - $rtfText .= '\par' . PHP_EOL; - - return $rtfText; - } } diff --git a/src/PhpWord/Writer/RTF/Part/AbstractPart.php b/src/PhpWord/Writer/RTF/Part/AbstractPart.php new file mode 100644 index 00000000..b10e5654 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Part/AbstractPart.php @@ -0,0 +1,29 @@ +writeInfo(); + $content .= $this->writeFormatting(); + $content .= $this->writeSections(); + + return $content; + } + + /** + * Write document information + * + * @return string + */ + private function writeInfo() + { + $docProps = $this->getParentWriter()->getPhpWord()->getDocumentProperties(); + $properties = array('title', 'subject', 'category', 'keywords', 'comment', + 'author', 'operator', 'creatim', 'revtim', 'company', 'manager'); + $mapping = array('comment' => 'description', 'author' => 'creator', 'operator' => 'lastModifiedBy', + 'creatim' => 'created', 'revtim' => 'modified'); + $dateFields = array('creatim', 'revtim'); + + $content = ''; + + $content .= '{'; + $content .= '\info'; + foreach ($properties as $property) { + $method = 'get' . (array_key_exists($property, $mapping) ? $mapping[$property] : $property); + $value = $docProps->$method(); + $value = in_array($property, $dateFields) ? $this->getDateValue($value) : $value; + $content .= "{\\{$property} {$value}}"; + } + $content .= '}'; + $content .= PHP_EOL; + + return $content; + } + + /** + * Write document formatting properties + * + * @return string + */ + private function writeFormatting() + { + $content = ''; + + $content .= '\deftab720'; // Set the default tab size (720 twips) + $content .= '\viewkind1'; // Set the view mode of the document + + $content .= '\uc1'; // Set the numberof bytes that follows a unicode character + $content .= '\pard'; // Resets to default paragraph properties. + $content .= '\nowidctlpar'; // No widow/orphan control + $content .= '\lang1036'; // Applies a language to a text run (1036 : French (France)) + $content .= '\kerning1'; // Point size (in half-points) above which to kern character pairs + $content .= '\fs' . (Settings::getDefaultFontSize() * 2); // Set the font size in half-points + $content .= PHP_EOL; + + return $content; + } + + /** + * Write sections + * + * @return string + */ + private function writeSections() + { + $content = ''; + + $sections = $this->getParentWriter()->getPhpWord()->getSections(); + foreach ($sections as $section) { + $writer = new Container($this->getParentWriter(), $section); + $content .= $writer->write(); + } + + return $content; + } + + /** + * Get date value + * + * The format of date value is `\yr?\mo?\dy?\hr?\min?\sec?` + * + * @param int $value + * @return string + */ + private function getDateValue($value) + { + $dateParts = array( + 'Y' => 'yr', + 'm' => 'mo', + 'd' => 'dy', + 'H' => 'hr', + 'i' => 'min', + 's' => 'sec', + ); + $result = ''; + foreach ($dateParts as $dateFormat => $controlWord) { + $result .= '\\' . $controlWord . date($dateFormat, $value); + } + + return $result; + } +} diff --git a/src/PhpWord/Writer/RTF/Part/Header.php b/src/PhpWord/Writer/RTF/Part/Header.php new file mode 100644 index 00000000..15a0c303 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Part/Header.php @@ -0,0 +1,227 @@ +fontTable; + } + + /** + * Get color table + */ + public function getColorTable() + { + return $this->colorTable; + } + + /** + * Write part + * + * @return string + */ + public function write() + { + $this->registerFont(); + + $content = ''; + + $content .= $this->writeCharset(); + $content .= $this->writeDefaults(); + $content .= $this->writeFontTable(); + $content .= $this->writeColorTable(); + $content .= $this->writeGenerator(); + $content .= PHP_EOL; + + return $content; + } + + /** + * Write character set + * + * @return string + */ + private function writeCharset() + { + $content = ''; + + $content .= '\ansi'; + $content .= '\ansicpg1252'; + $content .= PHP_EOL; + + return $content; + } + + /** + * Write header defaults + * + * @return string + */ + private function writeDefaults() + { + $content = ''; + + $content .= '\deff0'; + $content .= PHP_EOL; + + return $content; + } + + /** + * Write font table + * + * @return string + */ + private function writeFontTable() + { + $content = ''; + + $content .= '{'; + $content .= '\fonttbl'; + foreach ($this->fontTable as $index => $font) { + $content .= "{\\f{$index}\\fnil\\fcharset0 {$font};}"; + } + $content .= '}'; + $content .= PHP_EOL; + + return $content; + } + + /** + * Write color table + * + * @return string + */ + private function writeColorTable() + { + $content = ''; + + $content .= '{'; + $content .= '\colortbl'; + foreach ($this->colorTable as $color) { + list($red, $green, $blue) = Drawing::htmlToRGB($color); + $content .= ";\\red{$red}\\green{$green}\\blue{$blue}"; + } + $content .= '}'; + $content .= PHP_EOL; + + return $content; + } + + /** + * Write + * + * @return string + */ + private function writeGenerator() + { + $content = ''; + + $content .= '{\*\generator PhpWord;}'; // Set the generator + $content .= PHP_EOL; + + return $content; + } + + /** + * Register all fonts and colors in both named and inline styles to appropriate header table + */ + private function registerFont() + { + $phpWord = $this->getParentWriter()->getPhpWord(); + $this->fontTable[] = Settings::getDefaultFontName(); + + // Search named styles + $styles = Style::getStyles(); + foreach ($styles as $style) { + $this->registerFontItems($style); + } + + // Search inline styles + $sections = $phpWord->getSections(); + foreach ($sections as $section) { + $elements = $section->getElements(); + foreach ($elements as $element) { + if (method_exists($element, 'getFontStyle')) { + $style = $element->getFontStyle(); + $this->registerFontItems($style); + } + } + } + } + + /** + * Register fonts and colors + * + * @param \PhpOffice\PhpWord\Style\AbstractStyle $style + */ + private function registerFontItems($style) + { + $defaultFont = Settings::getDefaultFontName(); + $defaultColor = Settings::DEFAULT_FONT_COLOR; + + if ($style instanceof Font) { + $this->registerFontItem($this->fontTable, $style->getName(), $defaultFont); + $this->registerFontItem($this->colorTable, $style->getColor(), $defaultColor); + $this->registerFontItem($this->colorTable, $style->getFgColor(), $defaultColor); + } + } + + /** + * Register individual font and color + * + * @param array $table + * @param string $value + * @param string $default + */ + private function registerFontItem(&$table, $value, $default) + { + if (in_array($value, $table) === false && $value !== null && $value != $default) { + $table[] = $value; + } + } +} diff --git a/src/PhpWord/Writer/RTF/Style/AbstractStyle.php b/src/PhpWord/Writer/RTF/Style/AbstractStyle.php new file mode 100644 index 00000000..7b55fdc2 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Style/AbstractStyle.php @@ -0,0 +1,29 @@ +getStyle(); + if (!$style instanceof FontStyle) { + return ''; + } + + $content = ''; + $content .= '\cf' . $this->colorIndex; + $content .= '\f' . $this->nameIndex; + + $size = $style->getSize(); + $content .= $this->getValueIf(is_numeric($size), '\fs' . ($size * 2)); + + $content .= $this->getValueIf($style->isBold(), '\b'); + $content .= $this->getValueIf($style->isItalic(), '\i'); + $content .= $this->getValueIf($style->getUnderline() != FontStyle::UNDERLINE_NONE, '\ul'); + $content .= $this->getValueIf($style->isStrikethrough(), '\strike'); + $content .= $this->getValueIf($style->isSuperScript(), '\super'); + $content .= $this->getValueIf($style->isSubScript(), '\sub'); + + return $content . ' '; + } + + /** + * Set font name index + * + * @param int $value + */ + public function setNameIndex($value = 0) + { + $this->nameIndex = $value; + } + + /** + * Set font color index + * + * @param int $value + */ + public function setColorIndex($value = 0) + { + $this->colorIndex = $value; + } +} diff --git a/src/PhpWord/Writer/RTF/Style/Paragraph.php b/src/PhpWord/Writer/RTF/Style/Paragraph.php new file mode 100644 index 00000000..b166cc27 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Style/Paragraph.php @@ -0,0 +1,84 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Paragraph) { + return ''; + } + + $alignments = array( + Alignment::ALIGN_LEFT => '\ql', + Alignment::ALIGN_RIGHT => '\qr', + Alignment::ALIGN_CENTER => '\qc', + Alignment::ALIGN_BOTH => '\qj', + ); + + $align = $style->getAlign(); + $spaceAfter = $style->getSpaceAfter(); + $spaceBefore = $style->getSpaceBefore(); + + $content = ''; + if ($this->nestedLevel == 0) { + $content .= '\pard\nowidctlpar '; + } + if (isset($alignments[$align])) { + $content .= $alignments[$align]; + } + $content .= $this->getValueIf($spaceBefore !== null, '\sb' . $spaceBefore); + $content .= $this->getValueIf($spaceAfter !== null, '\sa' . $spaceAfter); + + return $content; + } + + /** + * Set nested level + * + * @param int $value + */ + public function setNestedLevel($value) + { + $this->nestedLevel = $value; + } +} diff --git a/src/PhpWord/Writer/Word2007.php b/src/PhpWord/Writer/Word2007.php index b87f1d24..751b58b6 100644 --- a/src/PhpWord/Writer/Word2007.php +++ b/src/PhpWord/Writer/Word2007.php @@ -1,18 +1,26 @@ array(), 'override' => array()); + private $contentTypes = array('default' => array(), 'override' => array()); /** * Document relationship * * @var array */ - private $docRels = array(); + private $relationships = array(); /** * Create new Word2007 writer @@ -44,16 +52,33 @@ class Word2007 extends AbstractWriter implements WriterInterface $this->setPhpWord($phpWord); // Create parts - $parts = array('ContentTypes', 'Rels', 'DocProps', 'Document', 'Styles', - 'Numbering', 'Settings', 'WebSettings', 'Header', 'Footer', 'Footnotes', - 'Endnotes', 'FontTable', 'Theme'); - foreach ($parts as $part) { - $partName = strtolower($part); - $partClass = 'PhpOffice\\PhpWord\\Writer\\Word2007\\Part\\' . $part; + $this->parts = array( + 'ContentTypes' => '[Content_Types].xml', + 'Rels' => '_rels/.rels', + 'DocPropsApp' => 'docProps/app.xml', + 'DocPropsCore' => 'docProps/core.xml', + 'DocPropsCustom' => 'docProps/custom.xml', + 'RelsDocument' => 'word/_rels/document.xml.rels', + 'Document' => 'word/document.xml', + 'Styles' => 'word/styles.xml', + 'Numbering' => 'word/numbering.xml', + 'Settings' => 'word/settings.xml', + 'WebSettings' => 'word/webSettings.xml', + 'FontTable' => 'word/fontTable.xml', + 'Theme' => 'word/theme/theme1.xml', + 'RelsPart' => '', + 'Header' => '', + 'Footer' => '', + 'Footnotes' => '', + 'Endnotes' => '', + ); + foreach (array_keys($this->parts) as $partName) { + $partClass = get_class($this) . '\\Part\\' . $partName; if (class_exists($partClass)) { - $partObject = new $partClass(); - $partObject->setParentWriter($this); - $this->writerParts[$partName] = $partObject; + /** @var \PhpOffice\PhpWord\Writer\Word2007\Part\AbstractPart $part Type hint */ + $part = new $partClass(); + $part->setParentWriter($this); + $this->writerParts[strtolower($partName)] = $part; } } @@ -68,84 +93,93 @@ class Word2007 extends AbstractWriter implements WriterInterface */ public function save($filename = null) { - if (!is_null($this->phpWord)) { - $filename = $this->getTempFile($filename); - $objZip = $this->getZipArchive($filename); + $filename = $this->getTempFile($filename); + $zip = $this->getZipArchive($filename); + $phpWord = $this->getPhpWord(); - // Content types - $this->cTypes['default'] = array( - 'rels' => 'application/vnd.openxmlformats-package.relationships+xml', - 'xml' => 'application/xml', - ); + // Content types + $this->contentTypes['default'] = array( + 'rels' => 'application/vnd.openxmlformats-package.relationships+xml', + 'xml' => 'application/xml', + ); - // Add section media files - $sectionMedia = Media::getElements('section'); - if (!empty($sectionMedia)) { - $this->addFilesToPackage($objZip, $sectionMedia); - $this->registerContentTypes($sectionMedia); - foreach ($sectionMedia as $element) { - $this->docRels[] = $element; - } + // Add section media files + $sectionMedia = Media::getElements('section'); + if (!empty($sectionMedia)) { + $this->addFilesToPackage($zip, $sectionMedia); + $this->registerContentTypes($sectionMedia); + foreach ($sectionMedia as $element) { + $this->relationships[] = $element; } - - // Add header/footer media files & relations - $this->addHeaderFooterMedia($objZip, 'header'); - $this->addHeaderFooterMedia($objZip, 'footer'); - - // Add header/footer contents - $rId = Media::countElements('section') + 6; // @see Rels::writeDocRels for 6 first elements - $sections = $this->phpWord->getSections(); - foreach ($sections as $section) { - $this->addHeaderFooterContent($section, $objZip, 'header', $rId); - $this->addHeaderFooterContent($section, $objZip, 'footer', $rId); - } - - $this->addNotes($objZip, $rId, 'footnote'); - $this->addNotes($objZip, $rId, 'endnote'); - - // Write parts - $objZip->addFromString('[Content_Types].xml', $this->getWriterPart('contenttypes')->writeContentTypes($this->cTypes)); - $objZip->addFromString('_rels/.rels', $this->getWriterPart('rels')->writeMainRels()); - $objZip->addFromString('docProps/app.xml', $this->getWriterPart('docprops')->writeDocPropsApp($this->phpWord)); - $objZip->addFromString('docProps/core.xml', $this->getWriterPart('docprops')->writeDocPropsCore($this->phpWord)); - $objZip->addFromString('word/_rels/document.xml.rels', $this->getWriterPart('rels')->writeDocRels($this->docRels)); - $objZip->addFromString('word/document.xml', $this->getWriterPart('document')->writeDocument($this->phpWord)); - $objZip->addFromString('word/styles.xml', $this->getWriterPart('styles')->writeStyles($this->phpWord)); - $objZip->addFromString('word/numbering.xml', $this->getWriterPart('numbering')->writeNumbering()); - $objZip->addFromString('word/settings.xml', $this->getWriterPart('settings')->writeSettings()); - $objZip->addFromString('word/webSettings.xml', $this->getWriterPart('websettings')->writeWebSettings()); - $objZip->addFromString('word/fontTable.xml', $this->getWriterPart('fonttable')->write()); - $objZip->addFromString('word/theme/theme1.xml', $this->getWriterPart('theme')->write()); - - // Close file - if ($objZip->close() === false) { - throw new Exception("Could not close zip file $filename."); - } - - $this->cleanupTempFile(); - } else { - throw new Exception("PhpWord object unassigned."); } + + // Add header/footer media files & relations + $this->addHeaderFooterMedia($zip, 'header'); + $this->addHeaderFooterMedia($zip, 'footer'); + + // Add header/footer contents + $rId = Media::countElements('section') + 6; // @see Rels::writeDocRels for 6 first elements + $sections = $phpWord->getSections(); + foreach ($sections as $section) { + $this->addHeaderFooterContent($section, $zip, 'header', $rId); + $this->addHeaderFooterContent($section, $zip, 'footer', $rId); + } + + $this->addNotes($zip, $rId, 'footnote'); + $this->addNotes($zip, $rId, 'endnote'); + + // Write parts + foreach ($this->parts as $partName => $fileName) { + if ($fileName != '') { + $zip->addFromString($fileName, $this->getWriterPart($partName)->write()); + } + } + + // Close zip archive and cleanup temp file + $zip->close(); + $this->cleanupTempFile(); } /** - * Add header/footer media files + * Get content types * - * @param mixed $objZip + * @return array + */ + public function getContentTypes() + { + return $this->contentTypes; + } + + /** + * Get content types + * + * @return array + */ + public function getRelationships() + { + return $this->relationships; + } + + /** + * Add header/footer media files, e.g. footer1.xml.rels + * + * @param \PhpOffice\PhpWord\Shared\ZipArchive $zip * @param string $docPart */ - private function addHeaderFooterMedia($objZip, $docPart) + private function addHeaderFooterMedia(ZipArchive $zip, $docPart) { $elements = Media::getElements($docPart); if (!empty($elements)) { foreach ($elements as $file => $media) { if (count($media) > 0) { if (!empty($media)) { - $this->addFilesToPackage($objZip, $media); + $this->addFilesToPackage($zip, $media); $this->registerContentTypes($media); } - $relsFile = "word/_rels/{$file}.xml.rels"; - $objZip->addFromString($relsFile, $this->getWriterPart('rels')->writeMediaRels($media)); + + /** @var \PhpOffice\PhpWord\Writer\Word2007\Part\AbstractPart $writerPart Type hint */ + $writerPart = $this->getWriterPart('relspart')->setMedia($media); + $zip->addFromString("word/_rels/{$file}.xml.rels", $writerPart->write()); } } } @@ -154,54 +188,64 @@ class Word2007 extends AbstractWriter implements WriterInterface /** * Add header/footer content * - * @param mixed $objZip - * @param string $elmType + * @param \PhpOffice\PhpWord\Element\Section $section + * @param \PhpOffice\PhpWord\Shared\ZipArchive $zip + * @param string $elmType header|footer * @param integer $rId */ - private function addHeaderFooterContent(Section &$section, $objZip, $elmType, &$rId) + private function addHeaderFooterContent(Section &$section, ZipArchive $zip, $elmType, &$rId) { $getFunction = $elmType == 'header' ? 'getHeaders' : 'getFooters'; - $writeFunction = $elmType == 'header' ? 'writeHeader' : 'writeFooter'; $elmCount = ($section->getSectionId() - 1) * 3; - $elmObjects = $section->$getFunction(); - foreach ($elmObjects as &$elmObject) { + $elements = $section->$getFunction(); + foreach ($elements as &$element) { + /** @var \PhpOffice\PhpWord\Element\AbstractElement $element Type hint */ $elmCount++; - $elmObject->setRelationId(++$rId); - $elmFile = "{$elmType}{$elmCount}.xml"; - $objZip->addFromString("word/$elmFile", $this->getWriterPart($elmType)->$writeFunction($elmObject)); - $this->cTypes['override']["/word/$elmFile"] = $elmType; - $this->docRels[] = array('target' => $elmFile, 'type' => $elmType, 'rID' => $rId); + $element->setRelationId(++$rId); + $elmFile = "{$elmType}{$elmCount}.xml"; // e.g. footer1.xml + $this->contentTypes['override']["/word/$elmFile"] = $elmType; + $this->relationships[] = array('target' => $elmFile, 'type' => $elmType, 'rID' => $rId); + + /** @var \PhpOffice\PhpWord\Writer\Word2007\Part\AbstractPart $writerPart Type hint */ + $writerPart = $this->getWriterPart($elmType)->setElement($element); + $zip->addFromString("word/$elmFile", $writerPart->write()); } } /** * Add footnotes/endnotes * - * @param mixed $objZip + * @param \PhpOffice\PhpWord\Shared\ZipArchive $zip * @param integer $rId - * @param string $notesType + * @param string $noteType */ - private function addNotes($objZip, &$rId, $notesType = 'footnote') + private function addNotes(ZipArchive $zip, &$rId, $noteType = 'footnote') { - $notesType = ($notesType == 'endnote') ? 'endnote' : 'footnote'; - $notesTypes = "{$notesType}s"; - $collection = 'PhpOffice\\PhpWord\\' . ucfirst($notesTypes); - $xmlFile = "{$notesTypes}.xml"; - $relsFile = "word/_rels/{$xmlFile}.rels"; - $xmlPath = "word/{$xmlFile}"; + $phpWord = $this->getPhpWord(); + $noteType = ($noteType == 'endnote') ? 'endnote' : 'footnote'; + $partName = "{$noteType}s"; + $method = 'get' . $partName; + $collection = $phpWord->$method(); // Add footnotes media files, relations, and contents - if ($collection::countElements() > 0) { - $media = Media::getElements($notesType); - $this->addFilesToPackage($objZip, $media); + /** @var \PhpOffice\PhpWord\Collection\AbstractCollection $collection Type hint */ + if ($collection->countItems() > 0) { + $media = Media::getElements($noteType); + $this->addFilesToPackage($zip, $media); $this->registerContentTypes($media); + $this->contentTypes['override']["/word/{$partName}.xml"] = $partName; + $this->relationships[] = array('target' => "{$partName}.xml", 'type' => $partName, 'rID' => ++$rId); + + // Write relationships file, e.g. word/_rels/footnotes.xml if (!empty($media)) { - $objZip->addFromString($relsFile, $this->getWriterPart('rels')->writeMediaRels($media)); + /** @var \PhpOffice\PhpWord\Writer\Word2007\Part\AbstractPart $writerPart Type hint */ + $writerPart = $this->getWriterPart('relspart')->setMedia($media); + $zip->addFromString("word/_rels/{$partName}.xml.rels", $writerPart->write()); } - $elements = $collection::getElements(); - $objZip->addFromString($xmlPath, $this->getWriterPart($notesTypes)->write($elements)); - $this->cTypes['override']["/{$xmlPath}"] = $notesTypes; - $this->docRels[] = array('target' => $xmlFile, 'type' => $notesTypes, 'rID' => ++$rId); + + // Write content file, e.g. word/footnotes.xml + $writerPart = $this->getWriterPart($partName)->setElements($collection->getItems()); + $zip->addFromString("word/{$partName}.xml", $writerPart->write()); } } @@ -216,12 +260,12 @@ class Word2007 extends AbstractWriter implements WriterInterface $mediumType = $medium['type']; if ($mediumType == 'image') { $extension = $medium['imageExtension']; - if (!array_key_exists($extension, $this->cTypes['default'])) { - $this->cTypes['default'][$extension] = $medium['imageType']; + if (!array_key_exists($extension, $this->contentTypes['default'])) { + $this->contentTypes['default'][$extension] = $medium['imageType']; } } elseif ($mediumType == 'object') { - if (!array_key_exists('bin', $this->cTypes['default'])) { - $this->cTypes['default']['bin'] = 'application/vnd.openxmlformats-officedocument.oleObject'; + if (!array_key_exists('bin', $this->contentTypes['default'])) { + $this->contentTypes['default']['bin'] = 'application/vnd.openxmlformats-officedocument.oleObject'; } } } diff --git a/src/PhpWord/Writer/Word2007/Element/AbstractElement.php b/src/PhpWord/Writer/Word2007/Element/AbstractElement.php new file mode 100644 index 00000000..52b4c62e --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/AbstractElement.php @@ -0,0 +1,128 @@ +xmlWriter = $xmlWriter; + $this->element = $element; + $this->withoutP = $withoutP; + } + + /** + * Get XML Writer + * + * @return \PhpOffice\PhpWord\Shared\XMLWriter + */ + protected function getXmlWriter() + { + return $this->xmlWriter; + } + + /** + * Get element + * + * @return \PhpOffice\PhpWord\Element\AbstractElement + */ + protected function getElement() + { + return $this->element; + } + + /** + * Has page break before + * + * @return bool + */ + public function hasPageBreakBefore() + { + return $this->pageBreakBefore; + } + + /** + * Set page break before + * + * @param bool $value + */ + public function setPageBreakBefore($value = true) + { + $this->pageBreakBefore = (bool)$value; + } + + /** + * Convert text to valid format + * + * @param string $text + * @return string + */ + protected function getText($text) + { + return String::controlCharacterPHP2OOXML(htmlspecialchars($text)); + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/CheckBox.php b/src/PhpWord/Writer/Word2007/Element/CheckBox.php index 12b28cf9..ea13b8f9 100644 --- a/src/PhpWord/Writer/Word2007/Element/CheckBox.php +++ b/src/PhpWord/Writer/Word2007/Element/CheckBox.php @@ -1,96 +1,90 @@ element->getName()); - $name = String::controlCharacterPHP2OOXML($name); - $text = htmlspecialchars($this->element->getText()); - $text = String::controlCharacterPHP2OOXML($text); - $fontStyle = $this->element->getFontStyle(); - $paragraphStyle = $this->element->getParagraphStyle(); - - if (!$this->withoutP) { - $styleWriter = new ParagraphStyleWriter($this->xmlWriter, $paragraphStyle); - $styleWriter->setIsInline(true); - - $this->xmlWriter->startElement('w:p'); - $styleWriter->write(); + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\CheckBox) { + return; } - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:fldChar'); - $this->xmlWriter->writeAttribute('w:fldCharType', 'begin'); - $this->xmlWriter->startElement('w:ffData'); - $this->xmlWriter->startElement('w:name'); - $this->xmlWriter->writeAttribute('w:val', $name); - $this->xmlWriter->endElement(); //w:name - $this->xmlWriter->writeAttribute('w:enabled', ''); - $this->xmlWriter->startElement('w:calcOnExit'); - $this->xmlWriter->writeAttribute('w:val', '0'); - $this->xmlWriter->endElement(); //w:calcOnExit - $this->xmlWriter->startElement('w:checkBox'); - $this->xmlWriter->writeAttribute('w:sizeAuto', ''); - $this->xmlWriter->startElement('w:default'); - $this->xmlWriter->writeAttribute('w:val', 0); - $this->xmlWriter->endElement(); //w:default - $this->xmlWriter->endElement(); //w:checkBox - $this->xmlWriter->endElement(); // w:ffData - $this->xmlWriter->endElement(); // w:fldChar - $this->xmlWriter->endElement(); // w:r + $this->writeOpeningWP(); - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:instrText'); - $this->xmlWriter->writeAttribute('xml:space', 'preserve'); - $this->xmlWriter->writeRaw(' FORMCHECKBOX '); - $this->xmlWriter->endElement();// w:instrText - $this->xmlWriter->endElement(); // w:r - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:fldChar'); - $this->xmlWriter->writeAttribute('w:fldCharType', 'seperate'); - $this->xmlWriter->endElement();// w:fldChar - $this->xmlWriter->endElement(); // w:r - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:fldChar'); - $this->xmlWriter->writeAttribute('w:fldCharType', 'end'); - $this->xmlWriter->endElement();// w:fldChar - $this->xmlWriter->endElement(); // w:r + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'begin'); + $xmlWriter->startElement('w:ffData'); + $xmlWriter->startElement('w:name'); + $xmlWriter->writeAttribute('w:val', $this->getText($element->getName())); + $xmlWriter->endElement(); //w:name + $xmlWriter->writeAttribute('w:enabled', ''); + $xmlWriter->startElement('w:calcOnExit'); + $xmlWriter->writeAttribute('w:val', '0'); + $xmlWriter->endElement(); //w:calcOnExit + $xmlWriter->startElement('w:checkBox'); + $xmlWriter->writeAttribute('w:sizeAuto', ''); + $xmlWriter->startElement('w:default'); + $xmlWriter->writeAttribute('w:val', 0); + $xmlWriter->endElement(); //w:default + $xmlWriter->endElement(); //w:checkBox + $xmlWriter->endElement(); // w:ffData + $xmlWriter->endElement(); // w:fldChar + $xmlWriter->endElement(); // w:r - $styleWriter = new FontStyleWriter($this->xmlWriter, $fontStyle); - $styleWriter->setIsInline(true); + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:instrText'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw(' FORMCHECKBOX '); + $xmlWriter->endElement();// w:instrText + $xmlWriter->endElement(); // w:r + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'seperate'); + $xmlWriter->endElement();// w:fldChar + $xmlWriter->endElement(); // w:r + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'end'); + $xmlWriter->endElement();// w:fldChar + $xmlWriter->endElement(); // w:r - $this->xmlWriter->startElement('w:r'); - $styleWriter->write(); - $this->xmlWriter->startElement('w:t'); - $this->xmlWriter->writeAttribute('xml:space', 'preserve'); - $this->xmlWriter->writeRaw($text); - $this->xmlWriter->endElement(); // w:t - $this->xmlWriter->endElement(); // w:r + $xmlWriter->startElement('w:r'); - if (!$this->withoutP) { - $this->xmlWriter->endElement(); // w:p - } + $this->writeFontStyle(); + + $xmlWriter->startElement('w:t'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw($this->getText($element->getText())); + $xmlWriter->endElement(); // w:t + $xmlWriter->endElement(); // w:r + + $this->writeClosingWP(); } } diff --git a/src/PhpWord/Writer/Word2007/Element/Container.php b/src/PhpWord/Writer/Word2007/Element/Container.php new file mode 100644 index 00000000..3dad824d --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Container.php @@ -0,0 +1,104 @@ +getElement(); + if (!$container instanceof ContainerElement) { + return; + } + $containerClass = substr(get_class($container), strrpos(get_class($container), '\\') + 1); + $withoutP = in_array($containerClass, array('TextRun', 'Footnote', 'Endnote', 'ListItemRun')) ? true : false; + $xmlWriter = $this->getXmlWriter(); + + // Loop through elements + $elements = $container->getElements(); + $elementClass = ''; + foreach ($elements as $element) { + $elementClass = $this->writeElement($xmlWriter, $element, $withoutP); + } + + // Special case for Cell: They have to contain a w:p element at the end. + // The $elementClass contains the last element name. If it's empty string + // or Table, the last element is not w:p + $writeLastTextBreak = ($containerClass == 'Cell') && ($elementClass == '' || $elementClass == 'Table'); + if ($writeLastTextBreak) { + $writerClass = $this->namespace . '\\TextBreak'; + /** @var \PhpOffice\PhpWord\Writer\Word2007\Element\AbstractElement $writer Type hint */ + $writer = new $writerClass($xmlWriter, new TextBreakElement(), $withoutP); + $writer->write(); + } + } + + /** + * Write individual element + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\AbstractElement $element + * @param bool $withoutP + * @return string + */ + private function writeElement(XMLWriter $xmlWriter, Element $element, $withoutP) + { + $elementClass = substr(get_class($element), strrpos(get_class($element), '\\') + 1); + $writerClass = $this->namespace . '\\' . $elementClass; + + // Check it's a page break. No need to write it, instead, flag containers' + // pageBreakBefore to be assigned to the next element + if ($elementClass == 'PageBreak') { + $this->setPageBreakBefore(true); + return $elementClass; + } + + if (class_exists($writerClass)) { + // Get container's page break before and reset it + $pageBreakBefore = $this->hasPageBreakBefore(); + $this->setPageBreakBefore(false); + + /** @var \PhpOffice\PhpWord\Writer\Word2007\Element\AbstractElement $writer Type hint */ + $writer = new $writerClass($xmlWriter, $element, $withoutP); + $writer->setPageBreakBefore($pageBreakBefore); + $writer->write(); + } + + return $elementClass; + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Element.php b/src/PhpWord/Writer/Word2007/Element/Element.php deleted file mode 100644 index 9c91beb7..00000000 --- a/src/PhpWord/Writer/Word2007/Element/Element.php +++ /dev/null @@ -1,78 +0,0 @@ -xmlWriter = $xmlWriter; - $this->parentWriter = $parentWriter; - $this->element = $element; - $this->withoutP = $withoutP; - } - - /** - * Write element - * - * @return string - */ - public function write() - { - $elmName = str_replace('PhpOffice\\PhpWord\\Element\\', '', get_class($this->element)); - $elmWriterClass = 'PhpOffice\\PhpWord\\Writer\\Word2007\\Element\\' . $elmName; - if (class_exists($elmWriterClass) === true) { - $elmWriter = new $elmWriterClass($this->xmlWriter, $this->parentWriter, $this->element, $this->withoutP); - $elmWriter->write(); - } - } -} diff --git a/src/PhpWord/Writer/Word2007/Element/Endnote.php b/src/PhpWord/Writer/Word2007/Element/Endnote.php index fbdf7a75..f627c13c 100644 --- a/src/PhpWord/Writer/Word2007/Element/Endnote.php +++ b/src/PhpWord/Writer/Word2007/Element/Endnote.php @@ -1,10 +1,18 @@ referenceType = 'endnoteReference'; - parent::write(); - } + protected $referenceType = 'endnoteReference'; } diff --git a/src/PhpWord/Writer/Word2007/Element/Field.php b/src/PhpWord/Writer/Word2007/Element/Field.php new file mode 100644 index 00000000..68c4c40c --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Field.php @@ -0,0 +1,87 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Field) { + return; + } + + $instruction = ' ' . $element->getType() . ' '; + $properties = $element->getProperties(); + foreach ($properties as $propkey => $propval) { + switch ($propkey) { + case 'format': + case 'numformat': + $instruction .= '\* ' . $propval . ' '; + break; + case 'dateformat': + $instruction .= '\@ "' . $propval . '" '; + break; + } + } + + $options = $element->getOptions(); + foreach ($options as $option) { + switch ($option) { + case 'PreserveFormat': + $instruction .= '\* MERGEFORMAT '; + break; + case 'LunarCalendar': + $instruction .= '\h '; + break; + case 'SakaEraCalendar': + $instruction .= '\s '; + break; + case 'LastUsedFormat': + $instruction .= '\l '; + break; + } + } + + $this->writeOpeningWP(); + $xmlWriter->startElement('w:fldSimple'); + $xmlWriter->writeAttribute('w:instr', $instruction); + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:rPr'); + $xmlWriter->startElement('w:noProof'); + $xmlWriter->endElement(); // w:noProof + $xmlWriter->endElement(); // w:rPr + + $xmlWriter->startElement('w:t'); + $xmlWriter->writeRaw('1'); + $xmlWriter->endElement(); // w:t + $xmlWriter->endElement(); // w:r + $xmlWriter->endElement(); // w:fldSimple + + $this->writeClosingWP(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Footnote.php b/src/PhpWord/Writer/Word2007/Element/Footnote.php index 20360ebc..240a8a00 100644 --- a/src/PhpWord/Writer/Word2007/Element/Footnote.php +++ b/src/PhpWord/Writer/Word2007/Element/Footnote.php @@ -1,10 +1,18 @@ referenceType = 'footnoteReference'; - parent::write(); + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Footnote) { + return; + } + + $this->writeOpeningWP(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:rPr'); + $xmlWriter->startElement('w:rStyle'); + $xmlWriter->writeAttribute('w:val', ucfirst($this->referenceType)); + $xmlWriter->endElement(); // w:rStyle + $xmlWriter->endElement(); // w:rPr + $xmlWriter->startElement("w:{$this->referenceType}"); + $xmlWriter->writeAttribute('w:id', $element->getRelationId()); + $xmlWriter->endElement(); // w:$referenceType + $xmlWriter->endElement(); // w:r + + $this->writeClosingWP(); } } diff --git a/src/PhpWord/Writer/Word2007/Element/Image.php b/src/PhpWord/Writer/Word2007/Element/Image.php index e944b7af..a882040e 100644 --- a/src/PhpWord/Writer/Word2007/Element/Image.php +++ b/src/PhpWord/Writer/Word2007/Element/Image.php @@ -1,147 +1,105 @@ element->getIsWatermark()) { - $this->writeWatermark(); + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof ImageElement) { + return; + } + + if ($element->isWatermark()) { + $this->writeWatermark($xmlWriter, $element); } else { - $this->writeImage(); + $this->writeImage($xmlWriter, $element); } } /** * Write image element */ - private function writeImage() + private function writeImage(XMLWriter $xmlWriter, ImageElement $element) { - $rId = $this->element->getRelationId() + ($this->element->isInSection() ? 6 : 0); - - $style = $this->element->getStyle(); - $width = $style->getWidth(); - $height = $style->getHeight(); - $align = $style->getAlign(); - $marginTop = $style->getMarginTop(); - $marginLeft = $style->getMarginLeft(); - $wrappingStyle = $style->getWrappingStyle(); - $w10wrapType = null; - $imgStyle = ''; - if (null !== $width) { - $imgStyle .= 'width:' . $width . 'px;'; - } - if (null !== $height) { - $imgStyle .= 'height:' . $height . 'px;'; - } - if (null !== $marginTop) { - $imgStyle .= 'margin-top:' . $marginTop . 'in;'; - } - if (null !== $marginLeft) { - $imgStyle .= 'margin-left:' . $marginLeft . 'in;'; - } - switch ($wrappingStyle) { - case ImageStyle::WRAPPING_STYLE_BEHIND: - $imgStyle .= 'position:absolute;z-index:-251658752;'; - break; - case ImageStyle::WRAPPING_STYLE_INFRONT: - $imgStyle .= 'position:absolute;z-index:251659264;mso-position-horizontal:absolute;mso-position-vertical:absolute;'; - break; - case ImageStyle::WRAPPING_STYLE_SQUARE: - $imgStyle .= 'position:absolute;z-index:251659264;mso-position-horizontal:absolute;mso-position-vertical:absolute;'; - $w10wrapType = 'square'; - break; - case ImageStyle::WRAPPING_STYLE_TIGHT: - $imgStyle .= 'position:absolute;z-index:251659264;mso-position-horizontal:absolute;mso-position-vertical:absolute;'; - $w10wrapType = 'tight'; - break; - } + $rId = $element->getRelationId() + ($element->isInSection() ? 6 : 0); + $style = $element->getStyle(); + $styleWriter = new ImageStyleWriter($xmlWriter, $style); if (!$this->withoutP) { - $this->xmlWriter->startElement('w:p'); - if (!is_null($align)) { - $this->xmlWriter->startElement('w:pPr'); - $this->xmlWriter->startElement('w:jc'); - $this->xmlWriter->writeAttribute('w:val', $align); - $this->xmlWriter->endElement(); // w:jc - $this->xmlWriter->endElement(); // w:pPr - } + $xmlWriter->startElement('w:p'); + $styleWriter->writeAlignment(); } - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:pict'); - $this->xmlWriter->startElement('v:shape'); - $this->xmlWriter->writeAttribute('type', '#_x0000_t75'); - $this->xmlWriter->writeAttribute('style', $imgStyle); - $this->xmlWriter->startElement('v:imagedata'); - $this->xmlWriter->writeAttribute('r:id', 'rId' . $rId); - $this->xmlWriter->writeAttribute('o:title', ''); - $this->xmlWriter->endElement(); // v:imagedata - if (!is_null($w10wrapType)) { - $this->xmlWriter->startElement('w10:wrap'); - $this->xmlWriter->writeAttribute('type', $w10wrapType); - $this->xmlWriter->endElement(); // w10:wrap - } - $this->xmlWriter->endElement(); // v:shape - $this->xmlWriter->endElement(); // w:pict - $this->xmlWriter->endElement(); // w:r + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:pict'); + $xmlWriter->startElement('v:shape'); + $xmlWriter->writeAttribute('type', '#_x0000_t75'); + $styleWriter->write(); + $xmlWriter->startElement('v:imagedata'); + $xmlWriter->writeAttribute('r:id', 'rId' . $rId); + $xmlWriter->writeAttribute('o:title', ''); + $xmlWriter->endElement(); // v:imagedata + $styleWriter->writeW10Wrap(); + $xmlWriter->endElement(); // v:shape + $xmlWriter->endElement(); // w:pict + $xmlWriter->endElement(); // w:r if (!$this->withoutP) { - $this->xmlWriter->endElement(); // w:p + $xmlWriter->endElement(); // w:p } } /** * Write watermark element */ - private function writeWatermark() + private function writeWatermark(XMLWriter $xmlWriter, ImageElement $element) { - $rId = $this->element->getRelationId(); + $rId = $element->getRelationId(); + $style = $element->getStyle(); + $style->setPositioning('absolute'); + $styleWriter = new ImageStyleWriter($xmlWriter, $style); - $style = $this->element->getStyle(); - $width = $style->getWidth(); - $height = $style->getHeight(); - $marginLeft = $style->getMarginLeft(); - $marginTop = $style->getMarginTop(); - $strStyle = 'position:absolute;'; - $strStyle .= ' width:' . $width . 'px;'; - $strStyle .= ' height:' . $height . 'px;'; - if (!is_null($marginTop)) { - $strStyle .= ' margin-top:' . $marginTop . 'px;'; - } - if (!is_null($marginLeft)) { - $strStyle .= ' margin-left:' . $marginLeft . 'px;'; - } - - $this->xmlWriter->startElement('w:p'); - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:pict'); - $this->xmlWriter->startElement('v:shape'); - $this->xmlWriter->writeAttribute('type', '#_x0000_t75'); - $this->xmlWriter->writeAttribute('style', $strStyle); - $this->xmlWriter->startElement('v:imagedata'); - $this->xmlWriter->writeAttribute('r:id', 'rId' . $rId); - $this->xmlWriter->writeAttribute('o:title', ''); - $this->xmlWriter->endElement(); // v:imagedata - $this->xmlWriter->endElement(); // v:shape - $this->xmlWriter->endElement(); // w:pict - $this->xmlWriter->endElement(); // w:r - $this->xmlWriter->endElement(); // w:p + $xmlWriter->startElement('w:p'); + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:pict'); + $xmlWriter->startElement('v:shape'); + $xmlWriter->writeAttribute('type', '#_x0000_t75'); + $styleWriter->write(); + $xmlWriter->startElement('v:imagedata'); + $xmlWriter->writeAttribute('r:id', 'rId' . $rId); + $xmlWriter->writeAttribute('o:title', ''); + $xmlWriter->endElement(); // v:imagedata + $xmlWriter->endElement(); // v:shape + $xmlWriter->endElement(); // w:pict + $xmlWriter->endElement(); // w:r + $xmlWriter->endElement(); // w:p } } diff --git a/src/PhpWord/Writer/Word2007/Element/Line.php b/src/PhpWord/Writer/Word2007/Element/Line.php new file mode 100644 index 00000000..1ae10694 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Line.php @@ -0,0 +1,84 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof LineElement) { + return; + } + + $style = $element->getStyle(); + $styleWriter = new LineStyleWriter($xmlWriter, $style); + + $elementId = $element->getElementIndex(); + if (!$this->withoutP) { + $xmlWriter->startElement('w:p'); + $styleWriter->writeAlignment(); + } + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:pict'); + // Shapetype could be defined for each line separately, but then a unique id would be necessary + if ($elementId == 1) { + $xmlWriter->startElement('v:shapetype'); + $xmlWriter->writeAttribute('id', '_x0000_t32'); + $xmlWriter->writeAttribute('coordsize', '21600,21600'); + $xmlWriter->writeAttribute('o:spt', '32'); + $xmlWriter->writeAttribute('o:oned', 't'); + $xmlWriter->writeAttribute('path', 'm,l21600,21600e'); + $xmlWriter->writeAttribute('filled', 'f'); + $xmlWriter->startElement('v:path'); + $xmlWriter->writeAttribute('arrowok', 't'); + $xmlWriter->writeAttribute('fillok', 'f'); + $xmlWriter->writeAttribute('o:connecttype', 'none'); + $xmlWriter->endElement(); // v:path + $xmlWriter->startElement('o:lock'); + $xmlWriter->writeAttribute('v:ext', 'edit'); + $xmlWriter->writeAttribute('shapetype', 't'); + $xmlWriter->endElement(); // o:lock + $xmlWriter->endElement(); // v:shapetype + } + $xmlWriter->startElement('v:shape'); + $xmlWriter->writeAttribute('id', sprintf('_x0000_s1%1$03d', $elementId)); + $xmlWriter->writeAttribute('type', '#_x0000_t32'); //type should correspond to shapetype id + $styleWriter->write(); + $styleWriter->writeStroke(); + $styleWriter->writeW10Wrap(); + $xmlWriter->endElement(); // v:shape + $xmlWriter->endElement(); // w:pict + $xmlWriter->endElement(); // w:r + + if (!$this->withoutP) { + $xmlWriter->endElement(); // w:p + } + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Link.php b/src/PhpWord/Writer/Word2007/Element/Link.php index e9cdad91..ec531bac 100644 --- a/src/PhpWord/Writer/Word2007/Element/Link.php +++ b/src/PhpWord/Writer/Word2007/Element/Link.php @@ -1,57 +1,58 @@ element->getRelationId() + ($this->element->isInSection() ? 6 : 0); - $fontStyle = $this->element->getFontStyle(); - $paragraphStyle = $this->element->getParagraphStyle(); - - if (!$this->withoutP) { - $styleWriter = new ParagraphStyleWriter($this->xmlWriter, $paragraphStyle); - $styleWriter->setIsInline(true); - - $this->xmlWriter->startElement('w:p'); - $styleWriter->write(); + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Link) { + return; } - $styleWriter = new FontStyleWriter($this->xmlWriter, $fontStyle); - $styleWriter->setIsInline(true); + $rId = $element->getRelationId() + ($element->isInSection() ? 6 : 0); - $this->xmlWriter->startElement('w:hyperlink'); - $this->xmlWriter->writeAttribute('r:id', 'rId' . $rId); - $this->xmlWriter->writeAttribute('w:history', '1'); - $this->xmlWriter->startElement('w:r'); - $styleWriter->write(); - $this->xmlWriter->startElement('w:t'); - $this->xmlWriter->writeAttribute('xml:space', 'preserve'); - $this->xmlWriter->writeRaw($this->element->getText()); - $this->xmlWriter->endElement(); // w:t - $this->xmlWriter->endElement(); // w:r - $this->xmlWriter->endElement(); // w:hyperlink - if (!$this->withoutP) { - $this->xmlWriter->endElement(); // w:p - } + $this->writeOpeningWP(); + + $xmlWriter->startElement('w:hyperlink'); + $xmlWriter->writeAttribute('r:id', 'rId' . $rId); + $xmlWriter->writeAttribute('w:history', '1'); + $xmlWriter->startElement('w:r'); + + $this->writeFontStyle(); + + $xmlWriter->startElement('w:t'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw($element->getText()); + $xmlWriter->endElement(); // w:t + $xmlWriter->endElement(); // w:r + $xmlWriter->endElement(); // w:hyperlink + + $this->writeClosingWP(); } } diff --git a/src/PhpWord/Writer/Word2007/Element/ListItem.php b/src/PhpWord/Writer/Word2007/Element/ListItem.php index d020fe6f..7b86efae 100644 --- a/src/PhpWord/Writer/Word2007/Element/ListItem.php +++ b/src/PhpWord/Writer/Word2007/Element/ListItem.php @@ -1,15 +1,22 @@ element->getTextObject(); - $depth = $this->element->getDepth(); - $numId = $this->element->getStyle()->getNumId(); - $paragraphStyle = $textObject->getParagraphStyle(); - $styleWriter = new ParagraphStyleWriter($this->xmlWriter, $paragraphStyle); + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\ListItem) { + return; + } + + $textObject = $element->getTextObject(); + + $styleWriter = new ParagraphStyleWriter($xmlWriter, $textObject->getParagraphStyle()); $styleWriter->setWithoutPPR(true); $styleWriter->setIsInline(true); - $this->xmlWriter->startElement('w:p'); + $xmlWriter->startElement('w:p'); - $this->xmlWriter->startElement('w:pPr'); + $xmlWriter->startElement('w:pPr'); $styleWriter->write(); - $this->xmlWriter->startElement('w:numPr'); - $this->xmlWriter->startElement('w:ilvl'); - $this->xmlWriter->writeAttribute('w:val', $depth); - $this->xmlWriter->endElement(); // w:ilvl - $this->xmlWriter->startElement('w:numId'); - $this->xmlWriter->writeAttribute('w:val', $numId); - $this->xmlWriter->endElement(); // w:numId - $this->xmlWriter->endElement(); // w:numPr - $this->xmlWriter->endElement(); // w:pPr - $elementWriter = new ElementWriter($this->xmlWriter, $this->parentWriter, $textObject, true); + $xmlWriter->startElement('w:numPr'); + $xmlWriter->startElement('w:ilvl'); + $xmlWriter->writeAttribute('w:val', $element->getDepth()); + $xmlWriter->endElement(); // w:ilvl + $xmlWriter->startElement('w:numId'); + $xmlWriter->writeAttribute('w:val', $element->getStyle()->getNumId()); + $xmlWriter->endElement(); // w:numId + $xmlWriter->endElement(); // w:numPr + + $xmlWriter->endElement(); // w:pPr + + $elementWriter = new Text($xmlWriter, $textObject, true); $elementWriter->write(); - $this->xmlWriter->endElement(); // w:p + $xmlWriter->endElement(); // w:p } } diff --git a/src/PhpWord/Writer/Word2007/Element/ListItemRun.php b/src/PhpWord/Writer/Word2007/Element/ListItemRun.php new file mode 100644 index 00000000..747c2625 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/ListItemRun.php @@ -0,0 +1,64 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\ListItemRun) { + return; + } + + $xmlWriter->startElement('w:p'); + + $xmlWriter->startElement('w:pPr'); + $paragraphStyle = $element->getParagraphStyle(); + $styleWriter = new ParagraphStyleWriter($xmlWriter, $paragraphStyle); + $styleWriter->setIsInline(true); + $styleWriter->write(); + + $xmlWriter->startElement('w:numPr'); + $xmlWriter->startElement('w:ilvl'); + $xmlWriter->writeAttribute('w:val', $element->getDepth()); + $xmlWriter->endElement(); // w:ilvl + $xmlWriter->startElement('w:numId'); + $xmlWriter->writeAttribute('w:val', $element->getStyle()->getNumId()); + $xmlWriter->endElement(); // w:numId + $xmlWriter->endElement(); // w:numPr + + $xmlWriter->endElement(); // w:pPr + + $containerWriter = new Container($xmlWriter, $element); + $containerWriter->write(); + + $xmlWriter->endElement(); // w:p + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Note.php b/src/PhpWord/Writer/Word2007/Element/Note.php deleted file mode 100644 index 1ba73de8..00000000 --- a/src/PhpWord/Writer/Word2007/Element/Note.php +++ /dev/null @@ -1,48 +0,0 @@ -withoutP) { - $this->xmlWriter->startElement('w:p'); - } - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:rPr'); - $this->xmlWriter->startElement('w:rStyle'); - $this->xmlWriter->writeAttribute('w:val', ucfirst($this->referenceType)); - $this->xmlWriter->endElement(); // w:rStyle - $this->xmlWriter->endElement(); // w:rPr - $this->xmlWriter->startElement("w:{$this->referenceType}"); - $this->xmlWriter->writeAttribute('w:id', $this->element->getRelationId()); - $this->xmlWriter->endElement(); // w:$referenceType - $this->xmlWriter->endElement(); // w:r - if (!$this->withoutP) { - $this->xmlWriter->endElement(); // w:p - } - } -} diff --git a/src/PhpWord/Writer/Word2007/Element/Object.php b/src/PhpWord/Writer/Word2007/Element/Object.php index 1a2dfa4a..ae03f04f 100644 --- a/src/PhpWord/Writer/Word2007/Element/Object.php +++ b/src/PhpWord/Writer/Word2007/Element/Object.php @@ -1,69 +1,79 @@ element->getRelationId() + ($this->element->isInSection() ? 6 : 0); - $rIdImage = $this->element->getImageRelationId() + ($this->element->isInSection() ? 6 : 0); + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Object) { + return; + } + + $rIdObject = $element->getRelationId() + ($element->isInSection() ? 6 : 0); + $rIdImage = $element->getImageRelationId() + ($element->isInSection() ? 6 : 0); $shapeId = md5($rIdObject . '_' . $rIdImage); - $objectId = $this->element->getRelationId() + 1325353440; - $style = $this->element->getStyle(); - $align = $style->getAlign(); + $objectId = $element->getRelationId() + 1325353440; + $style = $element->getStyle(); + $styleWriter = new ImageStyleWriter($xmlWriter, $style); if (!$this->withoutP) { - $this->xmlWriter->startElement('w:p'); + $xmlWriter->startElement('w:p'); + $styleWriter->writeAlignment(); } - if (!is_null($align)) { - $this->xmlWriter->startElement('w:pPr'); - $this->xmlWriter->startElement('w:jc'); - $this->xmlWriter->writeAttribute('w:val', $align); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); - } - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:object'); - $this->xmlWriter->writeAttribute('w:dxaOrig', '249'); - $this->xmlWriter->writeAttribute('w:dyaOrig', '160'); - $this->xmlWriter->startElement('v:shape'); - $this->xmlWriter->writeAttribute('id', $shapeId); - $this->xmlWriter->writeAttribute('type', '#_x0000_t75'); - $this->xmlWriter->writeAttribute('style', 'width:104px;height:67px'); - $this->xmlWriter->writeAttribute('o:ole', ''); - $this->xmlWriter->startElement('v:imagedata'); - $this->xmlWriter->writeAttribute('r:id', 'rId' . $rIdImage); - $this->xmlWriter->writeAttribute('o:title', ''); - $this->xmlWriter->endElement(); // v:imagedata - $this->xmlWriter->endElement(); // v:shape - $this->xmlWriter->startElement('o:OLEObject'); - $this->xmlWriter->writeAttribute('Type', 'Embed'); - $this->xmlWriter->writeAttribute('ProgID', 'Package'); - $this->xmlWriter->writeAttribute('ShapeID', $shapeId); - $this->xmlWriter->writeAttribute('DrawAspect', 'Icon'); - $this->xmlWriter->writeAttribute('ObjectID', '_' . $objectId); - $this->xmlWriter->writeAttribute('r:id', 'rId' . $rIdObject); - $this->xmlWriter->endElement(); // o:OLEObject - $this->xmlWriter->endElement(); // w:object - $this->xmlWriter->endElement(); // w:r + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:object'); + $xmlWriter->writeAttribute('w:dxaOrig', '249'); + $xmlWriter->writeAttribute('w:dyaOrig', '160'); + $xmlWriter->startElement('v:shape'); + $xmlWriter->writeAttribute('id', $shapeId); + $xmlWriter->writeAttribute('type', '#_x0000_t75'); + $xmlWriter->writeAttribute('style', 'width:104px;height:67px'); + $xmlWriter->writeAttribute('o:ole', ''); + $xmlWriter->startElement('v:imagedata'); + $xmlWriter->writeAttribute('r:id', 'rId' . $rIdImage); + $xmlWriter->writeAttribute('o:title', ''); + $xmlWriter->endElement(); // v:imagedata + $xmlWriter->endElement(); // v:shape + $xmlWriter->startElement('o:OLEObject'); + $xmlWriter->writeAttribute('Type', 'Embed'); + $xmlWriter->writeAttribute('ProgID', 'Package'); + $xmlWriter->writeAttribute('ShapeID', $shapeId); + $xmlWriter->writeAttribute('DrawAspect', 'Icon'); + $xmlWriter->writeAttribute('ObjectID', '_' . $objectId); + $xmlWriter->writeAttribute('r:id', 'rId' . $rIdObject); + $xmlWriter->endElement(); // o:OLEObject + $xmlWriter->endElement(); // w:object + $xmlWriter->endElement(); // w:r if (!$this->withoutP) { - $this->xmlWriter->endElement(); // w:p + $xmlWriter->endElement(); // w:p } } } diff --git a/src/PhpWord/Writer/Word2007/Element/PageBreak.php b/src/PhpWord/Writer/Word2007/Element/PageBreak.php index a6cdd27f..6974777a 100644 --- a/src/PhpWord/Writer/Word2007/Element/PageBreak.php +++ b/src/PhpWord/Writer/Word2007/Element/PageBreak.php @@ -1,10 +1,18 @@ xmlWriter->startElement('w:p'); - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:br'); - $this->xmlWriter->writeAttribute('w:type', 'page'); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:br'); + $xmlWriter->writeAttribute('w:type', 'page'); + $xmlWriter->endElement(); // w:br + $xmlWriter->writeElement('w:lastRenderedPageBreak'); + $xmlWriter->endElement(); // w:r } } diff --git a/src/PhpWord/Writer/Word2007/Element/PreserveText.php b/src/PhpWord/Writer/Word2007/Element/PreserveText.php index 72ff7f1b..dd5d9008 100644 --- a/src/PhpWord/Writer/Word2007/Element/PreserveText.php +++ b/src/PhpWord/Writer/Word2007/Element/PreserveText.php @@ -1,90 +1,91 @@ element->getFontStyle(); - $paragraphStyle = $this->element->getParagraphStyle(); - $texts = $this->element->getText(); + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\PreserveText) { + return; + } + + $texts = $element->getText(); if (!is_array($texts)) { $texts = array($texts); } - $styleWriter = new ParagraphStyleWriter($this->xmlWriter, $paragraphStyle); - $styleWriter->setIsInline(true); - - $this->xmlWriter->startElement('w:p'); - $styleWriter->write(); + $this->writeOpeningWP(); foreach ($texts as $text) { if (substr($text, 0, 1) == '{') { $text = substr($text, 1, -1); - $styleWriter = new FontStyleWriter($this->xmlWriter, $fontStyle); - $styleWriter->setIsInline(true); - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:fldChar'); - $this->xmlWriter->writeAttribute('w:fldCharType', 'begin'); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'begin'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); - $this->xmlWriter->startElement('w:r'); - $styleWriter->write(); - $this->xmlWriter->startElement('w:instrText'); - $this->xmlWriter->writeAttribute('xml:space', 'preserve'); - $this->xmlWriter->writeRaw($text); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); + $xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:fldChar'); - $this->xmlWriter->writeAttribute('w:fldCharType', 'separate'); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); + $this->writeFontStyle(); - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:fldChar'); - $this->xmlWriter->writeAttribute('w:fldCharType', 'end'); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); + $xmlWriter->startElement('w:instrText'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw($text); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'separate'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'end'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); } else { - $text = htmlspecialchars($text); - $text = String::controlCharacterPHP2OOXML($text); - $styleWriter = new FontStyleWriter($this->xmlWriter, $fontStyle); - $styleWriter->setIsInline(true); + $xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:r'); - $styleWriter->write(); - $this->xmlWriter->startElement('w:t'); - $this->xmlWriter->writeAttribute('xml:space', 'preserve'); - $this->xmlWriter->writeRaw($text); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); + $this->writeFontStyle(); + + $xmlWriter->startElement('w:t'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw($this->getText($text)); + $xmlWriter->endElement(); + $xmlWriter->endElement(); } } - $this->xmlWriter->endElement(); // p + $this->writeClosingWP(); } } diff --git a/src/PhpWord/Writer/Word2007/Element/TOC.php b/src/PhpWord/Writer/Word2007/Element/TOC.php index 5be287a3..1db2efdd 100644 --- a/src/PhpWord/Writer/Word2007/Element/TOC.php +++ b/src/PhpWord/Writer/Word2007/Element/TOC.php @@ -1,154 +1,205 @@ element->getTitles(); - $fontStyle = $this->element->getStyleFont(); - - $tocStyle = $this->element->getStyleTOC(); - $fIndent = $tocStyle->getIndent(); - $tabLeader = $tocStyle->getTabLeader(); - $tabPos = $tocStyle->getTabPos(); - - $maxDepth = $this->element->getMaxDepth(); - $minDepth = $this->element->getMinDepth(); - - $isObject = ($fontStyle instanceof Font) ? true : false; - - for ($i = 0; $i < count($titles); $i++) { - $title = $titles[$i]; - $indent = ($title['depth'] - 1) * $fIndent; - - $this->xmlWriter->startElement('w:p'); - - $this->xmlWriter->startElement('w:pPr'); - - if ($isObject && !is_null($fontStyle->getParagraphStyle())) { - $styleWriter = new ParagraphStyleWriter($this->xmlWriter, $fontStyle->getParagraphStyle()); - $styleWriter->write(); - } - - if ($indent > 0) { - $this->xmlWriter->startElement('w:ind'); - $this->xmlWriter->writeAttribute('w:left', $indent); - $this->xmlWriter->endElement(); - } - - if (!empty($fontStyle) && !$isObject) { - $this->xmlWriter->startElement('w:pPr'); - $this->xmlWriter->startElement('w:pStyle'); - $this->xmlWriter->writeAttribute('w:val', $fontStyle); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); - } - - $this->xmlWriter->startElement('w:tabs'); - $this->xmlWriter->startElement('w:tab'); - $this->xmlWriter->writeAttribute('w:val', 'right'); - if (!empty($tabLeader)) { - $this->xmlWriter->writeAttribute('w:leader', $tabLeader); - } - $this->xmlWriter->writeAttribute('w:pos', $tabPos); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); - - $this->xmlWriter->endElement(); // w:pPr - - - if ($i == 0) { - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:fldChar'); - $this->xmlWriter->writeAttribute('w:fldCharType', 'begin'); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); - - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:instrText'); - $this->xmlWriter->writeAttribute('xml:space', 'preserve'); - $this->xmlWriter->writeRaw('TOC \o "' . $minDepth . '-' . $maxDepth . '" \h \z \u'); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); - - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:fldChar'); - $this->xmlWriter->writeAttribute('w:fldCharType', 'separate'); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); - } - - $this->xmlWriter->startElement('w:hyperlink'); - $this->xmlWriter->writeAttribute('w:anchor', $title['anchor']); - $this->xmlWriter->writeAttribute('w:history', '1'); - - $this->xmlWriter->startElement('w:r'); - - if ($isObject) { - $styleWriter = new FontStyleWriter($this->xmlWriter, $fontStyle); - $styleWriter->write(); - } - - $this->xmlWriter->startElement('w:t'); - $this->xmlWriter->writeRaw($title['text']); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); - - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->writeElement('w:tab', null); - $this->xmlWriter->endElement(); - - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:fldChar'); - $this->xmlWriter->writeAttribute('w:fldCharType', 'begin'); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); - - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:instrText'); - $this->xmlWriter->writeAttribute('xml:space', 'preserve'); - $this->xmlWriter->writeRaw('PAGEREF ' . $title['anchor'] . ' \h'); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); - - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:fldChar'); - $this->xmlWriter->writeAttribute('w:fldCharType', 'end'); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); - - $this->xmlWriter->endElement(); // w:hyperlink - - $this->xmlWriter->endElement(); // w:p + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof TOCElement) { + return; } - $this->xmlWriter->startElement('w:p'); - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:fldChar'); - $this->xmlWriter->writeAttribute('w:fldCharType', 'end'); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); + $titles = $element->getTitles(); + $writeFieldMark = true; + + foreach ($titles as $title) { + $this->writeTitle($xmlWriter, $element, $title, $writeFieldMark); + if ($writeFieldMark) { + $writeFieldMark = false; + } + } + + $xmlWriter->startElement('w:p'); + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'end'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + } + + /** + * Write title + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\TOC $element + * @param \PhpOffice\PhpWord\Element\Title $title + * @param bool $writeFieldMark + */ + private function writeTitle(XMLWriter $xmlWriter, TOCElement $element, $title, $writeFieldMark) + { + $tocStyle = $element->getStyleTOC(); + $fontStyle = $element->getStyleFont(); + $isObject = ($fontStyle instanceof Font) ? true : false; + $rId = $title->getRelationId(); + $indent = ($title->getDepth() - 1) * $tocStyle->getIndent(); + + $xmlWriter->startElement('w:p'); + + // Write style and field mark + $this->writeStyle($xmlWriter, $element, $indent); + if ($writeFieldMark) { + $this->writeFieldMark($xmlWriter, $element); + } + + // Hyperlink + $xmlWriter->startElement('w:hyperlink'); + $xmlWriter->writeAttribute('w:anchor', "_Toc{$rId}"); + $xmlWriter->writeAttribute('w:history', '1'); + + // Title text + $xmlWriter->startElement('w:r'); + if ($isObject) { + $styleWriter = new FontStyleWriter($xmlWriter, $fontStyle); + $styleWriter->write(); + } + $xmlWriter->startElement('w:t'); + $xmlWriter->writeRaw($title->getText()); + $xmlWriter->endElement(); + $xmlWriter->endElement(); // w:r + + $xmlWriter->startElement('w:r'); + $xmlWriter->writeElement('w:tab', null); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'begin'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:instrText'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw("PAGEREF _Toc{$rId} \h"); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'end'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + $xmlWriter->endElement(); // w:hyperlink + + $xmlWriter->endElement(); // w:p + } + + /** + * Write style + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\TOC $element + * @param int $indent + */ + private function writeStyle(XMLWriter $xmlWriter, TOCElement $element, $indent) + { + $tocStyle = $element->getStyleTOC(); + $fontStyle = $element->getStyleFont(); + $isObject = ($fontStyle instanceof Font) ? true : false; + + $xmlWriter->startElement('w:pPr'); + + // Paragraph + if ($isObject && !is_null($fontStyle->getParagraph())) { + $styleWriter = new ParagraphStyleWriter($xmlWriter, $fontStyle->getParagraph()); + $styleWriter->write(); + } + + // Font + if (!empty($fontStyle) && !$isObject) { + $xmlWriter->startElement('w:rPr'); + $xmlWriter->startElement('w:rStyle'); + $xmlWriter->writeAttribute('w:val', $fontStyle); + $xmlWriter->endElement(); + $xmlWriter->endElement(); // w:rPr + } + + // Tab + $xmlWriter->startElement('w:tabs'); + $styleWriter = new TabStyleWriter($xmlWriter, $tocStyle); + $styleWriter->write(); + $xmlWriter->endElement(); + + // Indent + if ($indent > 0) { + $xmlWriter->startElement('w:ind'); + $xmlWriter->writeAttribute('w:left', $indent); + $xmlWriter->endElement(); + } + + $xmlWriter->endElement(); // w:pPr + } + + /** + * Write TOC Field + */ + private function writeFieldMark(XMLWriter $xmlWriter, TOCElement $element) + { + $minDepth = $element->getMinDepth(); + $maxDepth = $element->getMaxDepth(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'begin'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:instrText'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw("TOC \o {$minDepth}-{$maxDepth} \h \z \u"); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'separate'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); } } diff --git a/src/PhpWord/Writer/Word2007/Element/Table.php b/src/PhpWord/Writer/Word2007/Element/Table.php index c538561a..8cadfc38 100644 --- a/src/PhpWord/Writer/Word2007/Element/Table.php +++ b/src/PhpWord/Writer/Word2007/Element/Table.php @@ -1,134 +1,149 @@ element->getRows(); + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof TableElement) { + return; + } + + $rows = $element->getRows(); $rowCount = count($rows); if ($rowCount > 0) { - $this->xmlWriter->startElement('w:tbl'); + $xmlWriter->startElement('w:tbl'); - // Table grid - $cellWidths = array(); + // Write columns + $this->writeColumns($xmlWriter, $element); + + // Write style + $styleWriter = new TableStyleWriter($xmlWriter, $element->getStyle()); + $styleWriter->setWidth($element->getWidth()); + $styleWriter->write(); + + // Write rows for ($i = 0; $i < $rowCount; $i++) { - $row = $rows[$i]; - $cells = $row->getCells(); - if (count($cells) <= count($cellWidths)) { - continue; - } - $cellWidths = array(); - foreach ($cells as $cell) { - $cellWidths[] = $cell->getWidth(); - } - } - $this->xmlWriter->startElement('w:tblGrid'); - foreach ($cellWidths as $width) { - $this->xmlWriter->startElement('w:gridCol'); - if (!is_null($width)) { - $this->xmlWriter->writeAttribute('w:w', $width); - $this->xmlWriter->writeAttribute('w:type', 'dxa'); - } - $this->xmlWriter->endElement(); - } - $this->xmlWriter->endElement(); // w:tblGrid - - // Table style - $tblStyle = $this->element->getStyle(); - $tblWidth = $this->element->getWidth(); - if ($tblStyle instanceof TableStyle) { - $styleWriter = new TableStyleWriter($this->xmlWriter, $tblStyle); - $styleWriter->setIsFullStyle(false); - $styleWriter->write(); - } else { - if (!empty($tblStyle)) { - $this->xmlWriter->startElement('w:tblPr'); - $this->xmlWriter->startElement('w:tblStyle'); - $this->xmlWriter->writeAttribute('w:val', $tblStyle); - $this->xmlWriter->endElement(); - if (!is_null($tblWidth)) { - $this->xmlWriter->startElement('w:tblW'); - $this->xmlWriter->writeAttribute('w:w', $tblWidth); - $this->xmlWriter->writeAttribute('w:type', 'pct'); - $this->xmlWriter->endElement(); - } - $this->xmlWriter->endElement(); - } + $this->writeRow($xmlWriter, $rows[$i]); } - // Table rows - for ($i = 0; $i < $rowCount; $i++) { - $row = $rows[$i]; - $height = $row->getHeight(); - $rowStyle = $row->getStyle(); - $tblHeader = $rowStyle->getTblHeader(); - $cantSplit = $rowStyle->getCantSplit(); - $exactHeight = $rowStyle->getExactHeight(); - - $this->xmlWriter->startElement('w:tr'); - if (!is_null($height) || !is_null($tblHeader) || !is_null($cantSplit)) { - $this->xmlWriter->startElement('w:trPr'); - if (!is_null($height)) { - $this->xmlWriter->startElement('w:trHeight'); - $this->xmlWriter->writeAttribute('w:val', $height); - $this->xmlWriter->writeAttribute('w:hRule', ($exactHeight ? 'exact' : 'atLeast')); - $this->xmlWriter->endElement(); - } - if ($tblHeader) { - $this->xmlWriter->startElement('w:tblHeader'); - $this->xmlWriter->writeAttribute('w:val', '1'); - $this->xmlWriter->endElement(); - } - if ($cantSplit) { - $this->xmlWriter->startElement('w:cantSplit'); - $this->xmlWriter->writeAttribute('w:val', '1'); - $this->xmlWriter->endElement(); - } - $this->xmlWriter->endElement(); - } - foreach ($row->getCells() as $cell) { - $cellStyle = $cell->getStyle(); - $width = $cell->getWidth(); - $this->xmlWriter->startElement('w:tc'); - $this->xmlWriter->startElement('w:tcPr'); - $this->xmlWriter->startElement('w:tcW'); - $this->xmlWriter->writeAttribute('w:w', $width); - $this->xmlWriter->writeAttribute('w:type', 'dxa'); - $this->xmlWriter->endElement(); // w:tcW - if ($cellStyle instanceof Cell) { - $styleWriter = new CellStyleWriter($this->xmlWriter, $cellStyle); - $styleWriter->write(); - } - $this->xmlWriter->endElement(); // w:tcPr - $this->parentWriter->writeContainerElements($this->xmlWriter, $cell); - $this->xmlWriter->endElement(); // w:tc - } - $this->xmlWriter->endElement(); // w:tr - } - $this->xmlWriter->endElement(); + $xmlWriter->endElement(); // w:tbl } } + + /** + * Write column + */ + private function writeColumns(XMLWriter $xmlWriter, TableElement $element) + { + $rows = $element->getRows(); + $rowCount = count($rows); + + $cellWidths = array(); + for ($i = 0; $i < $rowCount; $i++) { + $row = $rows[$i]; + $cells = $row->getCells(); + if (count($cells) <= count($cellWidths)) { + continue; + } + $cellWidths = array(); + foreach ($cells as $cell) { + $cellWidths[] = $cell->getWidth(); + } + } + + $xmlWriter->startElement('w:tblGrid'); + foreach ($cellWidths as $width) { + $xmlWriter->startElement('w:gridCol'); + if ($width !== null) { + $xmlWriter->writeAttribute('w:w', $width); + $xmlWriter->writeAttribute('w:type', 'dxa'); + } + $xmlWriter->endElement(); + } + $xmlWriter->endElement(); // w:tblGrid + } + + /** + * Write row + */ + private function writeRow(XMLWriter $xmlWriter, RowElement $row) + { + $xmlWriter->startElement('w:tr'); + + // Write style + $rowStyle = $row->getStyle(); + if ($rowStyle instanceof RowStyle) { + $styleWriter = new RowStyleWriter($xmlWriter, $rowStyle); + $styleWriter->setHeight($row->getHeight()); + $styleWriter->write(); + } + + // Write cells + foreach ($row->getCells() as $cell) { + $this->writeCell($xmlWriter, $cell); + } + + $xmlWriter->endElement(); // w:tr + } + + /** + * Write cell + */ + private function writeCell(XMLWriter $xmlWriter, CellElement $cell) + { + + $xmlWriter->startElement('w:tc'); + + // Write style + $cellStyle = $cell->getStyle(); + if ($cellStyle instanceof CellStyle) { + $styleWriter = new CellStyleWriter($xmlWriter, $cellStyle); + $styleWriter->setWidth($cell->getWidth()); + $styleWriter->write(); + } + + // Write content + $containerWriter = new Container($xmlWriter, $cell); + $containerWriter->write(); + + $xmlWriter->endElement(); // w:tc + } } diff --git a/src/PhpWord/Writer/Word2007/Element/Text.php b/src/PhpWord/Writer/Word2007/Element/Text.php index 99ad4953..64c4b766 100644 --- a/src/PhpWord/Writer/Word2007/Element/Text.php +++ b/src/PhpWord/Writer/Word2007/Element/Text.php @@ -1,15 +1,23 @@ element->getFontStyle(); - $paragraphStyle = $this->element->getParagraphStyle(); - $text = htmlspecialchars($this->element->getText()); - $text = String::controlCharacterPHP2OOXML($text); - - if (!$this->withoutP) { - $styleWriter = new ParagraphStyleWriter($this->xmlWriter, $paragraphStyle); - $styleWriter->setIsInline(true); - - $this->xmlWriter->startElement('w:p'); - $styleWriter->write(); + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Text) { + return; } - $styleWriter = new FontStyleWriter($this->xmlWriter, $fontStyle); - $styleWriter->setIsInline(true); - $this->xmlWriter->startElement('w:r'); - $styleWriter->write(); - $this->xmlWriter->startElement('w:t'); - $this->xmlWriter->writeAttribute('xml:space', 'preserve'); - $this->xmlWriter->writeRaw($text); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); // w:r + $this->writeOpeningWP(); + + $xmlWriter->startElement('w:r'); + + $this->writeFontStyle(); + + $xmlWriter->startElement('w:t'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw($this->getText($element->getText())); + $xmlWriter->endElement(); + $xmlWriter->endElement(); // w:r + + $this->writeClosingWP(); + } + + /** + * Write opening + * + * @uses \PhpOffice\PhpWord\Writer\Word2007\Element\PageBreak::write() + */ + protected function writeOpeningWP() + { + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$this->withoutP) { - $this->xmlWriter->endElement(); // w:p + $xmlWriter->startElement('w:p'); + // Paragraph style + if (method_exists($element, 'getParagraphStyle')) { + $this->writeParagraphStyle(); + } + // PageBreak + if ($this->hasPageBreakBefore()) { + $elementWriter = new PageBreak($xmlWriter, new PageBreakElement()); + $elementWriter->write(); + } } } + + /** + * Write ending + */ + protected function writeClosingWP() + { + $xmlWriter = $this->getXmlWriter(); + + if (!$this->withoutP) { + $xmlWriter->endElement(); // w:p + } + } + + /** + * Write ending + */ + protected function writeParagraphStyle() + { + $xmlWriter = $this->getXmlWriter(); + + /** @var \PhpOffice\PhpWord\Element\Text $element Type hint */ + $element = $this->getElement(); + $paragraphStyle = $element->getParagraphStyle(); + $styleWriter = new ParagraphStyleWriter($xmlWriter, $paragraphStyle); + $styleWriter->setIsInline(true); + $styleWriter->write(); + } + + /** + * Write ending + */ + protected function writeFontStyle() + { + $xmlWriter = $this->getXmlWriter(); + + /** @var \PhpOffice\PhpWord\Element\Text $element Type hint */ + $element = $this->getElement(); + $fontStyle = $element->getFontStyle(); + $styleWriter = new FontStyleWriter($xmlWriter, $fontStyle); + $styleWriter->setIsInline(true); + $styleWriter->write(); + } } diff --git a/src/PhpWord/Writer/Word2007/Element/TextBox.php b/src/PhpWord/Writer/Word2007/Element/TextBox.php new file mode 100644 index 00000000..4ee5e68e --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/TextBox.php @@ -0,0 +1,71 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\TextBox) { + return; + } + $style = $element->getStyle(); + $styleWriter = new TextBoxStyleWriter($xmlWriter, $style); + + if (!$this->withoutP) { + $xmlWriter->startElement('w:p'); + $styleWriter->writeAlignment(); + } + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:pict'); + $xmlWriter->startElement('v:shape'); + $xmlWriter->writeAttribute('type', '#_x0000_t0202'); + $styleWriter->write(); + $xmlWriter->startElement('v:textbox'); + $styleWriter->writeInnerMargin(); + + // TextBox content, serving as a container + $xmlWriter->startElement('w:txbxContent'); + $containerWriter = new Container($xmlWriter, $element); + $containerWriter->write(); + $xmlWriter->endElement(); // w:txbxContent + + $xmlWriter->endElement(); // v: textbox + $styleWriter->writeW10Wrap(); + $xmlWriter->endElement(); // v:shape + $xmlWriter->endElement(); // w:pict + $xmlWriter->endElement(); // w:r + + if (!$this->withoutP) { + $xmlWriter->endElement(); // w:p + } + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/TextBreak.php b/src/PhpWord/Writer/Word2007/Element/TextBreak.php index 008e1e12..5f4bd3ce 100644 --- a/src/PhpWord/Writer/Word2007/Element/TextBreak.php +++ b/src/PhpWord/Writer/Word2007/Element/TextBreak.php @@ -1,58 +1,51 @@ getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\TextBreak) { + return; + } + if (!$this->withoutP) { - $hasStyle = false; - $fontStyle = null; - $paragraphStyle = null; - if (!is_null($this->element)) { - $fontStyle = $this->element->getFontStyle(); - $paragraphStyle = $this->element->getParagraphStyle(); - $hasStyle = !is_null($fontStyle) || !is_null($paragraphStyle); - } + $hasStyle = $element->hasStyle(); + $this->writeOpeningWP(); if ($hasStyle) { - $styleWriter = new ParagraphStyleWriter($this->xmlWriter, $paragraphStyle); - $styleWriter->setIsInline(true); - - $this->xmlWriter->startElement('w:p'); - $styleWriter->write(); - if (!is_null($fontStyle)) { - $styleWriter = new FontStyleWriter($this->xmlWriter, $fontStyle); - $styleWriter->setIsInline(true); - - $this->xmlWriter->startElement('w:pPr'); - $styleWriter->write(); - $this->xmlWriter->endElement(); // w:pPr - } - $this->xmlWriter->endElement(); // w:p - } else { - $this->xmlWriter->writeElement('w:p'); + $xmlWriter->startElement('w:pPr'); + $this->writeFontStyle(); + $xmlWriter->endElement(); // w:pPr } + $this->writeClosingWP(); } else { - $this->xmlWriter->writeElement('w:br'); + $xmlWriter->writeElement('w:br'); } } } diff --git a/src/PhpWord/Writer/Word2007/Element/TextRun.php b/src/PhpWord/Writer/Word2007/Element/TextRun.php index f23ef693..330e297c 100644 --- a/src/PhpWord/Writer/Word2007/Element/TextRun.php +++ b/src/PhpWord/Writer/Word2007/Element/TextRun.php @@ -1,35 +1,42 @@ element->getParagraphStyle(); - $styleWriter = new ParagraphStyleWriter($this->xmlWriter, $paragraphStyle); - $styleWriter->setIsInline(true); + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); - $this->xmlWriter->startElement('w:p'); - $styleWriter->write(); - $this->parentWriter->writeContainerElements($this->xmlWriter, $this->element); - $this->xmlWriter->endElement(); // w:p + $this->writeOpeningWP(); + + $containerWriter = new Container($xmlWriter, $element); + $containerWriter->write(); + + $this->writeClosingWP(); } } diff --git a/src/PhpWord/Writer/Word2007/Element/Title.php b/src/PhpWord/Writer/Word2007/Element/Title.php index 5570921f..144e67ab 100644 --- a/src/PhpWord/Writer/Word2007/Element/Title.php +++ b/src/PhpWord/Writer/Word2007/Element/Title.php @@ -1,65 +1,72 @@ element->getAnchor(); - $bookmarkId = $this->element->getBookmarkId(); - $style = $this->element->getStyle(); - $text = htmlspecialchars($this->element->getText()); - $text = String::controlCharacterPHP2OOXML($text); - - $this->xmlWriter->startElement('w:p'); - - if (!empty($style)) { - $this->xmlWriter->startElement('w:pPr'); - $this->xmlWriter->startElement('w:pStyle'); - $this->xmlWriter->writeAttribute('w:val', $style); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); + $xmlWriter = $this->getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Title) { + return; } - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:fldChar'); - $this->xmlWriter->writeAttribute('w:fldCharType', 'end'); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); + $style = $element->getStyle(); - $this->xmlWriter->startElement('w:bookmarkStart'); - $this->xmlWriter->writeAttribute('w:id', $bookmarkId); - $this->xmlWriter->writeAttribute('w:name', $anchor); - $this->xmlWriter->endElement(); + $xmlWriter->startElement('w:p'); - $this->xmlWriter->startElement('w:r'); - $this->xmlWriter->startElement('w:t'); - $this->xmlWriter->writeRaw($text); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); + if (!empty($style)) { + $xmlWriter->startElement('w:pPr'); + $xmlWriter->startElement('w:pStyle'); + $xmlWriter->writeAttribute('w:val', $style); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + } - $this->xmlWriter->startElement('w:bookmarkEnd'); - $this->xmlWriter->writeAttribute('w:id', $bookmarkId); - $this->xmlWriter->endElement(); + $rId = $element->getRelationId(); - $this->xmlWriter->endElement(); + // Bookmark start for TOC + $xmlWriter->startElement('w:bookmarkStart'); + $xmlWriter->writeAttribute('w:id', $rId); + $xmlWriter->writeAttribute('w:name', "_Toc{$rId}"); + $xmlWriter->endElement(); + + // Actual text + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:t'); + $xmlWriter->writeRaw($this->getText($element->getText())); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + // Bookmark end + $xmlWriter->startElement('w:bookmarkEnd'); + $xmlWriter->writeAttribute('w:id', $rId); + $xmlWriter->endElement(); + + $xmlWriter->endElement(); } } diff --git a/src/PhpWord/Writer/Word2007/Part/AbstractPart.php b/src/PhpWord/Writer/Word2007/Part/AbstractPart.php index afa84caf..610a7616 100644 --- a/src/PhpWord/Writer/Word2007/Part/AbstractPart.php +++ b/src/PhpWord/Writer/Word2007/Part/AbstractPart.php @@ -1,21 +1,25 @@ parentWriter = $pWriter; + $this->parentWriter = $writer; } /** * Get parent writer * - * @return \PhpOffice\PhpWord\Writer\WriterInterface + * @return \PhpOffice\PhpWord\Writer\AbstractWriter * @throws \PhpOffice\PhpWord\Exception\Exception */ public function getParentWriter() @@ -50,7 +66,7 @@ abstract class AbstractPart if (!is_null($this->parentWriter)) { return $this->parentWriter; } else { - throw new Exception("No parent WriterInterface assigned."); + throw new Exception('No parent WriterInterface assigned.'); } } @@ -63,7 +79,7 @@ abstract class AbstractPart { $useDiskCaching = false; if (!is_null($this->parentWriter)) { - if ($this->parentWriter->getUseDiskCaching()) { + if ($this->parentWriter->isUseDiskCaching()) { $useDiskCaching = true; } } @@ -73,48 +89,4 @@ abstract class AbstractPart return new XMLWriter(XMLWriter::STORAGE_MEMORY); } } - - /** - * Write container elements - * - * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter - * @param \PhpOffice\PhpWord\Element\AbstractElement $container - */ - public function writeContainerElements(XMLWriter $xmlWriter, AbstractElement $container) - { - // Check allowed elements - $elmCommon = array('Text', 'Link', 'TextBreak', 'Image', 'Object'); - $elmMainCell = array_merge($elmCommon, array('TextRun', 'ListItem', 'CheckBox')); - $allowedElements = array( - 'Section' => array_merge($elmMainCell, array('Table', 'Footnote', 'Title', 'PageBreak', 'TOC')), - 'Header' => array_merge($elmMainCell, array('Table', 'PreserveText')), - 'Footer' => array_merge($elmMainCell, array('Table', 'PreserveText')), - 'Cell' => array_merge($elmMainCell, array('PreserveText', 'Footnote', 'Endnote')), - 'TextRun' => array_merge($elmCommon, array('Footnote', 'Endnote')), - 'Footnote' => $elmCommon, - 'Endnote' => $elmCommon, - ); - $containerName = get_class($container); - $containerName = substr($containerName, strrpos($containerName, '\\') + 1); - if (!array_key_exists($containerName, $allowedElements)) { - throw new Exception('Invalid container.'); - } - - // Loop through elements - $elements = $container->getElements(); - $withoutP = in_array($containerName, array('TextRun', 'Footnote', 'Endnote')) ? true : false; - if (count($elements) > 0) { - foreach ($elements as $element) { - if ($element instanceof AbstractElement) { - $elementWriter = new ElementWriter($xmlWriter, $this, $element, $withoutP); - $elementWriter->write(); - } - } - } else { - if ($containerName == 'Cell') { - $elementWriter = new ElementWriter($xmlWriter, $this, new TextBreak(), $withoutP); - $elementWriter->write(); - } - } - } } diff --git a/src/PhpWord/Writer/Word2007/Part/ContentTypes.php b/src/PhpWord/Writer/Word2007/Part/ContentTypes.php index 00e05c76..b6f23f47 100644 --- a/src/PhpWord/Writer/Word2007/Part/ContentTypes.php +++ b/src/PhpWord/Writer/Word2007/Part/ContentTypes.php @@ -1,47 +1,59 @@ getParentWriter(); + $contentTypes = $parentWriter->getContentTypes(); + + $openXMLPrefix = 'application/vnd.openxmlformats-'; + $wordMLPrefix = $openXMLPrefix . 'officedocument.wordprocessingml.'; $overrides = array( - '/docProps/core.xml' => $OpenXMLPrefix . 'package.core-properties+xml', - '/docProps/app.xml' => $OpenXMLPrefix . 'officedocument.extended-properties+xml', - '/word/document.xml' => $WordMLPrefix . 'document.main+xml', - '/word/styles.xml' => $WordMLPrefix . 'styles+xml', - '/word/numbering.xml' => $WordMLPrefix . 'numbering+xml', - '/word/settings.xml' => $WordMLPrefix . 'settings+xml', - '/word/theme/theme1.xml' => $OpenXMLPrefix . 'officedocument.theme+xml', - '/word/webSettings.xml' => $WordMLPrefix . 'webSettings+xml', - '/word/fontTable.xml' => $WordMLPrefix . 'fontTable+xml', + '/docProps/core.xml' => $openXMLPrefix . 'package.core-properties+xml', + '/docProps/app.xml' => $openXMLPrefix . 'officedocument.extended-properties+xml', + '/docProps/custom.xml' => $openXMLPrefix . 'officedocument.custom-properties+xml', + '/word/document.xml' => $wordMLPrefix . 'document.main+xml', + '/word/styles.xml' => $wordMLPrefix . 'styles+xml', + '/word/numbering.xml' => $wordMLPrefix . 'numbering+xml', + '/word/settings.xml' => $wordMLPrefix . 'settings+xml', + '/word/theme/theme1.xml' => $openXMLPrefix . 'officedocument.theme+xml', + '/word/webSettings.xml' => $wordMLPrefix . 'webSettings+xml', + '/word/fontTable.xml' => $wordMLPrefix . 'fontTable+xml', ); $defaults = $contentTypes['default']; if (!empty($contentTypes['override'])) { foreach ($contentTypes['override'] as $key => $val) { - $overrides[$key] = $WordMLPrefix . $val . '+xml'; + $overrides[$key] = $wordMLPrefix . $val . '+xml'; } } @@ -65,21 +77,16 @@ class ContentTypes extends AbstractPart * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter XML Writer * @param array $parts * @param boolean $isDefault - * @throws \PhpOffice\PhpWord\Exception\Exception */ private function writeContentType(XMLWriter $xmlWriter, $parts, $isDefault) { foreach ($parts as $partName => $contentType) { - if ($partName != '' && $contentType != '') { - $partType = $isDefault ? 'Default' : 'Override'; - $partAttribute = $isDefault ? 'Extension' : 'PartName'; - $xmlWriter->startElement($partType); - $xmlWriter->writeAttribute($partAttribute, $partName); - $xmlWriter->writeAttribute('ContentType', $contentType); - $xmlWriter->endElement(); - } else { - throw new Exception("Invalid parameters passed."); - } + $partType = $isDefault ? 'Default' : 'Override'; + $partAttribute = $isDefault ? 'Extension' : 'PartName'; + $xmlWriter->startElement($partType); + $xmlWriter->writeAttribute($partAttribute, $partName); + $xmlWriter->writeAttribute('ContentType', $contentType); + $xmlWriter->endElement(); } } } diff --git a/src/PhpWord/Writer/Word2007/Part/DocPropsApp.php b/src/PhpWord/Writer/Word2007/Part/DocPropsApp.php new file mode 100644 index 00000000..1e6549c5 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/DocPropsApp.php @@ -0,0 +1,51 @@ +getParentWriter()->getPhpWord(); + $xmlWriter = $this->getXmlWriter(); + $schema = 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties'; + + $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); + $xmlWriter->startElement('Properties'); + $xmlWriter->writeAttribute('xmlns', $schema); + $xmlWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); + + $xmlWriter->writeElement('Application', 'PHPWord'); + $xmlWriter->writeElement('Company', $phpWord->getDocumentProperties()->getCompany()); + $xmlWriter->writeElement('Manager', $phpWord->getDocumentProperties()->getManager()); + + $xmlWriter->endElement(); // Properties + + return $xmlWriter->getData(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/DocProps.php b/src/PhpWord/Writer/Word2007/Part/DocPropsCore.php similarity index 50% rename from src/PhpWord/Writer/Word2007/Part/DocProps.php rename to src/PhpWord/Writer/Word2007/Part/DocPropsCore.php index ade15c0a..38f6d235 100644 --- a/src/PhpWord/Writer/Word2007/Part/DocProps.php +++ b/src/PhpWord/Writer/Word2007/Part/DocPropsCore.php @@ -1,62 +1,43 @@ getXmlWriter(); - - $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); - $xmlWriter->startElement('Properties'); - $xmlWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties'); - $xmlWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); - - $xmlWriter->writeElement('Application', 'PHPWord'); - $xmlWriter->writeElement('Company', $phpWord->getDocumentProperties()->getCompany()); - $xmlWriter->writeElement('Manager', $phpWord->getDocumentProperties()->getManager()); - - $xmlWriter->endElement(); // Properties - - return $xmlWriter->getData(); - } - - - /** - * Write docProps/core.xml + * Write part * - * @param \PhpOffice\PhpWord\PhpWord $phpWord + * @return string */ - public function writeDocPropsCore(PhpWord $phpWord = null) + public function write() { - if (is_null($phpWord)) { - throw new Exception("No PhpWord assigned."); - } + $phpWord = $this->getParentWriter()->getPhpWord(); $xmlWriter = $this->getXmlWriter(); + $schema = 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties'; $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); $xmlWriter->startElement('cp:coreProperties'); - $xmlWriter->writeAttribute('xmlns:cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties'); + $xmlWriter->writeAttribute('xmlns:cp', $schema); $xmlWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); $xmlWriter->writeAttribute('xmlns:dcterms', 'http://purl.org/dc/terms/'); $xmlWriter->writeAttribute('xmlns:dcmitype', 'http://purl.org/dc/dcmitype/'); @@ -73,13 +54,13 @@ class DocProps extends AbstractPart // dcterms:created $xmlWriter->startElement('dcterms:created'); $xmlWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); - $xmlWriter->writeRaw(date(DATE_W3C, $phpWord->getDocumentProperties()->getCreated())); + $xmlWriter->writeRaw(date($this->dateFormat, $phpWord->getDocumentProperties()->getCreated())); $xmlWriter->endElement(); // dcterms:modified $xmlWriter->startElement('dcterms:modified'); $xmlWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); - $xmlWriter->writeRaw(date(DATE_W3C, $phpWord->getDocumentProperties()->getModified())); + $xmlWriter->writeRaw(date($this->dateFormat, $phpWord->getDocumentProperties()->getModified())); $xmlWriter->endElement(); $xmlWriter->endElement(); // cp:coreProperties diff --git a/src/PhpWord/Writer/Word2007/Part/DocPropsCustom.php b/src/PhpWord/Writer/Word2007/Part/DocPropsCustom.php new file mode 100644 index 00000000..c5a3cf9e --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/DocPropsCustom.php @@ -0,0 +1,78 @@ +getParentWriter()->getPhpWord(); + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); + $xmlWriter->startElement('Properties'); + $xmlWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/custom-properties'); + $xmlWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); + + $docProps = $phpWord->getDocumentProperties(); + $properties = $docProps->getCustomProperties(); + foreach ($properties as $key => $property) { + $propertyValue = $docProps->getCustomPropertyValue($property); + $propertyType = $docProps->getCustomPropertyType($property); + + $xmlWriter->startElement('property'); + $xmlWriter->writeAttribute('fmtid', '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}'); + $xmlWriter->writeAttribute('pid', $key + 2); + $xmlWriter->writeAttribute('name', $property); + switch ($propertyType) { + case 'i': + $xmlWriter->writeElement('vt:i4', $propertyValue); + break; + case 'f': + $xmlWriter->writeElement('vt:r8', $propertyValue); + break; + case 'b': + $xmlWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false'); + break; + case 'd': + $xmlWriter->startElement('vt:filetime'); + $xmlWriter->writeRaw(date($this->dateFormat, $propertyValue)); + $xmlWriter->endElement(); + break; + default: + $xmlWriter->writeElement('vt:lpwstr', $propertyValue); + break; + } + $xmlWriter->endElement(); // property + } + + $xmlWriter->endElement(); // Properties + + return $xmlWriter->getData(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/Document.php b/src/PhpWord/Writer/Word2007/Part/Document.php index 535784b8..99570338 100644 --- a/src/PhpWord/Writer/Word2007/Part/Document.php +++ b/src/PhpWord/Writer/Word2007/Part/Document.php @@ -1,41 +1,46 @@ getParentWriter()->getPhpWord(); $xmlWriter = $this->getXmlWriter(); + $sections = $phpWord->getSections(); $sectionCount = count($sections); $currentSection = 0; + $drawingSchema = 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'; $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); $xmlWriter->startElement('w:document'); @@ -44,7 +49,7 @@ class Document extends AbstractPart $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); $xmlWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); $xmlWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); - $xmlWriter->writeAttribute('xmlns:wp', 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'); + $xmlWriter->writeAttribute('xmlns:wp', $drawingSchema); $xmlWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); $xmlWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); @@ -55,7 +60,10 @@ class Document extends AbstractPart if ($sectionCount > 0) { foreach ($sections as $section) { $currentSection++; - $this->writeContainerElements($xmlWriter, $section); + + $containerWriter = new Container($xmlWriter, $section); + $containerWriter->write(); + if ($currentSection == $sectionCount) { $this->writeSectionSettings($xmlWriter, $section); } else { diff --git a/src/PhpWord/Writer/Word2007/Part/Endnotes.php b/src/PhpWord/Writer/Word2007/Part/Endnotes.php index 9cecf402..f07bac5f 100644 --- a/src/PhpWord/Writer/Word2007/Part/Endnotes.php +++ b/src/PhpWord/Writer/Word2007/Part/Endnotes.php @@ -1,16 +1,24 @@ -'; + $str = ''; + $str .= ''; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + + return $str; } } diff --git a/src/PhpWord/Writer/Word2007/Part/Footer.php b/src/PhpWord/Writer/Word2007/Part/Footer.php index f31ece86..db6a2b33 100644 --- a/src/PhpWord/Writer/Word2007/Part/Footer.php +++ b/src/PhpWord/Writer/Word2007/Part/Footer.php @@ -1,46 +1,83 @@ getXmlWriter(); + $drawingSchema = 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'; $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); - $xmlWriter->startElement('w:ftr'); + $xmlWriter->startElement($this->rootElement); $xmlWriter->writeAttribute('xmlns:ve', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); $xmlWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); $xmlWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); $xmlWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); - $xmlWriter->writeAttribute('xmlns:wp', 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'); + $xmlWriter->writeAttribute('xmlns:wp', $drawingSchema); $xmlWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); $xmlWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); - $this->writeContainerElements($xmlWriter, $footer); + $containerWriter = new Container($xmlWriter, $this->element); + $containerWriter->write(); - $xmlWriter->endElement(); // w:ftr + $xmlWriter->endElement(); // $this->rootElement return $xmlWriter->getData(); } + + /** + * Set element + * + * @param \PhpOffice\PhpWord\Element\Footer|\PhpOffice\PhpWord\Element\Header $element + * @return self + */ + public function setElement($element) + { + $this->element = $element; + + return $this; + } } diff --git a/src/PhpWord/Writer/Word2007/Part/Footnotes.php b/src/PhpWord/Writer/Word2007/Part/Footnotes.php index 2356849e..903e5fe5 100644 --- a/src/PhpWord/Writer/Word2007/Part/Footnotes.php +++ b/src/PhpWord/Writer/Word2007/Part/Footnotes.php @@ -1,20 +1,29 @@ getXmlWriter(); + $drawingSchema = 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'; $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); $xmlWriter->startElement($this->rootNode); @@ -62,7 +79,7 @@ class Footnotes extends AbstractPart $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); $xmlWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); $xmlWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); - $xmlWriter->writeAttribute('xmlns:wp', 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'); + $xmlWriter->writeAttribute('xmlns:wp', $drawingSchema); $xmlWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); $xmlWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); @@ -89,7 +106,8 @@ class Footnotes extends AbstractPart $xmlWriter->endElement(); // w:p $xmlWriter->endElement(); // $this->elementNode - // Content + /** @var array $elements Type hint */ + $elements = $this->elements; foreach ($elements as $element) { if ($element instanceof Footnote) { $this->writeNote($xmlWriter, $element); @@ -101,6 +119,19 @@ class Footnotes extends AbstractPart return $xmlWriter->getData(); } + /** + * Set element + * + * @param \PhpOffice\PhpWord\Collection\Footnotes|\PhpOffice\PhpWord\Collection\Endnotes $elements + * @return self + */ + public function setElements($elements) + { + $this->elements = $elements; + + return $this; + } + /** * Write note item * @@ -136,7 +167,8 @@ class Footnotes extends AbstractPart $xmlWriter->endElement(); // w:t $xmlWriter->endElement(); // w:r - $this->writeContainerElements($xmlWriter, $element); + $containerWriter = new Container($xmlWriter, $element); + $containerWriter->write(); $xmlWriter->endElement(); // w:p $xmlWriter->endElement(); // $this->elementNode diff --git a/src/PhpWord/Writer/Word2007/Part/Header.php b/src/PhpWord/Writer/Word2007/Part/Header.php index d2af19da..638111d7 100644 --- a/src/PhpWord/Writer/Word2007/Part/Header.php +++ b/src/PhpWord/Writer/Word2007/Part/Header.php @@ -1,46 +1,31 @@ getXmlWriter(); - - $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); - $xmlWriter->startElement('w:hdr'); - $xmlWriter->writeAttribute('xmlns:ve', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); - $xmlWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); - $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - $xmlWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); - $xmlWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); - $xmlWriter->writeAttribute('xmlns:wp', 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'); - $xmlWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); - $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); - $xmlWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); - - $this->writeContainerElements($xmlWriter, $header); - - $xmlWriter->endElement(); // w:hdr - - return $xmlWriter->getData(); - } + protected $rootElement = 'w:hdr'; } diff --git a/src/PhpWord/Writer/Word2007/Part/Numbering.php b/src/PhpWord/Writer/Word2007/Part/Numbering.php index ea1b699b..8f735dd3 100644 --- a/src/PhpWord/Writer/Word2007/Part/Numbering.php +++ b/src/PhpWord/Writer/Word2007/Part/Numbering.php @@ -1,31 +1,44 @@ getXmlWriter(); + $styles = Style::getStyles(); + $drawingSchema = 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'; $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); $xmlWriter->startElement('w:numbering'); @@ -34,7 +47,7 @@ class Numbering extends AbstractPart $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); $xmlWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); $xmlWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); - $xmlWriter->writeAttribute('xmlns:wp', 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'); + $xmlWriter->writeAttribute('xmlns:wp', $drawingSchema); $xmlWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); $xmlWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); @@ -45,7 +58,7 @@ class Numbering extends AbstractPart $levels = $style->getLevels(); $xmlWriter->startElement('w:abstractNum'); - $xmlWriter->writeAttribute('w:abstractNumId', $style->getNumId()); + $xmlWriter->writeAttribute('w:abstractNumId', $style->getIndex()); $xmlWriter->startElement('w:nsid'); $xmlWriter->writeAttribute('w:val', $this->getRandomHexNumber()); @@ -56,91 +69,8 @@ class Numbering extends AbstractPart $xmlWriter->endElement(); // w:multiLevelType if (is_array($levels)) { - foreach ($levels as $levelNum => $levelObject) { - if ($levelObject instanceof NumberingLevel) { - $start = $levelObject->getStart(); - $format = $levelObject->getFormat(); - $restart = $levelObject->getRestart(); - $suffix = $levelObject->getSuffix(); - $text = $levelObject->getText(); - $align = $levelObject->getAlign(); - $tabPos = $levelObject->getTabPos(); - $left = $levelObject->getLeft(); - $hanging = $levelObject->getHanging(); - $font = $levelObject->getFont(); - $hint = $levelObject->getHint(); - - $xmlWriter->startElement('w:lvl'); - $xmlWriter->writeAttribute('w:ilvl', $levelNum); - - if (!is_null($start)) { - $xmlWriter->startElement('w:start'); - $xmlWriter->writeAttribute('w:val', $start); - $xmlWriter->endElement(); // w:start - } - if (!is_null($format)) { - $xmlWriter->startElement('w:numFmt'); - $xmlWriter->writeAttribute('w:val', $format); - $xmlWriter->endElement(); // w:numFmt - } - if (!is_null($restart)) { - $xmlWriter->startElement('w:lvlRestart'); - $xmlWriter->writeAttribute('w:val', $restart); - $xmlWriter->endElement(); // w:lvlRestart - } - if (!is_null($suffix)) { - $xmlWriter->startElement('w:suff'); - $xmlWriter->writeAttribute('w:val', $suffix); - $xmlWriter->endElement(); // w:suff - } - if (!is_null($text)) { - $xmlWriter->startElement('w:lvlText'); - $xmlWriter->writeAttribute('w:val', $text); - $xmlWriter->endElement(); // w:start - } - if (!is_null($align)) { - $xmlWriter->startElement('w:lvlJc'); - $xmlWriter->writeAttribute('w:val', $align); - $xmlWriter->endElement(); // w:lvlJc - } - if (!is_null($tabPos) || !is_null($left) || !is_null($hanging)) { - $xmlWriter->startElement('w:pPr'); - if (!is_null($tabPos)) { - $xmlWriter->startElement('w:tabs'); - $xmlWriter->startElement('w:tab'); - $xmlWriter->writeAttribute('w:val', 'num'); - $xmlWriter->writeAttribute('w:pos', $tabPos); - $xmlWriter->endElement(); // w:tab - $xmlWriter->endElement(); // w:tabs - } - if (!is_null($left) || !is_null($hanging)) { - $xmlWriter->startElement('w:ind'); - if (!is_null($left)) { - $xmlWriter->writeAttribute('w:left', $left); - } - if (!is_null($hanging)) { - $xmlWriter->writeAttribute('w:hanging', $hanging); - } - $xmlWriter->endElement(); // w:ind - } - $xmlWriter->endElement(); // w:pPr - } - if (!is_null($font) || !is_null($hint)) { - $xmlWriter->startElement('w:rPr'); - $xmlWriter->startElement('w:rFonts'); - if (!is_null($font)) { - $xmlWriter->writeAttribute('w:ascii', $font); - $xmlWriter->writeAttribute('w:hAnsi', $font); - $xmlWriter->writeAttribute('w:cs', $font); - } - if (!is_null($hint)) { - $xmlWriter->writeAttribute('w:hint', $hint); - } - $xmlWriter->endElement(); // w:rFonts - $xmlWriter->endElement(); // w:rPr - } - $xmlWriter->endElement(); // w:lvl - } + foreach ($levels as $level) { + $this->writeLevel($xmlWriter, $level); } } $xmlWriter->endElement(); // w:abstractNum @@ -151,9 +81,9 @@ class Numbering extends AbstractPart foreach ($styles as $style) { if ($style instanceof NumberingStyle) { $xmlWriter->startElement('w:num'); - $xmlWriter->writeAttribute('w:numId', $style->getNumId()); + $xmlWriter->writeAttribute('w:numId', $style->getIndex()); $xmlWriter->startElement('w:abstractNumId'); - $xmlWriter->writeAttribute('w:val', $style->getNumId()); + $xmlWriter->writeAttribute('w:val', $style->getIndex()); $xmlWriter->endElement(); // w:abstractNumId $xmlWriter->endElement(); // w:num } @@ -164,6 +94,90 @@ class Numbering extends AbstractPart return $xmlWriter->getData(); } + /** + * Write level + */ + private function writeLevel(XMLWriter $xmlWriter, NumberingLevel $level) + { + $xmlWriter->startElement('w:lvl'); + $xmlWriter->writeAttribute('w:ilvl', $level->getLevel()); + + // Numbering level properties + $properties = array( + 'start' => 'start', + 'format' => 'numFmt', + 'restart' => 'lvlRestart', + 'pStyle' => 'pStyle', + 'suffix' => 'suff', + 'text' => 'lvlText', + 'align' => 'lvlJc' + ); + foreach ($properties as $property => $nodeName) { + $getMethod = "get{$property}"; + if (!is_null($level->$getMethod())) { + $xmlWriter->startElement("w:{$nodeName}"); + $xmlWriter->writeAttribute('w:val', $level->$getMethod()); + $xmlWriter->endElement(); // w:start + } + } + + // Paragraph & font styles + $this->writeParagraph($xmlWriter, $level); + $this->writeFont($xmlWriter, $level); + + $xmlWriter->endElement(); // w:lvl + } + + /** + * Write level paragraph + * + * @since 0.11.0 + * @todo Use paragraph style writer + */ + private function writeParagraph(XMLWriter $xmlWriter, NumberingLevel $level) + { + $tabPos = $level->getTabPos(); + $left = $level->getLeft(); + $hanging = $level->getHanging(); + + $xmlWriter->startElement('w:pPr'); + + $xmlWriter->startElement('w:tabs'); + $xmlWriter->startElement('w:tab'); + $xmlWriter->writeAttribute('w:val', 'num'); + $xmlWriter->writeAttributeIf($tabPos !== null, 'w:pos', $tabPos); + $xmlWriter->endElement(); // w:tab + $xmlWriter->endElement(); // w:tabs + + $xmlWriter->startElement('w:ind'); + $xmlWriter->writeAttributeIf($left !== null, 'w:left', $left); + $xmlWriter->writeAttributeIf($hanging !== null, 'w:hanging', $hanging); + $xmlWriter->endElement(); // w:ind + + $xmlWriter->endElement(); // w:pPr + } + + /** + * Write level font + * + * @since 0.11.0 + * @todo Use font style writer + */ + private function writeFont(XMLWriter $xmlWriter, NumberingLevel $level) + { + $font = $level->getFont(); + $hint = $level->getHint(); + + $xmlWriter->startElement('w:rPr'); + $xmlWriter->startElement('w:rFonts'); + $xmlWriter->writeAttributeIf($font !== null, 'w:ascii', $font); + $xmlWriter->writeAttributeIf($font !== null, 'w:hAnsi', $font); + $xmlWriter->writeAttributeIf($font !== null, 'w:cs', $font); + $xmlWriter->writeAttributeIf($hint !== null, 'w:hint', $hint); + $xmlWriter->endElement(); // w:rFonts + $xmlWriter->endElement(); // w:rPr + } + /** * Get random hexadecimal number value * diff --git a/src/PhpWord/Writer/Word2007/Part/Rels.php b/src/PhpWord/Writer/Word2007/Part/Rels.php index 8771b0f6..562deb35 100644 --- a/src/PhpWord/Writer/Word2007/Part/Rels.php +++ b/src/PhpWord/Writer/Word2007/Part/Rels.php @@ -1,10 +1,18 @@ 'package/2006/relationships/metadata/core-properties', - 'docProps/app.xml' => 'officeDocument/2006/relationships/extended-properties', - 'word/document.xml' => 'officeDocument/2006/relationships/officeDocument', + 'docProps/core.xml' => 'package/2006/relationships/metadata/core-properties', + 'docProps/app.xml' => 'officeDocument/2006/relationships/extended-properties', + 'docProps/custom.xml' => 'officeDocument/2006/relationships/custom-properties', + 'word/document.xml' => 'officeDocument/2006/relationships/officeDocument', ); $xmlWriter = $this->getXmlWriter(); $this->writeRels($xmlWriter, $xmlRels); @@ -40,78 +46,55 @@ class Rels extends AbstractPart return $xmlWriter->getData(); } - /** - * Write word/_rels/document.xml.rels - * - * @param array $mediaRels - */ - public function writeDocRels($mediaRels) - { - $xmlRels = array( - 'styles.xml' => 'officeDocument/2006/relationships/styles', - 'numbering.xml' => 'officeDocument/2006/relationships/numbering', - 'settings.xml' => 'officeDocument/2006/relationships/settings', - 'theme/theme1.xml' => 'officeDocument/2006/relationships/theme', - 'webSettings.xml' => 'officeDocument/2006/relationships/webSettings', - 'fontTable.xml' => 'officeDocument/2006/relationships/fontTable', - ); - $xmlWriter = $this->getXmlWriter(); - $this->writeRels($xmlWriter, $xmlRels, $mediaRels); - - return $xmlWriter->getData(); - } - - /** - * Write word/_rels/(header|footer|footnotes)*.xml.rels - * - * @param array $mediaRels - */ - public function writeMediaRels($mediaRels) - { - $xmlWriter = $this->getXmlWriter(); - $this->writeRels($xmlWriter, null, $mediaRels); - - return $xmlWriter->getData(); - } - /** * Write relationships * * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter - * @param null|array $xmlRels - * @param null|array $mediaRels - * @param integer $relId + * @param array $xmlRels + * @param array $mediaRels + * @param int $relId */ - private function writeRels(XMLWriter $xmlWriter, $xmlRels = null, $mediaRels = null, $relId = 1) + protected function writeRels(XMLWriter $xmlWriter, $xmlRels = array(), $mediaRels = array(), $relId = 1) { $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); $xmlWriter->startElement('Relationships'); - $xmlWriter->writeAttribute('xmlns', self::RELS_BASE . 'package/2006/relationships'); + $xmlWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); // XML files relationships - if (is_array($xmlRels)) { - foreach ($xmlRels as $target => $type) { - $this->writeRel($xmlWriter, $relId++, $type, $target); - } + foreach ($xmlRels as $target => $type) { + $this->writeRel($xmlWriter, $relId++, $type, $target); } // Media relationships - if (!is_null($mediaRels) && is_array($mediaRels)) { - $mapping = array('image' => 'image', 'object' => 'oleObject', 'link' => 'hyperlink'); - $targetPaths = array('image' => 'media/', 'object' => 'embeddings/'); - foreach ($mediaRels as $mediaRel) { - $mediaType = $mediaRel['type']; - $type = array_key_exists($mediaType, $mapping) ? $mapping[$mediaType] : $mediaType; - $target = array_key_exists($mediaType, $targetPaths) ? $targetPaths[$mediaType] : ''; - $target .= $mediaRel['target']; - $targetMode = ($type == 'hyperlink') ? 'External' : ''; - $this->writeRel($xmlWriter, $relId++, "officeDocument/2006/relationships/{$type}", $target, $targetMode); - } + foreach ($mediaRels as $mediaRel) { + $this->writeMediaRel($xmlWriter, $relId++, $mediaRel); } $xmlWriter->endElement(); // Relationships } + /** + * Write media relationships + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param int $relId + * @param array $mediaRel + */ + private function writeMediaRel(XMLWriter $xmlWriter, $relId, $mediaRel) + { + $typePrefix = 'officeDocument/2006/relationships/'; + $typeMapping = array('image' => 'image', 'object' => 'oleObject', 'link' => 'hyperlink'); + $targetMapping = array('image' => 'media/', 'object' => 'embeddings/'); + + $mediaType = $mediaRel['type']; + $type = array_key_exists($mediaType, $typeMapping) ? $typeMapping[$mediaType] : $mediaType; + $targetPrefix = array_key_exists($mediaType, $targetMapping) ? $targetMapping[$mediaType] : ''; + $target = $mediaRel['target']; + $targetMode = ($type == 'hyperlink') ? 'External' : ''; + + $this->writeRel($xmlWriter, $relId, $typePrefix . $type, $targetPrefix . $target, $targetMode); + } + /** * Write individual rels entry * @@ -123,6 +106,7 @@ class Rels extends AbstractPart * @param string $type Relationship type * @param string $target Relationship target * @param string $targetMode Relationship target mode + * @throws \PhpOffice\PhpWord\Exception\Exception */ private function writeRel(XMLWriter $xmlWriter, $relId, $type, $target, $targetMode = '') { @@ -132,7 +116,7 @@ class Rels extends AbstractPart } $xmlWriter->startElement('Relationship'); $xmlWriter->writeAttribute('Id', $relId); - $xmlWriter->writeAttribute('Type', self::RELS_BASE . $type); + $xmlWriter->writeAttribute('Type', 'http://schemas.openxmlformats.org/' . $type); $xmlWriter->writeAttribute('Target', $target); if ($targetMode != '') { $xmlWriter->writeAttribute('TargetMode', $targetMode); diff --git a/src/PhpWord/Writer/Word2007/Part/RelsDocument.php b/src/PhpWord/Writer/Word2007/Part/RelsDocument.php new file mode 100644 index 00000000..744e14f9 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/RelsDocument.php @@ -0,0 +1,50 @@ + 'officeDocument/2006/relationships/styles', + 'numbering.xml' => 'officeDocument/2006/relationships/numbering', + 'settings.xml' => 'officeDocument/2006/relationships/settings', + 'theme/theme1.xml' => 'officeDocument/2006/relationships/theme', + 'webSettings.xml' => 'officeDocument/2006/relationships/webSettings', + 'fontTable.xml' => 'officeDocument/2006/relationships/fontTable', + ); + $xmlWriter = $this->getXmlWriter(); + + /** @var \PhpOffice\PhpWord\Writer\Word2007 $parentWriter Type hint */ + $parentWriter = $this->getParentWriter(); + $this->writeRels($xmlWriter, $xmlRels, $parentWriter->getRelationships()); + + return $xmlWriter->getData(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/RelsPart.php b/src/PhpWord/Writer/Word2007/Part/RelsPart.php new file mode 100644 index 00000000..627a2bcd --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/RelsPart.php @@ -0,0 +1,59 @@ +getXmlWriter(); + $this->writeRels($xmlWriter, array(), $this->media); + + return $xmlWriter->getData(); + } + + /** + * Set media + * + * @param array $media + * @return self + */ + public function setMedia($media) + { + $this->media = $media; + + return $this; + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/Settings.php b/src/PhpWord/Writer/Word2007/Part/Settings.php index 81a59679..784a5d1e 100644 --- a/src/PhpWord/Writer/Word2007/Part/Settings.php +++ b/src/PhpWord/Writer/Word2007/Part/Settings.php @@ -1,25 +1,35 @@ array('@attributes' => array('w:percent' => '100')), @@ -118,6 +128,8 @@ class Settings extends AbstractPart $xmlWriter->writeElement($settingKey); } else { $xmlWriter->startElement($settingKey); + + /** @var array $settingValue Type hint */ foreach ($settingValue as $childKey => $childValue) { if ($childKey == '@attributes') { foreach ($childValue as $key => $val) { diff --git a/src/PhpWord/Writer/Word2007/Part/Styles.php b/src/PhpWord/Writer/Word2007/Part/Styles.php index 579ae8e5..0d688e36 100644 --- a/src/PhpWord/Writer/Word2007/Part/Styles.php +++ b/src/PhpWord/Writer/Word2007/Part/Styles.php @@ -1,42 +1,47 @@ getXmlWriter(); $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); @@ -46,7 +51,7 @@ class Styles extends AbstractPart // Write default styles $styles = Style::getStyles(); - $this->writeDefaultStyles($xmlWriter, $phpWord, $styles); + $this->writeDefaultStyles($xmlWriter, $styles); // Write styles if (count($styles) > 0) { @@ -55,90 +60,11 @@ class Styles extends AbstractPart continue; } - // Font style - if ($style instanceof Font) { - $paragraphStyle = $style->getParagraphStyle(); - $styleType = $style->getStyleType(); - $type = ($styleType == 'title') ? 'paragraph' : 'character'; - if (!is_null($paragraphStyle)) { - $type = 'paragraph'; - } - - $xmlWriter->startElement('w:style'); - $xmlWriter->writeAttribute('w:type', $type); - if ($styleType == 'title') { - $arrStyle = explode('_', $styleName); - $styleId = 'Heading' . $arrStyle[1]; - $styleName = 'heading ' . $arrStyle[1]; - $styleLink = 'Heading' . $arrStyle[1] . 'Char'; - $xmlWriter->writeAttribute('w:styleId', $styleId); - - $xmlWriter->startElement('w:link'); - $xmlWriter->writeAttribute('w:val', $styleLink); - $xmlWriter->endElement(); - } - $xmlWriter->startElement('w:name'); - $xmlWriter->writeAttribute('w:val', $styleName); - $xmlWriter->endElement(); - if (!is_null($paragraphStyle)) { - // Point parent style to Normal - $xmlWriter->startElement('w:basedOn'); - $xmlWriter->writeAttribute('w:val', 'Normal'); - $xmlWriter->endElement(); - - $styleWriter = new ParagraphStyleWriter($xmlWriter, $paragraphStyle); - $styleWriter->write(); - } - - $styleWriter = new FontStyleWriter($xmlWriter, $style); - $styleWriter->write(); - $xmlWriter->endElement(); - - // Paragraph style - } elseif ($style instanceof Paragraph) { - $xmlWriter->startElement('w:style'); - $xmlWriter->writeAttribute('w:type', 'paragraph'); - $xmlWriter->writeAttribute('w:customStyle', '1'); - $xmlWriter->writeAttribute('w:styleId', $styleName); - $xmlWriter->startElement('w:name'); - $xmlWriter->writeAttribute('w:val', $styleName); - $xmlWriter->endElement(); - // Parent style - $basedOn = $style->getBasedOn(); - if (!is_null($basedOn)) { - $xmlWriter->startElement('w:basedOn'); - $xmlWriter->writeAttribute('w:val', $basedOn); - $xmlWriter->endElement(); - } - // Next paragraph style - $next = $style->getNext(); - if (!is_null($next)) { - $xmlWriter->startElement('w:next'); - $xmlWriter->writeAttribute('w:val', $next); - $xmlWriter->endElement(); - } - - $styleWriter = new ParagraphStyleWriter($xmlWriter, $style); - $styleWriter->write(); - $xmlWriter->endElement(); - - // Table style - } elseif ($style instanceof Table) { - $xmlWriter->startElement('w:style'); - $xmlWriter->writeAttribute('w:type', 'table'); - $xmlWriter->writeAttribute('w:customStyle', '1'); - $xmlWriter->writeAttribute('w:styleId', $styleName); - $xmlWriter->startElement('w:name'); - $xmlWriter->writeAttribute('w:val', $styleName); - $xmlWriter->endElement(); - $xmlWriter->startElement('w:uiPriority'); - $xmlWriter->writeAttribute('w:val', '99'); - $xmlWriter->endElement(); - - $styleWriter = new TableStyleWriter($xmlWriter, $style); - $styleWriter->write(); - - $xmlWriter->endElement(); // w:style + // Get style class and execute if the private method exists + $styleClass = substr(get_class($style), strrpos(get_class($style), '\\') + 1); + $method = "write{$styleClass}Style"; + if (method_exists($this, $method)) { + $this->$method($xmlWriter, $styleName, $style); } } } @@ -152,12 +78,12 @@ class Styles extends AbstractPart * Write default font and other default styles * * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter - * @param array $styles + * @param \PhpOffice\PhpWord\Style\AbstractStyle[] $styles */ - private function writeDefaultStyles(XMLWriter $xmlWriter, PhpWord $phpWord, $styles) + private function writeDefaultStyles(XMLWriter $xmlWriter, $styles) { - $fontName = $phpWord->getDefaultFontName(); - $fontSize = $phpWord->getDefaultFontSize(); + $fontName = PhpWordSettings::getDefaultFontName(); + $fontSize = PhpWordSettings::getDefaultFontSize(); // Default font $xmlWriter->startElement('w:docDefaults'); @@ -211,4 +137,115 @@ class Styles extends AbstractPart $xmlWriter->endElement(); // w:style } } + + /** + * Write font style + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param string $styleName + * @param \PhpOffice\PhpWord\Style\Font $style + */ + private function writeFontStyle(XMLWriter $xmlWriter, $styleName, FontStyle $style) + { + $paragraphStyle = $style->getParagraph(); + $styleType = $style->getStyleType(); + $type = ($styleType == 'title') ? 'paragraph' : 'character'; + if (!is_null($paragraphStyle)) { + $type = 'paragraph'; + } + + $xmlWriter->startElement('w:style'); + $xmlWriter->writeAttribute('w:type', $type); + + // Heading style + if ($styleType == 'title') { + $arrStyle = explode('_', $styleName); + $styleId = 'Heading' . $arrStyle[1]; + $styleName = 'heading ' . $arrStyle[1]; + $styleLink = 'Heading' . $arrStyle[1] . 'Char'; + $xmlWriter->writeAttribute('w:styleId', $styleId); + + $xmlWriter->startElement('w:link'); + $xmlWriter->writeAttribute('w:val', $styleLink); + $xmlWriter->endElement(); + } + + // Style name + $xmlWriter->startElement('w:name'); + $xmlWriter->writeAttribute('w:val', $styleName); + $xmlWriter->endElement(); + + // Parent style + $xmlWriter->writeElementIf(!is_null($paragraphStyle), 'w:basedOn', 'w:val', 'Normal'); + + // w:pPr + if (!is_null($paragraphStyle)) { + $styleWriter = new ParagraphStyleWriter($xmlWriter, $paragraphStyle); + $styleWriter->write(); + } + + // w:rPr + $styleWriter = new FontStyleWriter($xmlWriter, $style); + $styleWriter->write(); + + $xmlWriter->endElement(); + } + + /** + * Write paragraph style + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param string $styleName + * @param \PhpOffice\PhpWord\Style\Paragraph $style + */ + private function writeParagraphStyle(XMLWriter $xmlWriter, $styleName, ParagraphStyle $style) + { + $xmlWriter->startElement('w:style'); + $xmlWriter->writeAttribute('w:type', 'paragraph'); + $xmlWriter->writeAttribute('w:customStyle', '1'); + $xmlWriter->writeAttribute('w:styleId', $styleName); + $xmlWriter->startElement('w:name'); + $xmlWriter->writeAttribute('w:val', $styleName); + $xmlWriter->endElement(); + + // Parent style + $basedOn = $style->getBasedOn(); + $xmlWriter->writeElementIf(!is_null($basedOn), 'w:basedOn', 'w:val', $basedOn); + + // Next paragraph style + $next = $style->getNext(); + $xmlWriter->writeElementIf(!is_null($next), 'w:next', 'w:val', $next); + + // w:pPr + $styleWriter = new ParagraphStyleWriter($xmlWriter, $style); + $styleWriter->write(); + + $xmlWriter->endElement(); + } + + /** + * Write table style + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param string $styleName + * @param \PhpOffice\PhpWord\Style\Table $style + */ + private function writeTableStyle(XMLWriter $xmlWriter, $styleName, TableStyle $style) + { + $xmlWriter->startElement('w:style'); + $xmlWriter->writeAttribute('w:type', 'table'); + $xmlWriter->writeAttribute('w:customStyle', '1'); + $xmlWriter->writeAttribute('w:styleId', $styleName); + $xmlWriter->startElement('w:name'); + $xmlWriter->writeAttribute('w:val', $styleName); + $xmlWriter->endElement(); + $xmlWriter->startElement('w:uiPriority'); + $xmlWriter->writeAttribute('w:val', '99'); + $xmlWriter->endElement(); + + $styleWriter = new TableStyleWriter($xmlWriter, $style); + $styleWriter->write(); + + $xmlWriter->endElement(); // w:style + } } diff --git a/src/PhpWord/Writer/Word2007/Part/Theme.php b/src/PhpWord/Writer/Word2007/Part/Theme.php index 2e0b4c99..62911c54 100644 --- a/src/PhpWord/Writer/Word2007/Part/Theme.php +++ b/src/PhpWord/Writer/Word2007/Part/Theme.php @@ -1,27 +1,423 @@ -'; + $str = ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= $this->writeColorScheme(); + $str .= $this->writeFontScheme(); + $str .= $this->writeFormatScheme(); + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + return $str; + } + + + /** + * Write color scheme + * + * @return string + */ + private function writeColorScheme() + { + $str = ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + return $str; + } + + /** + * Write font scheme + * + * @return string + */ + private function writeFontScheme() + { + $str = ''; + + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + + return $str; + } + + /** + * Write format scheme + * + * @return string + */ + private function writeFormatScheme() + { + $str = ''; + + $str .= ''; + $str .= $this->writeFormatFill(); + $str .= $this->writeFormatLine(); + $str .= $this->writeFormatEffect(); + $str .= $this->writeFormatBackground(); + $str .= ''; + + return $str; + } + + /** + * Write fill format scheme + * + * @return string + */ + private function writeFormatFill() + { + $str = ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + return $str; + } + + /** + * Write line format scheme + * + * @return string + */ + private function writeFormatLine() + { + $str = ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + return $str; + } + + /** + * Write effect format scheme + * + * @return string + */ + private function writeFormatEffect() + { + $str = ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + return $str; + } + + /** + * Write background format scheme + * + * @return string + */ + private function writeFormatBackground() + { + $str = ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + return $str; } } diff --git a/src/PhpWord/Writer/Word2007/Part/WebSettings.php b/src/PhpWord/Writer/Word2007/Part/WebSettings.php index b1b5cc15..f800ebde 100644 --- a/src/PhpWord/Writer/Word2007/Part/WebSettings.php +++ b/src/PhpWord/Writer/Word2007/Part/WebSettings.php @@ -1,23 +1,33 @@ '', diff --git a/src/PhpWord/Writer/Word2007/Style/AbstractStyle.php b/src/PhpWord/Writer/Word2007/Style/AbstractStyle.php index 9b2d7ffd..61c8bae8 100644 --- a/src/PhpWord/Writer/Word2007/Style/AbstractStyle.php +++ b/src/PhpWord/Writer/Word2007/Style/AbstractStyle.php @@ -1,10 +1,18 @@ style = $style; } + /** + * Get XML Writer + * + * @return \PhpOffice\PhpWord\Shared\XMLWriter + */ + protected function getXmlWriter() + { + return $this->xmlWriter; + } + + /** + * Get Style + * + * @return \PhpOffice\PhpWord\Style\AbstractStyle + */ + protected function getStyle() + { + return $this->style; + } + /** * Convert twip value * * @param int|float $value - * @param int|float $default + * @param int $default (int|float) * @return int|float */ protected function convertTwip($value, $default = 0) { + $factors = array( + Settings::UNIT_CM => 567, + Settings::UNIT_MM => 56.7, + Settings::UNIT_INCH => 1440, + Settings::UNIT_POINT => 20, + Settings::UNIT_PICA => 240, + ); $unit = Settings::getMeasurementUnit(); - if ($unit == Settings::UNIT_TWIP || $value == $default) { - return $value; - } else { - return $value * $unit; + $factor = 1; + if (in_array($unit, $factors) && $value != $default) { + $factor = $factors[$unit]; } + + return $value * $factor; } } diff --git a/src/PhpWord/Writer/Word2007/Style/Alignment.php b/src/PhpWord/Writer/Word2007/Style/Alignment.php new file mode 100644 index 00000000..cefadb57 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Alignment.php @@ -0,0 +1,44 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Alignment) { + return; + } + $value = $style->getValue(); + if ($value !== null) { + $xmlWriter = $this->getXmlWriter(); + $xmlWriter->startElement('w:jc'); + $xmlWriter->writeAttribute('w:val', $value); + $xmlWriter->endElement(); // w:jc + } + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Cell.php b/src/PhpWord/Writer/Word2007/Style/Cell.php index d33eed56..a4b1ae90 100644 --- a/src/PhpWord/Writer/Word2007/Style/Cell.php +++ b/src/PhpWord/Writer/Word2007/Style/Cell.php @@ -1,16 +1,23 @@ style instanceof \PhpOffice\PhpWord\Style\Cell)) { + $style = $this->getStyle(); + if (!$style instanceof CellStyle) { return; } + $xmlWriter = $this->getXmlWriter(); - $brdSz = $this->style->getBorderSize(); - $brdCol = $this->style->getBorderColor(); - $hasBorders = false; - for ($i = 0; $i < 4; $i++) { - if (!is_null($brdSz[$i])) { - $hasBorders = true; - break; - } - } + $xmlWriter->startElement('w:tcPr'); - // Border - if ($hasBorders) { - $mbWriter = new MarginBorder($this->xmlWriter); - $mbWriter->setSizes($brdSz); - $mbWriter->setColors($brdCol); - $mbWriter->setAttributes(array('defaultColor' => CellStyle::DEFAULT_BORDER_COLOR)); - - $this->xmlWriter->startElement('w:tcBorders'); - $mbWriter->write(); - $this->xmlWriter->endElement(); - } + // Width + $xmlWriter->startElement('w:tcW'); + $xmlWriter->writeAttribute('w:w', $this->width); + $xmlWriter->writeAttribute('w:type', 'dxa'); + $xmlWriter->endElement(); // w:tcW // Text direction - if (!is_null($this->style->getTextDirection())) { - $this->xmlWriter->startElement('w:textDirection'); - $this->xmlWriter->writeAttribute('w:val', $this->style->getTextDirection()); - $this->xmlWriter->endElement(); + $textDir = $style->getTextDirection(); + $xmlWriter->writeElementIf(!is_null($textDir), 'w:textDirection', 'w:val', $textDir); + + // Vertical alignment + $vAlign = $style->getVAlign(); + $xmlWriter->writeElementIf(!is_null($vAlign), 'w:vAlign', 'w:val', $vAlign); + + // Border + if ($style->hasBorder()) { + $xmlWriter->startElement('w:tcBorders'); + + $styleWriter = new MarginBorder($xmlWriter); + $styleWriter->setSizes($style->getBorderSize()); + $styleWriter->setColors($style->getBorderColor()); + $styleWriter->setAttributes(array('defaultColor' => CellStyle::DEFAULT_BORDER_COLOR)); + $styleWriter->write(); + + $xmlWriter->endElement(); } // Shading - if (!is_null($this->style->getShading())) { - $styleWriter = new Shading($this->xmlWriter, $this->style->getShading()); + $shading = $style->getShading(); + if (!is_null($shading)) { + $styleWriter = new Shading($xmlWriter, $shading); $styleWriter->write(); } - // Alignment - if (!is_null($this->style->getVAlign())) { - $this->xmlWriter->startElement('w:vAlign'); - $this->xmlWriter->writeAttribute('w:val', $this->style->getVAlign()); - $this->xmlWriter->endElement(); - } + // Colspan & rowspan + $gridSpan = $style->getGridSpan(); + $vMerge = $style->getVMerge(); + $xmlWriter->writeElementIf(!is_null($gridSpan), 'w:gridSpan', 'w:val', $gridSpan); + $xmlWriter->writeElementIf(!is_null($vMerge), 'w:vMerge', 'w:val', $vMerge); - // Colspan - if (!is_null($this->style->getGridSpan())) { - $this->xmlWriter->startElement('w:gridSpan'); - $this->xmlWriter->writeAttribute('w:val', $this->style->getGridSpan()); - $this->xmlWriter->endElement(); - } + $xmlWriter->endElement(); // w:tcPr + } - // Row span - if (!is_null($this->style->getVMerge())) { - $this->xmlWriter->startElement('w:vMerge'); - $this->xmlWriter->writeAttribute('w:val', $this->style->getVMerge()); - $this->xmlWriter->endElement(); - } + /** + * Set width + * + * @param int $value + */ + public function setWidth($value = null) + { + $this->width = $value; } } diff --git a/src/PhpWord/Writer/Word2007/Style/Font.php b/src/PhpWord/Writer/Word2007/Style/Font.php index 6ffc6a87..0ef22f08 100644 --- a/src/PhpWord/Writer/Word2007/Style/Font.php +++ b/src/PhpWord/Writer/Word2007/Style/Font.php @@ -1,16 +1,22 @@ getXmlWriter(); + $isStyleName = $this->isInline && !is_null($this->style) && is_string($this->style); if ($isStyleName) { - $this->xmlWriter->startElement('w:rPr'); - $this->xmlWriter->startElement('w:rStyle'); - $this->xmlWriter->writeAttribute('w:val', $this->style); - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); + $xmlWriter->startElement('w:rPr'); + $xmlWriter->startElement('w:rStyle'); + $xmlWriter->writeAttribute('w:val', $this->style); + $xmlWriter->endElement(); + $xmlWriter->endElement(); } else { $this->writeStyle(); } @@ -47,106 +55,73 @@ class Font extends AbstractStyle */ private function writeStyle() { - if (!($this->style instanceof \PhpOffice\PhpWord\Style\Font)) { + $style = $this->getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Font) { return; } + $xmlWriter = $this->getXmlWriter(); - $font = $this->style->getName(); - $color = $this->style->getColor(); - $size = $this->style->getSize(); + $xmlWriter->startElement('w:rPr'); - $this->xmlWriter->startElement('w:rPr'); + // Style name + $styleName = $style->getStyleName(); + $xmlWriter->writeElementIf(!is_null($styleName), 'w:rStyle', 'w:val', $styleName); // Font name/family - if ($font != PhpWord::DEFAULT_FONT_NAME) { - $this->xmlWriter->startElement('w:rFonts'); - $this->xmlWriter->writeAttribute('w:ascii', $font); - $this->xmlWriter->writeAttribute('w:hAnsi', $font); - $this->xmlWriter->writeAttribute('w:eastAsia', $font); - $this->xmlWriter->writeAttribute('w:cs', $font); - //Font Content Type - if ($this->style->getHint() != PhpWord::DEFAULT_FONT_CONTENT_TYPE) { - $this->xmlWriter->writeAttribute('w:hint', $this->style->getHint()); - } - $this->xmlWriter->endElement(); + $font = $style->getName(); + $hint = $style->getHint(); + if ($font !== null) { + $xmlWriter->startElement('w:rFonts'); + $xmlWriter->writeAttribute('w:ascii', $font); + $xmlWriter->writeAttribute('w:hAnsi', $font); + $xmlWriter->writeAttribute('w:eastAsia', $font); + $xmlWriter->writeAttribute('w:cs', $font); + $xmlWriter->writeAttributeIf($hint !== null, 'w:hint', $hint); + $xmlWriter->endElement(); } // Color - if ($color != PhpWord::DEFAULT_FONT_COLOR) { - $this->xmlWriter->startElement('w:color'); - $this->xmlWriter->writeAttribute('w:val', $color); - $this->xmlWriter->endElement(); - } + $color = $style->getColor(); + $xmlWriter->writeElementIf($color !== null, 'w:color', 'w:val', $color); // Size - if ($size != PhpWord::DEFAULT_FONT_SIZE) { - $this->xmlWriter->startElement('w:sz'); - $this->xmlWriter->writeAttribute('w:val', $size * 2); - $this->xmlWriter->endElement(); - $this->xmlWriter->startElement('w:szCs'); - $this->xmlWriter->writeAttribute('w:val', $size * 2); - $this->xmlWriter->endElement(); - } + $size = $style->getSize(); + $xmlWriter->writeElementIf($size !== null, 'w:sz', 'w:val', $size * 2); + $xmlWriter->writeElementIf($size !== null, 'w:szCs', 'w:val', $size * 2); - // Bold - if ($this->style->getBold()) { - $this->xmlWriter->writeElement('w:b', null); - } + // Bold, italic + $xmlWriter->writeElementIf($style->isBold(), 'w:b'); + $xmlWriter->writeElementIf($style->isItalic(), 'w:i'); + $xmlWriter->writeElementIf($style->isItalic(), 'w:iCs'); - // Italic - if ($this->style->getItalic()) { - $this->xmlWriter->writeElement('w:i', null); - $this->xmlWriter->writeElement('w:iCs', null); - } + // Strikethrough, double strikethrough + $xmlWriter->writeElementIf($style->isStrikethrough(), 'w:strike'); + $xmlWriter->writeElementIf($style->isDoubleStrikethrough(), 'w:dstrike'); + + // Small caps, all caps + $xmlWriter->writeElementIf($style->isSmallCaps(), 'w:smallCaps'); + $xmlWriter->writeElementIf($style->isAllCaps(), 'w:caps'); // Underline - if ($this->style->getUnderline() != 'none') { - $this->xmlWriter->startElement('w:u'); - $this->xmlWriter->writeAttribute('w:val', $this->style->getUnderline()); - $this->xmlWriter->endElement(); - } - - // Strikethrough - if ($this->style->getStrikethrough()) { - $this->xmlWriter->writeElement('w:strike', null); - } - - // Double strikethrough - if ($this->style->getDoubleStrikethrough()) { - $this->xmlWriter->writeElement('w:dstrike', null); - } + $underline = $style->getUnderline(); + $xmlWriter->writeElementIf($underline != 'none', 'w:u', 'w:val', $underline); // Foreground-Color - if (!is_null($this->style->getFgColor())) { - $this->xmlWriter->startElement('w:highlight'); - $this->xmlWriter->writeAttribute('w:val', $this->style->getFgColor()); - $this->xmlWriter->endElement(); - } + $fgColor = $style->getFgColor(); + $xmlWriter->writeElementIf(!is_null($fgColor), 'w:highlight', 'w:val', $fgColor); + + // Superscript/subscript + $xmlWriter->writeElementIf($style->isSuperScript(), 'w:vertAlign', 'w:val', 'superscript'); + $xmlWriter->writeElementIf($style->isSubScript(), 'w:vertAlign', 'w:val', 'subscript'); // Background-Color - if (!is_null($this->style->getShading())) { - $styleWriter = new Shading($this->xmlWriter, $this->style->getShading()); + $shading = $style->getShading(); + if (!is_null($shading)) { + $styleWriter = new Shading($xmlWriter, $shading); $styleWriter->write(); } - // Superscript/subscript - if ($this->style->getSuperScript() || $this->style->getSubScript()) { - $this->xmlWriter->startElement('w:vertAlign'); - $this->xmlWriter->writeAttribute('w:val', $this->style->getSuperScript() ? 'superscript' : 'subscript'); - $this->xmlWriter->endElement(); - } - - // Small caps - if ($this->style->getSmallCaps()) { - $this->xmlWriter->writeElement('w:smallCaps', null); - } - - // All caps - if ($this->style->getAllCaps()) { - $this->xmlWriter->writeElement('w:caps', null); - } - - $this->xmlWriter->endElement(); + $xmlWriter->endElement(); } /** diff --git a/src/PhpWord/Writer/Word2007/Style/Image.php b/src/PhpWord/Writer/Word2007/Style/Image.php new file mode 100644 index 00000000..280b569a --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Image.php @@ -0,0 +1,173 @@ +getStyle(); + if (!$style instanceof ImageStyle) { + return; + } + $this->writeStyle($style); + } + + /** + * Write style attribute + * + * @param \PhpOffice\PhpWord\Style\Image $style + */ + protected function writeStyle($style) + { + $xmlWriter = $this->getXmlWriter(); + + $styles = $this->getElementStyle($style); + $imageStyle = $this->assembleStyle($styles); + + $xmlWriter->writeAttribute('style', $imageStyle); + } + + /** + * Write alignment + */ + public function writeAlignment() + { + $style = $this->getStyle(); + if (!$style instanceof ImageStyle) { + return; + } + + $xmlWriter = $this->getXmlWriter(); + $xmlWriter->startElement('w:pPr'); + $styleWriter = new Alignment($xmlWriter, new AlignmentStyle(array('value' => $style->getAlign()))); + $styleWriter->write(); + $xmlWriter->endElement(); // w:pPr + } + + /** + * Write w10 wrapping + */ + public function writeW10Wrap() + { + if (is_null($this->w10wrap)) { + return; + } + + $xmlWriter = $this->getXmlWriter(); + $xmlWriter->startElement('w10:wrap'); + $xmlWriter->writeAttribute('type', $this->w10wrap); + $xmlWriter->endElement(); // w10:wrap + } + + /** + * Get element style + * + * @param \PhpOffice\PhpWord\Style\Image $style + * @return array + */ + protected function getElementStyle(ImageStyle $style) + { + $styles = array( + 'mso-width-percent' => '0', + 'mso-height-percent' => '0', + 'mso-width-relative' => 'margin', + 'mso-height-relative' => 'margin', + ); + + // Dimension + $dimensions = array( + 'width' => $style->getWidth(), + 'height' => $style->getHeight(), + 'margin-top' => $style->getMarginTop(), + 'margin-left' => $style->getMarginLeft() + ); + foreach ($dimensions as $key => $value) { + if ($value !== null) { + $styles[$key] = $value . 'px'; + } + } + + // Absolute/relative positioning + $positioning = $style->getPositioning(); + $styles['position'] = $positioning; + if ($positioning !== null) { + $styles['mso-position-horizontal'] = $style->getPosHorizontal(); + $styles['mso-position-vertical'] = $style->getPosVertical(); + $styles['mso-position-horizontal-relative'] = $style->getPosHorizontalRel(); + $styles['mso-position-vertical-relative'] = $style->getPosVerticalRel(); + } + + // Wrapping style + $wrapping = $style->getWrappingStyle(); + if ($wrapping == ImageStyle::WRAPPING_STYLE_INLINE) { + // Nothing to do when inline + } elseif ($wrapping == ImageStyle::WRAPPING_STYLE_BEHIND) { + $styles['z-index'] = -251658752; + } else { + $styles['z-index'] = 251659264; + $styles['mso-position-horizontal'] = 'absolute'; + $styles['mso-position-vertical'] = 'absolute'; + } + + // w10 wrapping + if ($wrapping == ImageStyle::WRAPPING_STYLE_SQUARE) { + $this->w10wrap = 'square'; + } elseif ($wrapping == ImageStyle::WRAPPING_STYLE_TIGHT) { + $this->w10wrap = 'tight'; + } + + return $styles; + } + + /** + * Assemble style array into style string + * + * @param array $styles + * @return string + */ + protected function assembleStyle($styles = array()) + { + $style = ''; + foreach ($styles as $key => $value) { + if (!is_null($value) && $value != '') { + $style .= "{$key}:{$value}; "; + } + } + + return trim($style); + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Indentation.php b/src/PhpWord/Writer/Word2007/Style/Indentation.php index c31cdebf..f9bb696f 100644 --- a/src/PhpWord/Writer/Word2007/Style/Indentation.php +++ b/src/PhpWord/Writer/Word2007/Style/Indentation.php @@ -1,10 +1,18 @@ style instanceof \PhpOffice\PhpWord\Style\Indentation)) { + $style = $this->getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Indentation) { return; } + $xmlWriter = $this->getXmlWriter(); - $this->xmlWriter->startElement('w:ind'); - $this->xmlWriter->writeAttribute('w:left', $this->convertTwip($this->style->getLeft())); - $this->xmlWriter->writeAttribute('w:right', $this->convertTwip($this->style->getRight())); - if (!is_null($this->style->getFirstLine())) { - $this->xmlWriter->writeAttribute('w:firstLine', $this->convertTwip($this->style->getFirstLine())); - } - if (!is_null($this->style->getHanging())) { - $this->xmlWriter->writeAttribute('w:hanging', $this->convertTwip($this->style->getHanging())); - } - $this->xmlWriter->endElement(); + $xmlWriter->startElement('w:ind'); + + $xmlWriter->writeAttribute('w:left', $this->convertTwip($style->getLeft())); + $xmlWriter->writeAttribute('w:right', $this->convertTwip($style->getRight())); + + $firstLine = $style->getFirstLine(); + $xmlWriter->writeAttributeIf(!is_null($firstLine), 'w:firstLine', $this->convertTwip($firstLine)); + + $hanging = $style->getHanging(); + $xmlWriter->writeAttributeIf(!is_null($hanging), 'w:hanging', $this->convertTwip($hanging)); + + $xmlWriter->endElement(); } } diff --git a/src/PhpWord/Writer/Word2007/Style/Line.php b/src/PhpWord/Writer/Word2007/Style/Line.php new file mode 100644 index 00000000..dfecb4b0 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Line.php @@ -0,0 +1,110 @@ +getStyle(); + if (!$style instanceof LineStyle) { + return; + } + $this->writeStyle($style); + } + + /** + * Write style attribute + * + * @param \PhpOffice\PhpWord\Style\Line $style + */ + protected function writeStyle($style) + { + $xmlWriter = $this->getXmlWriter(); + + $styles = $this->getElementStyle($style); + if ($style->isFlip()) { + $styles['flip'] = 'y'; + } + $imageStyle = $this->assembleStyle($styles); + $xmlWriter->writeAttribute('style', $imageStyle); + + // Connector type + $xmlWriter->writeAttribute('o:connectortype', $style->getConnectorType()); + + // Weight + $weight = $style->getWeight(); + $xmlWriter->writeAttributeIf($weight !== null, 'strokeweight', $weight . 'pt'); + + // Color + $color = $style->getColor(); + $xmlWriter->writeAttributeIf($color !== null, 'strokecolor', $color); + } + + /** + * Write Line stroke + */ + public function writeStroke() + { + $xmlWriter = $this->getXmlWriter(); + $style = $this->getStyle(); + if (!$style instanceof LineStyle) { + return; + } + + $dash = $style->getDash(); + $beginArrow = $style->getBeginArrow(); + $endArrow = $style->getEndArrow(); + $dashStyles = array( + LineStyle::DASH_STYLE_DASH => 'dash', + LineStyle::DASH_STYLE_ROUND_DOT => '1 1', + LineStyle::DASH_STYLE_SQUARE_DOT => '1 1', + LineStyle::DASH_STYLE_DASH_DOT => 'dashDot', + LineStyle::DASH_STYLE_LONG_DASH => 'longDash', + LineStyle::DASH_STYLE_LONG_DASH_DOT => 'longDashDot', + LineStyle::DASH_STYLE_LONG_DASH_DOT_DOT => 'longDashDotDot', + ); + + if (($dash !== null) || ($beginArrow !== null) || ($endArrow !== null)) { + $xmlWriter->startElement('v:stroke'); + + $xmlWriter->writeAttributeIf($beginArrow !== null, 'startarrow', $beginArrow); + $xmlWriter->writeAttributeIf($endArrow !== null, 'endarrow', $endArrow); + + if ($dash !== null) { + if (array_key_exists($dash, $dashStyles)) { + $xmlWriter->writeAttribute('dashstyle', $dashStyles[$dash]); + } + if ($dash == LineStyle::DASH_STYLE_ROUND_DOT) { + $xmlWriter->writeAttribute('endcap', 'round'); + } + } + + $xmlWriter->endElement(); //v:stroke + } + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/LineNumbering.php b/src/PhpWord/Writer/Word2007/Style/LineNumbering.php index 6167e329..b3c103b6 100644 --- a/src/PhpWord/Writer/Word2007/Style/LineNumbering.php +++ b/src/PhpWord/Writer/Word2007/Style/LineNumbering.php @@ -1,10 +1,18 @@ style instanceof \PhpOffice\PhpWord\Style\LineNumbering)) { + $style = $this->getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\LineNumbering) { return; } + $xmlWriter = $this->getXmlWriter(); - $this->xmlWriter->startElement('w:lnNumType'); - $this->xmlWriter->writeAttribute('w:start', $this->style->getStart() - 1); - $this->xmlWriter->writeAttribute('w:countBy', $this->style->getIncrement()); - $this->xmlWriter->writeAttribute('w:distance', $this->style->getDistance()); - $this->xmlWriter->writeAttribute('w:restart', $this->style->getRestart()); - $this->xmlWriter->endElement(); + $xmlWriter->startElement('w:lnNumType'); + $xmlWriter->writeAttribute('w:start', $style->getStart() - 1); + $xmlWriter->writeAttribute('w:countBy', $style->getIncrement()); + $xmlWriter->writeAttribute('w:distance', $style->getDistance()); + $xmlWriter->writeAttribute('w:restart', $style->getRestart()); + $xmlWriter->endElement(); } } diff --git a/src/PhpWord/Writer/Word2007/Style/MarginBorder.php b/src/PhpWord/Writer/Word2007/Style/MarginBorder.php index ef6992db..88bb0109 100644 --- a/src/PhpWord/Writer/Word2007/Style/MarginBorder.php +++ b/src/PhpWord/Writer/Word2007/Style/MarginBorder.php @@ -1,14 +1,24 @@ getXmlWriter(); + $sides = array('top', 'left', 'right', 'bottom', 'insideH', 'insideV'); $sizeCount = count($this->sizes) - 1; for ($i = 0; $i < $sizeCount; $i++) { - if (!is_null($this->sizes[$i])) { - $this->xmlWriter->startElement('w:' . $sides[$i]); - if (!empty($this->colors)) { - if (is_null($this->colors[$i]) && !empty($this->attributes)) { - if (array_key_exists('defaultColor', $this->attributes)) { - $this->colors[$i] = $this->attributes['defaultColor']; - } - } - $this->xmlWriter->writeAttribute('w:val', 'single'); - $this->xmlWriter->writeAttribute('w:sz', $this->sizes[$i]); - $this->xmlWriter->writeAttribute('w:color', $this->colors[$i]); - if (!empty($this->attributes)) { - if (array_key_exists('space', $this->attributes)) { - $this->xmlWriter->writeAttribute('w:space', $this->attributes['space']); - } - } - } else { - $this->xmlWriter->writeAttribute('w:w', $this->sizes[$i]); - $this->xmlWriter->writeAttribute('w:type', 'dxa'); + if ($this->sizes[$i] !== null) { + $color = null; + if (isset($this->colors[$i])) { + $color = $this->colors[$i]; } - $this->xmlWriter->endElement(); + $this->writeSide($xmlWriter, $sides[$i], $this->sizes[$i], $color); } } } + /** + * Write side + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param string $side + * @param int $width + * @param string $color + */ + private function writeSide(XMLWriter $xmlWriter, $side, $width, $color = null) + { + $xmlWriter->startElement('w:' . $side); + if (!empty($this->colors)) { + if ($color === null && !empty($this->attributes)) { + if (array_key_exists('defaultColor', $this->attributes)) { + $color = $this->attributes['defaultColor']; + } + } + $xmlWriter->writeAttribute('w:val', 'single'); + $xmlWriter->writeAttribute('w:sz', $width); + $xmlWriter->writeAttribute('w:color', $color); + if (!empty($this->attributes)) { + if (array_key_exists('space', $this->attributes)) { + $xmlWriter->writeAttribute('w:space', $this->attributes['space']); + } + } + } else { + $xmlWriter->writeAttribute('w:w', $width); + $xmlWriter->writeAttribute('w:type', 'dxa'); + } + $xmlWriter->endElement(); + } + /** * Set sizes * - * @param int[] $value + * @param integer[] $value */ public function setSizes($value) { diff --git a/src/PhpWord/Writer/Word2007/Style/Paragraph.php b/src/PhpWord/Writer/Word2007/Style/Paragraph.php index b92e1714..f3287700 100644 --- a/src/PhpWord/Writer/Word2007/Style/Paragraph.php +++ b/src/PhpWord/Writer/Word2007/Style/Paragraph.php @@ -1,17 +1,26 @@ getXmlWriter(); + $isStyleName = $this->isInline && !is_null($this->style) && is_string($this->style); if ($isStyleName) { if (!$this->withoutPPR) { - $this->xmlWriter->startElement('w:pPr'); + $xmlWriter->startElement('w:pPr'); } - $this->xmlWriter->startElement('w:pStyle'); - $this->xmlWriter->writeAttribute('w:val', $this->style); - $this->xmlWriter->endElement(); + $xmlWriter->startElement('w:pStyle'); + $xmlWriter->writeAttribute('w:val', $this->style); + $xmlWriter->endElement(); if (!$this->withoutPPR) { - $this->xmlWriter->endElement(); + $xmlWriter->endElement(); } } else { $this->writeStyle(); @@ -60,73 +71,107 @@ class Paragraph extends AbstractStyle */ private function writeStyle() { - if (!($this->style instanceof \PhpOffice\PhpWord\Style\Paragraph)) { + $style = $this->getStyle(); + if (!$style instanceof ParagraphStyle) { return; } - - $widowControl = $this->style->getWidowControl(); - $keepNext = $this->style->getKeepNext(); - $keepLines = $this->style->getKeepLines(); - $pageBreakBefore = $this->style->getPageBreakBefore(); + $xmlWriter = $this->getXmlWriter(); + $styles = $style->getStyleValues(); if (!$this->withoutPPR) { - $this->xmlWriter->startElement('w:pPr'); + $xmlWriter->startElement('w:pPr'); } + // Style name + $xmlWriter->writeElementIf($styles['name'] !== null, 'w:pStyle', 'w:val', $styles['name']); + // Alignment - if (!is_null($this->style->getAlign())) { - $this->xmlWriter->startElement('w:jc'); - $this->xmlWriter->writeAttribute('w:val', $this->style->getAlign()); - $this->xmlWriter->endElement(); - } - - // Indentation - if (!is_null($this->style->getIndentation())) { - $styleWriter = new Indentation($this->xmlWriter, $this->style->getIndentation()); - $styleWriter->write(); - } - - // Spacing - if (!is_null($this->style->getSpace())) { - $styleWriter = new Spacing($this->xmlWriter, $this->style->getSpace()); - $styleWriter->write(); - } + $styleWriter = new Alignment($xmlWriter, new AlignmentStyle(array('value' => $styles['alignment']))); + $styleWriter->write(); // Pagination - if (!$widowControl) { - $this->xmlWriter->startElement('w:widowControl'); - $this->xmlWriter->writeAttribute('w:val', '0'); - $this->xmlWriter->endElement(); - } - if ($keepNext) { - $this->xmlWriter->startElement('w:keepNext'); - $this->xmlWriter->writeAttribute('w:val', '1'); - $this->xmlWriter->endElement(); - } - if ($keepLines) { - $this->xmlWriter->startElement('w:keepLines'); - $this->xmlWriter->writeAttribute('w:val', '1'); - $this->xmlWriter->endElement(); - } - if ($pageBreakBefore) { - $this->xmlWriter->startElement('w:pageBreakBefore'); - $this->xmlWriter->writeAttribute('w:val', '1'); - $this->xmlWriter->endElement(); - } + $xmlWriter->writeElementIf($styles['pagination']['widowControl'] === false, 'w:widowControl', 'w:val', '0'); + $xmlWriter->writeElementIf($styles['pagination']['keepNext'] === true, 'w:keepNext', 'w:val', '1'); + $xmlWriter->writeElementIf($styles['pagination']['keepLines'] === true, 'w:keepLines', 'w:val', '1'); + $xmlWriter->writeElementIf($styles['pagination']['pageBreak'] === true, 'w:pageBreakBefore', 'w:val', '1'); + + // Indentation & spacing + $this->writeChildStyle($xmlWriter, 'Indentation', $styles['indentation']); + $this->writeChildStyle($xmlWriter, 'Spacing', $styles['spacing']); // Tabs - $tabs = $this->style->getTabs(); - if (!empty($tabs)) { - $this->xmlWriter->startElement("w:tabs"); - foreach ($tabs as $tab) { - $styleWriter = new Tab($this->xmlWriter, $tab); - $styleWriter->write(); - } - $this->xmlWriter->endElement(); - } + $this->writeTabs($xmlWriter, $styles['tabs']); + + // Numbering + $this->writeNumbering($xmlWriter, $styles['numbering']); if (!$this->withoutPPR) { - $this->xmlWriter->endElement(); // w:pPr + $xmlWriter->endElement(); // w:pPr + } + } + + /** + * Write child style + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param string $name + * @param mixed $value + */ + private function writeChildStyle(XMLWriter $xmlWriter, $name, $value) + { + if ($value !== null) { + $class = "PhpOffice\\PhpWord\\Writer\\Word2007\\Style\\" . $name; + + /** @var \PhpOffice\PhpWord\Writer\Word2007\Style\AbstractStyle $writer */ + $writer = new $class($xmlWriter, $value); + $writer->write(); + } + } + + /** + * Write tabs + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\Tab[] $tabs + */ + private function writeTabs(XMLWriter $xmlWriter, $tabs) + { + if (!empty($tabs)) { + $xmlWriter->startElement("w:tabs"); + foreach ($tabs as $tab) { + $styleWriter = new Tab($xmlWriter, $tab); + $styleWriter->write(); + } + $xmlWriter->endElement(); + } + } + + /** + * Write numbering + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param array $numbering + */ + private function writeNumbering(XMLWriter $xmlWriter, $numbering) + { + $numStyle = $numbering['style']; + $numLevel = $numbering['level']; + + /** @var \PhpOffice\PhpWord\Style\Numbering $numbering */ + $numbering = Style::getStyle($numStyle); + if ($numStyle !== null && $numbering !== null) { + $xmlWriter->startElement('w:numPr'); + $xmlWriter->startElement('w:numId'); + $xmlWriter->writeAttribute('w:val', $numbering->getIndex()); + $xmlWriter->endElement(); // w:numId + $xmlWriter->startElement('w:ilvl'); + $xmlWriter->writeAttribute('w:val', $numLevel); + $xmlWriter->endElement(); // w:ilvl + $xmlWriter->endElement(); // w:numPr + + $xmlWriter->startElement('w:outlineLvl'); + $xmlWriter->writeAttribute('w:val', $numLevel); + $xmlWriter->endElement(); // w:outlineLvl } } diff --git a/src/PhpWord/Writer/Word2007/Style/Row.php b/src/PhpWord/Writer/Word2007/Style/Row.php new file mode 100644 index 00000000..5517cc2b --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Row.php @@ -0,0 +1,66 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Row) { + return; + } + + $xmlWriter = $this->getXmlWriter(); + $xmlWriter->startElement('w:trPr'); + + if ($this->height !== null) { + $xmlWriter->startElement('w:trHeight'); + $xmlWriter->writeAttribute('w:val', $this->height); + $xmlWriter->writeAttribute('w:hRule', ($style->isExactHeight() ? 'exact' : 'atLeast')); + $xmlWriter->endElement(); + } + $xmlWriter->writeElementIf($style->isTblHeader(), 'w:tblHeader', 'w:val', '1'); + $xmlWriter->writeElementIf($style->isCantSplit(), 'w:cantSplit', 'w:val', '1'); + + $xmlWriter->endElement(); // w:trPr + } + + /** + * Set height + * + * @param int $value + */ + public function setHeight($value = null) + { + $this->height = $value; + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Section.php b/src/PhpWord/Writer/Word2007/Style/Section.php index e00a3226..fb32a39a 100644 --- a/src/PhpWord/Writer/Word2007/Style/Section.php +++ b/src/PhpWord/Writer/Word2007/Style/Section.php @@ -1,17 +1,23 @@ style instanceof \PhpOffice\PhpWord\Style\Section)) { + $style = $this->getStyle(); + if (!$style instanceof SectionStyle) { return; } + $xmlWriter = $this->getXmlWriter(); - // Section break - if (!is_null($this->style->getBreakType())) { - $this->xmlWriter->startElement('w:type'); - $this->xmlWriter->writeAttribute('w:val', $this->style->getBreakType()); - $this->xmlWriter->endElement(); - } + // Break type + $breakType = $style->getBreakType(); + $xmlWriter->writeElementIf(!is_null($breakType), 'w:type', 'w:val', $breakType); // Page size & orientation - $this->xmlWriter->startElement('w:pgSz'); - $this->xmlWriter->writeAttribute('w:orient', $this->style->getOrientation()); - $this->xmlWriter->writeAttribute('w:w', $this->style->getPageSizeW()); - $this->xmlWriter->writeAttribute('w:h', $this->style->getPageSizeH()); - $this->xmlWriter->endElement(); // w:pgSz + $xmlWriter->startElement('w:pgSz'); + $xmlWriter->writeAttribute('w:orient', $style->getOrientation()); + $xmlWriter->writeAttribute('w:w', $style->getPageSizeW()); + $xmlWriter->writeAttribute('w:h', $style->getPageSizeH()); + $xmlWriter->endElement(); // w:pgSz // Margins - $this->xmlWriter->startElement('w:pgMar'); - $this->xmlWriter->writeAttribute('w:top', $this->convertTwip($this->style->getMarginTop(), SectionStyle::DEFAULT_MARGIN)); - $this->xmlWriter->writeAttribute('w:right', $this->convertTwip($this->style->getMarginRight(), SectionStyle::DEFAULT_MARGIN)); - $this->xmlWriter->writeAttribute('w:bottom', $this->convertTwip($this->style->getMarginBottom(), SectionStyle::DEFAULT_MARGIN)); - $this->xmlWriter->writeAttribute('w:left', $this->convertTwip($this->style->getMarginLeft(), SectionStyle::DEFAULT_MARGIN)); - $this->xmlWriter->writeAttribute('w:header', $this->convertTwip($this->style->getHeaderHeight(), SectionStyle::DEFAULT_HEADER_HEIGHT)); - $this->xmlWriter->writeAttribute('w:footer', $this->convertTwip($this->style->getFooterHeight(), SectionStyle::DEFAULT_FOOTER_HEIGHT)); - $this->xmlWriter->writeAttribute('w:gutter', $this->convertTwip($this->style->getGutter(), SectionStyle::DEFAULT_GUTTER)); - $this->xmlWriter->endElement(); + $margins = array( + 'w:top' => array('getMarginTop', SectionStyle::DEFAULT_MARGIN), + 'w:right' => array('getMarginRight', SectionStyle::DEFAULT_MARGIN), + 'w:bottom' => array('getMarginBottom', SectionStyle::DEFAULT_MARGIN), + 'w:left' => array('getMarginLeft', SectionStyle::DEFAULT_MARGIN), + 'w:header' => array('getHeaderHeight', SectionStyle::DEFAULT_HEADER_HEIGHT), + 'w:footer' => array('getFooterHeight', SectionStyle::DEFAULT_FOOTER_HEIGHT), + 'w:gutter' => array('getGutter', SectionStyle::DEFAULT_GUTTER), + ); + $xmlWriter->startElement('w:pgMar'); + foreach ($margins as $attribute => $value) { + list($method, $default) = $value; + $xmlWriter->writeAttribute($attribute, $this->convertTwip($style->$method(), $default)); + } + $xmlWriter->endElement(); // Borders - $borders = $this->style->getBorderSize(); - $hasBorders = false; - for ($i = 0; $i < 4; $i++) { - if (!is_null($borders[$i])) { - $hasBorders = true; - break; - } - } - if ($hasBorders) { - $styleWriter = new MarginBorder($this->xmlWriter); - $styleWriter->setSizes($borders); - $styleWriter->setColors($this->style->getBorderColor()); + if ($style->hasBorder()) { + $xmlWriter->startElement('w:pgBorders'); + $xmlWriter->writeAttribute('w:offsetFrom', 'page'); + + $styleWriter = new MarginBorder($xmlWriter); + $styleWriter->setSizes($style->getBorderSize()); + $styleWriter->setColors($style->getBorderColor()); $styleWriter->setAttributes(array('space' => '24')); - - $this->xmlWriter->startElement('w:pgBorders'); - $this->xmlWriter->writeAttribute('w:offsetFrom', 'page'); $styleWriter->write(); - $this->xmlWriter->endElement(); - } - // Page numbering - if (!is_null($this->style->getPageNumberingStart())) { - $this->xmlWriter->startElement('w:pgNumType'); - $this->xmlWriter->writeAttribute('w:start', $this->style->getPageNumberingStart()); - $this->xmlWriter->endElement(); + $xmlWriter->endElement(); } // Columns - $this->xmlWriter->startElement('w:cols'); - $this->xmlWriter->writeAttribute('w:num', $this->style->getColsNum()); - $this->xmlWriter->writeAttribute('w:space', $this->convertTwip($this->style->getColsSpace(), SectionStyle::DEFAULT_COLUMN_SPACING)); - $this->xmlWriter->endElement(); + $colsSpace = $style->getColsSpace(); + $xmlWriter->startElement('w:cols'); + $xmlWriter->writeAttribute('w:num', $style->getColsNum()); + $xmlWriter->writeAttribute('w:space', $this->convertTwip($colsSpace, SectionStyle::DEFAULT_COLUMN_SPACING)); + $xmlWriter->endElement(); + + // Page numbering start + $pageNum = $style->getPageNumberingStart(); + $xmlWriter->writeElementIf(!is_null($pageNum), 'w:pgNumType', 'w:start', $pageNum); // Line numbering - $styleWriter = new LineNumbering($this->xmlWriter, $this->style->getLineNumbering()); + $styleWriter = new LineNumbering($xmlWriter, $style->getLineNumbering()); $styleWriter->write(); } } diff --git a/src/PhpWord/Writer/Word2007/Style/Shading.php b/src/PhpWord/Writer/Word2007/Style/Shading.php index 3d831935..72054c20 100644 --- a/src/PhpWord/Writer/Word2007/Style/Shading.php +++ b/src/PhpWord/Writer/Word2007/Style/Shading.php @@ -1,10 +1,18 @@ style instanceof \PhpOffice\PhpWord\Style\Shading)) { + $style = $this->getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Shading) { return; } + $xmlWriter = $this->getXmlWriter(); - $this->xmlWriter->startElement('w:shd'); - $this->xmlWriter->writeAttribute('w:val', $this->style->getPattern()); - $this->xmlWriter->writeAttribute('w:color', $this->style->getColor()); - $this->xmlWriter->writeAttribute('w:fill', $this->style->getFill()); - $this->xmlWriter->endElement(); + $xmlWriter->startElement('w:shd'); + $xmlWriter->writeAttribute('w:val', $style->getPattern()); + $xmlWriter->writeAttribute('w:color', $style->getColor()); + $xmlWriter->writeAttribute('w:fill', $style->getFill()); + $xmlWriter->endElement(); } } diff --git a/src/PhpWord/Writer/Word2007/Style/Spacing.php b/src/PhpWord/Writer/Word2007/Style/Spacing.php index 94f02a3c..5dfb5c43 100644 --- a/src/PhpWord/Writer/Word2007/Style/Spacing.php +++ b/src/PhpWord/Writer/Word2007/Style/Spacing.php @@ -1,10 +1,18 @@ style instanceof \PhpOffice\PhpWord\Style\Spacing)) { + $style = $this->getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Spacing) { return; } + $xmlWriter = $this->getXmlWriter(); - $this->xmlWriter->startElement('w:spacing'); - if (!is_null($this->style->getBefore())) { - $this->xmlWriter->writeAttribute('w:before', $this->convertTwip($this->style->getBefore())); - } - if (!is_null($this->style->getAfter())) { - $this->xmlWriter->writeAttribute('w:after', $this->convertTwip($this->style->getAfter())); - } - if (!is_null($this->style->getLine())) { - $this->xmlWriter->writeAttribute('w:line', $this->style->getLine()); - $this->xmlWriter->writeAttribute('w:lineRule', $this->style->getRule()); - } - $this->xmlWriter->endElement(); + $xmlWriter->startElement('w:spacing'); + + $before = $style->getBefore(); + $xmlWriter->writeAttributeIf(!is_null($before), 'w:before', $this->convertTwip($before)); + + $after = $style->getAfter(); + $xmlWriter->writeAttributeIf(!is_null($after), 'w:after', $this->convertTwip($after)); + + $line = $style->getLine(); + $xmlWriter->writeAttributeIf(!is_null($line), 'w:line', $line); + + $xmlWriter->writeAttributeIf(!is_null($line), 'w:lineRule', $style->getRule()); + + $xmlWriter->endElement(); } } diff --git a/src/PhpWord/Writer/Word2007/Style/Tab.php b/src/PhpWord/Writer/Word2007/Style/Tab.php index 403c6173..865a5a9c 100644 --- a/src/PhpWord/Writer/Word2007/Style/Tab.php +++ b/src/PhpWord/Writer/Word2007/Style/Tab.php @@ -1,10 +1,18 @@ style instanceof \PhpOffice\PhpWord\Style\Tab)) { + $style = $this->getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Tab) { return; } + $xmlWriter = $this->getXmlWriter(); - $this->xmlWriter->startElement("w:tab"); - $this->xmlWriter->writeAttribute("w:val", $this->style->getStopType()); - $this->xmlWriter->writeAttribute("w:leader", $this->style->getLeader()); - $this->xmlWriter->writeAttribute('w:pos', $this->convertTwip($this->style->getPosition())); - $this->xmlWriter->endElement(); + $xmlWriter->startElement("w:tab"); + $xmlWriter->writeAttribute("w:val", $style->getType()); + $xmlWriter->writeAttribute("w:leader", $style->getLeader()); + $xmlWriter->writeAttribute('w:pos', $this->convertTwip($style->getPosition())); + $xmlWriter->endElement(); } } diff --git a/src/PhpWord/Writer/Word2007/Style/Table.php b/src/PhpWord/Writer/Word2007/Style/Table.php index 00bda8a4..e89b121c 100644 --- a/src/PhpWord/Writer/Word2007/Style/Table.php +++ b/src/PhpWord/Writer/Word2007/Style/Table.php @@ -1,15 +1,25 @@ style instanceof \PhpOffice\PhpWord\Style\Table)) { - return; - } + $style = $this->getStyle(); + $xmlWriter = $this->getXmlWriter(); - $brdCol = $this->style->getBorderColor(); - $brdSz = $this->style->getBorderSize(); - $cellMargin = $this->style->getCellMargin(); - - // If any of the borders/margins is set, process them - $hasBorders = false; - for ($i = 0; $i < 6; $i++) { - if (!is_null($brdSz[$i])) { - $hasBorders = true; - break; - } - } - $hasMargins = false; - for ($i = 0; $i < 4; $i++) { - if (!is_null($cellMargin[$i])) { - $hasMargins = true; - break; - } - } - if ($hasMargins || $hasBorders) { - $this->xmlWriter->startElement('w:tblPr'); - if ($hasMargins) { - $mbWriter = new MarginBorder($this->xmlWriter); - $mbWriter->setSizes($cellMargin); - - $this->xmlWriter->startElement('w:tblCellMar'); - $mbWriter->write(); - $this->xmlWriter->endElement(); // w:tblCellMar - } - if ($hasBorders) { - $mbWriter = new MarginBorder($this->xmlWriter); - $mbWriter->setSizes($brdSz); - $mbWriter->setColors($brdCol); - - $this->xmlWriter->startElement('w:tblBorders'); - $mbWriter->write(); - $this->xmlWriter->endElement(); // w:tblBorders - } - $this->xmlWriter->endElement(); // w:tblPr - } - // Only write background color and first row for full style - if ($this->isFullStyle) { - // Background color - if (!is_null($this->style->getShading())) { - $this->xmlWriter->startElement('w:tcPr'); - $styleWriter = new Shading($this->xmlWriter, $this->style->getShading()); - $styleWriter->write(); - $this->xmlWriter->endElement(); - } - // First Row - $firstRow = $this->style->getFirstRow(); - if ($firstRow instanceof \PhpOffice\PhpWord\Style\Table) { - $this->writeFirstRow($firstRow, 'firstRow'); + if ($style instanceof TableStyle) { + $this->writeStyle($xmlWriter, $style); + } elseif (is_string($style)) { + $xmlWriter->startElement('w:tblPr'); + $xmlWriter->startElement('w:tblStyle'); + $xmlWriter->writeAttribute('w:val', $style); + $xmlWriter->endElement(); + if ($this->width !== null) { + $this->writeWidth($xmlWriter, $this->width, 'pct'); } + $xmlWriter->endElement(); } } /** - * Set is full style - * - * @param bool $value + * Write full style */ - public function setIsFullStyle($value) + private function writeStyle(XMLWriter $xmlWriter, TableStyle $style) { - $this->isFullStyle = $value; + // w:tblPr + $xmlWriter->startElement('w:tblPr'); + + // Alignment + $styleWriter = new Alignment($xmlWriter, new AlignmentStyle(array('value' => $style->getAlign()))); + $styleWriter->write(); + + $this->writeWidth($xmlWriter, $style->getWidth(), $style->getUnit()); + $this->writeMargin($xmlWriter, $style); + $this->writeBorder($xmlWriter, $style); + + $xmlWriter->endElement(); // w:tblPr + + $this->writeShading($xmlWriter, $style); + + // First row style + $firstRow = $style->getFirstRow(); + if ($firstRow instanceof TableStyle) { + $this->writeFirstRow($xmlWriter, $firstRow); + } + } + + /** + * Write width + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param int $width + * @param string $unit + */ + private function writeWidth(XMLWriter $xmlWriter, $width, $unit) + { + $xmlWriter->startElement('w:tblW'); + $xmlWriter->writeAttribute('w:w', $width); + $xmlWriter->writeAttribute('w:type', $unit); + $xmlWriter->endElement(); // w:tblW + } + + /** + * Write margin + */ + private function writeMargin(XMLWriter $xmlWriter, TableStyle $style) + { + if ($style->hasMargin()) { + $xmlWriter->startElement('w:tblCellMar'); + + $styleWriter = new MarginBorder($xmlWriter); + $styleWriter->setSizes($style->getCellMargin()); + $styleWriter->write(); + + $xmlWriter->endElement(); // w:tblCellMar + } + } + + /** + * Write border + */ + private function writeBorder(XMLWriter $xmlWriter, TableStyle $style) + { + if ($style->hasBorder()) { + $xmlWriter->startElement('w:tblBorders'); + + $styleWriter = new MarginBorder($xmlWriter); + $styleWriter->setSizes($style->getBorderSize()); + $styleWriter->setColors($style->getBorderColor()); + $styleWriter->write(); + + $xmlWriter->endElement(); // w:tblBorders + } } /** * Write row style - * - * @param string $type */ - private function writeFirstRow(\PhpOffice\PhpWord\Style\Table $style, $type) + private function writeFirstRow(XMLWriter $xmlWriter, TableStyle $style) { - $this->xmlWriter->startElement('w:tblStylePr'); - $this->xmlWriter->writeAttribute('w:type', $type); - $this->xmlWriter->startElement('w:tcPr'); - if (!is_null($style->getShading())) { - $styleWriter = new Shading($this->xmlWriter, $style->getShading()); + $xmlWriter->startElement('w:tblStylePr'); + $xmlWriter->writeAttribute('w:type', 'firstRow'); + $xmlWriter->startElement('w:tcPr'); + + $this->writeBorder($xmlWriter, $style); + $this->writeShading($xmlWriter, $style); + + $xmlWriter->endElement(); // w:tcPr + $xmlWriter->endElement(); // w:tblStylePr + } + + /** + * Write shading + */ + private function writeShading(XMLWriter $xmlWriter, TableStyle $style) + { + if ($style->getShading() !== null) { + $xmlWriter->startElement('w:tcPr'); + + $styleWriter = new Shading($xmlWriter, $style->getShading()); $styleWriter->write(); - } - // Borders - $brdSz = $style->getBorderSize(); - $brdCol = $style->getBorderColor(); - $hasBorders = false; - for ($i = 0; $i < 6; $i++) { - if (!is_null($brdSz[$i])) { - $hasBorders = true; - } + $xmlWriter->endElement(); } - if ($hasBorders) { - $mbWriter = new MarginBorder($this->xmlWriter); - $mbWriter->setSizes($brdSz); - $mbWriter->setColors($brdCol); + } - $this->xmlWriter->startElement('w:tcBorders'); - $mbWriter->write(); - $this->xmlWriter->endElement(); // w:tcBorders - } - - $this->xmlWriter->endElement(); // w:tcPr - $this->xmlWriter->endElement(); // w:tblStylePr + /** + * Set width + * + * @param int $value + */ + public function setWidth($value = null) + { + $this->width = $value; } } diff --git a/src/PhpWord/Writer/Word2007/Style/TextBox.php b/src/PhpWord/Writer/Word2007/Style/TextBox.php new file mode 100644 index 00000000..13f40256 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/TextBox.php @@ -0,0 +1,125 @@ +getStyle(); + if (!$style instanceof TextBoxStyle) { + return; + } + $this->writeStyle($style); + $this->writeBorder($style); + } + + /** + * Write w10 wrapping + * + * @return array + */ + public function writeW10Wrap() + { + if (is_null($this->w10wrap)) { + return; + } + $style = $this->getStyle(); + if (!$style instanceof TextBoxStyle) { + return; + } + + $relativePositions = array( + TextBoxStyle::POSITION_RELATIVE_TO_MARGIN => 'margin', + TextBoxStyle::POSITION_RELATIVE_TO_PAGE => 'page', + TextBoxStyle::POSITION_RELATIVE_TO_TMARGIN => 'margin', + TextBoxStyle::POSITION_RELATIVE_TO_BMARGIN => 'page', + TextBoxStyle::POSITION_RELATIVE_TO_LMARGIN => 'margin', + TextBoxStyle::POSITION_RELATIVE_TO_RMARGIN => 'page', + ); + $pos = $style->getPositioning(); + $vPos = $style->getPosVerticalRel(); + $hPos = $style->getPosHorizontalRel(); + + $xmlWriter = $this->getXmlWriter(); + $xmlWriter->startElement('w10:wrap'); + $xmlWriter->writeAttribute('type', $this->w10wrap); + + if ($pos == TextBoxStyle::POSITION_ABSOLUTE) { + $xmlWriter->writeAttribute('anchorx', "page"); + $xmlWriter->writeAttribute('anchory', "page"); + } elseif ($pos == TextBoxStyle::POSITION_RELATIVE) { + if (array_key_exists($vPos, $relativePositions)) { + $xmlWriter->writeAttribute('anchory', $relativePositions[$vPos]); + } + if (array_key_exists($hPos, $relativePositions)) { + $xmlWriter->writeAttribute('anchorx', $relativePositions[$hPos]); + } + } + + $xmlWriter->endElement(); // w10:wrap + } + + /** + * Writer inner margin + */ + public function writeInnerMargin() + { + $style = $this->getStyle(); + if (!$style instanceof TextBoxStyle || !$style->hasInnerMargins()) { + return; + } + + $xmlWriter = $this->getXmlWriter(); + $margins = implode(', ', $style->getInnerMargin()); + $xmlWriter->writeAttribute('inset', $margins); + } + + /** + * Writer border + */ + private function writeBorder(TextBoxStyle $style) + { + $xmlWriter = $this->getXmlWriter(); + + // Border size + $borderSize = $style->getBorderSize(); + if ($borderSize !== null) { + $xmlWriter->writeAttribute('strokeweight', $borderSize . 'pt'); + } + + // Border color + $borderColor = $style->getBorderColor(); + if (empty($borderColor)) { + $xmlWriter->writeAttribute('stroked', 'f'); + } else { + $xmlWriter->writeAttribute('strokecolor', $borderColor); + } + //@todo + } +} diff --git a/src/PhpWord/Writer/WriterInterface.php b/src/PhpWord/Writer/WriterInterface.php index 2c225b2c..eda99f27 100644 --- a/src/PhpWord/Writer/WriterInterface.php +++ b/src/PhpWord/Writer/WriterInterface.php @@ -1,10 +1,18 @@ addItem(new Footnote()); // addItem #1 + + $this->assertEquals(2, $object->addItem(new Footnote())); // addItem #2. Should returns new item index + $this->assertEquals(2, $object->countItems()); // There are two items now + $this->assertEquals(2, count($object->getItems())); // getItems returns array + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Footnote', $object->getItem(1)); // getItem returns object + $this->assertNull($object->getItem(3)); // getItem returns null when invalid index is referenced + + $object->setItem(2, null); // Set item #2 to null + + $this->assertNull($object->getItem(2)); // Check if it's null + } +} diff --git a/tests/PhpWord/Tests/DocumentPropertiesTest.php b/tests/PhpWord/Tests/DocumentPropertiesTest.php index 207eb195..30b2a7bc 100644 --- a/tests/PhpWord/Tests/DocumentPropertiesTest.php +++ b/tests/PhpWord/Tests/DocumentPropertiesTest.php @@ -1,10 +1,18 @@ assertInstanceOf('PhpOffice\\PhpWord\\Element\\Cell', $oCell); $this->assertEquals($oCell->getWidth(), null); @@ -35,8 +42,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testConstructWithStyleArray() { - $iVal = rand(1, 1000); - $oCell = new Cell('section', $iVal, null, array('valign' => 'center')); + $oCell = new Cell(null, array('valign' => 'center')); $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\Cell', $oCell->getStyle()); $this->assertEquals($oCell->getWidth(), null); @@ -47,7 +53,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddText() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addText('text'); $this->assertCount(1, $oCell->getElements()); @@ -59,7 +65,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddTextNotUTF8() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addText(utf8_decode('ééé')); $this->assertCount(1, $oCell->getElements()); @@ -72,7 +78,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddLink() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addLink(utf8_decode('ééé'), utf8_decode('ééé')); $this->assertCount(1, $oCell->getElements()); @@ -84,7 +90,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddTextBreak() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $oCell->addTextBreak(); $this->assertCount(1, $oCell->getElements()); @@ -95,7 +101,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddListItem() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addListItem('text'); $this->assertCount(1, $oCell->getElements()); @@ -108,7 +114,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddListItemNotUTF8() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addListItem(utf8_decode('ééé')); $this->assertCount(1, $oCell->getElements()); @@ -122,7 +128,7 @@ class CellTest extends \PHPUnit_Framework_TestCase public function testAddImageSection() { $src = __DIR__ . "/../_files/images/earth.jpg"; - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addImage($src); $this->assertCount(1, $oCell->getElements()); @@ -160,37 +166,9 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddImageSectionByUrl() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addImage( - 'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png' - ); - - $this->assertCount(1, $oCell->getElements()); - $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Image', $element); - } - - /** - * Add image header by URL - */ - public function testAddImageHeaderByUrl() - { - $oCell = new Cell('header', 1); - $element = $oCell->addImage( - 'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png' - ); - - $this->assertCount(1, $oCell->getElements()); - $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Image', $element); - } - - /** - * Add image footer by URL - */ - public function testAddImageFooterByUrl() - { - $oCell = new Cell('footer', 1); - $element = $oCell->addImage( - 'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png' + 'http://php.net/images/logos/php-med-trans-light.gif' ); $this->assertCount(1, $oCell->getElements()); @@ -203,7 +181,7 @@ class CellTest extends \PHPUnit_Framework_TestCase public function testAddObjectXLS() { $src = __DIR__ . "/../_files/documents/sheet.xls"; - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addObject($src); $this->assertCount(1, $oCell->getElements()); @@ -218,8 +196,8 @@ class CellTest extends \PHPUnit_Framework_TestCase public function testAddObjectException() { $src = __DIR__ . "/../_files/xsl/passthrough.xsl"; - $oCell = new Cell('section', 1); - $element = $oCell->addObject($src); + $oCell = new Cell(); + $oCell->addObject($src); } /** @@ -227,7 +205,8 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddPreserveText() { - $oCell = new Cell('header', 1); + $oCell = new Cell(); + $oCell->setDocPart('Header', 1); $element = $oCell->addPreserveText('text'); $this->assertCount(1, $oCell->getElements()); @@ -239,7 +218,8 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddPreserveTextNotUTF8() { - $oCell = new Cell('header', 1); + $oCell = new Cell(); + $oCell->setDocPart('Header', 1); $element = $oCell->addPreserveText(utf8_decode('ééé')); $this->assertCount(1, $oCell->getElements()); @@ -254,8 +234,9 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddPreserveTextException() { - $oCell = new Cell('section', 1); - $element = $oCell->addPreserveText('text'); + $oCell = new Cell(); + $oCell->setDocPart('Section', 1); + $oCell->addPreserveText('text'); } /** @@ -263,7 +244,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testCreateTextRun() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addTextRun(); $this->assertCount(1, $oCell->getElements()); @@ -275,7 +256,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddCheckBox() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addCheckBox(utf8_decode('ééé'), utf8_decode('ééé')); $this->assertCount(1, $oCell->getElements()); @@ -287,7 +268,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testGetElements() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $this->assertInternalType('array', $oCell->getElements()); } diff --git a/tests/PhpWord/Tests/Element/CheckBoxTest.php b/tests/PhpWord/Tests/Element/CheckBoxTest.php index e4611618..8f7bf3cd 100644 --- a/tests/PhpWord/Tests/Element/CheckBoxTest.php +++ b/tests/PhpWord/Tests/Element/CheckBoxTest.php @@ -1,10 +1,18 @@ assertInstanceOf('PhpOffice\\PhpWord\\Element\\Field', $oField); + } + + /** + * New instance with type + */ + public function testConstructWithType() + { + $oField = new Field('DATE'); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Field', $oField); + $this->assertEquals($oField->getType(), 'DATE'); + } + + /** + * New instance with type and properties + */ + public function testConstructWithTypeProperties() + { + $oField = new Field('DATE', array('dateformat'=>'d-M-yyyy')); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Field', $oField); + $this->assertEquals($oField->getType(), 'DATE'); + $this->assertEquals($oField->getProperties(), array('dateformat'=>'d-M-yyyy')); + } + + /** + * New instance with type and properties and options + */ + public function testConstructWithTypePropertiesOptions() + { + $oField = new Field('DATE', array('dateformat'=>'d-M-yyyy'), array('SakaEraCalendar', 'PreserveFormat')); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Field', $oField); + $this->assertEquals($oField->getType(), 'DATE'); + $this->assertEquals($oField->getProperties(), array('dateformat'=>'d-M-yyyy')); + $this->assertEquals($oField->getOptions(), array('SakaEraCalendar', 'PreserveFormat')); + } + + /** + * Test setType exception + * + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Invalid type + */ + public function testSetTypeException() + { + $object = new Field(); + $object->setType('foo'); + } + + /** + * Test setProperties exception + * + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Invalid property + */ + public function testSetPropertiesException() + { + $object = new Field('PAGE'); + $object->setProperties(array('foo' => 'bar')); + } + + /** + * Test setOptions exception + * + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Invalid option + */ + public function testSetOptionsException() + { + $object = new Field('PAGE'); + $object->setOptions(array('foo' => 'bar')); + } +} diff --git a/tests/PhpWord/Tests/Element/FooterTest.php b/tests/PhpWord/Tests/Element/FooterTest.php index d4201149..c5d04b41 100644 --- a/tests/PhpWord/Tests/Element/FooterTest.php +++ b/tests/PhpWord/Tests/Element/FooterTest.php @@ -1,10 +1,18 @@ addImage( - 'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png' + 'http://php.net/images/logos/php-med-trans-light.gif' ); $this->assertCount(1, $oFooter->getElements()); diff --git a/tests/PhpWord/Tests/Element/FootnoteTest.php b/tests/PhpWord/Tests/Element/FootnoteTest.php index c2571afe..2ba015d7 100644 --- a/tests/PhpWord/Tests/Element/FootnoteTest.php +++ b/tests/PhpWord/Tests/Element/FootnoteTest.php @@ -1,10 +1,18 @@ addImage( - 'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png' + 'http://php.net/images/logos/php-med-trans-light.gif' ); $this->assertCount(1, $oHeader->getElements()); diff --git a/tests/PhpWord/Tests/Element/ImageTest.php b/tests/PhpWord/Tests/Element/ImageTest.php index eb482398..11b33d87 100644 --- a/tests/PhpWord/Tests/Element/ImageTest.php +++ b/tests/PhpWord/Tests/Element/ImageTest.php @@ -1,10 +1,18 @@ assertInstanceOf('PhpOffice\\PhpWord\\Element\\Image', $oImage); $this->assertEquals($oImage->getSource(), $src); $this->assertEquals($oImage->getMediaId(), md5($src)); - $this->assertEquals($oImage->getIsWatermark(), false); + $this->assertEquals($oImage->isWatermark(), false); + $this->assertEquals($oImage->getSourceType(), Image::SOURCE_LOCAL); $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\Image', $oImage->getStyle()); } @@ -72,7 +81,7 @@ class ImageTest extends \PHPUnit_Framework_TestCase $this->assertEquals($image->getImageExtension(), $extension); $this->assertEquals($image->getImageCreateFunction(), $createFunction); $this->assertEquals($image->getImageFunction(), $imageFunction); - $this->assertFalse($image->getIsMemImage()); + $this->assertFalse($image->isMemImage()); } } @@ -107,6 +116,7 @@ class ImageTest extends \PHPUnit_Framework_TestCase public function testInvalidImagePhp() { $object = new Image('test.php'); + $object->getSource(); } /** @@ -117,6 +127,7 @@ class ImageTest extends \PHPUnit_Framework_TestCase public function testUnsupportedImage() { $object = new Image('http://samples.libav.org/image-samples/RACECAR.BMP'); + $object->getSource(); } /** diff --git a/tests/PhpWord/Tests/Element/LineTest.php b/tests/PhpWord/Tests/Element/LineTest.php new file mode 100644 index 00000000..429f9df6 --- /dev/null +++ b/tests/PhpWord/Tests/Element/LineTest.php @@ -0,0 +1,76 @@ +assertInstanceOf('PhpOffice\\PhpWord\\Element\\Line', $oLine); + $this->assertEquals($oLine->getStyle(), null); + } + + /** + * Get style name + */ + public function testStyleText() + { + $oLine = new Line('lineStyle'); + + $this->assertEquals($oLine->getStyle(), 'lineStyle'); + } + + /** + * Get style array + */ + public function testStyleArray() + { + $oLine = new Line( + array( + 'width' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(14), + 'height' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(4), + 'positioning' => 'absolute', + 'posHorizontalRel' => 'page', + 'posVerticalRel' => 'page', + 'flip' => true, + 'marginLeft' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(5), + 'marginTop' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(3), + 'wrappingStyle' => \PhpOffice\PhpWord\Style\Image::WRAPPING_STYLE_SQUARE, + 'beginArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_BLOCK, + 'endArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_OVAL, + 'dash' => \PhpOffice\PhpWord\Style\Line::DASH_STYLE_LONG_DASH_DOT_DOT, + 'weight' => 10 + ) + ); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\Line', $oLine->getStyle()); + } +} diff --git a/tests/PhpWord/Tests/Element/LinkTest.php b/tests/PhpWord/Tests/Element/LinkTest.php index 3840ede8..0e582b13 100644 --- a/tests/PhpWord/Tests/Element/LinkTest.php +++ b/tests/PhpWord/Tests/Element/LinkTest.php @@ -1,10 +1,18 @@ assertInstanceOf('PhpOffice\\PhpWord\\Element\\ListItemRun', $oListItemRun); + $this->assertCount(0, $oListItemRun->getElements()); + $this->assertEquals($oListItemRun->getParagraphStyle(), null); + } + + /** + * New instance with string + */ + public function testConstructString() + { + $oListItemRun = new ListItemRun(0, null, 'pStyle'); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\ListItemRun', $oListItemRun); + $this->assertCount(0, $oListItemRun->getElements()); + $this->assertEquals($oListItemRun->getParagraphStyle(), 'pStyle'); + } + + /** + * New instance with string + */ + public function testConstructListString() + { + $oListItemRun = new ListItemRun(0, 'numberingStyle'); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\ListItemRun', $oListItemRun); + $this->assertCount(0, $oListItemRun->getElements()); + } + + /** + * New instance with array + */ + public function testConstructArray() + { + $oListItemRun = new ListItemRun(0, null, array('spacing' => 100)); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\ListItemRun', $oListItemRun); + $this->assertCount(0, $oListItemRun->getElements()); + $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\Paragraph', $oListItemRun->getParagraphStyle()); + } + + /** + * Get style + */ + public function testStyle() + { + $oListItemRun = new ListItemRun(1, array('listType' => \PhpOffice\PhpWord\Style\ListItem::TYPE_NUMBER)); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\ListItem', $oListItemRun->getStyle()); + $this->assertEquals($oListItemRun->getStyle()->getListType(), \PhpOffice\PhpWord\Style\ListItem::TYPE_NUMBER); + } + /** + * getDepth + */ + public function testDepth() + { + $iVal = rand(1, 1000); + $oListItemRun = new ListItemRun($iVal); + + $this->assertEquals($oListItemRun->getDepth(), $iVal); + } + + /** + * Add text + */ + public function testAddText() + { + $oListItemRun = new ListItemRun(); + $element = $oListItemRun->addText('text'); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Text', $element); + $this->assertCount(1, $oListItemRun->getElements()); + $this->assertEquals($element->getText(), 'text'); + } + + /** + * Add text non-UTF8 + */ + public function testAddTextNotUTF8() + { + $oListItemRun = new ListItemRun(); + $element = $oListItemRun->addText(utf8_decode('ééé')); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Text', $element); + $this->assertCount(1, $oListItemRun->getElements()); + $this->assertEquals($element->getText(), 'ééé'); + } + + /** + * Add link + */ + public function testAddLink() + { + $oListItemRun = new ListItemRun(); + $element = $oListItemRun->addLink('http://www.google.fr'); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Link', $element); + $this->assertCount(1, $oListItemRun->getElements()); + $this->assertEquals($element->getTarget(), 'http://www.google.fr'); + } + + /** + * Add link with name + */ + public function testAddLinkWithName() + { + $oListItemRun = new ListItemRun(); + $element = $oListItemRun->addLink('http://www.google.fr', utf8_decode('ééé')); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Link', $element); + $this->assertCount(1, $oListItemRun->getElements()); + $this->assertEquals($element->getTarget(), 'http://www.google.fr'); + $this->assertEquals($element->getText(), 'ééé'); + } + + /** + * Add text break + */ + public function testAddTextBreak() + { + $oListItemRun = new ListItemRun(); + $oListItemRun->addTextBreak(2); + + $this->assertCount(2, $oListItemRun->getElements()); + } + + /** + * Add image + */ + public function testAddImage() + { + $src = __DIR__ . "/../_files/images/earth.jpg"; + + $oListItemRun = new ListItemRun(); + $element = $oListItemRun->addImage($src); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Image', $element); + $this->assertCount(1, $oListItemRun->getElements()); + } +} diff --git a/tests/PhpWord/Tests/Element/ListItemTest.php b/tests/PhpWord/Tests/Element/ListItemTest.php index 6526f571..1362eb43 100644 --- a/tests/PhpWord/Tests/Element/ListItemTest.php +++ b/tests/PhpWord/Tests/Element/ListItemTest.php @@ -1,10 +1,18 @@ assertInstanceOf('PhpOffice\\PhpWord\\Element\\Object', $oObject); - $this->assertEquals($oObject->getSource(), null); - $this->assertEquals($oObject->getStyle(), null); + $oObject->getSource(); } /** diff --git a/tests/PhpWord/Tests/Element/PageBreakTest.php b/tests/PhpWord/Tests/Element/PageBreakTest.php index 0c6379f5..6b038a82 100644 --- a/tests/PhpWord/Tests/Element/PageBreakTest.php +++ b/tests/PhpWord/Tests/Element/PageBreakTest.php @@ -1,10 +1,18 @@ assertInstanceOf('PhpOffice\\PhpWord\\Element\\Row', $oRow); $this->assertEquals($oRow->getHeight(), null); @@ -40,15 +47,9 @@ class RowTest extends \PHPUnit_Framework_TestCase public function testConstructWithParams() { $iVal = rand(1, 1000); - $iVal2 = rand(1, 1000); - $oRow = new Row( - 'section', - $iVal, - $iVal2, - array('borderBottomSize' => 18, 'borderBottomColor' => '0000FF', 'bgColor' => '66BBFF') - ); + $oRow = new Row($iVal, array('borderBottomSize' => 18, 'borderBottomColor' => '0000FF', 'bgColor' => '66BBFF')); - $this->assertEquals($oRow->getHeight(), $iVal2); + $this->assertEquals($oRow->getHeight(), $iVal); $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\Row', $oRow->getStyle()); } @@ -57,7 +58,7 @@ class RowTest extends \PHPUnit_Framework_TestCase */ public function testAddCell() { - $oRow = new Row('section', 1); + $oRow = new Row(); $element = $oRow->addCell(); $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Cell', $element); diff --git a/tests/PhpWord/Tests/Element/SectionTest.php b/tests/PhpWord/Tests/Element/SectionTest.php index 415e43ad..af7595e2 100644 --- a/tests/PhpWord/Tests/Element/SectionTest.php +++ b/tests/PhpWord/Tests/Element/SectionTest.php @@ -1,17 +1,26 @@ setSettings(array('orientation' => $expected)); + $object->setSettings(array('orientation' => $expected, 'foo' => null)); $this->assertEquals($expected, $object->getSettings()->getOrientation()); } @@ -75,9 +84,10 @@ class SectionTest extends \PHPUnit_Framework_TestCase { $objectSource = __DIR__ . "/../_files/documents/reader.docx"; $imageSource = __DIR__ . "/../_files/images/PhpWord.png"; - $imageUrl = 'http://php.net//images/logos/php-med-trans-light.gif'; + // $imageUrl = 'http://php.net//images/logos/php-med-trans-light.gif'; $section = new Section(0); + $section->setPhpWord(new PhpWord()); $section->addText(utf8_decode('ä')); $section->addLink(utf8_decode('http://äää.com'), utf8_decode('ä')); $section->addTextBreak(); @@ -96,10 +106,10 @@ class SectionTest extends \PHPUnit_Framework_TestCase $elementTypes = array('Text', 'Link', 'TextBreak', 'PageBreak', 'Table', 'ListItem', 'Object', 'Image', 'Title', 'TextRun', 'Footnote', 'CheckBox', 'TOC'); - $i = 0; + $elmCount = 0; foreach ($elementTypes as $elementType) { - $this->assertInstanceOf("PhpOffice\\PhpWord\\Element\\{$elementType}", $elementCollection[$i]); - $i++; + $this->assertInstanceOf("PhpOffice\\PhpWord\\Element\\{$elementType}", $elementCollection[$elmCount]); + $elmCount++; } } @@ -122,6 +132,7 @@ class SectionTest extends \PHPUnit_Framework_TestCase { Style::addTitleStyle(1, array('size' => 14)); $section = new Section(0); + $section->setPhpWord(new PhpWord()); $section->addTitle('Test', 1); $elementCollection = $section->getElements(); @@ -163,6 +174,6 @@ class SectionTest extends \PHPUnit_Framework_TestCase public function testAddHeaderException() { $object = new Section(1); - $header = $object->addHeader('ODD'); + $object->addHeader('ODD'); } } diff --git a/tests/PhpWord/Tests/Element/TOCTest.php b/tests/PhpWord/Tests/Element/TOCTest.php index 207f6969..d0ebf343 100644 --- a/tests/PhpWord/Tests/Element/TOCTest.php +++ b/tests/PhpWord/Tests/Element/TOCTest.php @@ -1,15 +1,25 @@ 9062, - 'tabLeader' => \PhpOffice\PhpWord\Style\TOC::TABLEADER_DOT, + 'position' => 9062, + 'leader' => \PhpOffice\PhpWord\Style\Tab::TAB_LEADER_DOT, 'indent' => 200, ); - $object = new TOC(array('_size' => 11), array('_tabPos' => $expected['tabPos'])); + $object = new TOC(array('size' => 11), array('position' => $expected['position'])); $tocStyle = $object->getStyleTOC(); $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\TOC', $tocStyle); @@ -46,27 +56,40 @@ class TOCTest extends \PHPUnit_Framework_TestCase public function testConstructWithStyleName() { $object = new TOC('Font Style'); - $tocStyle = $object->getStyleTOC(); + // $tocStyle = $object->getStyleTOC(); $this->assertEquals('Font Style', $object->getStyleFont()); } + /** + * Test when no PHPWord object is assigned: + */ + public function testNoPhpWord() + { + $object = new TOC(); + + $this->assertEmpty($object->getTitles()); + $this->assertNull($object->getPhpWord()); + } + /** * Set/get minDepth and maxDepth */ public function testSetGetMinMaxDepth() { - $toc = new TOC(); $titles = array( 'Heading 1' => 1, 'Heading 2' => 2, 'Heading 3' => 3, 'Heading 4' => 4, ); - foreach ($titles as $text => $depth) { - \PhpOffice\PhpWord\TOC::addTitle($text, $depth); - } + $phpWord = new PhpWord(); + foreach ($titles as $text => $depth) { + $phpWord->addTitle(new Title($text, $depth)); + } + $toc = new TOC(); + $toc->setPhpWord($phpWord); $this->assertEquals(1, $toc->getMinDepth()); $this->assertEquals(9, $toc->getMaxDepth()); diff --git a/tests/PhpWord/Tests/Element/TableTest.php b/tests/PhpWord/Tests/Element/TableTest.php index 3fc51f98..0977639f 100644 --- a/tests/PhpWord/Tests/Element/TableTest.php +++ b/tests/PhpWord/Tests/Element/TableTest.php @@ -1,10 +1,18 @@ assertInstanceOf('PhpOffice\\PhpWord\\Element\\Table', $oTable); $this->assertEquals($oTable->getStyle(), null); @@ -38,7 +46,7 @@ class TableTest extends \PHPUnit_Framework_TestCase */ public function testStyleText() { - $oTable = new Table('section', 1, 'tableStyle'); + $oTable = new Table('tableStyle'); $this->assertEquals($oTable->getStyle(), 'tableStyle'); } @@ -48,7 +56,7 @@ class TableTest extends \PHPUnit_Framework_TestCase */ public function testStyleArray() { - $oTable = new Table('section', 1, array( + $oTable = new Table(array( 'borderSize' => 6, 'borderColor' => '006699', 'cellMargin' => 80 @@ -62,7 +70,7 @@ class TableTest extends \PHPUnit_Framework_TestCase */ public function testWidth() { - $oTable = new Table('section', 1); + $oTable = new Table(); $iVal = rand(1, 1000); $oTable->setWidth($iVal); $this->assertEquals($oTable->getWidth(), $iVal); @@ -73,7 +81,7 @@ class TableTest extends \PHPUnit_Framework_TestCase */ public function testRow() { - $oTable = new Table('section', 1); + $oTable = new Table(); $element = $oTable->addRow(); $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Row', $element); $this->assertCount(1, $oTable->getRows()); @@ -84,7 +92,7 @@ class TableTest extends \PHPUnit_Framework_TestCase */ public function testCell() { - $oTable = new Table('section', 1); + $oTable = new Table(); $oTable->addRow(); $element = $oTable->addCell(); $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Cell', $element); @@ -95,7 +103,7 @@ class TableTest extends \PHPUnit_Framework_TestCase */ public function testCountColumns() { - $oTable = new Table('section', 1); + $oTable = new Table(); $oTable->addRow(); $element = $oTable->addCell(); $this->assertEquals($oTable->countColumns(), 1); diff --git a/tests/PhpWord/Tests/Element/TextBoxTest.php b/tests/PhpWord/Tests/Element/TextBoxTest.php new file mode 100644 index 00000000..c3c89ed4 --- /dev/null +++ b/tests/PhpWord/Tests/Element/TextBoxTest.php @@ -0,0 +1,72 @@ +assertInstanceOf('PhpOffice\\PhpWord\\Element\\TextBox', $oTextBox); + $this->assertEquals($oTextBox->getStyle(), null); + } + + /** + * Get style name + */ + public function testStyleText() + { + $oTextBox = new TextBox('textBoxStyle'); + + $this->assertEquals($oTextBox->getStyle(), 'textBoxStyle'); + } + + /** + * Get style array + */ + public function testStyleArray() + { + $oTextBox = new TextBox( + array( + 'width' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(4.5), + 'height' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(17.5), + 'positioning' => 'absolute', + 'marginLeft' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(15.4), + 'marginTop' => \PhpOffice\PhpWord\Shared\Drawing::centimetersToPixels(9.9), + 'stroke' => 0, + 'innerMargin' => 0, + 'borderSize' => 1, + 'borderColor' => '' + ) + ); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\TextBox', $oTextBox->getStyle()); + } +} diff --git a/tests/PhpWord/Tests/Element/TextBreakTest.php b/tests/PhpWord/Tests/Element/TextBreakTest.php index c228215f..1d9479ee 100644 --- a/tests/PhpWord/Tests/Element/TextBreakTest.php +++ b/tests/PhpWord/Tests/Element/TextBreakTest.php @@ -1,10 +1,18 @@ addTextBreak(2); + $oTextRun->addTextBreak(2); $this->assertCount(2, $oTextRun->getElements()); } @@ -138,6 +147,7 @@ class TextRunTest extends \PHPUnit_Framework_TestCase public function testCreateFootnote() { $oTextRun = new TextRun(); + $oTextRun->setPhpWord(new PhpWord()); $element = $oTextRun->addFootnote(); $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Footnote', $element); diff --git a/tests/PhpWord/Tests/Element/TextTest.php b/tests/PhpWord/Tests/Element/TextTest.php index 953dfc8f..a306d4b9 100644 --- a/tests/PhpWord/Tests/Element/TextTest.php +++ b/tests/PhpWord/Tests/Element/TextTest.php @@ -1,10 +1,18 @@ assertEquals($oTitle->getStyle(), null); } - - /** - * Get style not null - */ - public function testStyleNotNull() - { - $oTitle = new Title('text', 1, 'style'); - - $this->assertEquals($oTitle->getStyle(), 'style'); - } - - /** - * Get anchor - */ - public function testAnchor() - { - $oTitle = new Title('text'); - - $iVal = rand(1, 1000); - $oTitle->setAnchor($iVal); - $this->assertEquals($oTitle->getAnchor(), $iVal); - } - - /** - * Get bookmark Id - */ - public function testBookmarkID() - { - $oTitle = new Title('text'); - - $iVal = rand(1, 1000); - $oTitle->setBookmarkId($iVal); - $this->assertEquals($oTitle->getBookmarkId(), $iVal); - } } diff --git a/tests/PhpWord/Tests/EndnotesTest.php b/tests/PhpWord/Tests/EndnotesTest.php deleted file mode 100644 index a72e85f9..00000000 --- a/tests/PhpWord/Tests/EndnotesTest.php +++ /dev/null @@ -1,39 +0,0 @@ -assertEquals(1, $rId); - $this->assertEquals(1, count(Endnotes::getElements())); - $this->assertEquals($endnote2, Endnotes::getElement(1)); - $this->assertNull(Endnotes::getElement(2)); - - Endnotes::resetElements(); - $this->assertEquals(0, Endnotes::countElements()); - } -} diff --git a/tests/PhpWord/Tests/Exception/ExceptionTest.php b/tests/PhpWord/Tests/Exception/ExceptionTest.php index 04eb03e0..38d0f7f2 100644 --- a/tests/PhpWord/Tests/Exception/ExceptionTest.php +++ b/tests/PhpWord/Tests/Exception/ExceptionTest.php @@ -1,10 +1,18 @@ assertEquals(1, $rId); - $this->assertEquals(1, count(Footnotes::getElements())); - $this->assertEquals($footnote2, Footnotes::getElement(1)); - $this->assertNull(Footnotes::getElement(2)); - - Footnotes::resetElements(); - $this->assertEquals(0, Footnotes::countElements()); - } -} diff --git a/tests/PhpWord/Tests/IOFactoryTest.php b/tests/PhpWord/Tests/IOFactoryTest.php index 405eabe0..60db16d0 100644 --- a/tests/PhpWord/Tests/IOFactoryTest.php +++ b/tests/PhpWord/Tests/IOFactoryTest.php @@ -1,16 +1,24 @@ assertEquals(new DocumentProperties(), $phpWord->getDocumentProperties()); - $this->assertEquals(PhpWord::DEFAULT_FONT_NAME, $phpWord->getDefaultFontName()); - $this->assertEquals(PhpWord::DEFAULT_FONT_SIZE, $phpWord->getDefaultFontSize()); + $this->assertEquals(Settings::DEFAULT_FONT_NAME, $phpWord->getDefaultFontName()); + $this->assertEquals(Settings::DEFAULT_FONT_SIZE, $phpWord->getDefaultFontSize()); } /** @@ -51,9 +59,8 @@ class PhpWordTest extends \PHPUnit_Framework_TestCase public function testCreateGetSections() { $phpWord = new PhpWord(); - $this->assertEquals(new Section(1), $phpWord->addSection()); $phpWord->addSection(); - $this->assertEquals(2, count($phpWord->getSections())); + $this->assertEquals(1, count($phpWord->getSections())); } /** @@ -63,7 +70,7 @@ class PhpWordTest extends \PHPUnit_Framework_TestCase { $phpWord = new PhpWord(); $fontName = 'Times New Roman'; - $this->assertEquals(PhpWord::DEFAULT_FONT_NAME, $phpWord->getDefaultFontName()); + $this->assertEquals(Settings::DEFAULT_FONT_NAME, $phpWord->getDefaultFontName()); $phpWord->setDefaultFontName($fontName); $this->assertEquals($fontName, $phpWord->getDefaultFontName()); } @@ -75,7 +82,7 @@ class PhpWordTest extends \PHPUnit_Framework_TestCase { $phpWord = new PhpWord(); $fontSize = 16; - $this->assertEquals(PhpWord::DEFAULT_FONT_SIZE, $phpWord->getDefaultFontSize()); + $this->assertEquals(Settings::DEFAULT_FONT_SIZE, $phpWord->getDefaultFontSize()); $phpWord->setDefaultFontSize($fontSize); $this->assertEquals($fontSize, $phpWord->getDefaultFontSize()); } diff --git a/tests/PhpWord/Tests/Reader/HTMLTest.php b/tests/PhpWord/Tests/Reader/HTMLTest.php new file mode 100644 index 00000000..cb3dc55c --- /dev/null +++ b/tests/PhpWord/Tests/Reader/HTMLTest.php @@ -0,0 +1,51 @@ +assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', $phpWord); + } + + /** + * Test load exception + * + * @expectedException \Exception + * @expectedExceptionMessage Cannot read + */ + public function testLoadException() + { + $filename = __DIR__ . '/../_files/documents/foo.html'; + IOFactory::load($filename, 'HTML'); + } +} diff --git a/tests/PhpWord/Tests/Reader/ODTextTest.php b/tests/PhpWord/Tests/Reader/ODTextTest.php index 6136b0c4..fc4d2e33 100644 --- a/tests/PhpWord/Tests/Reader/ODTextTest.php +++ b/tests/PhpWord/Tests/Reader/ODTextTest.php @@ -1,10 +1,18 @@ assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', $object); + $phpWord = IOFactory::load($filename, 'ODText'); + $this->assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', $phpWord); } } diff --git a/tests/PhpWord/Tests/Reader/RTFTest.php b/tests/PhpWord/Tests/Reader/RTFTest.php new file mode 100644 index 00000000..c495db68 --- /dev/null +++ b/tests/PhpWord/Tests/Reader/RTFTest.php @@ -0,0 +1,51 @@ +assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', $phpWord); + } + + /** + * Test load exception + * + * @expectedException \Exception + * @expectedExceptionMessage Cannot read + */ + public function testLoadException() + { + $filename = __DIR__ . '/../_files/documents/foo.rtf'; + IOFactory::load($filename, 'RTF'); + } +} diff --git a/tests/PhpWord/Tests/Reader/Word2007Test.php b/tests/PhpWord/Tests/Reader/Word2007Test.php index 3a572f4d..f2257012 100644 --- a/tests/PhpWord/Tests/Reader/Word2007Test.php +++ b/tests/PhpWord/Tests/Reader/Word2007Test.php @@ -1,16 +1,24 @@ assertTrue($object->canRead($fqFilename)); + $filename = __DIR__ . '/../_files/documents/reader.docx'; + $this->assertTrue($object->canRead($filename)); } /** * Can read exception - * - * @expectedException \PhpOffice\PhpWord\Exception\Exception */ public function testCanReadFailed() { $object = new Word2007(); - $fqFilename = join( - DIRECTORY_SEPARATOR, - array(PHPWORD_TESTS_BASE_DIR, 'PhpWord', 'Tests', '_files', 'documents', 'foo.docx') - ); - $this->assertFalse($object->canRead($fqFilename)); - $object = IOFactory::load($fqFilename); + $filename = __DIR__ . '/../_files/documents/foo.docx'; + $this->assertFalse($object->canRead($filename)); } /** @@ -61,11 +53,8 @@ class Word2007Test extends \PHPUnit_Framework_TestCase */ public function testLoad() { - $fqFilename = join( - DIRECTORY_SEPARATOR, - array(PHPWORD_TESTS_BASE_DIR, 'PhpWord', 'Tests', '_files', 'documents', 'reader.docx') - ); - $object = IOFactory::load($fqFilename); - $this->assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', $object); + $filename = __DIR__ . '/../_files/documents/reader.docx'; + $phpWord = IOFactory::load($filename); + $this->assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', $phpWord); } } diff --git a/tests/PhpWord/Tests/SettingsTest.php b/tests/PhpWord/Tests/SettingsTest.php index 64a09994..61364034 100644 --- a/tests/PhpWord/Tests/SettingsTest.php +++ b/tests/PhpWord/Tests/SettingsTest.php @@ -1,10 +1,18 @@ assertTrue(Settings::getCompatibility()); + $this->assertTrue(Settings::hasCompatibility()); $this->assertTrue(Settings::setCompatibility(false)); - $this->assertFalse(Settings::getCompatibility()); - $this->assertFalse(Settings::setCompatibility('Non boolean')); + $this->assertFalse(Settings::hasCompatibility()); } /** @@ -62,4 +69,48 @@ class SettingsTest extends \PHPUnit_Framework_TestCase $this->assertTrue(Settings::setMeasurementUnit(Settings::UNIT_INCH)); $this->assertFalse(Settings::setMeasurementUnit('foo')); } + + /** + * Test set/get default font name + */ + public function testSetGetDefaultFontName() + { + $this->assertEquals(Settings::DEFAULT_FONT_NAME, Settings::getDefaultFontName()); + $this->assertTrue(Settings::setDefaultFontName('Times New Roman')); + $this->assertFalse(Settings::setDefaultFontName(' ')); + } + + /** + * Test set/get default font size + */ + public function testSetGetDefaultFontSize() + { + $this->assertEquals(Settings::DEFAULT_FONT_SIZE, Settings::getDefaultFontSize()); + $this->assertTrue(Settings::setDefaultFontSize(12)); + $this->assertFalse(Settings::setDefaultFontSize(null)); + } + + /** + * Test load config + */ + public function testLoadConfig() + { + $expected = array( + 'compatibility' => true, + 'zipClass' => 'ZipArchive', + 'pdfRendererName' => 'DomPDF', + 'pdfRendererPath' => '', + 'defaultFontName' => 'Arial', + 'defaultFontSize' => 10, + ); + + // Test default value + $this->assertEquals($expected, Settings::loadConfig()); + + // Test with valid file + $this->assertEquals($expected, Settings::loadConfig(__DIR__ . '/../../../phpword.ini.dist')); + + // Test with invalid file + $this->assertEmpty(Settings::loadConfig(__DIR__ . '/../../../phpunit.xml.dist')); + } } diff --git a/tests/PhpWord/Tests/Shared/DrawingTest.php b/tests/PhpWord/Tests/Shared/DrawingTest.php index 713cebcd..25fd3a38 100644 --- a/tests/PhpWord/Tests/Shared/DrawingTest.php +++ b/tests/PhpWord/Tests/Shared/DrawingTest.php @@ -1,10 +1,18 @@ assertEquals(round($value * 9525), $result); - $result = Drawing::EMUToPixels($value); + $result = Drawing::emuToPixels($value); $this->assertEquals(round($value / 9525), $result); $result = Drawing::pixelsToPoints($value); - $this->assertEquals($value * 0.67777777, $result); + $this->assertEquals($value * 0.75, $result); $result = Drawing::pointsToPixels($value); $this->assertEquals($value * 1.333333333, $result); @@ -48,10 +56,10 @@ class DrawingTest extends \PHPUnit_Framework_TestCase $this->assertEquals(round($value / 60000), $result); $result = Drawing::pixelsToCentimeters($value); - $this->assertEquals($value * 0.028, $result); + $this->assertEquals($value * 0.026458333, $result); $result = Drawing::centimetersToPixels($value); - $this->assertEquals($value / 0.028, $result); + $this->assertEquals($value / 0.026458333, $result); } } diff --git a/tests/PhpWord/Tests/Shared/FontTest.php b/tests/PhpWord/Tests/Shared/FontTest.php index f36f1074..c10f7739 100644 --- a/tests/PhpWord/Tests/Shared/FontTest.php +++ b/tests/PhpWord/Tests/Shared/FontTest.php @@ -1,15 +1,22 @@ assertEquals(0, $section->countElements()); + + // Heading + $styles = array('strong', 'em', 'sup', 'sub'); + for ($level = 1; $level <= 6; $level++) { + $content .= "Heading {$level}"; + } + + // Styles + $content .= '

'; + foreach ($styles as $style) { + $content .= "<{$style}>{$style}"; + } + $content .= '

'; + + // Add HTML + Html::addHtml($section, $content); + $this->assertEquals(7, $section->countElements()); + + // Other parts + $section = new Section(1); + $content = ''; + $content .= '
HeaderContent
'; + $content .= '
  • Bullet
    • Bullet
'; + $content .= '
  1. Bullet
'; + Html::addHtml($section, $content); + } +} diff --git a/tests/PhpWord/Tests/Shared/StringTest.php b/tests/PhpWord/Tests/Shared/StringTest.php index 02b4898a..bf5862fb 100644 --- a/tests/PhpWord/Tests/Shared/StringTest.php +++ b/tests/PhpWord/Tests/Shared/StringTest.php @@ -1,10 +1,18 @@ assertEquals('', String::controlCharacterPHP2OOXML('')); $this->assertEquals('_x0008_', String::controlCharacterPHP2OOXML(chr(0x08))); } + + /** + * Test unicode conversion + */ + public function testToUnicode() + { + $this->assertEquals('a', String::toUnicode('a')); + $this->assertEquals('\uc0{\u8364}', String::toUnicode('€')); + $this->assertEquals('\uc0{\u233}', String::toUnicode('é')); + } } diff --git a/tests/PhpWord/Tests/Shared/XMLReaderTest.php b/tests/PhpWord/Tests/Shared/XMLReaderTest.php index 759bf580..2bb6ef65 100644 --- a/tests/PhpWord/Tests/Shared/XMLReaderTest.php +++ b/tests/PhpWord/Tests/Shared/XMLReaderTest.php @@ -1,10 +1,18 @@ getDomFromZip($filename, 'yadayadaya'); + } + /** * Test get DOMDocument from ZipArchive returns false */ diff --git a/tests/PhpWord/Tests/Shared/XMLWriterTest.php b/tests/PhpWord/Tests/Shared/XMLWriterTest.php new file mode 100644 index 00000000..08db3918 --- /dev/null +++ b/tests/PhpWord/Tests/Shared/XMLWriterTest.php @@ -0,0 +1,40 @@ +foo(); + } +} diff --git a/tests/PhpWord/Tests/Shared/ZipArchiveTest.php b/tests/PhpWord/Tests/Shared/ZipArchiveTest.php index 2e45fcf8..11a0d9a3 100644 --- a/tests/PhpWord/Tests/Shared/ZipArchiveTest.php +++ b/tests/PhpWord/Tests/Shared/ZipArchiveTest.php @@ -1,14 +1,23 @@ open($zipFile, ZipArchive::CREATE); + // $object->addFromString('content/string.txt', 'Test'); + + // // Lock the file + // $resource = fopen($zipFile, "w"); + // flock($resource, LOCK_EX); + + // // Closing the file should throws an exception + // $object->close(); + + // // Unlock the file + // flock($resource, LOCK_UN); + // fclose($resource); + + // @unlink($zipFile); + } + /** * Test all methods * + * @param string $zipClass * @covers :: */ - public function testAllMethods() + public function testZipArchive($zipClass = 'ZipArchive') { // Preparation $existingFile = __DIR__ . "/../_files/documents/sheet.xls"; $zipFile = __DIR__ . "/../_files/documents/ziptest.zip"; - $destination1 = __DIR__ . "/../_files/extract1"; - $destination2 = __DIR__ . "/../_files/extract2"; - $destination3 = __DIR__ . "/../_files/extract3"; + $destination1 = __DIR__ . "/../_files/documents/extract1"; + $destination2 = __DIR__ . "/../_files/documents/extract2"; @mkdir($destination1); @mkdir($destination2); - @mkdir($destination3); + + Settings::setZipClass($zipClass); $object = new ZipArchive(); - $object->open($zipFile); + $object->open($zipFile, ZipArchive::CREATE); $object->addFile($existingFile, 'xls/new.xls'); $object->addFromString('content/string.txt', 'Test'); $object->close(); + $object->open($zipFile); // Run tests $this->assertEquals(0, $object->locateName('xls/new.xls')); @@ -60,10 +101,19 @@ class ZipArchiveTest extends \PHPUnit_Framework_TestCase // Cleanup $this->deleteDir($destination1); $this->deleteDir($destination2); - $this->deleteDir($destination3); @unlink($zipFile); } + /** + * Test PclZip + * + * @covers :: + */ + public function testPCLZip() + { + $this->testZipArchive('PhpOffice\PhpWord\Shared\ZipArchive'); + } + /** * Delete directory * diff --git a/tests/PhpWord/Tests/Style/AbstractStyleTest.php b/tests/PhpWord/Tests/Style/AbstractStyleTest.php index ae11c27c..d35e1090 100644 --- a/tests/PhpWord/Tests/Style/AbstractStyleTest.php +++ b/tests/PhpWord/Tests/Style/AbstractStyleTest.php @@ -1,10 +1,18 @@ assertEquals(true, self::callProtectedMethod($stub, 'setBoolVal', array(true, false))); $this->assertEquals(12, self::callProtectedMethod($stub, 'setIntVal', array(12, 200))); $this->assertEquals(871.1, self::callProtectedMethod($stub, 'setFloatVal', array(871.1, 2.1))); + $this->assertEquals(871.1, self::callProtectedMethod($stub, 'setFloatVal', array('871.1', 2.1))); $this->assertEquals('a', self::callProtectedMethod($stub, 'setEnumVal', array('a', array('a', 'b'), 'b'))); } @@ -50,6 +59,18 @@ class AbstractStyleTest extends \PHPUnit_Framework_TestCase $this->assertEquals(false, self::callProtectedMethod($stub, 'setBoolVal', array('a', false))); $this->assertEquals(200, self::callProtectedMethod($stub, 'setIntVal', array('foo', 200))); $this->assertEquals(2.1, self::callProtectedMethod($stub, 'setFloatVal', array('foo', 2.1))); + $this->assertEquals('b', self::callProtectedMethod($stub, 'setEnumVal', array(null, array('a', 'b'), 'b'))); + } + + /** + * Test setEnumVal exception + * + * @expectedException \InvalidArgumentException + */ + public function testSetValEnumException() + { + $stub = $this->getMockForAbstractClass('\PhpOffice\PhpWord\Style\AbstractStyle'); + $this->assertEquals('b', self::callProtectedMethod($stub, 'setEnumVal', array('z', array('a', 'b'), 'b'))); } diff --git a/tests/PhpWord/Tests/Style/CellTest.php b/tests/PhpWord/Tests/Style/CellTest.php index 5e3d959d..f9131728 100644 --- a/tests/PhpWord/Tests/Style/CellTest.php +++ b/tests/PhpWord/Tests/Style/CellTest.php @@ -1,10 +1,18 @@ 'left', + 'valign' => Cell::VALIGN_TOP, 'textDirection' => Cell::TEXT_DIR_BTLR, 'bgColor' => 'FFFF00', 'borderTopSize' => 120, @@ -39,12 +47,16 @@ class CellTest extends \PHPUnit_Framework_TestCase 'borderBottomSize' => 120, 'borderBottomColor' => 'FFFF00', 'gridSpan' => 2, - 'vMerge' => 2, + 'vMerge' => Cell::VMERGE_RESTART, ); foreach ($attributes as $key => $value) { $set = "set{$key}"; $get = "get{$key}"; + + $this->assertNull($object->$get()); // Init with null value + $object->$set($value); + $this->assertEquals($value, $object->$get()); } } @@ -56,7 +68,6 @@ class CellTest extends \PHPUnit_Framework_TestCase { $object = new Cell(); - $default = '000000'; $value = 'FF0000'; $object->setStyleValue('borderColor', $value); diff --git a/tests/PhpWord/Tests/Style/FontTest.php b/tests/PhpWord/Tests/Style/FontTest.php index 9185d646..432b29fb 100644 --- a/tests/PhpWord/Tests/Style/FontTest.php +++ b/tests/PhpWord/Tests/Style/FontTest.php @@ -1,15 +1,24 @@ PhpWord::DEFAULT_FONT_NAME, - 'size' => PhpWord::DEFAULT_FONT_SIZE, + 'name' => null, + 'size' => null, + 'hint' => null, + 'color' => null, 'bold' => false, 'italic' => false, + 'underline' => Font::UNDERLINE_NONE, 'superScript' => false, 'subScript' => false, - 'underline' => Font::UNDERLINE_NONE, 'strikethrough' => false, - 'color' => PhpWord::DEFAULT_FONT_COLOR, + 'doubleStrikethrough' => false, + 'smallCaps' => false, + 'allCaps' => false, 'fgColor' => null, 'bgColor' => null, - 'hint' => PhpWord::DEFAULT_FONT_CONTENT_TYPE, ); foreach ($attributes as $key => $default) { - $get = "get{$key}"; + $get = is_bool($default) ? "is{$key}" : "get{$key}"; + $this->assertEquals($default, $object->$get()); $object->setStyleValue("$key", null); $this->assertEquals($default, $object->$get()); $object->setStyleValue("$key", ''); @@ -79,20 +92,24 @@ class FontTest extends \PHPUnit_Framework_TestCase $attributes = array( 'name' => 'Times New Roman', 'size' => 9, + 'color' => '999999', + 'hint' => 'eastAsia', 'bold' => true, 'italic' => true, + 'underline' => Font::UNDERLINE_HEAVY, 'superScript' => true, 'subScript' => false, - 'underline' => Font::UNDERLINE_HEAVY, 'strikethrough' => true, - 'color' => '999999', + 'doubleStrikethrough' => false, + 'smallCaps' => true, + 'allCaps' => false, 'fgColor' => Font::FGCOLOR_YELLOW, 'bgColor' => 'FFFF00', - 'hint' => 'eastAsia', + 'lineHeight' => 2, ); - $object->setArrayStyle($attributes); + $object->setStyleByArray($attributes); foreach ($attributes as $key => $value) { - $get = "get{$key}"; + $get = is_bool($value) ? "is{$key}" : "get{$key}"; $this->assertEquals($value, $object->$get()); } } diff --git a/tests/PhpWord/Tests/Style/ImageTest.php b/tests/PhpWord/Tests/Style/ImageTest.php index fd74d73c..1a679da3 100644 --- a/tests/PhpWord/Tests/Style/ImageTest.php +++ b/tests/PhpWord/Tests/Style/ImageTest.php @@ -1,10 +1,18 @@ 200, 'align' => 'left', 'marginTop' => 240, - 'marginLeft' => 240 + 'marginLeft' => 240, + 'positioning' => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE, + 'posHorizontal' => \PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_CENTER, + 'posVertical' => \PhpOffice\PhpWord\Style\Image::POSITION_VERTICAL_TOP, + 'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_COLUMN, + 'posVerticalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_IMARGIN ); foreach ($properties as $key => $value) { $get = "get{$key}"; diff --git a/tests/PhpWord/Tests/Style/IndentationTest.php b/tests/PhpWord/Tests/Style/IndentationTest.php new file mode 100644 index 00000000..d0e88f2c --- /dev/null +++ b/tests/PhpWord/Tests/Style/IndentationTest.php @@ -0,0 +1,53 @@ + array(0, 10), + 'right' => array(0, 10), + 'firstLine' => array(null, 20), + 'hanging' => array(null, 20), + ); + foreach ($properties as $property => $value) { + list($default, $expected) = $value; + $get = "get{$property}"; + $set = "set{$property}"; + + $this->assertEquals($default, $object->$get()); // Default value + + $object->$set($expected); + + $this->assertEquals($expected, $object->$get()); // New value + } + } +} diff --git a/tests/PhpWord/Tests/Style/LineNumberingTest.php b/tests/PhpWord/Tests/Style/LineNumberingTest.php new file mode 100644 index 00000000..bc4dc603 --- /dev/null +++ b/tests/PhpWord/Tests/Style/LineNumberingTest.php @@ -0,0 +1,53 @@ + array(1, 2), + 'increment' => array(1, 10), + 'distance' => array(null, 10), + 'restart' => array(null, 'continuous'), + ); + foreach ($properties as $property => $value) { + list($default, $expected) = $value; + $get = "get{$property}"; + $set = "set{$property}"; + + $this->assertEquals($default, $object->$get()); // Default value + + $object->$set($expected); + + $this->assertEquals($expected, $object->$get()); // New value + } + } +} diff --git a/tests/PhpWord/Tests/Style/LineTest.php b/tests/PhpWord/Tests/Style/LineTest.php new file mode 100644 index 00000000..02d5ba16 --- /dev/null +++ b/tests/PhpWord/Tests/Style/LineTest.php @@ -0,0 +1,151 @@ + \PhpOffice\PhpWord\Style\Line::CONNECTOR_TYPE_STRAIGHT, + 'beginArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_BLOCK, + 'endArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_OVAL, + 'dash' => \PhpOffice\PhpWord\Style\Line::DASH_STYLE_LONG_DASH_DOT_DOT, + 'weight' => 10, + 'color' => 'red' + ); + foreach ($properties as $key => $value) { + $set = "set{$key}"; + $get = "get{$key}"; + $object->$set($value); + $this->assertEquals($value, $object->$get()); + } + } + + /** + * Test setStyleValue method + */ + public function testSetStyleValue() + { + $object = new Line(); + + $properties = array( + 'connectorType' => \PhpOffice\PhpWord\Style\Line::CONNECTOR_TYPE_STRAIGHT, + 'beginArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_BLOCK, + 'endArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_OVAL, + 'dash' => \PhpOffice\PhpWord\Style\Line::DASH_STYLE_LONG_DASH_DOT_DOT, + 'weight' => 10, + 'color' => 'red' + ); + foreach ($properties as $key => $value) { + $get = "get{$key}"; + $object->setStyleValue("{$key}", $value); + $this->assertEquals($value, $object->$get()); + } + } + + /** + * Test set/get flip + */ + public function testSetGetFlip() + { + $expected=true; + $object = new Line(); + $object->setFlip($expected); + $this->assertEquals($expected, $object->isFlip()); + } + + /** + * Test set/get connectorType + */ + public function testSetGetConnectorType() + { + $expected=\PhpOffice\PhpWord\Style\Line::CONNECTOR_TYPE_STRAIGHT; + $object = new Line(); + $object->setConnectorType($expected); + $this->assertEquals($expected, $object->getConnectorType()); + } + + /** + * Test set/get weight + */ + public function testSetGetWeight() + { + $expected=10; + $object = new Line(); + $object->setWeight($expected); + $this->assertEquals($expected, $object->getWeight()); + } + + /** + * Test set/get color + */ + public function testSetGetColor() + { + $expected='red'; + $object = new Line(); + $object->setColor($expected); + $this->assertEquals($expected, $object->getColor()); + } + + /** + * Test set/get dash + */ + public function testSetGetDash() + { + $expected=\PhpOffice\PhpWord\Style\Line::DASH_STYLE_LONG_DASH_DOT_DOT; + $object = new Line(); + $object->setDash($expected); + $this->assertEquals($expected, $object->getDash()); + } + + /** + * Test set/get beginArrow + */ + public function testSetGetBeginArrow() + { + $expected=\PhpOffice\PhpWord\Style\Line::ARROW_STYLE_BLOCK; + $object = new Line(); + $object->setBeginArrow($expected); + $this->assertEquals($expected, $object->getBeginArrow()); + } + + /** + * Test set/get endArrow + */ + public function testSetGetEndArrow() + { + $expected=\PhpOffice\PhpWord\Style\Line::ARROW_STYLE_CLASSIC; + $object = new Line(); + $object->setEndArrow($expected); + $this->assertEquals($expected, $object->getEndArrow()); + } +} diff --git a/tests/PhpWord/Tests/Style/ListItemTest.php b/tests/PhpWord/Tests/Style/ListItemTest.php index 6eef720c..a97c8dd6 100644 --- a/tests/PhpWord/Tests/Style/ListItemTest.php +++ b/tests/PhpWord/Tests/Style/ListItemTest.php @@ -1,10 +1,18 @@ 1, 'format' => 'decimal', 'restart' => 1, + 'pStyle' => 'pStyle', 'suffix' => 'space', 'text' => '%1.', 'align' => 'left', diff --git a/tests/PhpWord/Tests/Style/NumberingTest.php b/tests/PhpWord/Tests/Style/NumberingTest.php new file mode 100644 index 00000000..e1575357 --- /dev/null +++ b/tests/PhpWord/Tests/Style/NumberingTest.php @@ -0,0 +1,61 @@ +object = new Numbering(); + $this->properties = array( + 'numId' => array(null, 1), + 'type' => array(null, 'singleLevel'), + ); + foreach ($this->properties as $property => $value) { + list($default, $expected) = $value; + $get = "get{$property}"; + $set = "set{$property}"; + + $this->assertEquals($default, $this->object->$get()); // Default value + + $this->object->$set($expected); + + $this->assertEquals($expected, $this->object->$get()); // New value + } + } + + /** + * Test get level + */ + public function testGetLevels() + { + $this->object = new Numbering(); + + $this->assertEmpty($this->object->getLevels()); + } +} diff --git a/tests/PhpWord/Tests/Style/ParagraphTest.php b/tests/PhpWord/Tests/Style/ParagraphTest.php index 690e34e1..12aa51ce 100644 --- a/tests/PhpWord/Tests/Style/ParagraphTest.php +++ b/tests/PhpWord/Tests/Style/ParagraphTest.php @@ -1,10 +1,18 @@ 120, 'basedOn' => 'Normal', 'next' => 'Normal', + 'numStyle' => 'numStyle', + 'numLevel' => 1, 'widowControl' => false, 'keepNext' => true, 'keepLines' => true, @@ -88,6 +98,20 @@ class ParagraphTest extends \PHPUnit_Framework_TestCase } } + /** + * Test get null style value + */ + public function testGetNullStyleValue() + { + $object = new Paragraph(); + + $attributes = array('spacing', 'indent', 'hanging', 'spaceBefore', 'spaceAfter'); + foreach ($attributes as $key) { + $get = "get{$key}"; + $this->assertNull($object->$get()); + } + } + /** * Test tabs */ diff --git a/tests/PhpWord/Tests/Style/RowTest.php b/tests/PhpWord/Tests/Style/RowTest.php index ad193f80..679e9982 100644 --- a/tests/PhpWord/Tests/Style/RowTest.php +++ b/tests/PhpWord/Tests/Style/RowTest.php @@ -1,10 +1,18 @@ assertEquals($iVal, $oSettings->getHeaderHeight()); $oSettings->setSettingValue('lineNumbering', array()); - $oSettings->setSettingValue('lineNumbering', array('start' => 1, 'increment' => 1, 'distance' => 240, 'restart' => 'newPage')); + $oSettings->setSettingValue('lineNumbering', array('start' => 1, 'increment' => 1, + 'distance' => 240, 'restart' => 'newPage')); $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\LineNumbering', $oSettings->getLineNumbering()); $oSettings->setSettingValue('lineNumbering', null); @@ -240,12 +249,14 @@ class SettingsTest extends \PHPUnit_Framework_TestCase // Default $this->assertEquals(1, $oSettings->getColsNum()); + // Null value + $oSettings->setColsNum(); + $this->assertEquals(1, $oSettings->getColsNum()); + + // Random value $iVal = rand(1, 1000); $oSettings->setColsNum($iVal); $this->assertEquals($iVal, $oSettings->getColsNum()); - - $oSettings->setColsNum(); - $this->assertEquals(1, $oSettings->getColsNum()); } /** diff --git a/tests/PhpWord/Tests/Style/ShadingTest.php b/tests/PhpWord/Tests/Style/ShadingTest.php new file mode 100644 index 00000000..5a965e1d --- /dev/null +++ b/tests/PhpWord/Tests/Style/ShadingTest.php @@ -0,0 +1,52 @@ + array('clear', 'solid'), + 'color' => array(null, 'FF0000'), + 'fill' => array(null, 'FF0000'), + ); + foreach ($properties as $property => $value) { + list($default, $expected) = $value; + $get = "get{$property}"; + $set = "set{$property}"; + + $this->assertEquals($default, $object->$get()); // Default value + + $object->$set($expected); + + $this->assertEquals($expected, $object->$get()); // New value + } + } +} diff --git a/tests/PhpWord/Tests/Style/SpacingTest.php b/tests/PhpWord/Tests/Style/SpacingTest.php new file mode 100644 index 00000000..a4022b74 --- /dev/null +++ b/tests/PhpWord/Tests/Style/SpacingTest.php @@ -0,0 +1,53 @@ + array(null, 10), + 'after' => array(null, 10), + 'line' => array(null, 10), + 'rule' => array('auto', 'exact'), + ); + foreach ($properties as $property => $value) { + list($default, $expected) = $value; + $get = "get{$property}"; + $set = "set{$property}"; + + $this->assertEquals($default, $object->$get()); // Default value + + $object->$set($expected); + + $this->assertEquals($expected, $object->$get()); // New value + } + } +} diff --git a/tests/PhpWord/Tests/Style/TOCTest.php b/tests/PhpWord/Tests/Style/TOCTest.php index 2c10de8d..e6e32e6b 100644 --- a/tests/PhpWord/Tests/Style/TOCTest.php +++ b/tests/PhpWord/Tests/Style/TOCTest.php @@ -1,10 +1,18 @@ 9062, - 'tabLeader' => TOC::TABLEADER_DOT, - 'indent' => 200, + 'tabLeader' => array(TOC::TAB_LEADER_DOT, TOC::TAB_LEADER_UNDERSCORE), + 'tabPos' => array(9062, 10), + 'indent' => array(200, 10), ); - foreach ($properties as $key => $value) { - // set/get - $set = "set{$key}"; - $get = "get{$key}"; - $object->$set($value); - $this->assertEquals($value, $object->$get()); + foreach ($properties as $property => $value) { + list($default, $expected) = $value; + $get = "get{$property}"; + $set = "set{$property}"; - // setStyleValue - $object->setStyleValue("{$key}", null); - $this->assertEquals(null, $object->$get()); + $this->assertEquals($default, $object->$get()); // Default value + + $object->$set($expected); + + $this->assertEquals($expected, $object->$get()); // New value } } } diff --git a/tests/PhpWord/Tests/Style/TabTest.php b/tests/PhpWord/Tests/Style/TabTest.php new file mode 100644 index 00000000..784b4e47 --- /dev/null +++ b/tests/PhpWord/Tests/Style/TabTest.php @@ -0,0 +1,52 @@ + array(Tab::TAB_STOP_CLEAR, Tab::TAB_STOP_RIGHT), + 'leader' => array(Tab::TAB_LEADER_NONE, Tab::TAB_LEADER_DOT), + 'position' => array(0, 10), + ); + foreach ($properties as $property => $value) { + list($default, $expected) = $value; + $get = "get{$property}"; + $set = "set{$property}"; + + $this->assertEquals($default, $object->$get()); // Default value + + $object->$set($expected); + + $this->assertEquals($expected, $object->$get()); // New value + } + } +} diff --git a/tests/PhpWord/Tests/Style/TableTest.php b/tests/PhpWord/Tests/Style/TableTest.php index e5c3ab66..2afbab74 100644 --- a/tests/PhpWord/Tests/Style/TableTest.php +++ b/tests/PhpWord/Tests/Style/TableTest.php @@ -1,10 +1,18 @@ 'FF0000'); $styleFirstRow = array('borderBottomSize' => 3); + $object = new Table(); + $this->assertNull($object->getBgColor()); + $object = new Table($styleTable, $styleFirstRow); $this->assertEquals('FF0000', $object->getBgColor()); @@ -63,6 +74,9 @@ class TableTest extends \PHPUnit_Framework_TestCase 'cellMarginLeft' => 240, 'cellMarginRight' => 240, 'cellMarginBottom' => 240, + 'align' => 'center', + 'width' => 100, + 'unit' => 'pct', ); foreach ($attributes as $key => $value) { $set = "set{$key}"; @@ -135,6 +149,7 @@ class TableTest extends \PHPUnit_Framework_TestCase $this->assertEquals($value, $object->$get()); } $this->assertEquals($values, $object->getCellMargin()); + $this->assertTrue($object->hasMargin()); } /** diff --git a/tests/PhpWord/Tests/Style/TabsTest.php b/tests/PhpWord/Tests/Style/TabsTest.php deleted file mode 100644 index 26ee41d0..00000000 --- a/tests/PhpWord/Tests/Style/TabsTest.php +++ /dev/null @@ -1,47 +0,0 @@ -addParagraphStyle('tabbed', array('tabs' => array(new Tab('left', 1440, 'dot')))); - $doc = TestHelperDOCX::getDocument($phpWord); - $file = 'word/styles.xml'; - $path = '/w:styles/w:style[@w:styleId="tabbed"]/w:pPr/w:tabs/w:tab[1]'; - $element = $doc->getElement($path, $file); - $this->assertEquals('left', $element->getAttribute('w:val')); - $this->assertEquals(1440, $element->getAttribute('w:pos')); - $this->assertEquals('dot', $element->getAttribute('w:leader')); - } -} diff --git a/tests/PhpWord/Tests/Style/TextBoxTest.php b/tests/PhpWord/Tests/Style/TextBoxTest.php new file mode 100644 index 00000000..cd2d8695 --- /dev/null +++ b/tests/PhpWord/Tests/Style/TextBoxTest.php @@ -0,0 +1,305 @@ + 200, + 'height' => 200, + 'align' => 'left', + 'marginTop' => 240, + 'marginLeft' => 240, + 'wrappingStyle' => 'inline', + 'positioning' => 'absolute', + 'posHorizontal' => 'center', + 'posVertical' => 'top', + 'posHorizontalRel' => 'margin', + 'posVerticalRel' => 'page', + 'innerMarginTop' => '5', + 'innerMarginRight' => '5', + 'innerMarginBottom' => '5', + 'innerMarginLeft' => '5', + 'borderSize' => '2', + 'borderColor' => 'red' + ); + foreach ($properties as $key => $value) { + $set = "set{$key}"; + $get = "get{$key}"; + $object->$set($value); + $this->assertEquals($value, $object->$get()); + } + } + + /** + * Test setStyleValue method + */ + public function testSetStyleValue() + { + $object = new TextBox(); + + $properties = array( + 'width' => 200, + 'height' => 200, + 'align' => 'left', + 'marginTop' => 240, + 'marginLeft' => 240, + 'wrappingStyle' => 'inline', + 'positioning' => 'absolute', + 'posHorizontal' => 'center', + 'posVertical' => 'top', + 'posHorizontalRel' => 'margin', + 'posVerticalRel' => 'page', + 'innerMarginTop' => '5', + 'innerMarginRight' => '5', + 'innerMarginBottom' => '5', + 'innerMarginLeft' => '5', + 'borderSize' => '2', + 'borderColor' => 'red' + ); + foreach ($properties as $key => $value) { + $get = "get{$key}"; + $object->setStyleValue("{$key}", $value); + $this->assertEquals($value, $object->$get()); + } + } + + /** + * Test setWrappingStyle exception + * + * @expectedException \InvalidArgumentException + */ + public function testSetWrappingStyleException() + { + $object = new TextBox(); + $object->setWrappingStyle('foo'); + } + + /** + * Test set/get width + */ + public function testSetGetWidth() + { + $expected=200; + $object = new TextBox(); + $object->setWidth($expected); + $this->assertEquals($expected, $object->getWidth()); + } + + /** + * Test set/get height + */ + public function testSetGetHeight() + { + $expected=200; + $object = new TextBox(); + $object->setHeight($expected); + $this->assertEquals($expected, $object->getHeight()); + } + + /** + * Test set/get height + */ + public function testSetGetAlign() + { + $expected='left'; + $object = new TextBox(); + $object->setAlign($expected); + $this->assertEquals($expected, $object->getAlign()); + } + + /** + * Test set/get marginTop + */ + public function testSetGetMarginTop() + { + $expected=5; + $object = new TextBox(); + $object->setMarginTop($expected); + $this->assertEquals($expected, $object->getMarginTop()); + } + + /** + * Test set/get marginLeft + */ + public function testSetGetMarginLeft() + { + $expected=5; + $object = new TextBox(); + $object->setMarginLeft($expected); + $this->assertEquals($expected, $object->getMarginLeft()); + } + /** + * Test set/get innerMarginTop + */ + public function testSetGetInnerMarginTop() + { + $expected=5; + $object = new TextBox(); + $object->setInnerMarginTop($expected); + $this->assertEquals($expected, $object->getInnerMarginTop()); + } + + /** + * Test set/get wrappingStyle + */ + public function testSetGetWrappingStyle() + { + $expected='inline'; + $object = new TextBox(); + $object->setWrappingStyle($expected); + $this->assertEquals($expected, $object->getWrappingStyle()); + } + + /** + * Test set/get positioning + */ + public function testSetGetPositioning() + { + $expected='absolute'; + $object = new TextBox(); + $object->setPositioning($expected); + $this->assertEquals($expected, $object->getPositioning()); + } + + /** + * Test set/get posHorizontal + */ + public function testSetGetPosHorizontal() + { + $expected='center'; + $object = new TextBox(); + $object->setPosHorizontal($expected); + $this->assertEquals($expected, $object->getPosHorizontal()); + } + + /** + * Test set/get posVertical + */ + public function testSetGetPosVertical() + { + $expected='top'; + $object = new TextBox(); + $object->setPosVertical($expected); + $this->assertEquals($expected, $object->getPosVertical()); + } + + /** + * Test set/get posHorizontalRel + */ + public function testSetGetPosHorizontalRel() + { + $expected='margin'; + $object = new TextBox(); + $object->setPosHorizontalRel($expected); + $this->assertEquals($expected, $object->getPosHorizontalRel()); + } + + /** + * Test set/get posVerticalRel + */ + public function testSetGetPosVerticalRel() + { + $expected='page'; + $object = new TextBox(); + $object->setPosVerticalRel($expected); + $this->assertEquals($expected, $object->getPosVerticalRel()); + } + + + /** + * Test set/get innerMarginRight + */ + public function testSetGetInnerMarginRight() + { + $expected=5; + $object = new TextBox(); + $object->setInnerMarginRight($expected); + $this->assertEquals($expected, $object->getInnerMarginRight()); + } + + /** + * Test set/get innerMarginBottom + */ + public function testSetGetInnerMarginBottom() + { + $expected=5; + $object = new TextBox(); + $object->setInnerMarginBottom($expected); + $this->assertEquals($expected, $object->getInnerMarginBottom()); + } + + /** + * Test set/get innerMarginLeft + */ + public function testSetGetInnerMarginLeft() + { + $expected=5; + $object = new TextBox(); + $object->setInnerMarginLeft($expected); + $this->assertEquals($expected, $object->getInnerMarginLeft()); + } + + /** + * Test set/get innerMarginLeft + */ + public function testSetGetInnerMargin() + { + $expected=5; + $object = new TextBox(); + $object->setInnerMargin($expected); + $this->assertEquals(array($expected, $expected, $expected, $expected), $object->getInnerMargin()); + } + + /** + * Test set/get borderSize + */ + public function testSetGetBorderSize() + { + $expected=2; + $object = new TextBox(); + $object->setBorderSize($expected); + $this->assertEquals($expected, $object->getBorderSize()); + } + + /** + * Test set/get borderColor + */ + public function testSetGetBorderColor() + { + $expected='red'; + $object = new TextBox(); + $object->setBorderColor($expected); + $this->assertEquals($expected, $object->getBorderColor()); + } +} diff --git a/tests/PhpWord/Tests/StyleTest.php b/tests/PhpWord/Tests/StyleTest.php index 4ace72b6..f446ecdf 100644 --- a/tests/PhpWord/Tests/StyleTest.php +++ b/tests/PhpWord/Tests/StyleTest.php @@ -1,10 +1,18 @@ 1, - 'Heading 2' => 2, - 'Heading 3' => 3, - ); - $toc = new TOC(); - - foreach ($titles as $text => $depth) { - $response = $toc->addTitle($text, $depth); - } - $this->assertEquals($anchor, $response[0]); - $this->assertEquals($bookmark, $response[1]); - - $i = 0; - $savedTitles = $toc->getTitles(); - foreach ($titles as $text => $depth) { - $this->assertEquals($text, $savedTitles[$i]['text']); - $this->assertEquals($depth, $savedTitles[$i]['depth']); - $i++; - } - - TOC::resetTitles(); - $this->assertEquals(0, count($toc->getTitles())); - } -} diff --git a/tests/PhpWord/Tests/TemplateTest.php b/tests/PhpWord/Tests/TemplateTest.php index f99ce294..57ee229e 100644 --- a/tests/PhpWord/Tests/TemplateTest.php +++ b/tests/PhpWord/Tests/TemplateTest.php @@ -1,15 +1,22 @@ assertEquals('', $object->write()); + } + } + + /** + * Test write element text + */ + public function testWriteTextElement() + { + $object = new Text(new HTML(), new TextElement('A')); + $object->setOpeningText('-'); + $object->setClosingText('-'); + $object->setWithoutP(true); + + $this->assertEquals('-A-', $object->write()); + } +} diff --git a/tests/PhpWord/Tests/Writer/HTML/PartTest.php b/tests/PhpWord/Tests/Writer/HTML/PartTest.php new file mode 100644 index 00000000..93e9a98e --- /dev/null +++ b/tests/PhpWord/Tests/Writer/HTML/PartTest.php @@ -0,0 +1,36 @@ +getParentWriter(); + } +} diff --git a/tests/PhpWord/Tests/Writer/HTML/StyleTest.php b/tests/PhpWord/Tests/Writer/HTML/StyleTest.php new file mode 100644 index 00000000..8af1e479 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/HTML/StyleTest.php @@ -0,0 +1,39 @@ +assertEquals('', $object->write()); + } + } +} diff --git a/tests/PhpWord/Tests/Writer/HTMLTest.php b/tests/PhpWord/Tests/Writer/HTMLTest.php index 265c4f6b..f9b8e6ba 100644 --- a/tests/PhpWord/Tests/Writer/HTMLTest.php +++ b/tests/PhpWord/Tests/Writer/HTMLTest.php @@ -1,10 +1,18 @@ getDocumentProperties(); $docProps->setTitle('HTML Test'); - $phpWord->addFontStyle('Font', array('name' => 'Verdana', 'size' => 11, 'color' => 'FF0000', 'fgColor' => 'FF0000')); - $phpWord->addParagraphStyle('Paragraph', array('align' => 'center')); + $phpWord->addTitleStyle(1, array('bold' => true)); + $phpWord->addFontStyle('Font', array('name' => 'Verdana', 'size' => 11, + 'color' => 'FF0000', 'fgColor' => 'FF0000')); + $phpWord->addParagraphStyle('Paragraph', array('align' => 'center', 'spaceAfter' => 20, 'spaceBefore' => 20)); $section = $phpWord->addSection(); $section->addText('Test 1', 'Font', 'Paragraph'); $section->addTextBreak(); @@ -82,8 +92,8 @@ class HTMLTest extends \PHPUnit_Framework_TestCase $textrun = $section->addTextRun('Paragraph'); $textrun->addLink('http://test.com'); $textrun->addImage($localImage); - $textrun->addFootnote(); - $textrun->addEndnote(); + $textrun->addFootnote()->addText('Footnote'); + $textrun->addEndnote()->addText('Endnote'); $section = $phpWord->addSection(); diff --git a/tests/PhpWord/Tests/Writer/ODText/ElementTest.php b/tests/PhpWord/Tests/Writer/ODText/ElementTest.php new file mode 100644 index 00000000..fa9532d1 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/ODText/ElementTest.php @@ -0,0 +1,42 @@ +write(); + + $this->assertEquals('', $xmlWriter->getData()); + } + } +} diff --git a/tests/PhpWord/Tests/Writer/ODText/Part/AbstractPartTest.php b/tests/PhpWord/Tests/Writer/ODText/Part/AbstractPartTest.php index bde6b413..92fab26f 100644 --- a/tests/PhpWord/Tests/Writer/ODText/Part/AbstractPartTest.php +++ b/tests/PhpWord/Tests/Writer/ODText/Part/AbstractPartTest.php @@ -1,10 +1,18 @@ writeContent(); - } - /** * Test write content */ @@ -51,11 +47,15 @@ class ContentTest extends \PHPUnit_Framework_TestCase $phpWord = new PhpWord(); + $docProps = $phpWord->getDocumentProperties(); + $docProps->setCustomProperty('Company', 'PHPWord'); + $phpWord->setDefaultFontName('Verdana'); $phpWord->addFontStyle('Font', array('size' => 11)); $phpWord->addParagraphStyle('Paragraph', array('align' => 'center')); + $phpWord->addTableStyle('tblStyle', array('width' => 100)); - $section = $phpWord->addSection(); + $section = $phpWord->addSection(array('colsNum' => 2)); $section->addText($expected); $section->addText('Test font style', 'Font'); $section->addText('Test paragraph style', null, 'Paragraph'); @@ -64,14 +64,14 @@ class ContentTest extends \PHPUnit_Framework_TestCase $section->addTextBreak(); $section->addPageBreak(); $section->addListItem('Test list item'); - $section->addImage($imageSrc); + $section->addImage($imageSrc, array('width' => 50)); $section->addObject($objectSrc); $section->addTOC(); $textrun = $section->addTextRun(); $textrun->addText('Test text run'); - $table = $section->addTable(); + $table = $section->addTable(array('width' => 50)); $cell = $table->addRow()->addCell(); $cell = $table->addRow()->addCell(); $cell->addText('Test'); @@ -86,9 +86,11 @@ class ContentTest extends \PHPUnit_Framework_TestCase $footer = $section->addFooter(); $footer->addPreserveText('{PAGE}'); + $table = $section->addTable('tblStyle')->addRow()->addCell(); + $doc = TestHelperDOCX::getDocument($phpWord, 'ODText'); - $element = "/office:document-content/office:body/office:text/text:p"; + $element = "/office:document-content/office:body/office:text/text:section/text:p"; $this->assertEquals($expected, $doc->getElement($element, 'content.xml')->nodeValue); } diff --git a/tests/PhpWord/Tests/Writer/ODText/Part/MetaTest.php b/tests/PhpWord/Tests/Writer/ODText/Part/MetaTest.php deleted file mode 100644 index fde04579..00000000 --- a/tests/PhpWord/Tests/Writer/ODText/Part/MetaTest.php +++ /dev/null @@ -1,32 +0,0 @@ -writeMeta(); - } -} diff --git a/tests/PhpWord/Tests/Writer/ODText/Part/StylesTest.php b/tests/PhpWord/Tests/Writer/ODText/Part/StylesTest.php deleted file mode 100644 index 556bc804..00000000 --- a/tests/PhpWord/Tests/Writer/ODText/Part/StylesTest.php +++ /dev/null @@ -1,32 +0,0 @@ -writeStyles(); - } -} diff --git a/tests/PhpWord/Tests/Writer/ODText/StyleTest.php b/tests/PhpWord/Tests/Writer/ODText/StyleTest.php new file mode 100644 index 00000000..cd5ea0eb --- /dev/null +++ b/tests/PhpWord/Tests/Writer/ODText/StyleTest.php @@ -0,0 +1,41 @@ +write(); + + $this->assertEquals('', $xmlWriter->getData()); + } + } +} diff --git a/tests/PhpWord/Tests/Writer/ODTextTest.php b/tests/PhpWord/Tests/Writer/ODTextTest.php index b02c3f9f..25b8095b 100644 --- a/tests/PhpWord/Tests/Writer/ODTextTest.php +++ b/tests/PhpWord/Tests/Writer/ODTextTest.php @@ -1,10 +1,18 @@ addLink('http://test.com'); $section->addTitle('Test', 1); $section->addPageBreak(); - $section->addTable(); + $section->addTable()->addRow()->addCell()->addText('Test'); $section->addListItem('Test'); $section->addImage($imageSrc); $section->addObject($objectSrc); @@ -101,18 +109,6 @@ class ODTextTest extends \PHPUnit_Framework_TestCase $writer->save('php://output'); } - /** - * Save with no PhpWord object assigned - * - * @expectedException \PhpOffice\PhpWord\Exception\Exception - * @expectedExceptionMessage PhpWord object unassigned. - */ - public function testSaveException() - { - $writer = new ODText(); - $writer->save(); - } - /** * Get writer part return null value */ @@ -129,7 +125,7 @@ class ODTextTest extends \PHPUnit_Framework_TestCase { $object = new ODText(); $object->setUseDiskCaching(true, PHPWORD_TESTS_BASE_DIR); - $this->assertTrue($object->getUseDiskCaching()); + $this->assertTrue($object->isUseDiskCaching()); $this->assertEquals(PHPWORD_TESTS_BASE_DIR, $object->getDiskCachingDirectory()); } diff --git a/tests/PhpWord/Tests/Writer/PDF/DomPDFTest.php b/tests/PhpWord/Tests/Writer/PDF/DomPDFTest.php index 3282eecb..a22cb530 100644 --- a/tests/PhpWord/Tests/Writer/PDF/DomPDFTest.php +++ b/tests/PhpWord/Tests/Writer/PDF/DomPDFTest.php @@ -1,10 +1,18 @@ addSection(); @@ -48,7 +56,6 @@ class DomPDFTest extends \PHPUnit_Framework_TestCase public function testSetGetAbstractRendererProperties() { define('DOMPDF_ENABLE_AUTOLOAD', false); - $file = __DIR__ . "/../../_files/temp.pdf"; $rendererName = Settings::PDF_RENDERER_DOMPDF; $rendererLibraryPath = realpath(PHPWORD_TESTS_BASE_DIR . '/../vendor/dompdf/dompdf'); diff --git a/tests/PhpWord/Tests/Writer/PDF/MPDFTest.php b/tests/PhpWord/Tests/Writer/PDF/MPDFTest.php new file mode 100644 index 00000000..4728b7f1 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/PDF/MPDFTest.php @@ -0,0 +1,51 @@ +addSection(); + $section->addText('Test 1'); + + $rendererName = Settings::PDF_RENDERER_MPDF; + $rendererLibraryPath = realpath(PHPWORD_TESTS_BASE_DIR . '/../vendor/mpdf/mpdf'); + Settings::setPdfRenderer($rendererName, $rendererLibraryPath); + $writer = new PDF($phpWord); + $writer->save($file); + + $this->assertTrue(file_exists($file)); + + unlink($file); + } +} diff --git a/tests/PhpWord/Tests/Writer/PDF/TCPDFTest.php b/tests/PhpWord/Tests/Writer/PDF/TCPDFTest.php new file mode 100644 index 00000000..c73f0043 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/PDF/TCPDFTest.php @@ -0,0 +1,51 @@ +addSection(); + $section->addText('Test 1'); + + $rendererName = Settings::PDF_RENDERER_TCPDF; + $rendererLibraryPath = realpath(PHPWORD_TESTS_BASE_DIR . '/../vendor/tecnick.com/tcpdf'); + Settings::setPdfRenderer($rendererName, $rendererLibraryPath); + $writer = new PDF($phpWord); + $writer->save($file); + + $this->assertTrue(file_exists($file)); + + unlink($file); + } +} diff --git a/tests/PhpWord/Tests/Writer/PDFTest.php b/tests/PhpWord/Tests/Writer/PDFTest.php index fba93054..87814b41 100644 --- a/tests/PhpWord/Tests/Writer/PDFTest.php +++ b/tests/PhpWord/Tests/Writer/PDFTest.php @@ -1,10 +1,18 @@ save(); } } diff --git a/tests/PhpWord/Tests/Writer/RTF/ElementTest.php b/tests/PhpWord/Tests/Writer/RTF/ElementTest.php new file mode 100644 index 00000000..e090b349 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/RTF/ElementTest.php @@ -0,0 +1,41 @@ +assertEquals('', $object->write()); + } + } +} diff --git a/tests/PhpWord/Tests/Writer/RTF/StyleTest.php b/tests/PhpWord/Tests/Writer/RTF/StyleTest.php new file mode 100644 index 00000000..8b4a4441 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/RTF/StyleTest.php @@ -0,0 +1,39 @@ +assertEquals('', $object->write()); + } + } +} diff --git a/tests/PhpWord/Tests/Writer/RTFTest.php b/tests/PhpWord/Tests/Writer/RTFTest.php index 9cc7ed71..c1448106 100644 --- a/tests/PhpWord/Tests/Writer/RTFTest.php +++ b/tests/PhpWord/Tests/Writer/RTFTest.php @@ -1,10 +1,18 @@ addFontStyle('Font', array('name' => 'Verdana', 'size' => 11, 'color' => 'FF0000', 'fgColor' => 'FF0000')); + $phpWord->addFontStyle('Font', array('name' => 'Verdana', 'size' => 11, + 'color' => 'FF0000', 'fgColor' => '00FF00')); $phpWord->addParagraphStyle('Paragraph', array('align' => 'center')); $section = $phpWord->addSection(); $section->addText('Test 1', 'Font', 'Paragraph'); @@ -59,7 +68,16 @@ class RTFTest extends \PHPUnit_Framework_TestCase $section->addLink('http://test.com'); $section->addTitle('Test', 1); $section->addPageBreak(); - $section->addTable(); + + // Rowspan + $table = $section->addTable(); + $table->addRow()->addCell(null, array('vMerge' => 'restart'))->addText('Test'); + $table->addRow()->addCell(null, array('vMerge' => 'continue'))->addText('Test'); + + // Nested table + $cell = $section->addTable()->addRow()->addCell(); + $cell->addTable()->addRow()->addCell(); + $section->addListItem('Test'); $section->addImage($imageSrc); $section->addObject($objectSrc); @@ -89,16 +107,4 @@ class RTFTest extends \PHPUnit_Framework_TestCase $writer = new RTF($phpWord); $writer->save('php://output'); } - - /** - * Save with no PhpWord object assigned - * - * @expectedException \PhpOffice\PhpWord\Exception\Exception - * @expectedExceptionMessage PhpWord object unassigned. - */ - public function testSaveException() - { - $writer = new RTF(); - $writer->save(); - } } diff --git a/tests/PhpWord/Tests/Writer/Word2007/ElementTest.php b/tests/PhpWord/Tests/Writer/Word2007/ElementTest.php new file mode 100644 index 00000000..da7504b5 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/Word2007/ElementTest.php @@ -0,0 +1,70 @@ +write(); + + $this->assertEquals('', $xmlWriter->getData()); + } + } + + /** + * Test line element + */ + public function testLineElement() + { + $phpWord = new PhpWord(); + $section = $phpWord->addSection(); + $section->addLine(array('width' => 1000, 'height' => 1000, 'positioning' => 'absolute', 'flip' => true)); + $doc = TestHelperDOCX::getDocument($phpWord); + + $element = "/w:document/w:body/w:p/w:r/w:pict/v:shapetype"; + $this->assertTrue($doc->elementExists($element)); + } +} diff --git a/tests/PhpWord/Tests/Writer/Word2007/Part/AbstractPartTest.php b/tests/PhpWord/Tests/Writer/Word2007/Part/AbstractPartTest.php index 81786b14..2ff80ab8 100644 --- a/tests/PhpWord/Tests/Writer/Word2007/Part/AbstractPartTest.php +++ b/tests/PhpWord/Tests/Writer/Word2007/Part/AbstractPartTest.php @@ -1,10 +1,18 @@ writeDocPropsApp(); - } - - /** - * Test write docProps/core.xml with no PhpWord - * - * @expectedException \PhpOffice\PhpWord\Exception\Exception - * @expectedExceptionMessage No PhpWord assigned. - */ - public function testWriteDocPropsCoreNoPhpWord() - { - $object = new DocProps(); - $object->writeDocPropsCore(); - } -} diff --git a/tests/PhpWord/Tests/Writer/Word2007/Part/DocumentTest.php b/tests/PhpWord/Tests/Writer/Word2007/Part/DocumentTest.php index 0cc4895d..e27d072a 100644 --- a/tests/PhpWord/Tests/Writer/Word2007/Part/DocumentTest.php +++ b/tests/PhpWord/Tests/Writer/Word2007/Part/DocumentTest.php @@ -1,10 +1,18 @@ writeDocument(); - } - /** * Write end section page numbering */ @@ -47,6 +43,8 @@ class DocumentTest extends \PHPUnit_Framework_TestCase { $phpWord = new PhpWord(); $section = $phpWord->addSection(); + $section->addHeader(); + $section->addHeader('first'); $settings = $section->getSettings(); $settings->setLandscape(); $settings->setPageNumberingStart(2); @@ -72,13 +70,37 @@ class DocumentTest extends \PHPUnit_Framework_TestCase $section = $phpWord->addSection(); $section->addTOC(); $section->addPageBreak(); + $section->addText('After page break.'); $section->addTitle('Title 1', 1); $section->addListItem('List Item 1', 0); $section->addListItem('List Item 2', 0); $section->addListItem('List Item 3', 0); + $section = $phpWord->addSection(); $section->addTitle('Title 2', 2); $section->addObject($objectSrc); + $section->addTextBox(array()); + $section->addTextBox(array('wrappingStyle' => 'square', 'positioning' => 'relative', + 'posHorizontalRel' => 'margin', 'posVerticalRel' => 'margin', + 'innerMargin' => 10, 'borderSize' => 1, 'borderColor' => '#FF0')); + $section->addTextBox(array('wrappingStyle' => 'tight', 'positioning' => 'absolute', 'align' => 'center')); + $section->addListItemRun()->addText('List item run 1'); + $section->addField('DATE', array('dateformat'=>'dddd d MMMM yyyy H:mm:ss'), array('PreserveFormat', 'LunarCalendar')); + $section->addField('DATE', array('dateformat'=>'dddd d MMMM yyyy H:mm:ss'), array('PreserveFormat', 'SakaEraCalendar')); + $section->addField('DATE', array('dateformat'=>'dddd d MMMM yyyy H:mm:ss'), array('PreserveFormat', 'LastUsedFormat')); + $section->addField('PAGE', array('format'=>'ArabicDash')); + $section->addLine( + array( + 'width' => 10, + 'height' => 10, + 'positioning' => 'absolute', + 'beginArrow' => 'block', + 'endArrow' => 'open', + 'dash' => 'rounddot', + 'weight' => 10 + ) + ); + $doc = TestHelperDOCX::getDocument($phpWord); // TOC @@ -111,22 +133,27 @@ class DocumentTest extends \PHPUnit_Framework_TestCase { $objectSrc = __DIR__ . "/../../../_files/documents/sheet.xls"; + $tabs = array(new \PhpOffice\PhpWord\Style\Tab('right', 9090)); $phpWord = new PhpWord(); - $phpWord->addParagraphStyle('pStyle', array('align' => 'center')); // Style #1 - $phpWord->addFontStyle('fStyle', array('size' => '20', 'doubleStrikethrough' => true, 'allCaps' => true)); // Style #2 - $phpWord->addTitleStyle(1, array('color' => '333333', 'bold' => true)); // Style #3 + $phpWord->addParagraphStyle('pStyle', array('align' => 'center', 'tabs' => $tabs)); // Style #1 + $phpWord->addFontStyle('fStyle', array('size' => '20', 'bold' => true, 'allCaps' => true)); // Style #2 + $phpWord->addTitleStyle(1, array('color' => '333333', 'doubleStrikethrough' => true)); // Style #3 + $phpWord->addTableStyle('tStyle', array('borderSize' => 1)); $fontStyle = new Font('text', array('align' => 'center')); + $section = $phpWord->addSection(); - $section->addListItem('List Item', 0, null, null, 'pStyle'); // Style #4 + $section->addListItem('List Item', 0, null, null, 'pStyle'); // Style #5 $section->addObject($objectSrc, array('align' => 'center')); $section->addTOC($fontStyle); $section->addTitle('Title 1', 1); $section->addTOC('fStyle'); + $table = $section->addTable('tStyle'); + $table->setWidth(100); $doc = TestHelperDOCX::getDocument($phpWord); // List item $element = $doc->getElement('/w:document/w:body/w:p[1]/w:pPr/w:numPr/w:numId'); - $this->assertEquals(4, $element->getAttribute('w:val')); + $this->assertEquals(5, $element->getAttribute('w:val')); // Object $element = $doc->getElement('/w:document/w:body/w:p[2]/w:r/w:object/o:OLEObject'); @@ -177,7 +204,7 @@ class DocumentTest extends \PHPUnit_Framework_TestCase $textrun->addTextBreak(); $textrun = $section->addTextRun($aStyle); $textrun->addLink('http://test.com'); - $textrun->addImage($imageSrc, array('align' => 'top')); + $textrun->addImage($imageSrc, array('align' => 'center')); $textrun->addFootnote(); $doc = TestHelperDOCX::getDocument($phpWord); @@ -317,8 +344,6 @@ class DocumentTest extends \PHPUnit_Framework_TestCase $element = "/w:document/w:body/w:p/w:pPr/w:pStyle"; $this->assertEquals('Heading1', $doc->getElementAttribute($element, 'w:val')); - $element = "/w:document/w:body/w:p/w:r/w:fldChar"; - $this->assertEquals('end', $doc->getElementAttribute($element, 'w:fldCharType')); } /** @@ -330,10 +355,10 @@ class DocumentTest extends \PHPUnit_Framework_TestCase $pStyle = 'pStyle'; $phpWord = new PhpWord(); - $phpWord->addFontStyle($rStyle, array('bold' => true)); - $phpWord->addParagraphStyle($pStyle, array('hanging' => 120, 'indent' => 120)); + // $phpWord->addFontStyle($rStyle, array('bold' => true)); + // $phpWord->addParagraphStyle($pStyle, array('hanging' => 120, 'indent' => 120)); $section = $phpWord->addSection(); - $section->addCheckbox('Check1', 'Test', $rStyle, $pStyle); + $section->addCheckBox('Check1', 'Test', $rStyle, $pStyle); $doc = TestHelperDOCX::getDocument($phpWord); $element = '/w:document/w:body/w:p/w:r/w:fldChar/w:ffData/w:name'; @@ -361,11 +386,11 @@ class DocumentTest extends \PHPUnit_Framework_TestCase $doc = TestHelperDOCX::getDocument($phpWord); // Test the attributes - $i = 0; + $attributeCount = 0; foreach ($attributes as $key => $value) { - $i++; + $attributeCount++; $nodeName = ($key == 'align') ? 'jc' : $key; - $path = "/w:document/w:body/w:p[{$i}]/w:pPr/w:{$nodeName}"; + $path = "/w:document/w:body/w:p[{$attributeCount}]/w:pPr/w:{$nodeName}"; if ($key != 'align') { $value = $value ? 1 : 0; } @@ -416,7 +441,6 @@ class DocumentTest extends \PHPUnit_Framework_TestCase public function testWriteTableStyle() { $phpWord = new PhpWord(); - $tWidth = 120; $rHeight = 120; $cWidth = 120; $imageSrc = __DIR__ . "/../../../_files/images/earth.jpg"; @@ -496,6 +520,10 @@ class DocumentTest extends \PHPUnit_Framework_TestCase $table->addCell(40); $table->addCell(40); + $table->addRow(); + $cell = $table->addCell(200, array('borderRightColor' => 'FF0000')); + $cell->getStyle()->setGridSpan(5); + $doc = TestHelperDOCX::getDocument($phpWord); $element = $doc->getElement('/w:document/w:body/w:tbl/w:tr/w:tc/w:tcPr/w:gridSpan'); @@ -511,7 +539,7 @@ class DocumentTest extends \PHPUnit_Framework_TestCase $lineNumberingPath = '/w:document/w:body/w:sectPr/w:lnNumType'; $phpWord = new PhpWord(); - $section = $phpWord->addSection(array('gutter' => 240, 'lineNumbering' => array())); + $phpWord->addSection(array('gutter' => 240, 'lineNumbering' => array())); $doc = TestHelperDOCX::getDocument($phpWord); $this->assertEquals(240, $doc->getElement($pageMarginPath)->getAttribute('w:gutter')); diff --git a/tests/PhpWord/Tests/Writer/Word2007/Part/FooterTest.php b/tests/PhpWord/Tests/Writer/Word2007/Part/FooterTest.php index 513d4d2c..5c9d2d30 100644 --- a/tests/PhpWord/Tests/Writer/Word2007/Part/FooterTest.php +++ b/tests/PhpWord/Tests/Writer/Word2007/Part/FooterTest.php @@ -1,16 +1,23 @@ addImage($imageSrc); $writer = new Word2007(); + $writer->setUseDiskCaching(true); $object = new Footer(); $object->setParentWriter($writer); - $object->writeFooter($container); - $writer->setUseDiskCaching(true); - $xml = simplexml_load_string($object->writeFooter($container)); + $object->setElement($container); + $xml = simplexml_load_string($object->write()); $this->assertInstanceOf('SimpleXMLElement', $xml); } diff --git a/tests/PhpWord/Tests/Writer/Word2007/Part/FootnotesTest.php b/tests/PhpWord/Tests/Writer/Word2007/Part/FootnotesTest.php index 3f9aaae7..d7a3d667 100644 --- a/tests/PhpWord/Tests/Writer/Word2007/Part/FootnotesTest.php +++ b/tests/PhpWord/Tests/Writer/Word2007/Part/FootnotesTest.php @@ -1,10 +1,18 @@ addWatermark($imageSrc); $writer = new Word2007(); + $writer->setUseDiskCaching(true); $object = new Header(); $object->setParentWriter($writer); - $object->writeHeader($container); - $writer->setUseDiskCaching(true); - $xml = simplexml_load_string($object->writeHeader($container)); + $object->setElement($container); + $xml = simplexml_load_string($object->write()); $this->assertInstanceOf('SimpleXMLElement', $xml); } diff --git a/tests/PhpWord/Tests/Writer/Word2007/Part/NumberingTest.php b/tests/PhpWord/Tests/Writer/Word2007/Part/NumberingTest.php index 8d76f016..ebc3aa2e 100644 --- a/tests/PhpWord/Tests/Writer/Word2007/Part/NumberingTest.php +++ b/tests/PhpWord/Tests/Writer/Word2007/Part/NumberingTest.php @@ -1,18 +1,23 @@ writeStyles(); - } - /** * Test write styles */ @@ -53,22 +49,19 @@ class StylesTest extends \PHPUnit_Framework_TestCase $rStyle = array('size' => 20); $tStyle = array( 'bgColor' => 'FF0000', - 'cellMarginTop' => 120, - 'cellMarginBottom' => 120, - 'cellMarginLeft' => 120, - 'cellMarginRight' => 120, - 'borderTopSize' => 120, - 'borderBottomSize' => 120, - 'borderLeftSize' => 120, - 'borderRightSize' => 120, - 'borderInsideHSize' => 120, - 'borderInsideVSize' => 120, + 'cellMargin' => 120, + 'borderSize' => 120, + ); + $firstRowStyle = array( + 'bgColor' => '0000FF', + 'borderSize' => 120, + 'borderColor' => '00FF00', ); $phpWord->setDefaultParagraphStyle($pStyle); $phpWord->addParagraphStyle('Base Style', $pBase); $phpWord->addParagraphStyle('New Style', $pNew); $phpWord->addFontStyle('New Style', $rStyle, $pStyle); - $phpWord->addTableStyle('Table Style', $tStyle, $tStyle); + $phpWord->addTableStyle('Table Style', $tStyle, $firstRowStyle); $phpWord->addTitleStyle(1, $rStyle, $pStyle); $doc = TestHelperDOCX::getDocument($phpWord); diff --git a/tests/PhpWord/Tests/Writer/Word2007/PartTest.php b/tests/PhpWord/Tests/Writer/Word2007/PartTest.php new file mode 100644 index 00000000..c3d29331 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/Word2007/PartTest.php @@ -0,0 +1,41 @@ +setMedia(array(array('type' => '', 'target' => ''))); + $object->write(); + } +} diff --git a/tests/PhpWord/Tests/Writer/Word2007/StyleTest.php b/tests/PhpWord/Tests/Writer/Word2007/StyleTest.php new file mode 100644 index 00000000..71cbc300 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/Word2007/StyleTest.php @@ -0,0 +1,64 @@ +write(); + + $this->assertEquals('', $xmlWriter->getData()); + } + } + + /** + * Test method exceptions + */ + public function testMethodExceptions() + { + $styles = array( + 'Image' => 'writeAlignment', + 'Line' => 'writeStroke', + ); + foreach ($styles as $style => $method) { + $objectClass = 'PhpOffice\\PhpWord\\Writer\\Word2007\\Style\\' . $style; + $xmlWriter = new XMLWriter(); + $object = new $objectClass($xmlWriter); + $object->$method(); + + $this->assertEquals('', $xmlWriter->getData()); + } + } +} diff --git a/tests/PhpWord/Tests/Writer/Word2007Test.php b/tests/PhpWord/Tests/Writer/Word2007Test.php index 74f3b1fd..db6e5cad 100644 --- a/tests/PhpWord/Tests/Writer/Word2007Test.php +++ b/tests/PhpWord/Tests/Writer/Word2007Test.php @@ -1,16 +1,24 @@ 'ContentTypes', 'Rels' => 'Rels', - 'DocProps' => 'DocProps', + 'DocPropsApp' => 'DocPropsApp', 'Document' => 'Document', 'Styles' => 'Styles', 'Numbering' => 'Numbering', @@ -114,18 +122,6 @@ class Word2007Test extends \PHPUnit_Framework_TestCase unlink($file); } - /** - * Save with no PhpWord object assigned - * - * @expectedException \PhpOffice\PhpWord\Exception\Exception - * @expectedExceptionMessage PhpWord object unassigned. - */ - public function testSaveException() - { - $writer = new Word2007(); - $writer->save(); - } - /** * Check content types */ @@ -171,13 +167,13 @@ class Word2007Test extends \PHPUnit_Framework_TestCase public function testSetGetUseDiskCaching() { $phpWord = new PhpWord(); - $section = $phpWord->addSection(); + $phpWord->addSection(); $object = new Word2007($phpWord); $object->setUseDiskCaching(true, PHPWORD_TESTS_BASE_DIR); $writer = new Word2007($phpWord); $writer->save('php://output'); - $this->assertTrue($object->getUseDiskCaching()); + $this->assertTrue($object->isUseDiskCaching()); } /** diff --git a/tests/PhpWord/Tests/_files/documents/reader.docx b/tests/PhpWord/Tests/_files/documents/reader.docx index 5f37ef4b..d09091b1 100644 Binary files a/tests/PhpWord/Tests/_files/documents/reader.docx and b/tests/PhpWord/Tests/_files/documents/reader.docx differ diff --git a/tests/PhpWord/Tests/_files/documents/reader.html b/tests/PhpWord/Tests/_files/documents/reader.html new file mode 100644 index 00000000..5593298b --- /dev/null +++ b/tests/PhpWord/Tests/_files/documents/reader.html @@ -0,0 +1,15 @@ + + + +PHPWord + + +

Adding element via HTML

+

Some well formed HTML snippet needs to be used

+

With for example some1 inline formatting1

+

Unordered (bulleted) list:

+
  • Item 1
  • Item 2
    • Item 2.1
    • Item 2.1
+

Ordered (numbered) list:

+
  1. Item 1
  2. Item 2
+ + diff --git a/tests/PhpWord/Tests/_files/documents/reader.odt b/tests/PhpWord/Tests/_files/documents/reader.odt index 9e18e619..d37c4e66 100644 Binary files a/tests/PhpWord/Tests/_files/documents/reader.odt and b/tests/PhpWord/Tests/_files/documents/reader.odt differ diff --git a/tests/PhpWord/Tests/_files/documents/reader.rtf b/tests/PhpWord/Tests/_files/documents/reader.rtf new file mode 100644 index 00000000..400f43a5 --- /dev/null +++ b/tests/PhpWord/Tests/_files/documents/reader.rtf @@ -0,0 +1,21 @@ +{\rtf1 +\ansi\ansicpg1252 +\deff0 +{\fonttbl{\f0\fnil\fcharset0 Arial;}{\f1\fnil\fcharset0 Times New Roman;}} +{\colortbl;\red255\green0\blue0;\red14\green0\blue0} +{\*\generator PhpWord;} + +{\info{\title }{\subject }{\category }{\keywords }{\comment }{\author }{\operator }{\creatim \yr2014\mo05\dy27\hr23\min36\sec45}{\revtim \yr2014\mo05\dy27\hr23\min36\sec45}{\company }{\manager }} +\deftab720\viewkind1\uc1\pard\nowidctlpar\lang1036\kerning1\fs20 +{Welcome to PhpWord}\par +\pard\nowidctlpar{\cf0\f0 Hello World!}\par +\par +\par +\pard\nowidctlpar{\cf0\f0\fs32\b\i I am styled by a definition.}\par +\pard\nowidctlpar{\cf0\f0 I am styled by a paragraph style definition.}\par +\pard\nowidctlpar\qc\sa100{\cf0\f0\fs32\b\i I am styled by both font and paragraph style.}\par +\pard\nowidctlpar{\cf1\f1\fs40\b\i\ul\strike\super I am inline styled.}\par +\par +{\field {\*\fldinst {HYPERLINK "http://www.google.com"}}{\fldrslt {Google}}}\par +\par +} \ No newline at end of file diff --git a/tests/PhpWord/Tests/_includes/TestHelperDOCX.php b/tests/PhpWord/Tests/_includes/TestHelperDOCX.php index bea0d037..7998cbdc 100644 --- a/tests/PhpWord/Tests/_includes/TestHelperDOCX.php +++ b/tests/PhpWord/Tests/_includes/TestHelperDOCX.php @@ -1,16 +1,24 @@