repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/de_CH/AddressTest.php | test/Faker/Provider/de_CH/AddressTest.php | <?php
namespace Faker\Test\Provider\de_CH;
use Faker\Generator;
use Faker\Provider\de_CH\Address;
use Faker\Provider\de_CH\Person;
use PHPUnit\Framework\TestCase;
final class AddressTest extends TestCase
{
/**
* @var Faker\Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Address($faker));
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
/**
* @test
*/
public function canton ()
{
$canton = $this->faker->canton();
$this->assertInternalType('array', $canton);
$this->assertCount(1, $canton);
foreach ($canton as $cantonShort => $cantonName){
$this->assertInternalType('string', $cantonShort);
$this->assertEquals(2, strlen($cantonShort));
$this->assertInternalType('string', $cantonName);
$this->assertGreaterThan(2, strlen($cantonName));
}
}
/**
* @test
*/
public function cantonName ()
{
$cantonName = $this->faker->cantonName();
$this->assertInternalType('string', $cantonName);
$this->assertGreaterThan(2, strlen($cantonName));
}
/**
* @test
*/
public function cantonShort ()
{
$cantonShort = $this->faker->cantonShort();
$this->assertInternalType('string', $cantonShort);
$this->assertEquals(2, strlen($cantonShort));
}
/**
* @test
*/
public function address ()
{
$address = $this->faker->address();
$this->assertInternalType('string', $address);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/de_CH/PhoneNumberTest.php | test/Faker/Provider/de_CH/PhoneNumberTest.php | <?php
namespace Faker\Test\Provider\de_CH;
use Faker\Generator;
use Faker\Provider\de_CH\PhoneNumber;
use PHPUnit\Framework\TestCase;
final class PhoneNumberTest extends TestCase
{
/**
* @var Faker\Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new PhoneNumber($faker));
$this->faker = $faker;
}
public function testPhoneNumber()
{
$this->assertRegExp('/^0\d{2} ?\d{3} ?\d{2} ?\d{2}|\+41 ?(\(0\))?\d{2} ?\d{3} ?\d{2} ?\d{2}$/', $this->faker->phoneNumber());
}
public function testMobileNumber()
{
$this->assertRegExp('/^07[56789] ?\d{3} ?\d{2} ?\d{2}$/', $this->faker->mobileNumber());
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/it_IT/PersonTest.php | test/Faker/Provider/it_IT/PersonTest.php | <?php
namespace Faker\Test\Provider\it_IT;
use Faker\Generator;
use Faker\Provider\it_IT\Person;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
public function testIfTaxIdCanReturnData()
{
$taxId = $this->faker->taxId();
$this->assertRegExp('/^[a-zA-Z]{6}[0-9]{2}[a-zA-Z][0-9]{2}[a-zA-Z][0-9]{3}[a-zA-Z]$/', $taxId);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/it_IT/CompanyTest.php | test/Faker/Provider/it_IT/CompanyTest.php | <?php
namespace Faker\Test\Provider\it_IT;
use Faker\Generator;
use Faker\Provider\it_IT\Company;
use PHPUnit\Framework\TestCase;
final class CompanyTest extends TestCase
{
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Company($faker));
$this->faker = $faker;
}
public function testIfTaxIdCanReturnData()
{
$vatId = $this->faker->vatId();
$this->assertRegExp('/^IT[0-9]{11}$/', $vatId);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_US/PersonTest.php | test/Faker/Provider/en_US/PersonTest.php | <?php
namespace Faker\Test\Provider\en_US;
use Faker\Provider\en_US\Person;
use Faker\Generator;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
public function testSsn()
{
for ($i = 0; $i < 100; $i++) {
$number = $this->faker->ssn;
// should be in the format ###-##-####
$this->assertRegExp('/^[0-9]{3}-[0-9]{2}-[0-9]{4}$/', $number);
$parts = explode("-", $number);
// first part must be between 001 and 899, excluding 666
$this->assertNotEquals(666, $parts[0]);
$this->assertGreaterThan(0, $parts[0]);
$this->assertLessThan(900, $parts[0]);
// second part must be between 01 and 99
$this->assertGreaterThan(0, $parts[1]);
$this->assertLessThan(100, $parts[1]);
// the third part must be between 0001 and 9999
$this->assertGreaterThan(0, $parts[2]);
$this->assertLessThan(10000, $parts[2]);
}
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_US/PaymentTest.php | test/Faker/Provider/en_US/PaymentTest.php | <?php
namespace Faker\Provider\en_US;
use Faker\Generator;
use PHPUnit\Framework\TestCase;
final class PaymentTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Payment($faker));
$this->faker = $faker;
}
public function testBankAccountNumber()
{
$accNo = $this->faker->bankAccountNumber;
$this->assertTrue(ctype_digit($accNo));
$this->assertLessThanOrEqual(17, strlen($accNo));
}
public function testBankRoutingNumber()
{
$routingNo = $this->faker->bankRoutingNumber;
$this->assertRegExp('/^\d{9}$/', $routingNo);
$this->assertEquals(Payment::calculateRoutingNumberChecksum($routingNo), $routingNo[8]);
}
public function routingNumberProvider()
{
return array(
array('122105155'),
array('082000549'),
array('121122676'),
array('122235821'),
array('102101645'),
array('102000021'),
array('123103729'),
array('071904779'),
array('081202759'),
array('074900783'),
array('104000029'),
array('073000545'),
array('101000187'),
array('042100175'),
array('083900363'),
array('091215927'),
array('091300023'),
array('091000022'),
array('081000210'),
array('101200453'),
array('092900383'),
array('104000029'),
array('121201694'),
array('107002312'),
array('091300023'),
array('041202582'),
array('042000013'),
array('123000220'),
array('091408501'),
array('064000059'),
array('124302150'),
array('125000105'),
array('075000022'),
array('307070115'),
array('091000022'),
);
}
/**
* @dataProvider routingNumberProvider
*/
public function testCalculateRoutingNumberChecksum($routingNo)
{
$this->assertEquals($routingNo[8], Payment::calculateRoutingNumberChecksum($routingNo), $routingNo);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_US/PhoneNumberTest.php | test/Faker/Provider/en_US/PhoneNumberTest.php | <?php
namespace Faker\Test\Provider\en_US;
use Faker\Generator;
use Faker\Provider\en_US\PhoneNumber;
use PHPUnit\Framework\TestCase;
final class PhoneNumberTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new PhoneNumber($faker));
$this->faker = $faker;
}
public function testPhoneNumber()
{
for ($i = 0; $i < 100; $i++) {
$number = $this->faker->phoneNumber;
$baseNumber = preg_replace('/ *x.*$/', '', $number); // Remove possible extension
$digits = array_values(array_filter(str_split($baseNumber), 'ctype_digit'));
// Prefix '1' allowed
if (count($digits) === 11) {
$this->assertEquals('1', $digits[0]);
$digits = array_slice($digits, 1);
}
// 10 digits
$this->assertCount(10, $digits);
// Last two digits of area code cannot be identical
$this->assertNotEquals($digits[1], $digits[2]);
// Last two digits of exchange code cannot be 1
if ($digits[4] === 1) {
$this->assertNotEquals($digits[4], $digits[5]);
}
// Test format
$this->assertRegExp('/^(\+?1)?([ -.]*\d{3}[ -.]*| *\(\d{3}\) *)\d{3}[-.]?\d{4}$/', $baseNumber);
}
}
public function testTollFreeAreaCode()
{
$this->assertContains($this->faker->tollFreeAreaCode, array(800, 822, 833, 844, 855, 866, 877, 888, 880, 887, 889));
}
public function testTollFreePhoneNumber()
{
for ($i = 0; $i < 100; $i++) {
$number = $this->faker->tollFreePhoneNumber;
$digits = array_values(array_filter(str_split($number), 'ctype_digit'));
// Prefix '1' allowed
if (count($digits) === 11) {
$this->assertEquals('1', $digits[0]);
$digits = array_slice($digits, 1);
}
// 10 digits
$this->assertCount(10, $digits);
$areaCode = $digits[0] . $digits[1] . $digits[2];
$this->assertContains($areaCode, array('800', '822', '833', '844', '855', '866', '877', '888', '880', '887', '889'));
// Last two digits of exchange code cannot be 1
if ($digits[4] === 1) {
$this->assertNotEquals($digits[4], $digits[5]);
}
// Test format
$this->assertRegExp('/^(\+?1)?([ -.]*\d{3}[ -.]*| *\(\d{3}\) *)\d{3}[-.]?\d{4}$/', $number);
}
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_US/CompanyTest.php | test/Faker/Provider/en_US/CompanyTest.php | <?php
namespace Faker\Test\Provider\en_US;
use Faker\Provider\en_US\Company;
use Faker\Generator;
use PHPUnit\Framework\TestCase;
final class CompanyTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Company($faker));
$this->faker = $faker;
}
/**
* @link https://stackoverflow.com/questions/4242433/regex-for-ein-number-and-ssn-number-format-in-jquery/35471665#35471665
*/
public function testEin()
{
$number = $this->faker->ein;
// should be in the format ##-#######, with a valid prefix
$this->assertRegExp('/^(0[1-6]||1[0-6]|2[0-7]|[35]\d|[468][0-8]|7[1-7]|9[0-58-9])-\d{7}$/', $number);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/it_CH/PersonTest.php | test/Faker/Provider/it_CH/PersonTest.php | <?php
namespace Faker\Test\Provider\it_CH;
use Faker\Calculator\Ean;
use Faker\Generator;
use Faker\Provider\it_CH\Person;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
public function testAvs13Number()
{
$avs = $this->faker->avs13;
$this->assertRegExp('/^756\.([0-9]{4})\.([0-9]{4})\.([0-9]{2})$/', $avs);
$this->assertTrue(Ean::isValid(str_replace('.', '', $avs)));
}
} | php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/it_CH/InternetTest.php | test/Faker/Provider/it_CH/InternetTest.php | <?php
namespace Faker\Test\Provider\it_CH;
use Faker\Generator;
use Faker\Provider\it_CH\Person;
use Faker\Provider\it_CH\Internet;
use Faker\Provider\it_CH\Company;
use PHPUnit\Framework\TestCase;
final class InternetTest extends TestCase
{
/**
* @var Faker\Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->addProvider(new Internet($faker));
$faker->addProvider(new Company($faker));
$this->faker = $faker;
}
/**
* @test
*/
public function emailIsValid()
{
$email = $this->faker->email();
$this->assertNotFalse(filter_var($email, FILTER_VALIDATE_EMAIL));
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/it_CH/AddressTest.php | test/Faker/Provider/it_CH/AddressTest.php | <?php
namespace Faker\Test\Provider\it_CH;
use Faker\Generator;
use Faker\Provider\it_CH\Address;
use Faker\Provider\it_CH\Person;
use PHPUnit\Framework\TestCase;
final class AddressTest extends TestCase
{
/**
* @var Faker\Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Address($faker));
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
/**
* @test
*/
public function canton ()
{
$canton = $this->faker->canton();
$this->assertInternalType('array', $canton);
$this->assertCount(1, $canton);
foreach ($canton as $cantonShort => $cantonName){
$this->assertInternalType('string', $cantonShort);
$this->assertEquals(2, strlen($cantonShort));
$this->assertInternalType('string', $cantonName);
$this->assertGreaterThan(2, strlen($cantonName));
}
}
/**
* @test
*/
public function cantonName ()
{
$cantonName = $this->faker->cantonName();
$this->assertInternalType('string', $cantonName);
$this->assertGreaterThan(2, strlen($cantonName));
}
/**
* @test
*/
public function cantonShort ()
{
$cantonShort = $this->faker->cantonShort();
$this->assertInternalType('string', $cantonShort);
$this->assertEquals(2, strlen($cantonShort));
}
/**
* @test
*/
public function address ()
{
$address = $this->faker->address();
$this->assertInternalType('string', $address);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/it_CH/PhoneNumberTest.php | test/Faker/Provider/it_CH/PhoneNumberTest.php | <?php
namespace Faker\Test\Provider\it_CH;
use Faker\Generator;
use Faker\Provider\it_CH\PhoneNumber;
use PHPUnit\Framework\TestCase;
final class PhoneNumberTest extends TestCase
{
/**
* @var Faker\Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new PhoneNumber($faker));
$this->faker = $faker;
}
public function testPhoneNumber()
{
$this->assertRegExp('/^0\d{2} ?\d{3} ?\d{2} ?\d{2}|\+41 ?(\(0\))?\d{2} ?\d{3} ?\d{2} ?\d{2}$/', $this->faker->phoneNumber());
}
public function testMobileNumber()
{
$this->assertRegExp('/^07[56789] ?\d{3} ?\d{2} ?\d{2}$/', $this->faker->mobileNumber());
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/ms_MY/PersonTest.php | test/Faker/Provider/ms_MY/PersonTest.php | <?php
namespace Faker\Test\Provider\ms_MY;
use Faker\Generator;
use Faker\Provider\ms_MY\Person;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
/**
* @link https://en.wikipedia.org/wiki/Malaysian_identity_card#Structure_of_the_National_Registration_Identity_Card_Number_(NRIC)
*/
public function testPersonalIdentityCardNumber()
{
$myKadNumber = $this->faker->myKadNumber;
$yy = substr($myKadNumber, 0, 2);
//match any year from 00-99
$this->assertRegExp("/^[0-9]{2}$/", $yy);
$mm = substr($myKadNumber, 2, 2);
//match any month from 01-12
$this->assertRegExp("/^0[1-9]|1[0-2]$/", $mm);
$dd = substr($myKadNumber, 4, 2);
//match any date from 01-31
$this->assertRegExp("/^0[1-9]|1[0-9]|2[0-9]|3[0-1]$/", $dd);
$pb = substr($myKadNumber, 6, 2);
//match any valid place of birth code from 01-59 except 17-20
$this->assertRegExp("/^(0[1-9]|1[0-6])|(2[1-9]|3[0-9]|4[0-9]|5[0-9])$/", $pb);
$nnnn = substr($myKadNumber, 8, 4);
//match any number from 0000-9999
$this->assertRegExp("/^[0-9]{4}$/", $nnnn);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/es_ES/PersonTest.php | test/Faker/Provider/es_ES/PersonTest.php | <?php
namespace Faker\Test\Provider\es_ES;
use Faker\Generator;
use Faker\Provider\es_ES\Person;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
protected function setUp()
{
$faker = new Generator();
$faker->seed(1);
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
public function testDNI()
{
$dni = $this->faker->dni;
$this->assertTrue($this->isValidDNI($dni));
}
// validation taken from http://kiwwito.com/php-function-for-spanish-dni-nie-validation/
public function isValidDNI($string)
{
if (strlen($string) != 9 ||
preg_match('/^[XYZ]?([0-9]{7,8})([A-Z])$/i', $string, $matches) !== 1) {
return false;
}
$map = 'TRWAGMYFPDXBNJZSQVHLCKE';
list(, $number, $letter) = $matches;
return strtoupper($letter) === $map[((int) $number) % 23];
}
public function testLicenceCode()
{
$validLicenceCodes = array('AM', 'A1', 'A2', 'A','B', 'B+E', 'C1', 'C1+E', 'C', 'C+E', 'D1', 'D1+E', 'D', 'D+E');
$this->assertContains($this->faker->licenceCode, $validLicenceCodes);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/es_ES/PaymentTest.php | test/Faker/Provider/es_ES/PaymentTest.php | <?php
namespace Faker\Test\Provider\es_ES;
use Faker\Generator;
use Faker\Provider\es_ES\Payment;
use PHPUnit\Framework\TestCase;
final class PaymentTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Payment($faker));
$this->faker = $faker;
}
public function testVAT()
{
$vat = $this->faker->vat();
$this->assertTrue($this->isValidCIF($vat));
}
/**
* Validation taken from https://github.com/amnesty/drupal-nif-nie-cif-validator/
* @link https://github.com/amnesty/drupal-nif-nie-cif-validator/blob/master/includes/nif-nie-cif.php
*/
function isValidCIF($docNumber)
{
$fixedDocNumber = strtoupper($docNumber);
return $this->isValidCIFFormat($fixedDocNumber);
}
function isValidCIFFormat($docNumber)
{
return $this->respectsDocPattern($docNumber, '/^[PQSNWR][0-9][0-9][0-9][0-9][0-9][0-9][0-9][A-Z0-9]/')
||
$this->respectsDocPattern($docNumber, '/^[ABCDEFGHJUV][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]/');
}
function respectsDocPattern($givenString, $pattern)
{
$isValid = FALSE;
$fixedString = strtoupper($givenString);
if (is_int(substr($fixedString, 0, 1))) {
$fixedString = substr("000000000" . $givenString, -9);
}
if (preg_match($pattern, $fixedString)) {
$isValid = TRUE;
}
return $isValid;
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/es_ES/PhoneNumberTest.php | test/Faker/Provider/es_ES/PhoneNumberTest.php | <?php
namespace Faker\Test\Provider\es_ES;
use Faker\Generator;
use Faker\Provider\es_ES\PhoneNumber;
final class PhoneNumberTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new PhoneNumber($faker));
$this->faker = $faker;
}
public function testMobileNumber()
{
$this->assertNotEquals('', $this->faker->mobileNumber());
}
public function testTollFreeNumber()
{
$this->assertEquals(11, strlen($this->faker->tollFreeNumber()));
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/es_ES/TextTest.php | test/Faker/Provider/es_ES/TextTest.php | <?php
namespace Faker\Test\Provider\es_ES;
use Faker\Generator;
use Faker\Provider\es_ES\Text;
use PHPUnit\Framework\TestCase;
final class TextTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Text($faker));
$this->faker = $faker;
}
public function testText()
{
$this->assertNotSame('', $this->faker->realtext(200, 2));
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/es_VE/PersonTest.php | test/Faker/Provider/es_VE/PersonTest.php | <?php
namespace Faker\Test\Provider\es_VE;
use Faker\Generator;
use Faker\Provider\es_VE\Person;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->seed(1);
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
/**
* national Id format validator
*/
public function testNationalId()
{
$pattern = '/(?:^V-?\d{5,9}$)|(?:^E-?\d{8,9}$)/';
$cedula = $this->faker->nationalId;
$this->assertRegExp($pattern, $cedula);
$cedula = $this->faker->nationalId('-');
$this->assertRegExp($pattern, $cedula);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/es_VE/CompanyTest.php | test/Faker/Provider/es_VE/CompanyTest.php | <?php
namespace Faker\Test\Provider\es_VE;
use Faker\Generator;
use Faker\Provider\es_VE\Company;
use PHPUnit\Framework\TestCase;
final class CompanyTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->seed(1);
$faker->addProvider(new Company($faker));
$this->faker = $faker;
}
/**
* national Id format validator
*/
public function testNationalId()
{
$pattern = '/^[VJGECP]-?\d{8}-?\d$/';
$rif = $this->faker->taxpayerIdentificationNumber;
$this->assertRegExp($pattern, $rif);
$rif = $this->faker->taxpayerIdentificationNumber('-');
$this->assertRegExp($pattern, $rif);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/ru_RU/PersonTest.php | test/Faker/Provider/ru_RU/PersonTest.php | <?php
namespace Faker\Test\Provider\ru_RU;
use Faker\Generator;
use Faker\Provider\ru_RU\Person;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
public function testLastNameFemale()
{
$this->assertEquals("а", substr($this->faker->lastName('female'), -2, 2));
}
public function testLastNameMale()
{
$this->assertNotEquals("а", substr($this->faker->lastName('male'), -2, 2));
}
public function testLastNameRandom()
{
$this->assertNotNull($this->faker->lastName());
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/ru_RU/CompanyTest.php | test/Faker/Provider/ru_RU/CompanyTest.php | <?php
namespace Faker\Test\Provider\ru_RU;
use Faker\Generator;
use Faker\Provider\ru_RU\Company;
use PHPUnit\Framework\TestCase;
final class CompanyTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Company($faker));
$this->faker = $faker;
}
public function testINN()
{
$this->assertRegExp('/^[0-9]{10}$/', $this->faker->inn);
$this->assertEquals("77", substr($this->faker->inn("77"), 0, 2));
$this->assertEquals("02", substr($this->faker->inn(2), 0, 2));
}
public function testKPP()
{
$this->assertRegExp('/^[0-9]{9}$/', $this->faker->kpp);
$this->assertEquals("01001", substr($this->faker->kpp, -5, 5));
$inn = $this->faker->inn;
$this->assertEquals(substr($inn, 0, 4), substr($this->faker->kpp($inn), 0, 4));
}
public function testCatchPhrase()
{
$phrase = $this->faker->catchPhrase;
$this->assertNotNull($phrase);
$this->assertGreaterThanOrEqual(3,
count(explode(' ', $this->faker->catchPhrase)),
"'$phrase' - should be contain 3 word");
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/ru_RU/TextTest.php | test/Faker/Provider/ru_RU/TextTest.php | <?php
namespace Faker\Test\Provider\ru_RU;
use PHPUnit\Framework\TestCase;
final class TextTest extends TestCase
{
private $textClass;
protected function setUp()
{
$this->textClass = new \ReflectionClass('Faker\Provider\ru_RU\Text');
}
protected function getMethod($name) {
$method = $this->textClass->getMethod($name);
$method->setAccessible(true);
return $method;
}
function testItShouldAppendEndPunctToTheEndOfString()
{
$this->assertSame(
'На другой день Чичиков отправился на обед и вечер.',
$this->getMethod('appendEnd')->invokeArgs(null, array('На другой день Чичиков отправился на обед и вечер '))
);
$this->assertSame(
'На другой день Чичиков отправился на обед и вечер.',
$this->getMethod('appendEnd')->invokeArgs(null, array('На другой день Чичиков отправился на обед и вечер—'))
);
$this->assertSame(
'На другой день Чичиков отправился на обед и вечер.',
$this->getMethod('appendEnd')->invokeArgs(null, array('На другой день Чичиков отправился на обед и вечер,'))
);
$this->assertSame(
'На другой день Чичиков отправился на обед и вечер!.',
$this->getMethod('appendEnd')->invokeArgs(null, array('На другой день Чичиков отправился на обед и вечер! '))
);
$this->assertSame(
'На другой день Чичиков отправился на обед и вечер.',
$this->getMethod('appendEnd')->invokeArgs(null, array('На другой день Чичиков отправился на обед и вечер; '))
);
$this->assertSame(
'На другой день Чичиков отправился на обед и вечер.',
$this->getMethod('appendEnd')->invokeArgs(null, array('На другой день Чичиков отправился на обед и вечер: '))
);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/mn_MN/PersonTest.php | test/Faker/Provider/mn_MN/PersonTest.php | <?php
namespace Faker\Test\Provider\mn_MN;
use Faker\Generator;
use Faker\Provider\mn_MN\Person;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
public function testName()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->seed(1);
$this->assertRegExp('/^[А-Я]{1}\.[\w\W]+$/u', $faker->name);
}
public function testIdNumber()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->seed(2);
$this->assertRegExp('/^[А-Я]{2}\d{8}$/u', $faker->idNumber);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/da_DK/InternetTest.php | test/Faker/Provider/da_DK/InternetTest.php | <?php
namespace Faker\Test\Provider\da_DK;
use Faker\Generator;
use Faker\Provider\da_DK\Person;
use Faker\Provider\da_DK\Internet;
use Faker\Provider\da_DK\Company;
use PHPUnit\Framework\TestCase;
final class InternetTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->addProvider(new Internet($faker));
$faker->addProvider(new Company($faker));
$this->faker = $faker;
}
public function testEmailIsValid()
{
$email = $this->faker->email();
$this->assertNotFalse(filter_var($email, FILTER_VALIDATE_EMAIL));
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/pt_PT/PersonTest.php | test/Faker/Provider/pt_PT/PersonTest.php | <?php
namespace Faker\Test\Provider\pt_PT;
use Faker\Generator;
use Faker\Provider\pt_PT\Person;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
public function testTaxpayerIdentificationNumberIsValid()
{
$tin = $this->faker->taxpayerIdentificationNumber();
$this->assertTrue($this->isValidTin($tin), $tin);
}
/**
*
* @link http://pt.wikipedia.org/wiki/N%C3%BAmero_de_identifica%C3%A7%C3%A3o_fiscal
*
* @param type $tin
*
* @return boolean
*/
public static function isValidTin($tin)
{
$regex = '(([1,2,3,5,6,8]{1}[0-9]{8})|((45)|(70)|(71)|(72)|(77)|(79)|(90|(98|(99))))[0-9]{7})';
if (is_null($tin) || !is_numeric($tin) || !strlen($tin) == 9 || preg_match("/$regex/", $tin) !== 1) {
return false;
}
$n = str_split($tin);
// cd - Control Digit
$cd = ($n[0] * 9 + $n[1] * 8 + $n[2] * 7 + $n[3] * 6 + $n[4] * 5 + $n[5] * 4 + $n[6] * 3 + $n[7] * 2) % 11;
if ($cd === 0 || $cd === 1) {
$cd = 0;
} else {
$cd = 11 - $cd;
}
if ($cd === intval($n[8])) {
return true;
}
return false;
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/pt_PT/AddressTest.php | test/Faker/Provider/pt_PT/AddressTest.php | <?php
namespace Faker\Test\Provider\pt_PT;
use Faker\Generator;
use Faker\Provider\pt_PT\Address;
use Faker\Provider\pt_PT\Person;
use PHPUnit\Framework\TestCase;
final class AddressTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Address($faker));
$this->faker = $faker;
}
public function testPostCodeIsValid()
{
$main = '[1-9]{1}[0-9]{2}[0,1,4,5,9]{1}';
$pattern = "/^($main)|($main-[0-9]{3})+$/";
$postcode = $this->faker->postcode();
$this->assertSame(preg_match($pattern, $postcode), 1, $postcode);
}
public function testAddressIsSingleLine()
{
$this->faker->addProvider(new Person($this->faker));
$address = $this->faker->address();
$this->assertFalse(strstr($address, "\n"));
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/pt_PT/PhoneNumberTest.php | test/Faker/Provider/pt_PT/PhoneNumberTest.php | <?php
namespace Faker\Test\Provider\pt_PT;
use Faker\Generator;
use Faker\Provider\pt_PT\PhoneNumber;
use PHPUnit\Framework\TestCase;
final class PhoneNumberTest extends TestCase
{
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new PhoneNumber($faker));
$this->faker = $faker;
}
public function testPhoneNumberReturnsPhoneNumberWithOrWithoutPrefix()
{
$this->assertRegExp('/^(9[1,2,3,6][0-9]{7})|(2[0-9]{8})|(\+351 [2][0-9]{8})|(\+351 9[1,2,3,6][0-9]{7})/', $this->faker->phoneNumber());
}
public function testMobileNumberReturnsMobileNumberWithOrWithoutPrefix()
{
$this->assertRegExp('/^(9[1,2,3,6][0-9]{7})/', $this->faker->mobileNumber());
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/at_AT/PaymentTest.php | test/Faker/Provider/at_AT/PaymentTest.php | <?php
namespace Faker\Test\Provider\at_AT;
use Faker\Generator;
use Faker\Provider\at_AT\Payment;
use PHPUnit\Framework\TestCase;
final class PaymentTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Payment($faker));
$this->faker = $faker;
}
public function testVatIsValid()
{
$vat = $this->faker->vat();
$unspacedVat = $this->faker->vat(false);
$this->assertRegExp('/^(AT U\d{8})$/', $vat);
$this->assertRegExp('/^(ATU\d{8})$/', $unspacedVat);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_SG/AddressTest.php | test/Faker/Provider/en_SG/AddressTest.php | <?php
namespace Faker\Test\Provider\en_SG;
use Faker\Factory;
use Faker\Provider\en_SG\Address;
use PHPUnit\Framework\TestCase;
final class AddressTest extends TestCase
{
protected function setUp()
{
$faker = Factory::create('en_SG');
$faker->addProvider(new Address($faker));
$this->faker = $faker;
}
public function testStreetNumber()
{
$this->assertRegExp('/^\d{2,3}$/', $this->faker->streetNumber());
}
public function testBlockNumber()
{
$this->assertRegExp('/^Blk\s*\d{2,3}[A-H]*$/i', $this->faker->blockNumber());
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_SG/PhoneNumberTest.php | test/Faker/Provider/en_SG/PhoneNumberTest.php | <?php
namespace Faker\Test\Provider\en_SG;
use Faker\Factory;
use Faker\Provider\en_SG\PhoneNumber;
use PHPUnit\Framework\TestCase;
final class PhoneNumberTest extends TestCase
{
private $faker;
protected function setUp()
{
$this->faker = Factory::create('en_SG');
$this->faker->seed(1);
$this->faker->addProvider(new PhoneNumber($this->faker));
}
// http://en.wikipedia.org/wiki/Telephone_numbers_in_Singapore#Numbering_plan
// x means 0 to 9
// y means 0 to 8 only
public function testMobilePhoneNumberStartWith9Returns9yxxxxxx()
{
$startsWith9 = false;
while (!$startsWith9) {
$mobileNumber = $this->faker->mobileNumber();
$startsWith9 = preg_match('/^(\+65|65)?\s*9/', $mobileNumber);
}
$this->assertRegExp('/^(\+65|65)?\s*9\s*[0-8]\d{2}\s*\d{4}$/', $mobileNumber);
}
// http://en.wikipedia.org/wiki/Telephone_numbers_in_Singapore#Numbering_plan
// x means 0 to 9
// z means 1 to 8 only
public function testMobilePhoneNumberStartWith8Returns8zxxxxxx()
{
$startsWith8 = false;
while (!$startsWith8) {
$mobileNumber = $this->faker->mobileNumber();
$startsWith8 = preg_match('/^(\+65|65)?\s*8/', $mobileNumber);
}
$this->assertRegExp('/^(\+65|65)?\s*8\s*[1-8]\d{2}\s*\d{4}$/', $mobileNumber);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/bg_BG/PaymentTest.php | test/Faker/Provider/bg_BG/PaymentTest.php | <?php
namespace Faker\Test\Provider\bg_BG;
use Faker\Generator;
use Faker\Provider\bg_BG\Payment;
use PHPUnit\Framework\TestCase;
final class PaymentTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Payment($faker));
$this->faker = $faker;
}
public function testVatIsValid()
{
$vat = $this->faker->vat();
$unspacedVat = $this->faker->vat(false);
$this->assertRegExp('/^(BG \d{9,10})$/', $vat);
$this->assertRegExp('/^(BG\d{9,10})$/', $unspacedVat);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/de_DE/InternetTest.php | test/Faker/Provider/de_DE/InternetTest.php | <?php
namespace Faker\Test\Provider\de_DE;
use Faker\Generator;
use Faker\Provider\de_DE\Person;
use Faker\Provider\de_DE\Internet;
use Faker\Provider\de_DE\Company;
use PHPUnit\Framework\TestCase;
final class InternetTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->addProvider(new Internet($faker));
$faker->addProvider(new Company($faker));
$this->faker = $faker;
}
public function testEmailIsValid()
{
$email = $this->faker->email();
$this->assertNotFalse(filter_var($email, FILTER_VALIDATE_EMAIL));
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/uk_UA/PersonTest.php | test/Faker/Provider/uk_UA/PersonTest.php | <?php
namespace Faker\Test\Provider\uk_UA;
use Faker\Generator;
use Faker\Provider\uk_UA\Person;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
public function testFirstNameMaleReturns()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->seed(1);
$this->assertEquals('Максим', $faker->firstNameMale());
}
public function testFirstNameFemaleReturns()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->seed(1);
$this->assertEquals('Людмила', $faker->firstNameFemale());
}
public function testMiddleNameMaleReturns()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->seed(1);
$this->assertEquals('Миколайович', $faker->middleNameMale());
}
public function testMiddleNameFemaleReturns()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->seed(1);
$this->assertEquals('Миколаївна', $faker->middleNameFemale());
}
public function testLastNameReturns()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->seed(1);
$this->assertEquals('Броваренко', $faker->lastName());
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/uk_UA/AddressTest.php | test/Faker/Provider/uk_UA/AddressTest.php | <?php
namespace Faker\Test\Provider\uk_UA;
use Faker\Generator;
use Faker\Provider\uk_UA\Address;
use PHPUnit\Framework\TestCase;
final class AddressTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Address($faker));
$this->faker = $faker;
}
public function testPostCodeIsValid()
{
$main = '[0-9]{5}';
$pattern = "/^($main)|($main-[0-9]{3})+$/";
$postcode = $this->faker->postcode;
$this->assertRegExp($pattern, $postcode, 'Post code ' . $postcode . ' is wrong!');
}
public function testEmptySuffixes()
{
$this->assertEmpty($this->faker->citySuffix, 'City suffix should be empty!');
$this->assertEmpty($this->faker->streetSuffix, 'Street suffix should be empty!');
}
public function testStreetCyrOnly()
{
$pattern = "/[0-9А-ЩЯІЇЄЮа-щяіїєюьIVXCM][0-9А-ЩЯІЇЄЮа-щяіїєюь \'-.]*[А-Яа-я.]/u";
$streetName = $this->faker->streetName;
$this->assertSame(
preg_match($pattern, $streetName),
1,
'Street name ' . $streetName . ' is wrong!'
);
}
public function testCityNameCyrOnly()
{
$pattern = "/[А-ЩЯІЇЄЮа-щяіїєюь][0-9А-ЩЯІЇЄЮа-щяіїєюь \'-]*[А-Яа-я]/u";
$city = $this->faker->city;
$this->assertSame(
preg_match($pattern, $city),
1,
'City name ' . $city . ' is wrong!'
);
}
public function testRegionNameCyrOnly()
{
$pattern = "/[А-ЩЯІЇЄЮ][А-ЩЯІЇЄЮа-щяіїєюь]*а$/u";
$regionName = $this->faker->region;
$this->assertSame(
preg_match($pattern, $regionName),
1,
'Region name ' . $regionName . ' is wrong!'
);
}
public function testCountryCyrOnly()
{
$pattern = "/[А-ЩЯІЇЄЮа-щяіїєюьIVXCM][А-ЩЯІЇЄЮа-щяіїєюь \'-]*[А-Яа-я.]/u";
$country = $this->faker->country;
$this->assertSame(
preg_match($pattern, $country),
1,
'Country name ' . $country . ' is wrong!'
);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/uk_UA/PhoneNumberTest.php | test/Faker/Provider/uk_UA/PhoneNumberTest.php | <?php
namespace Faker\Test\Provider\uk_UA;
use Faker\Generator;
use Faker\Provider\uk_UA\PhoneNumber;
use PHPUnit\Framework\TestCase;
final class PhoneNumberTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new PhoneNumber($faker));
$this->faker = $faker;
}
public function testPhoneNumberFormat()
{
$pattern = "/((\+38)(((\(\d{3}\))\d{7}|(\(\d{4}\))\d{6})|(\d{8})))|0\d{9}/";
$phoneNumber = $this->faker->phoneNumber;
$this->assertSame(
preg_match($pattern, $phoneNumber),
1,
'Phone number format ' . $phoneNumber . ' is wrong!'
);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_GB/AddressTest.php | test/Faker/Provider/en_GB/AddressTest.php | <?php
namespace Faker\Provider\en_GB;
use Faker\Generator;
use PHPUnit\Framework\TestCase;
final class AddressTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Address($faker));
$this->faker = $faker;
}
/**
*
*/
public function testPostcode()
{
$postcode = $this->faker->postcode();
$this->assertNotEmpty($postcode);
$this->assertInternalType('string', $postcode);
$this->assertRegExp('@^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$@i', $postcode);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/zh_TW/PersonTest.php | test/Faker/Provider/zh_TW/PersonTest.php | <?php
namespace Faker\Test\Provider\zh_TW;
use Faker\Generator;
use Faker\Provider\zh_TW\Person;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
/**
* @see https://zh.wikipedia.org/wiki/%E4%B8%AD%E8%8F%AF%E6%B0%91%E5%9C%8B%E5%9C%8B%E6%B0%91%E8%BA%AB%E5%88%86%E8%AD%89
*/
public function testPersonalIdentityNumber()
{
$id = $this->faker->personalIdentityNumber;
$firstChar = substr($id, 0, 1);
$codesString = Person::$idBirthplaceCode[$firstChar] . substr($id, 1);
// After transfer the first alphabet word into 2 digit number, there should be totally 11 numbers
$this->assertRegExp("/^[0-9]{11}$/", $codesString);
$total = 0;
$codesArray = str_split($codesString);
foreach ($codesArray as $key => $code) {
$total += $code * Person::$idDigitValidator[$key];
}
// Validate
$this->assertEquals(0, $total % 10);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/zh_TW/CompanyTest.php | test/Faker/Provider/zh_TW/CompanyTest.php | <?php
namespace Faker\Test\Provider\zh_TW;
use Faker\Generator;
use Faker\Provider\zh_TW\Company;
use PHPUnit\Framework\TestCase;
final class CompanyTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Company($faker));
$this->faker = $faker;
}
public function testVAT()
{
$this->assertEquals(8, floor(log10($this->faker->VAT) + 1));
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/zh_TW/TextTest.php | test/Faker/Provider/zh_TW/TextTest.php | <?php
namespace Faker\Test\Provider\zh_TW;
use PHPUnit\Framework\TestCase;
final class TextTest extends TestCase
{
private $textClass;
protected function setUp()
{
$this->textClass = new \ReflectionClass('Faker\Provider\zh_TW\Text');
}
protected function getMethod($name) {
$method = $this->textClass->getMethod($name);
$method->setAccessible(true);
return $method;
}
function testItShouldExplodeTheStringToArray()
{
$this->assertSame(
array('中', '文', '測', '試', '真', '有', '趣'),
$this->getMethod('explode')->invokeArgs(null, array('中文測試真有趣'))
);
$this->assertSame(
array('標', '點', ',', '符', '號', '!'),
$this->getMethod('explode')->invokeArgs(null, array('標點,符號!'))
);
}
function testItShouldReturnTheStringLength()
{
$this->assertContains(
$this->getMethod('strlen')->invokeArgs(null, array('中文測試真有趣')),
array(7, 21)
);
}
function testItShouldReturnTheCharacterIsValidStartOrNot()
{
$this->assertTrue($this->getMethod('validStart')->invokeArgs(null, array('中')));
$this->assertTrue($this->getMethod('validStart')->invokeArgs(null, array('2')));
$this->assertTrue($this->getMethod('validStart')->invokeArgs(null, array('Hello')));
$this->assertFalse($this->getMethod('validStart')->invokeArgs(null, array('。')));
$this->assertFalse($this->getMethod('validStart')->invokeArgs(null, array('!')));
}
function testItShouldAppendEndPunctToTheEndOfString()
{
$this->assertSame(
'中文測試真有趣。',
$this->getMethod('appendEnd')->invokeArgs(null, array('中文測試真有趣'))
);
$this->assertSame(
'中文測試真有趣。',
$this->getMethod('appendEnd')->invokeArgs(null, array('中文測試真有趣,'))
);
$this->assertSame(
'中文測試真有趣!',
$this->getMethod('appendEnd')->invokeArgs(null, array('中文測試真有趣!'))
);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/bn_BD/PersonTest.php | test/Faker/Provider/bn_BD/PersonTest.php | <?php
namespace Faker\Test\Provider\bn_BD;
use Faker\Generator;
use Faker\Provider\bn_BD\Person;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
public function testIfFirstNameMaleCanReturnData()
{
$firstNameMale = $this->faker->firstNameMale();
$this->assertNotEmpty($firstNameMale);
}
public function testIfFirstNameFemaleCanReturnData()
{
$firstNameFemale = $this->faker->firstNameFemale();
$this->assertNotEmpty($firstNameFemale);
}
}
?>
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/nl_BE/PersonTest.php | test/Faker/Provider/nl_BE/PersonTest.php | <?php
namespace Faker\Test\Provider\nl_BE;
use Faker\Generator;
use Faker\Provider\nl_BE\Person;
use PHPUnit\Framework\TestCase;
use Datetime;
/**
* @group Person
*/
final class PersonTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
public function testRrnIsValid()
{
$rrn = $this->faker->rrn();
$this->assertEquals(11, strlen($rrn));
$ctrlNumber = substr($rrn, 9, 2);
$calcCtrl = 97 - (substr($rrn, 0, 9) % 97);
$altcalcCtrl = 97 - ((2 . substr($rrn, 0, 9)) % 97);
$this->assertContains($ctrlNumber, array($calcCtrl, $altcalcCtrl));
$middle = substr($rrn, 6, 3);
$this->assertGreaterThan(1, $middle);
$this->assertLessThan(997, $middle);
}
public function testRrnIsMale()
{
$rrn = $this->faker->rrn('male');
$this->assertEquals(substr($rrn, 6, 3) % 2, 1);
}
public function testRrnIsFemale()
{
$rrn = $this->faker->rrn('female');
$this->assertEquals(substr($rrn, 6, 3) % 2, 0);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/nl_BE/PaymentTest.php | test/Faker/Provider/nl_BE/PaymentTest.php | <?php
namespace Faker\Test\Provider\nl_BE;
use Faker\Generator;
use Faker\Provider\nl_BE\Payment;
use PHPUnit\Framework\TestCase;
final class PaymentTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Payment($faker));
$this->faker = $faker;
}
public function testVatIsValid()
{
$vat = $this->faker->vat();
$unspacedVat = $this->faker->vat(false);
$this->assertRegExp('/^(BE 0\d{9})$/', $vat);
$this->assertRegExp('/^(BE0\d{9})$/', $unspacedVat);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_PH/AddressTest.php | test/Faker/Provider/en_PH/AddressTest.php | <?php
namespace Faker\Test\Provider\en_PH;
use Faker\Generator;
use Faker\Provider\en_PH\Address;
use PHPUnit\Framework\TestCase;
final class AddressTest extends TestCase
{
/**
* @var Faker\Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Address($faker));
$this->faker = $faker;
}
public function testProvince()
{
$province = $this->faker->province();
$this->assertNotEmpty($province);
$this->assertInternalType('string', $province);
}
public function testCity()
{
$city = $this->faker->city();
$this->assertNotEmpty($city);
$this->assertInternalType('string', $city);
}
public function testMunicipality()
{
$municipality = $this->faker->municipality();
$this->assertNotEmpty($municipality);
$this->assertInternalType('string', $municipality);
}
public function testBarangay()
{
$barangay = $this->faker->barangay();
$this->assertInternalType('string', $barangay);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/ar_SA/InternetTest.php | test/Faker/Provider/ar_SA/InternetTest.php | <?php
namespace Faker\Test\Provider\ar_SA;
use Faker\Generator;
use Faker\Provider\ar_SA\Person;
use Faker\Provider\ar_SA\Internet;
use Faker\Provider\ar_SA\Company;
use PHPUnit\Framework\TestCase;
final class InternetTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->addProvider(new Internet($faker));
$faker->addProvider(new Company($faker));
$this->faker = $faker;
}
public function testEmailIsValid()
{
$email = $this->faker->email();
$this->assertNotFalse(filter_var($email, FILTER_VALIDATE_EMAIL));
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/ar_JO/InternetTest.php | test/Faker/Provider/ar_JO/InternetTest.php | <?php
namespace Faker\Test\Provider\ar_JO;
use Faker\Generator;
use Faker\Provider\fi_FI\Person;
use Faker\Provider\fi_FI\Internet;
use Faker\Provider\fi_FI\Company;
use PHPUnit\Framework\TestCase;
final class InternetTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->addProvider(new Internet($faker));
$faker->addProvider(new Company($faker));
$this->faker = $faker;
}
public function testEmailIsValid()
{
$email = $this->faker->email();
$this->assertNotFalse(filter_var($email, FILTER_VALIDATE_EMAIL));
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_ZA/PersonTest.php | test/Faker/Provider/en_ZA/PersonTest.php | <?php
namespace Faker\Test\Provider\en_ZA;
use Faker\Generator;
use Faker\Provider\en_ZA\Person;
use Faker\Provider\DateTime;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->addProvider(new DateTime($faker));
$this->faker = $faker;
}
public function testIdNumberWithDefaults()
{
$idNumber = $this->faker->idNumber();
$this->assertEquals(13, strlen($idNumber));
$this->assertRegExp('#^\d{13}$#', $idNumber);
$this->assertInternalType('string', $idNumber);
}
public function testIdNumberForMales()
{
$idNumber = $this->faker->idNumber(new \DateTime(), true, 'male');
$genderDigit = substr($idNumber, 6, 1);
$this->assertContains($genderDigit, array('5', '6', '7', '8', '9'));
}
public function testIdNumberForFemales()
{
$idNumber = $this->faker->idNumber(new \DateTime(), true, 'female');
$genderDigit = substr($idNumber, 6, 1);
$this->assertContains($genderDigit, array('0', '1', '2', '3', '4'));
}
public function testLicenceCode()
{
$validLicenceCodes = array('A', 'A1', 'B', 'C', 'C1', 'C2', 'EB', 'EC', 'EC1', 'I', 'L', 'L1');
$this->assertContains($this->faker->licenceCode, $validLicenceCodes);
}
public function testMaleTitles()
{
$validMaleTitles = array('Mr.', 'Dr.', 'Prof.', 'Rev.', 'Hon.');
$this->assertContains(Person::titleMale(), $validMaleTitles);
}
public function testFemaleTitles()
{
$validateFemaleTitles = array('Mrs.', 'Ms.', 'Miss', 'Dr.', 'Prof.', 'Rev.', 'Hon.');
$this->assertContains(Person::titleFemale(), $validateFemaleTitles);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_ZA/InternetTest.php | test/Faker/Provider/en_ZA/InternetTest.php | <?php
namespace Faker\Test\Provider\en_ZA;
use Faker\Generator;
use Faker\Provider\en_ZA\Person;
use Faker\Provider\en_ZA\Internet;
use Faker\Provider\en_ZA\Company;
use PHPUnit\Framework\TestCase;
final class InternetTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->addProvider(new Internet($faker));
$faker->addProvider(new Company($faker));
$this->faker = $faker;
}
public function testEmailIsValid()
{
$email = $this->faker->email();
$this->assertNotFalse(filter_var($email, FILTER_VALIDATE_EMAIL));
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_ZA/PhoneNumberTest.php | test/Faker/Provider/en_ZA/PhoneNumberTest.php | <?php
namespace Faker\Test\Provider\en_ZA;
use Faker\Generator;
use Faker\Provider\en_ZA\PhoneNumber;
use PHPUnit\Framework\TestCase;
final class PhoneNumberTest extends TestCase
{
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new PhoneNumber($faker));
$this->faker = $faker;
}
public function testPhoneNumber()
{
for ($i = 0; $i < 10; $i++) {
$number = $this->faker->phoneNumber;
$digits = array_values(array_filter(str_split($number), 'ctype_digit'));
// 10 digits
if($digits[0] = 2 && $digits[1] == 7) {
$this->assertLessThanOrEqual(11, count($digits));
} else {
$this->assertGreaterThanOrEqual(10, count($digits));
}
}
}
public function testTollFreePhoneNumber()
{
for ($i = 0; $i < 10; $i++) {
$number = $this->faker->tollFreeNumber;
$digits = array_values(array_filter(str_split($number), 'ctype_digit'));
if (count($digits) === 11) {
$this->assertEquals('0', $digits[0]);
}
$areaCode = $digits[0] . $digits[1] . $digits[2] . $digits[3];
$this->assertContains($areaCode, array('0800', '0860', '0861', '0862'));
}
}
public function testCellPhoneNumber()
{
for ($i = 0; $i < 10; $i++) {
$number = $this->faker->mobileNumber;
$digits = array_values(array_filter(str_split($number), 'ctype_digit'));
if($digits[0] = 2 && $digits[1] == 7) {
$this->assertLessThanOrEqual(11, count($digits));
} else {
$this->assertGreaterThanOrEqual(10, count($digits));
}
$this->assertRegExp('/^(\+27|27)?(\()?0?([6][0-4]|[7][1-9]|[8][1-9])(\))?( |-|\.|_)?(\d{3})( |-|\.|_)?(\d{4})/', $number);
}
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_ZA/CompanyTest.php | test/Faker/Provider/en_ZA/CompanyTest.php | <?php
namespace Faker\Test\Provider\en_ZA;
use Faker\Generator;
use Faker\Provider\en_ZA\Company;
use PHPUnit\Framework\TestCase;
final class CompanyTest extends TestCase
{
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Company($faker));
$this->faker = $faker;
}
public function testGenerateValidCompanyNumber()
{
$companyRegNo = $this->faker->companyNumber();
$this->assertEquals(14, strlen($companyRegNo));
$this->assertRegExp('#^\d{4}/\d{6}/\d{2}$#', $companyRegNo);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_NG/PersonTest.php | test/Faker/Provider/en_NG/PersonTest.php | <?php
namespace Faker\Test\Provider\ng_NG;
use Faker\Generator;
use Faker\Provider\en_NG\Person;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
public function testPersonNameIsAValidString()
{
$name = $this->faker->name;
$this->assertNotEmpty($name);
$this->assertInternalType('string', $name);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_NG/InternetTest.php | test/Faker/Provider/en_NG/InternetTest.php | <?php
namespace Faker\Test\Provider\ng_NG;
use Faker\Generator;
use Faker\Provider\en_NG\Person;
use Faker\Provider\en_NG\Internet;
use PHPUnit\Framework\TestCase;
final class InternetTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->addProvider(new Internet($faker));
$this->faker = $faker;
}
public function testEmailIsValid()
{
$email = $this->faker->email();
$this->assertNotFalse(filter_var($email, FILTER_VALIDATE_EMAIL));
$this->assertNotEmpty($email);
$this->assertInternalType('string', $email);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_NG/AddressTest.php | test/Faker/Provider/en_NG/AddressTest.php | <?php
namespace Faker\Provider\ng_NG;
use Faker\Generator;
use Faker\Provider\en_NG\Address;
use PHPUnit\Framework\TestCase;
final class AddressTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Address($faker));
$this->faker = $faker;
}
/**
*
*/
public function testPostcodeIsNotEmptyAndIsValid()
{
$postcode = $this->faker->postcode();
$this->assertNotEmpty($postcode);
$this->assertInternalType('string', $postcode);
}
/**
* Test the name of the Nigerian State/County
*/
public function testCountyIsAValidString()
{
$county = $this->faker->county;
$this->assertNotEmpty($county);
$this->assertInternalType('string', $county);
}
/**
* Test the name of the Nigerian Region in a State.
*/
public function testRegionIsAValidString()
{
$region = $this->faker->region;
$this->assertNotEmpty($region);
$this->assertInternalType('string', $region);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_NG/PhoneNumberTest.php | test/Faker/Provider/en_NG/PhoneNumberTest.php | <?php
namespace Faker\Test\Provider\ng_NG;
use Faker\Generator;
use Faker\Provider\en_NG\PhoneNumber;
use PHPUnit\Framework\TestCase;
final class PhoneNumberTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new PhoneNumber($faker));
$this->faker = $faker;
}
public function testPhoneNumberReturnsPhoneNumberWithOrWithoutCountryCode()
{
$phoneNumber = $this->faker->phoneNumber();
$this->assertNotEmpty($phoneNumber);
$this->assertInternalType('string', $phoneNumber);
$this->assertRegExp('/^(0|(\+234))\s?[789][01]\d\s?(\d{3}\s?\d{4})/', $phoneNumber);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_AU/AddressTest.php | test/Faker/Provider/en_AU/AddressTest.php | <?php
namespace Faker\Provider\en_AU;
use Faker\Generator;
use Faker\Provider\en_AU\Address;
use PHPUnit\Framework\TestCase;
final class AddressTest extends TestCase
{
/**
* @var Faker\Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Address($faker));
$this->faker = $faker;
}
public function testCityPrefix()
{
$cityPrefix = $this->faker->cityPrefix();
$this->assertNotEmpty($cityPrefix);
$this->assertInternalType('string', $cityPrefix);
$this->assertRegExp('/[A-Z][a-z]+/', $cityPrefix);
}
public function testStreetSuffix()
{
$streetSuffix = $this->faker->streetSuffix();
$this->assertNotEmpty($streetSuffix);
$this->assertInternalType('string', $streetSuffix);
$this->assertRegExp('/[A-Z][a-z]+/', $streetSuffix);
}
public function testState()
{
$state = $this->faker->state();
$this->assertNotEmpty($state);
$this->assertInternalType('string', $state);
$this->assertRegExp('/[A-Z][a-z]+/', $state);
}
}
?>
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/es_PE/PersonTest.php | test/Faker/Provider/es_PE/PersonTest.php | <?php
namespace Faker\Test\Provider\es_PE;
use Faker\Generator;
use Faker\Provider\es_PE\Person;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->seed(1);
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
public function testDNI()
{
$dni = $this->faker->dni;
$this->assertRegExp('/\A[0-9]{8}\Z/', $dni);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/fa_IR/PersonTest.php | test/Faker/Provider/fa_IR/PersonTest.php | <?php
namespace Faker\Test\Provider\fa_IR;
use Faker\Provider\fa_IR\Person;
use Faker\Generator;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
public function testNationalCode()
{
for ($i = 0; $i < 100; $i++) {
$nationalCode = $this->faker->nationalCode;
// nationalCode should be in the format ##########
$this->assertRegExp('/^[0-9]{10}$/', $nationalCode);
$areaCode = substr($nationalCode, 0, 3);
$controlCode = substr($nationalCode, 9, 1);
// the areaCode must in the format ###, excluding '000'
$this->assertNotEquals('000', $areaCode);
// the controlCode should comply with the Iranian National Code validation algorithm
$sum = 0;
$count = 0;
for ($j = 10; $j > 1; $j--) {
$sum += $nationalCode[$count] * ($j);
$count++;
}
if (($sum % 11) < 2) {
$this->assertEquals($sum % 11, (int)$controlCode);
} else {
$this->assertEquals(11 - ($sum % 11), (int)$controlCode);
}
}
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/id_ID/PersonTest.php | test/Faker/Provider/id_ID/PersonTest.php | <?php
namespace Faker\Test\Provider\id_ID;
use Faker\Generator;
use Faker\Provider\DateTime;
use Faker\Provider\id_ID\Person;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
/**
* @see Person::$birthPlaceCode
*/
protected static $birthPlaceCode = array(
'1101', '1102', '1103', '1104', '1105', '1106', '1107', '1108', '1109', '1110', '1111', '1112', '1113', '1114', '1115', '1116',
'1117', '1118', '1171', '1172', '1173', '1174', '1175', '1201', '1202', '1203', '1204', '1205', '1206', '1207', '1208', '1209',
'1210', '1211', '1212', '1213', '1214', '1215', '1216', '1217', '1218', '1219', '1220', '1221', '1222', '1223', '1224', '1225',
'1271', '1272', '1273', '1274', '1275', '1276', '1277', '1278', '1301', '1302', '1303', '1304', '1305', '1306', '1307', '1308',
'1309', '1310', '1311', '1312', '1371', '1372', '1373', '1374', '1375', '1376', '1377', '1401', '1402', '1403', '1404', '1405',
'1406', '1407', '1408', '1409', '1410', '1471', '1472', '1501', '1502', '1503', '1504', '1505', '1506', '1507', '1508', '1509',
'1571', '1572', '1601', '1602', '1603', '1604', '1605', '1606', '1607', '1608', '1609', '1610', '1611', '1612', '1613', '1671',
'1672', '1673', '1674', '1701', '1702', '1703', '1704', '1705', '1706', '1707', '1708', '1709', '1771', '1801', '1802', '1803',
'1804', '1805', '1806', '1807', '1808', '1809', '1810', '1811', '1812', '1813', '1871', '1872', '1901', '1902', '1903', '1904',
'1905', '1906', '1971', '2101', '2102', '2103', '2104', '2105', '2171', '2172', '3101', '3171', '3172', '3173', '3174', '3175',
'3201', '3202', '3203', '3204', '3205', '3206', '3207', '3208', '3209', '3210', '3211', '3212', '3213', '3214', '3215', '3216',
'3217', '3218', '3271', '3272', '3273', '3274', '3275', '3276', '3277', '3278', '3279', '3301', '3302', '3303', '3304', '3305',
'3306', '3307', '3308', '3309', '3310', '3311', '3312', '3313', '3314', '3315', '3316', '3317', '3318', '3319', '3320', '3321',
'3322', '3323', '3324', '3325', '3326', '3327', '3328', '3329', '3371', '3372', '3373', '3374', '3375', '3376', '3401', '3402',
'3403', '3404', '3471', '3501', '3502', '3503', '3504', '3505', '3506', '3507', '3508', '3509', '3510', '3511', '3512', '3513',
'3514', '3515', '3516', '3517', '3518', '3519', '3520', '3521', '3522', '3523', '3524', '3525', '3526', '3527', '3528', '3529',
'3571', '3572', '3573', '3574', '3575', '3576', '3577', '3578', '3579', '3601', '3602', '3603', '3604', '3671', '3672', '3673',
'3674', '5101', '5102', '5103', '5104', '5105', '5106', '5107', '5108', '5171', '5201', '5202', '5203', '5204', '5205', '5206',
'5207', '5208', '5271', '5272', '5301', '5302', '5303', '5304', '5305', '5306', '5307', '5308', '5309', '5310', '5311', '5312',
'5313', '5314', '5315', '5316', '5317', '5318', '5319', '5320', '5321', '5371', '6101', '6102', '6103', '6104', '6105', '6106',
'6107', '6108', '6109', '6110', '6111', '6112', '6171', '6172', '6201', '6202', '6203', '6204', '6205', '6206', '6207', '6208',
'6209', '6210', '6211', '6212', '6213', '6271', '6301', '6302', '6303', '6304', '6305', '6306', '6307', '6308', '6309', '6310',
'6311', '6371', '6401', '6402', '6403', '6407', '6408', '6409', '6411', '6471', '6472', '6474', '6501', '6502', '6503', '6504',
'6571', '7101', '7102', '7103', '7104', '7105', '7106', '7107', '7108', '7109', '7110', '7111', '7171', '7201', '7202', '7203',
'7204', '7205', '7206', '7207', '7208', '7209', '7210', '7211', '7212', '7271', '7301', '7302', '7303', '7304', '7305', '7306',
'7307', '7308', '7309', '7310', '7311', '7312', '7313', '7314', '7315', '7316', '7317', '7318', '7322', '7324', '7326', '7371',
'7372', '7373', '7401', '7402', '7403', '7404', '7405', '7406', '7407', '7408', '7409', '7410', '7411', '7412', '7413', '7414',
'7415', '7471', '7472', '7501', '7502', '7503', '7504', '7505', '7571', '7601', '7602', '7603', '7604', '7605', '7606', '8101',
'8102', '8103', '8104', '8105', '8106', '8107', '8108', '8109', '8171', '8172', '8201', '8202', '8203', '8204', '8205', '8206',
'8207', '8208', '8271', '8272', '9101', '9102', '9103', '9104', '9105', '9106', '9107', '9108', '9109', '9110', '9111', '9112',
'9113', '9114', '9115', '9116', '9117', '9118', '9119', '9120', '9121', '9122', '9123', '9124', '9125', '9126', '9127', '9128',
'9171', '9201', '9202', '9203', '9204', '9205', '9206', '9207', '9208', '9209', '9210', '9211', '9212', '9271',
);
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->addProvider(new DateTime($faker));
$this->faker = $faker;
}
public function testIfFirstNameMaleCanReturnData()
{
$firstNameMale = $this->faker->firstNameMale();
$this->assertNotEmpty($firstNameMale);
}
public function testIfLastNameMaleCanReturnData()
{
$lastNameMale = $this->faker->lastNameMale();
$this->assertNotEmpty($lastNameMale);
}
public function testIfFirstNameFemaleCanReturnData()
{
$firstNameFemale = $this->faker->firstNameFemale();
$this->assertNotEmpty($firstNameFemale);
}
public function testIfLastNameFemaleCanReturnData()
{
$lastNameFemale = $this->faker->lastNameFemale();
$this->assertNotEmpty($lastNameFemale);
}
public function testNikContainsBirthPlace()
{
$nik = $this->faker->nik();
$this->assertContains(substr($nik, 0, 4), static::$birthPlaceCode);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/ka_GE/TextTest.php | test/Faker/Provider/ka_GE/TextTest.php | <?php
namespace Faker\Test\Provider\ka_GE;
use PHPUnit\Framework\TestCase;
final class TextTest extends TestCase
{
private $textClass;
protected function setUp()
{
$this->textClass = new \ReflectionClass('Faker\Provider\el_GR\Text');
}
protected function getMethod($name) {
$method = $this->textClass->getMethod($name);
$method->setAccessible(true);
return $method;
}
function testItShouldAppendEndPunctToTheEndOfString()
{
$this->assertSame(
'ჭეშმარიტია. ჩვენც ისე.',
$this->getMethod('appendEnd')->invokeArgs(null, array('ჭეშმარიტია. ჩვენც ისე '))
);
$this->assertSame(
'ჭეშმარიტია. ჩვენც ისე.',
$this->getMethod('appendEnd')->invokeArgs(null, array('ჭეშმარიტია. ჩვენც ისე— '))
);
$this->assertSame(
'ჭეშმარიტია. ჩვენც ისე.',
$this->getMethod('appendEnd')->invokeArgs(null, array('ჭეშმარიტია. ჩვენც ისე, '))
);
$this->assertSame(
'ჭეშმარიტია. ჩვენც ისე!.',
$this->getMethod('appendEnd')->invokeArgs(null, array('ჭეშმარიტია. ჩვენც ისე! '))
);
$this->assertSame(
'ჭეშმარიტია. ჩვენც ისე.',
$this->getMethod('appendEnd')->invokeArgs(null, array('ჭეშმარიტია. ჩვენც ისე; '))
);
$this->assertSame(
'ჭეშმარიტია. ჩვენც ისე.',
$this->getMethod('appendEnd')->invokeArgs(null, array('ჭეშმარიტია. ჩვენც ისე: '))
);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/ko_KR/TextTest.php | test/Faker/Provider/ko_KR/TextTest.php | <?php
namespace Faker\Test\Provider\ko_KR;
use PHPUnit\Framework\TestCase;
final class TextTest extends TestCase
{
private $textClass;
protected function setUp()
{
$this->textClass = new \ReflectionClass('Faker\Provider\el_GR\Text');
}
protected function getMethod($name) {
$method = $this->textClass->getMethod($name);
$method->setAccessible(true);
return $method;
}
function testItShouldAppendEndPunctToTheEndOfString()
{
$this->assertSame(
'최석(崔晳)으로부터 최후의 편지가.',
$this->getMethod('appendEnd')->invokeArgs(null, array('최석(崔晳)으로부터 최후의 편지가 '))
);
$this->assertSame(
'최석(崔晳)으로부터 최후의 편지가.',
$this->getMethod('appendEnd')->invokeArgs(null, array('최석(崔晳)으로부터 최후의 편지가—'))
);
$this->assertSame(
'최석(崔晳)으로부터 최후의 편지가.',
$this->getMethod('appendEnd')->invokeArgs(null, array('최석(崔晳)으로부터 최후의 편지가,'))
);
$this->assertSame(
'최석(崔晳)으로부터 최후의 편지가!.',
$this->getMethod('appendEnd')->invokeArgs(null, array('최석(崔晳)으로부터 최후의 편지가! '))
);
$this->assertSame(
'최석(崔晳)으로부터 최후의 편지가.',
$this->getMethod('appendEnd')->invokeArgs(null, array('최석(崔晳)으로부터 최후의 편지가: '))
);
$this->assertSame(
'최석(崔晳)으로부터 최후의 편지가.',
$this->getMethod('appendEnd')->invokeArgs(null, array('최석(崔晳)으로부터 최후의 편지가; '))
);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/ro_RO/PersonTest.php | test/Faker/Provider/ro_RO/PersonTest.php | <?php
namespace Faker\Test\Provider\ro_RO;
use Faker\Generator;
use Faker\Provider\DateTime;
use Faker\Provider\ro_RO\Person;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
const TEST_CNP_REGEX = '/^[1-9][0-9]{2}(?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])(?:0[1-9]|[123][0-9]|4[0-6]|5[12])[0-9]{3}[0-9]$/';
/**
* @var \Faker\Generator
*
*/
protected $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new DateTime($faker));
$faker->addProvider(new Person($faker));
$faker->setDefaultTimezone('Europe/Bucharest');
$this->faker = $faker;
}
protected function tearDown()
{
$this->faker->setDefaultTimezone();
}
public function invalidGenderProvider()
{
return array(
array('elf'),
array('ent'),
array('fmle'),
array('mal'),
);
}
public function invalidYearProvider()
{
return array(
array(1652),
array(1799),
array(2100),
array(2252),
);
}
public function validYearProvider()
{
return array(
array(null),
array(''),
array(1800),
array(1850),
array(1900),
array(1990),
array(2000),
array(2099),
);
}
public function validCountyCodeProvider()
{
return array(
array('AB'), array('AR'), array('AG'), array('B'), array('BC'), array('BH'), array('BN'), array('BT'),
array('BV'), array('BR'), array('BZ'), array('CS'), array('CL'), array('CJ'), array('CT'), array('CV'),
array('DB'), array('DJ'), array('GL'), array('GR'), array('GJ'), array('HR'), array('HD'), array('IL'),
array('IS'), array('IF'), array('MM'), array('MH'), array('MS'), array('NT'), array('OT'), array('PH'),
array('SM'), array('SJ'), array('SB'), array('SV'), array('TR'), array('TM'), array('TL'), array('VS'),
array('VL'), array('VN'), array('B1'), array('B2'), array('B3'), array('B4'), array('B5'), array('B6')
);
}
public function invalidCountyCodeProvider()
{
return array(
array('JK'), array('REW'), array('x'), array('FF'), array('aaaddadaada')
);
}
public function validInputDataProvider()
{
return array(
array(Person::GENDER_MALE, '1981-06-16','B2', true, '181061642'),
array(Person::GENDER_FEMALE, '1981-06-16','B2', true, '281061642'),
array(Person::GENDER_MALE, '1981-06-16','B2', false, '981061642'),
array(Person::GENDER_FEMALE, '1981-06-16','B2', false, '981061642'),
);
}
/**
*
*/
public function test_allRandom_returnsValidCnp()
{
$cnp = $this->faker->cnp;
$this->assertTrue(
$this->isValidCnp($cnp),
sprintf("Invalid CNP '%' generated", $cnp)
);
}
/**
*
*/
public function test_validGender_returnsValidCnp()
{
$cnp = $this->faker->cnp(Person::GENDER_MALE);
$this->assertTrue(
$this->isValidMaleCnp($cnp),
sprintf("Invalid CNP '%' generated for '%s' gender", $cnp, Person::GENDER_MALE)
);
$cnp = $this->faker->cnp(Person::GENDER_FEMALE);
$this->assertTrue(
$this->isValidFemaleCnp($cnp),
sprintf("Invalid CNP '%' generated for '%s' gender", $cnp, Person::GENDER_FEMALE)
);
}
/**
* @param string $value
*
* @dataProvider invalidGenderProvider
*/
public function test_invalidGender_throwsException($value)
{
$this->setExpectedException('InvalidArgumentException');
$this->faker->cnp($value);
}
/**
* @param string $value year of birth
*
* @dataProvider validYearProvider
*/
public function test_validYear_returnsValidCnp($value)
{
$cnp = $this->faker->cnp(null, $value);
$this->assertTrue(
$this->isValidCnp($cnp),
sprintf("Invalid CNP '%' generated for valid year '%s'", $cnp, $value)
);
}
/**
* @param string $value year of birth
*
* @dataProvider invalidYearProvider
*/
public function test_invalidYear_throwsException($value)
{
$this->setExpectedException('InvalidArgumentException');
$this->faker->cnp(null, $value);
}
/**
* @param $value
* @dataProvider validCountyCodeProvider
*/
public function test_validCountyCode_returnsValidCnp($value)
{
$cnp = $this->faker->cnp(null, null, $value);
$this->assertTrue(
$this->isValidCnp($cnp),
sprintf("Invalid CNP '%' generated for valid year '%s'", $cnp, $value)
);
}
/**
* @param $value
* @dataProvider invalidCountyCodeProvider
*/
public function test_invalidCountyCode_throwsException($value)
{
$this->setExpectedException('InvalidArgumentException');
$this->faker->cnp(null, null, $value);
}
/**
*
*/
public function test_nonResident_returnsValidCnp()
{
$cnp = $this->faker->cnp(null, null, null, false);
$this->assertTrue(
$this->isValidCnp($cnp),
sprintf("Invalid CNP '%' generated for non resident", $cnp)
);
$this->assertStringStartsWith(
'9',
$cnp,
sprintf("Invalid CNP '%' generated for non resident (should start with 9)", $cnp)
);
}
/**
*
* @param $gender
* @param $dateOfBirth
* @param $county
* @param $isResident
* @param $expectedCnpStart
*
* @dataProvider validInputDataProvider
*/
public function test_validInputData_returnsValidCnp($gender, $dateOfBirth, $county, $isResident, $expectedCnpStart)
{
$cnp = $this->faker->cnp($gender, $dateOfBirth, $county, $isResident);
$this->assertStringStartsWith(
$expectedCnpStart,
$cnp,
sprintf("Invalid CNP '%' generated for non valid data", $cnp)
);
}
protected function isValidFemaleCnp($value)
{
return $this->isValidCnp($value) && in_array($value[0], array(2, 4, 6, 8, 9));
}
protected function isValidMaleCnp($value)
{
return $this->isValidCnp($value) && in_array($value[0], array(1, 3, 5, 7, 9));
}
protected function isValidCnp($cnp)
{
if (preg_match(static::TEST_CNP_REGEX, $cnp) !== false) {
$checkNumber = 279146358279;
$checksum = 0;
foreach (range(0, 11) as $digit) {
$checksum += (int)substr($cnp, $digit, 1) * (int)substr($checkNumber, $digit, 1);
}
$checksum %= 11;
$checksum = $checksum == 10 ? 1 : $checksum;
if ($checksum == substr($cnp, -1)) {
return true;
}
}
return false;
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/ro_RO/PhoneNumberTest.php | test/Faker/Provider/ro_RO/PhoneNumberTest.php | <?php
namespace Faker\Test\Provider\ro_RO;
use Faker\Generator;
use Faker\Provider\ro_RO\PhoneNumber;
use PHPUnit\Framework\TestCase;
final class PhoneNumberTest extends TestCase
{
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new PhoneNumber($faker));
$this->faker = $faker;
}
public function testPhoneNumberReturnsNormalPhoneNumber()
{
$this->assertRegExp('/^0(?:[23][13-7]|7\d)\d{7}$/', $this->faker->phoneNumber());
}
public function testTollFreePhoneNumberReturnsTollFreePhoneNumber()
{
$this->assertRegExp('/^08(?:0[01267]|70)\d{6}$/', $this->faker->tollFreePhoneNumber());
}
public function testPremiumRatePhoneNumberReturnsPremiumRatePhoneNumber()
{
$this->assertRegExp('/^090[036]\d{6}$/', $this->faker->premiumRatePhoneNumber());
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/en_UG/AddressTest.php | test/Faker/Provider/en_UG/AddressTest.php | <?php
namespace Faker\Test\Provider\en_UG;
use Faker\Generator;
use Faker\Provider\en_UG\Address;
use PHPUnit\Framework\TestCase;
final class AddressTest extends TestCase
{
/**
* @var Faker\Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Address($faker));
$this->faker = $faker;
}
public function testCityName()
{
$city = $this->faker->cityName();
$this->assertNotEmpty($city);
$this->assertInternalType('string', $city);
}
public function testDistrict()
{
$district = $this->faker->district();
$this->assertNotEmpty($district);
$this->assertInternalType('string', $district);
}
public function testRegion()
{
$region = $this->faker->region();
$this->assertNotEmpty($region);
$this->assertInternaltype('string', $region);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/cs_CZ/PersonTest.php | test/Faker/Provider/cs_CZ/PersonTest.php | <?php
namespace Faker\Test\Provider\cs_CZ;
use Faker\Generator;
use Faker\Provider\cs_CZ\Person;
use Faker\Provider\Miscellaneous;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
public function testBirthNumber()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$faker->addProvider(new Miscellaneous($faker));
for ($i = 0; $i < 1000; $i++) {
$birthNumber = $faker->birthNumber();
$birthNumber = str_replace('/', '', $birthNumber);
// check date
$year = intval(substr($birthNumber, 0, 2), 10);
$month = intval(substr($birthNumber, 2, 2), 10);
$day = intval(substr($birthNumber, 4, 2), 10);
// make 4 digit year from 2 digit representation
$year += $year < 54 ? 2000 : 1900;
// adjust special cases for month
if ($month > 50) $month -= 50;
if ($year >= 2004 && $month > 20) $month -= 20;
$this->assertTrue(checkdate($month, $day, $year), "Birth number $birthNumber: date $year/$month/$day is invalid.");
// check CRC if presented
if (strlen($birthNumber) == 10) {
$crc = intval(substr($birthNumber, -1), 10);
$refCrc = intval(substr($birthNumber, 0, -1), 10) % 11;
if ($refCrc == 10) {
$refCrc = 0;
}
$this->assertEquals($crc, $refCrc, "Birth number $birthNumber: checksum $crc doesn't match expected $refCrc.");
}
}
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/pl_PL/PersonTest.php | test/Faker/Provider/pl_PL/PersonTest.php | <?php
namespace Faker\Provider\pl_PL;
use DateTime;
use Faker\Generator;
use PHPUnit\Framework\TestCase;
final class PersonTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Person($faker));
$this->faker = $faker;
}
public function testPeselLenght()
{
$pesel = $this->faker->pesel();
$this->assertEquals(11, strlen($pesel));
}
public function testPeselDate()
{
$date = new DateTime('1990-01-01');
$pesel = $this->faker->pesel($date);
$this->assertEquals('90', substr($pesel, 0, 2));
$this->assertEquals('01', substr($pesel, 2, 2));
$this->assertEquals('01', substr($pesel, 4, 2));
}
public function testPeselDateWithYearAfter2000()
{
$date = new DateTime('2001-01-01');
$pesel = $this->faker->pesel($date);
$this->assertEquals('01', substr($pesel, 0, 2));
$this->assertEquals('21', substr($pesel, 2, 2));
$this->assertEquals('01', substr($pesel, 4, 2));
}
public function testPeselDateWithYearAfter2100()
{
$date = new DateTime('2101-01-01');
$pesel = $this->faker->pesel($date);
$this->assertEquals('01', substr($pesel, 0, 2));
$this->assertEquals('41', substr($pesel, 2, 2));
$this->assertEquals('01', substr($pesel, 4, 2));
}
public function testPeselDateWithYearAfter2200()
{
$date = new DateTime('2201-01-01');
$pesel = $this->faker->pesel($date);
$this->assertEquals('01', substr($pesel, 0, 2));
$this->assertEquals('61', substr($pesel, 2, 2));
$this->assertEquals('01', substr($pesel, 4, 2));
}
public function testPeselDateWithYearBefore1900()
{
$date = new DateTime('1801-01-01');
$pesel = $this->faker->pesel($date);
$this->assertEquals('01', substr($pesel, 0, 2));
$this->assertEquals('81', substr($pesel, 2, 2));
$this->assertEquals('01', substr($pesel, 4, 2));
}
public function testPeselSex()
{
$male = $this->faker->pesel(null, 'M');
$female = $this->faker->pesel(null, 'F');
$this->assertEquals(1, $male[9] % 2);
$this->assertEquals(0, $female[9] % 2);
}
public function testPeselCheckSum()
{
$pesel = $this->faker->pesel();
$weights = array(1, 3, 7, 9, 1, 3, 7, 9, 1, 3, 1);
$sum = 0;
foreach ($weights as $key => $weight) {
$sum += $pesel[$key] * $weight;
}
$this->assertEquals(0, $sum % 10);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Provider/pl_PL/AddressTest.php | test/Faker/Provider/pl_PL/AddressTest.php | <?php
namespace Faker\Provider\pl_PL;
use Faker\Generator;
use PHPUnit\Framework\TestCase;
final class AddressTest extends TestCase
{
/**
* @var Generator
*/
private $faker;
protected function setUp()
{
$faker = new Generator();
$faker->addProvider(new Address($faker));
$this->faker = $faker;
}
/**
* Test the validity of state
*/
public function testState()
{
$state = $this->faker->state();
$this->assertNotEmpty($state);
$this->assertInternalType('string', $state);
$this->assertRegExp('/[a-z]+/', $state);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Calculator/IbanTest.php | test/Faker/Calculator/IbanTest.php | <?php
namespace Faker\Test\Calculator;
use Faker\Calculator\Iban;
use PHPUnit\Framework\TestCase;
final class IbanTest extends TestCase
{
public function checksumProvider()
{
return array(
array('AL47212110090000000235698741', '47'),
array('AD1200012030200359100100', '12'),
array('AT611904300234573201', '61'),
array('AZ21NABZ00000000137010001944', '21'),
array('BH67BMAG00001299123456', '67'),
array('BE68539007547034', '68'),
array('BA391290079401028494', '39'),
array('BR7724891749412660603618210F3', '77'),
array('BG80BNBG96611020345678', '80'),
array('CR0515202001026284066', '05'),
array('HR1210010051863000160', '12'),
array('CY17002001280000001200527600', '17'),
array('CZ6508000000192000145399', '65'),
array('DK5000400440116243', '50'),
array('DO28BAGR00000001212453611324', '28'),
array('EE382200221020145685', '38'),
array('FO6264600001631634', '62'),
array('FI2112345600000785', '21'),
array('FR1420041010050500013M02606', '14'),
array('GE29NB0000000101904917', '29'),
array('DE89370400440532013000', '89'),
array('GI75NWBK000000007099453', '75'),
array('GR1601101250000000012300695', '16'),
array('GL8964710001000206', '89'),
array('GT82TRAJ01020000001210029690', '82'),
array('HU42117730161111101800000000', '42'),
array('IS140159260076545510730339', '14'),
array('IE29AIBK93115212345678', '29'),
array('IL620108000000099999999', '62'),
array('IT60X0542811101000000123456', '60'),
array('KZ86125KZT5004100100', '86'),
array('KW81CBKU0000000000001234560101', '81'),
array('LV80BANK0000435195001', '80'),
array('LB62099900000001001901229114', '62'),
array('LI21088100002324013AA', '21'),
array('LT121000011101001000', '12'),
array('LU280019400644750000', '28'),
array('MK07250120000058984', '07'),
array('MT84MALT011000012345MTLCAST001S', '84'),
array('MR1300020001010000123456753', '13'),
array('MU17BOMM0101101030300200000MUR', '17'),
array('MD24AG000225100013104168', '24'),
array('MC5811222000010123456789030', '58'),
array('ME25505000012345678951', '25'),
array('NL91ABNA0417164300', '91'),
array('NO9386011117947', '93'),
array('PK36SCBL0000001123456702', '36'),
array('PL61109010140000071219812874', '61'),
array('PS92PALS000000000400123456702', '92'),
array('PT50000201231234567890154', '50'),
array('QA58DOHB00001234567890ABCDEFG', '58'),
array('RO49AAAA1B31007593840000', '49'),
array('SM86U0322509800000000270100', '86'),
array('SA0380000000608010167519', '03'),
array('RS35260005601001611379', '35'),
array('SK3112000000198742637541', '31'),
array('SI56263300012039086', '56'),
array('ES9121000418450200051332', '91'),
array('SE4550000000058398257466', '45'),
array('CH9300762011623852957', '93'),
array('TN5910006035183598478831', '59'),
array('TR330006100519786457841326', '33'),
array('AE070331234567890123456', '07'),
array('GB29NWBK60161331926819', '29'),
array('VG96VPVG0000012345678901', '96'),
array('YY24KIHB12476423125915947930915268', '24'),
array('ZZ25VLQT382332233206588011313776421', '25'),
);
}
/**
* @dataProvider checksumProvider
*/
public function testChecksum($iban, $checksum)
{
$this->assertEquals($checksum, Iban::checksum($iban), $iban);
}
public function validatorProvider()
{
return array(
array('AL47212110090000000235698741', true),
array('AD1200012030200359100100', true),
array('AT611904300234573201', true),
array('AZ21NABZ00000000137010001944', true),
array('BH67BMAG00001299123456', true),
array('BE68539007547034', true),
array('BA391290079401028494', true),
array('BR7724891749412660603618210F3', true),
array('BG80BNBG96611020345678', true),
array('CR0515202001026284066', true),
array('HR1210010051863000160', true),
array('CY17002001280000001200527600', true),
array('CZ6508000000192000145399', true),
array('DK5000400440116243', true),
array('DO28BAGR00000001212453611324', true),
array('EE382200221020145685', true),
array('FO6264600001631634', true),
array('FI2112345600000785', true),
array('FR1420041010050500013M02606', true),
array('GE29NB0000000101904917', true),
array('DE89370400440532013000', true),
array('GI75NWBK000000007099453', true),
array('GR1601101250000000012300695', true),
array('GL8964710001000206', true),
array('GT82TRAJ01020000001210029690', true),
array('HU42117730161111101800000000', true),
array('IS140159260076545510730339', true),
array('IE29AIBK93115212345678', true),
array('IL620108000000099999999', true),
array('IT60X0542811101000000123456', true),
array('KZ86125KZT5004100100', true),
array('KW81CBKU0000000000001234560101', true),
array('LV80BANK0000435195001', true),
array('LB62099900000001001901229114', true),
array('LI21088100002324013AA', true),
array('LT121000011101001000', true),
array('LU280019400644750000', true),
array('MK07250120000058984', true),
array('MT84MALT011000012345MTLCAST001S', true),
array('MR1300020001010000123456753', true),
array('MU17BOMM0101101030300200000MUR', true),
array('MD24AG000225100013104168', true),
array('MC5811222000010123456789030', true),
array('ME25505000012345678951', true),
array('NL91ABNA0417164300', true),
array('NO9386011117947', true),
array('PK36SCBL0000001123456702', true),
array('PL61109010140000071219812874', true),
array('PS92PALS000000000400123456702', true),
array('PT50000201231234567890154', true),
array('QA58DOHB00001234567890ABCDEFG', true),
array('RO49AAAA1B31007593840000', true),
array('SM86U0322509800000000270100', true),
array('SA0380000000608010167519', true),
array('RS35260005601001611379', true),
array('SK3112000000198742637541', true),
array('SI56263300012039086', true),
array('ES9121000418450200051332', true),
array('SE4550000000058398257466', true),
array('CH9300762011623852957', true),
array('TN5910006035183598478831', true),
array('TR330006100519786457841326', true),
array('AE070331234567890123456', true),
array('GB29NWBK60161331926819', true),
array('VG96VPVG0000012345678901', true),
array('YY24KIHB12476423125915947930915268', true),
array('ZZ25VLQT382332233206588011313776421', true),
array('AL4721211009000000023569874', false),
array('AD120001203020035910010', false),
array('AT61190430023457320', false),
array('AZ21NABZ0000000013701000194', false),
array('BH67BMAG0000129912345', false),
array('BE6853900754703', false),
array('BA39129007940102849', false),
array('BR7724891749412660603618210F', false),
array('BG80BNBG9661102034567', false),
array('CR051520200102628406', false),
array('HR121001005186300016', false),
array('CY1700200128000000120052760', false),
array('CZ650800000019200014539', false),
array('DK500040044011624', false),
array('DO28BAGR0000000121245361132', false),
array('EE38220022102014568', false),
array('FO626460000163163', false),
array('FI2112345600000780', false),
array('FR1420041010050500013M0260', false),
array('GE29NB000000010190491', false),
array('DE8937040044053201300', false),
array('GI75NWBK00000000709945', false),
array('GR160110125000000001230069', false),
array('GL896471000100020', false),
array('GT82TRAJ0102000000121002969', false),
array('HU4211773016111110180000000', false),
array('IS14015926007654551073033', false),
array('IE29AIBK9311521234567', false),
array('IL62010800000009999999', false),
array('IT60X054281110100000012345', false),
array('KZ86125KZT500410010', false),
array('KW81CBKU000000000000123456010', false),
array('LV80BANK000043519500', false),
array('LB6209990000000100190122911', false),
array('LI21088100002324013A', false),
array('LT12100001110100100', false),
array('LU28001940064475000', false),
array('MK0725012000005898', false),
array('MT84MALT011000012345MTLCAST001', false),
array('MR130002000101000012345675', false),
array('MU17BOMM0101101030300200000MU', false),
array('MD24AG00022510001310416', false),
array('MC58112220000101234567890', false),
array('ME2550500001234567895', false),
array('NL91ABNA041716430', false),
array('NO938601111794', false),
array('PK36SCBL000000112345670', false),
array('PL6110901014000007121981287', false),
array('PS92PALS00000000040012345670', false),
array('PT5000020123123456789015', false),
array('QA58DOHB00001234567890ABCDEF', false),
array('RO49AAAA1B3100759384000', false),
array('SM86U032250980000000027010', false),
array('SA038000000060801016751', false),
array('RS3526000560100161137', false),
array('SK311200000019874263754', false),
array('SI5626330001203908', false),
array('ES912100041845020005133', false),
array('SE455000000005839825746', false),
array('CH930076201162385295', false),
array('TN591000603518359847883', false),
array('TR33000610051978645784132', false),
array('AE07033123456789012345', false),
array('GB29NWBK6016133192681', false),
array('VG96VPVG000001234567890', false),
array('YY24KIHB1247642312591594793091526', false),
array('ZZ25VLQT38233223320658801131377642', false),
);
}
/**
* @dataProvider validatorProvider
*/
public function testIsValid($iban, $isValid)
{
$this->assertEquals($isValid, Iban::isValid($iban), $iban);
}
public function alphaToNumberProvider()
{
return array(
array('A', 10),
array('B', 11),
array('C', 12),
array('D', 13),
array('E', 14),
array('F', 15),
array('G', 16),
array('H', 17),
array('I', 18),
array('J', 19),
array('K', 20),
array('L', 21),
array('M', 22),
array('N', 23),
array('O', 24),
array('P', 25),
array('Q', 26),
array('R', 27),
array('S', 28),
array('T', 29),
array('U', 30),
array('V', 31),
array('W', 32),
array('X', 33),
array('Y', 34),
array('Z', 35),
);
}
/**
* @dataProvider alphaToNumberProvider
*/
public function testAlphaToNumber($letter, $number)
{
$this->assertEquals($number, Iban::alphaToNumber($letter), $letter);
}
public function mod97Provider()
{
// Large numbers
$return = array(
array('123456789123456789', 7),
array('111222333444555666', 73),
array('4242424242424242424242', 19),
array('271828182845904523536028', 68),
);
// 0-200
for ($i = 0; $i < 200; $i++) {
$return[] = array((string)$i, $i % 97);
}
return $return;
}
/**
* @dataProvider mod97Provider
*/
public function testMod97($number, $result)
{
$this->assertEquals($result, Iban::mod97($number), $number);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Calculator/EanTest.php | test/Faker/Calculator/EanTest.php | <?php
namespace Faker\Test\Calculator;
use Faker\Calculator\Ean;
use PHPUnit\Framework\TestCase;
final class EanTest extends TestCase
{
public function Ean8checksumProvider()
{
return array(
array('1234567', '0'),
array('2345678', '5'),
array('3456789', '0'),
);
}
public function ean8ValidationProvider()
{
return array(
array('1234567891231', true),
array('2354698521469', true),
array('3001092650834', false),
array('3921092190838', false),
);
}
/**
* @dataProvider Ean8checksumProvider
*/
public function testChecksumEan8($partial, $checksum)
{
$this->assertEquals($checksum, Ean::checksum($partial));
}
/**
* @dataProvider ean8ValidationProvider
*/
public function testEan8Validation($ean8, $valid)
{
$this->assertTrue(Ean::isValid($ean8) === $valid);
}
public function Ean13checksumProvider()
{
return array(
array('123456789123', '1'),
array('978020137962', '4'),
array('235469852146', '9'),
array('300109265083', '5'),
array('392109219083', '7'),
);
}
public function ean13ValidationProvider()
{
return array(
array('1234567891231', true),
array('2354698521469', true),
array('3001092650834', false),
array('3921092190838', false),
);
}
/**
* @dataProvider Ean13checksumProvider
*/
public function testChecksumEan13($partial, $checksum)
{
$this->assertEquals($checksum, Ean::checksum($partial));
}
/**
* @dataProvider ean13ValidationProvider
*/
public function testEan13Validation($ean13, $valid)
{
$this->assertTrue(Ean::isValid($ean13) === $valid);
}
} | php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Calculator/LuhnTest.php | test/Faker/Calculator/LuhnTest.php | <?php
namespace Faker\Test\Calculator;
use Faker\Calculator\Luhn;
use PHPUnit\Framework\TestCase;
final class LuhnTest extends TestCase
{
public function checkDigitProvider()
{
return array(
array('7992739871', '3'),
array('3852000002323', '7'),
array('37144963539843', '1'),
array('561059108101825', '0'),
array('601100099013942', '4'),
array('510510510510510', '0'),
array(7992739871, '3'),
array(3852000002323, '7'),
array('37144963539843', '1'),
array('561059108101825', '0'),
array('601100099013942', '4'),
array('510510510510510', '0')
);
}
/**
* @dataProvider checkDigitProvider
*/
public function testComputeCheckDigit($partialNumber, $checkDigit)
{
$this->assertInternalType('string', $checkDigit);
$this->assertEquals($checkDigit, Luhn::computeCheckDigit($partialNumber));
}
public function validatorProvider()
{
return array(
array('79927398710', false),
array('79927398711', false),
array('79927398712', false),
array('79927398713', true),
array('79927398714', false),
array('79927398715', false),
array('79927398716', false),
array('79927398717', false),
array('79927398718', false),
array('79927398719', false),
array(79927398713, true),
array(79927398714, false),
);
}
/**
* @dataProvider validatorProvider
*/
public function testIsValid($number, $isValid)
{
$this->assertEquals($isValid, Luhn::isValid($number));
}
/**
* @expectedException InvalidArgumentException
* @expectedExceptionMessage Argument should be an integer.
*/
public function testGenerateLuhnNumberWithInvalidPrefix()
{
Luhn::generateLuhnNumber('abc');
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Calculator/InnTest.php | test/Faker/Calculator/InnTest.php | <?php
namespace Faker\Test\Calculator;
use Faker\Calculator\Inn;
use PHPUnit\Framework\TestCase;
final class InnTest extends TestCase
{
public function checksumProvider()
{
return array(
array('143525744', '4'),
array('500109285', '3'),
array('500109285', '3'),
array('500109285', '3'),
array('027615723', '1')
);
}
/**
* @dataProvider checksumProvider
*/
public function testChecksum($inn, $checksum)
{
$this->assertEquals($checksum, Inn::checksum($inn), $inn);
}
public function validatorProvider()
{
return array(
array('5902179757', true),
array('5408294405', true),
array('2724164617', true),
array('0726000515', true),
array('6312123552', true),
array('1111111111', false),
array('0123456789', false),
);
}
/**
* @dataProvider validatorProvider
*/
public function testIsValid($inn, $isValid)
{
$this->assertEquals($isValid, Inn::isValid($inn), $inn);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/test/Faker/Calculator/TCNoTest.php | test/Faker/Calculator/TCNoTest.php | <?php
namespace Faker\Test\Calculator;
use Faker\Calculator\TCNo;
use PHPUnit\Framework\TestCase;
final class TCNoTest extends TestCase
{
public function checksumProvider()
{
return array(
array('553006348', '82'),
array('350630743', '78'),
array('550600932', '88'),
array('487932947', '70'),
array('168113862', '40')
);
}
/**
* @dataProvider checksumProvider
* @param $tcNo
* @param $checksum
*/
public function testChecksum($tcNo, $checksum)
{
$this->assertEquals($checksum, TCNo::checksum($tcNo), $tcNo);
}
public function validatorProvider()
{
return array(
array('22978160678', true),
array('26480045324', true),
array('47278360658', true),
array('34285002510', true),
array('19874561012', true),
array('11111111111', false),
array('11234567899', false),
);
}
/**
* @dataProvider validatorProvider
* @param $tcNo
* @param $isValid
*/
public function testIsValid($tcNo, $isValid)
{
$this->assertEquals($isValid, TCNo::isValid($tcNo), $tcNo);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/.php-cs-fixer.dist.php | .php-cs-fixer.dist.php | <?php
$finder = PhpCsFixer\Finder::create()
->exclude(['vendor', 'docs', '.git', '.github'])
->notPath('src/PhpSpreadsheet/Writer/ZipStream3.php')
->in(__DIR__);
$config = new PhpCsFixer\Config();
$config
->setRiskyAllowed(true)
->setFinder($finder)
->setParallelConfig(PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect(null, 600))
->setCacheFile(sys_get_temp_dir() . '/php-cs-fixer' . preg_replace('~\W~', '-', __DIR__))
->setRules([
'align_multiline_comment' => true,
'array_indentation' => true,
'array_syntax' => ['syntax' => 'short'],
'backtick_to_shell_exec' => true,
'binary_operator_spaces' => true,
'blank_line_after_namespace' => true,
'blank_lines_before_namespace' => ['max_line_breaks' => 2, 'min_line_breaks' => 2], // we want 1 blank line before namespace
'blank_line_after_opening_tag' => true,
'blank_line_before_statement' => true,
'cast_spaces' => true,
'class_attributes_separation' => ['elements' => ['method' => 'one', 'property' => 'one']], // const are often grouped with other related const
'class_definition' => false, // phpcs disagree
'combine_consecutive_issets' => true,
'combine_consecutive_unsets' => true,
'combine_nested_dirname' => true,
'comment_to_phpdoc' => false, // interferes with annotations
'compact_nullable_type_declaration' => true,
'concat_space' => ['spacing' => 'one'],
'constant_case' => true,
'date_time_immutable' => false, // Break our unit tests
'declare_equal_normalize' => true,
'declare_strict_types' => false, // Too early to adopt strict types
'dir_constant' => true,
'doctrine_annotation_array_assignment' => true,
'doctrine_annotation_braces' => true,
'doctrine_annotation_indentation' => true,
'doctrine_annotation_spaces' => true,
'elseif' => true,
'empty_loop_body' => true,
'empty_loop_condition' => true,
'encoding' => true,
'ereg_to_preg' => true,
'error_suppression' => false, // it breaks \PhpOffice\PhpSpreadsheet\Helper\Handler
'explicit_indirect_variable' => false, // I feel it makes the code actually harder to read
'explicit_string_variable' => false, // I feel it makes the code actually harder to read
'final_class' => false, // We need non-final classes
'final_internal_class' => true,
'final_public_method_for_abstract_class' => false, // We need non-final methods
'fopen_flag_order' => true,
'fopen_flags' => true,
'full_opening_tag' => true,
'fully_qualified_strict_types' => true,
'function_declaration' => true,
'function_to_constant' => true,
'general_phpdoc_annotation_remove' => ['annotations' => ['access', 'category', 'copyright']],
'general_phpdoc_tag_rename' => true,
'global_namespace_import' => true,
'group_import' => false, // I feel it makes the code actually harder to read
'header_comment' => false, // We don't use common header in all our files
'heredoc_indentation' => true,
'heredoc_to_nowdoc' => false, // Not sure about this one
'implode_call' => true,
'include' => true,
'increment_style' => true,
'indentation_type' => true,
'integer_literal_case' => true,
'is_null' => true,
'lambda_not_used_import' => true,
'line_ending' => true,
'linebreak_after_opening_tag' => true,
'list_syntax' => ['syntax' => 'short'],
'logical_operators' => true,
'lowercase_cast' => true,
'lowercase_keywords' => true,
'lowercase_static_reference' => true,
'magic_constant_casing' => true,
'magic_method_casing' => true,
'mb_str_functions' => false, // No, too dangerous to change that
'method_argument_space' => true,
'method_chaining_indentation' => true,
'modernize_strpos' => true,
'modernize_types_casting' => true,
'modifier_keywords' => ['elements' => ['property', 'method']], // not const
'multiline_comment_opening_closing' => true,
'multiline_whitespace_before_semicolons' => true,
'native_constant_invocation' => false, // Micro optimization that look messy
'native_function_casing' => true,
'native_function_invocation' => false, // I suppose this would be best, but I am still unconvinced about the visual aspect of it
'new_with_parentheses' => ['anonymous_class' => true, 'named_class' => true],
'no_alias_functions' => true,
'no_alias_language_construct_call' => true,
'no_alternative_syntax' => true,
'no_binary_string' => true,
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
'no_break_comment' => true,
'no_closing_tag' => true,
'no_empty_comment' => true,
'no_empty_phpdoc' => true,
'no_empty_statement' => true,
'no_extra_blank_lines' => true,
'no_homoglyph_names' => true,
'no_leading_import_slash' => true,
'no_leading_namespace_whitespace' => true,
'no_mixed_echo_print' => true,
'no_multiline_whitespace_around_double_arrow' => true,
'no_null_property_initialization' => true,
'no_php4_constructor' => true,
'no_short_bool_cast' => true,
'echo_tag_syntax' => ['format' => 'long'],
'no_singleline_whitespace_before_semicolons' => true,
'no_space_around_double_colon' => true,
'no_spaces_after_function_name' => true,
'no_spaces_around_offset' => true,
'no_superfluous_elseif' => false, // Might be risky on a huge code base
'no_superfluous_phpdoc_tags' => ['allow_mixed' => true],
'no_trailing_comma_in_singleline' => ['elements' => ['arguments', 'array_destructuring', 'array', 'group_import']],
'no_trailing_whitespace' => true,
'no_trailing_whitespace_in_comment' => true,
'no_trailing_whitespace_in_string' => false, // Too dangerous
'no_unneeded_control_parentheses' => true,
'no_unneeded_braces' => true,
'no_unneeded_final_method' => true,
'no_unreachable_default_argument_value' => true,
'no_unset_cast' => true,
'no_unset_on_property' => false,
'no_unused_imports' => true,
'no_useless_else' => true,
'no_useless_return' => true,
'no_useless_sprintf' => true,
'no_whitespace_before_comma_in_array' => true,
'no_whitespace_in_blank_line' => true,
'non_printable_character' => true,
'normalize_index_brace' => true,
'not_operator_with_space' => false, // No we prefer to keep '!' without spaces
'not_operator_with_successor_space' => false, // idem
'nullable_type_declaration_for_default_null_value' => true,
'object_operator_without_whitespace' => true,
'octal_notation' => true,
'operator_linebreak' => true,
'ordered_class_elements' => false, // We prefer to keep some freedom
'ordered_imports' => true,
'ordered_interfaces' => true,
'ordered_traits' => true,
'php_unit_attributes' => ['keep_annotations' => false],
'php_unit_construct' => true,
'php_unit_dedicate_assert' => true,
'php_unit_dedicate_assert_internal_type' => true,
'php_unit_expectation' => true,
'php_unit_fqcn_annotation' => true,
'php_unit_internal_class' => false, // Because tests are excluded from package
'php_unit_method_casing' => true,
'php_unit_mock' => true,
'php_unit_mock_short_will_return' => true,
'php_unit_namespaced' => true,
'php_unit_no_expectation_annotation' => true,
'phpdoc_order_by_value' => ['annotations' => ['covers']],
'php_unit_set_up_tear_down_visibility' => true,
'php_unit_size_class' => false, // That seems extra work to maintain for little benefits
'php_unit_strict' => false, // We sometime actually need assertEquals
'php_unit_test_annotation' => true,
'php_unit_test_case_static_method_calls' => ['call_type' => 'self'],
'php_unit_test_class_requires_covers' => false, // We don't care as much as we should about coverage
'phpdoc_add_missing_param_annotation' => false, // Don't add things that bring no value
'phpdoc_align' => false, // Waste of time
'phpdoc_annotation_without_dot' => false,
'phpdoc_indent' => true,
'phpdoc_line_span' => false, // Unfortunately our old comments turn even uglier with this
'phpdoc_no_access' => true,
'phpdoc_no_alias_tag' => true,
'phpdoc_no_empty_return' => true,
'phpdoc_no_package' => true,
'phpdoc_no_useless_inheritdoc' => true,
'phpdoc_order' => true,
'phpdoc_return_self_reference' => true,
'phpdoc_scalar' => true,
'phpdoc_separation' => true,
'phpdoc_single_line_var_spacing' => true,
'phpdoc_summary' => true,
'phpdoc_tag_casing' => true,
'phpdoc_tag_type' => true,
'phpdoc_to_comment' => false, // interferes with annotations
'phpdoc_to_param_type' => false, // Because experimental, but interesting for one shot use
'phpdoc_to_property_type' => false, // Because experimental, but interesting for one shot use
'phpdoc_to_return_type' => false, // Because experimental, but interesting for one shot use
'phpdoc_trim' => true,
'phpdoc_trim_consecutive_blank_line_separation' => true,
'phpdoc_types' => true,
'phpdoc_types_order' => true,
'phpdoc_var_annotation_correct_order' => true,
'phpdoc_var_without_name' => true,
'pow_to_exponentiation' => true,
'protected_to_private' => true,
'psr_autoloading' => true,
'random_api_migration' => true,
'return_assignment' => false, // Sometimes useful for clarity or debug
'return_type_declaration' => true,
'self_accessor' => true,
'self_static_accessor' => true,
'semicolon_after_instruction' => false, // Buggy in `samples/index.php`
'set_type_to_cast' => true,
'short_scalar_cast' => true,
'simple_to_complex_string_variable' => false, // Would differ from TypeScript without obvious advantages
'simplified_if_return' => false, // Even if technically correct we prefer to be explicit
'simplified_null_return' => false, // Even if technically correct we prefer to be explicit
'single_blank_line_at_eof' => true,
'single_class_element_per_statement' => true,
'single_import_per_statement' => true,
'single_line_after_imports' => true,
'single_line_comment_style' => true,
'single_line_throw' => false, // I don't see any reason for having a special case for Exception
'single_quote' => true,
'single_trait_insert_per_statement' => true,
'space_after_semicolon' => true,
'spaces_inside_parentheses' => ['space' => 'none'],
'standardize_increment' => true,
'standardize_not_equals' => true,
'static_lambda' => false, // Risky if we can't guarantee nobody use `bindTo()`
'strict_comparison' => false, // No, too dangerous to change that
'string_implicit_backslashes' => ['single_quoted' => 'unescape', 'double_quoted' => 'escape', 'heredoc' => 'escape'], // was escape_implicit_backslashes
'strict_param' => false, // No, too dangerous to change that
'string_length_to_empty' => true,
'string_line_ending' => true,
'switch_case_semicolon_to_colon' => true,
'switch_case_space' => true,
'switch_continue_to_break' => true,
'ternary_operator_spaces' => true,
'ternary_to_elvis_operator' => true,
'ternary_to_null_coalescing' => true,
'trailing_comma_in_multiline' => true,
'trim_array_spaces' => true,
'type_declaration_spaces' => ['elements' => ['function', 'property']], // was function_typehint_space
'types_spaces' => true,
'unary_operator_spaces' => true,
'use_arrow_functions' => true,
'void_return' => true,
'whitespace_after_comma_in_array' => true,
'yoda_style' => false,
]);
return $config;
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Theme.php | src/PhpSpreadsheet/Theme.php | <?php
namespace PhpOffice\PhpSpreadsheet;
class Theme
{
private string $themeColorName = 'Office';
private string $themeFontName = 'Office';
public const HYPERLINK_THEME = 10;
public const COLOR_SCHEME_2013_2022_NAME = 'Office 2013-2022';
public const COLOR_SCHEME_2013_2022 = [
'dk1' => '000000',
'lt1' => 'FFFFFF',
'dk2' => '44546A',
'lt2' => 'E7E6E6',
'accent1' => '4472C4',
'accent2' => 'ED7D31',
'accent3' => 'A5A5A5',
'accent4' => 'FFC000',
'accent5' => '5B9BD5',
'accent6' => '70AD47',
'hlink' => '0563C1',
'folHlink' => '954F72',
];
private const COLOR_SCHEME_2013_PLUS_NAME = 'Office 2013+';
public const COLOR_SCHEME_2007_2010_NAME = 'Office 2007-2010';
public const COLOR_SCHEME_2007_2010 = [
'dk1' => '000000',
'lt1' => 'FFFFFF',
'dk2' => '1F497D',
'lt2' => 'EEECE1',
'accent1' => '4F81BD',
'accent2' => 'C0504D',
'accent3' => '9BBB59',
'accent4' => '8064A2',
'accent5' => '4BACC6',
'accent6' => 'F79646',
'hlink' => '0000FF',
'folHlink' => '800080',
];
public const COLOR_SCHEME_2023_PLUS_NAME = 'Office 2023+';
public const COLOR_SCHEME_2023_PLUS = [
'dk1' => '000000',
'lt1' => 'FFFFFF',
'dk2' => '0E2841',
'lt2' => 'E8E8E8',
'accent1' => '156082',
'accent2' => 'E97132',
'accent3' => '196B24',
'accent4' => '0F9ED5',
'accent5' => 'A02B93',
'accent6' => '4EA72E',
'hlink' => '467886',
'folHlink' => '96607D',
];
/** @var string[] */
private array $themeColors = self::COLOR_SCHEME_2007_2010;
private string $majorFontLatin = 'Cambria';
private string $majorFontEastAsian = '';
private string $majorFontComplexScript = '';
private string $minorFontLatin = 'Calibri';
private string $minorFontEastAsian = '';
private string $minorFontComplexScript = '';
/**
* Map of Major (header) fonts to write.
*
* @var string[]
*/
private array $majorFontSubstitutions = self::FONTS_TIMES_SUBSTITUTIONS;
/**
* Map of Minor (body) fonts to write.
*
* @var string[]
*/
private array $minorFontSubstitutions = self::FONTS_ARIAL_SUBSTITUTIONS;
public const FONTS_TIMES_SUBSTITUTIONS = [
'Jpan' => 'MS Pゴシック',
'Hang' => '맑은 고딕',
'Hans' => '宋体',
'Hant' => '新細明體',
'Arab' => 'Times New Roman',
'Hebr' => 'Times New Roman',
'Thai' => 'Tahoma',
'Ethi' => 'Nyala',
'Beng' => 'Vrinda',
'Gujr' => 'Shruti',
'Khmr' => 'MoolBoran',
'Knda' => 'Tunga',
'Guru' => 'Raavi',
'Cans' => 'Euphemia',
'Cher' => 'Plantagenet Cherokee',
'Yiii' => 'Microsoft Yi Baiti',
'Tibt' => 'Microsoft Himalaya',
'Thaa' => 'MV Boli',
'Deva' => 'Mangal',
'Telu' => 'Gautami',
'Taml' => 'Latha',
'Syrc' => 'Estrangelo Edessa',
'Orya' => 'Kalinga',
'Mlym' => 'Kartika',
'Laoo' => 'DokChampa',
'Sinh' => 'Iskoola Pota',
'Mong' => 'Mongolian Baiti',
'Viet' => 'Times New Roman',
'Uigh' => 'Microsoft Uighur',
'Geor' => 'Sylfaen',
];
public const FONTS_ARIAL_SUBSTITUTIONS = [
'Jpan' => 'MS Pゴシック',
'Hang' => '맑은 고딕',
'Hans' => '宋体',
'Hant' => '新細明體',
'Arab' => 'Arial',
'Hebr' => 'Arial',
'Thai' => 'Tahoma',
'Ethi' => 'Nyala',
'Beng' => 'Vrinda',
'Gujr' => 'Shruti',
'Khmr' => 'DaunPenh',
'Knda' => 'Tunga',
'Guru' => 'Raavi',
'Cans' => 'Euphemia',
'Cher' => 'Plantagenet Cherokee',
'Yiii' => 'Microsoft Yi Baiti',
'Tibt' => 'Microsoft Himalaya',
'Thaa' => 'MV Boli',
'Deva' => 'Mangal',
'Telu' => 'Gautami',
'Taml' => 'Latha',
'Syrc' => 'Estrangelo Edessa',
'Orya' => 'Kalinga',
'Mlym' => 'Kartika',
'Laoo' => 'DokChampa',
'Sinh' => 'Iskoola Pota',
'Mong' => 'Mongolian Baiti',
'Viet' => 'Arial',
'Uigh' => 'Microsoft Uighur',
'Geor' => 'Sylfaen',
];
/** @return string[] */
public function getThemeColors(): array
{
return $this->themeColors;
}
public function setThemeColor(string $key, string $value): self
{
$this->themeColors[$key] = $value;
return $this;
}
public function getThemeColorName(): string
{
return $this->themeColorName;
}
/** @param null|string[] $themeColors */
public function setThemeColorName(string $name, ?array $themeColors = null, ?Spreadsheet $spreadsheet = null): self
{
if ($name === self::COLOR_SCHEME_2013_PLUS_NAME) {
// Ensure against this value being found in
// spreadsheets created while constant was public.
$name = self::COLOR_SCHEME_2013_2022_NAME;
}
$this->themeColorName = $name;
if ($name === self::COLOR_SCHEME_2007_2010_NAME) {
$themeColors = $themeColors ?? self::COLOR_SCHEME_2007_2010;
$this->majorFontLatin = 'Cambria';
$this->minorFontLatin = 'Calibri';
} elseif ($name === self::COLOR_SCHEME_2013_2022_NAME) {
$themeColors = $themeColors ?? self::COLOR_SCHEME_2013_2022;
$this->majorFontLatin = 'Calibri Light';
$this->minorFontLatin = 'Calibri';
} elseif ($name === self::COLOR_SCHEME_2023_PLUS_NAME) {
$themeColors = $themeColors ?? self::COLOR_SCHEME_2023_PLUS;
$this->majorFontLatin = 'Aptos Display';
$this->minorFontLatin = 'Aptos Narrow';
}
if ($themeColors !== null) {
$this->themeColors = $themeColors;
}
if ($spreadsheet !== null) {
$spreadsheet->getDefaultStyle()->getFont()
->applyThemeFonts($this);
}
return $this;
}
public function getMajorFontLatin(): string
{
return $this->majorFontLatin;
}
public function getMajorFontEastAsian(): string
{
return $this->majorFontEastAsian;
}
public function getMajorFontComplexScript(): string
{
return $this->majorFontComplexScript;
}
/** @return string[] */
public function getMajorFontSubstitutions(): array
{
return $this->majorFontSubstitutions;
}
/** @param null|string[] $substitutions */
public function setMajorFontValues(?string $latin, ?string $eastAsian, ?string $complexScript, ?array $substitutions): self
{
if (!empty($latin)) {
$this->majorFontLatin = $latin;
}
if ($eastAsian !== null) {
$this->majorFontEastAsian = $eastAsian;
}
if ($complexScript !== null) {
$this->majorFontComplexScript = $complexScript;
}
if ($substitutions !== null) {
$this->majorFontSubstitutions = $substitutions;
}
return $this;
}
public function getMinorFontLatin(): string
{
return $this->minorFontLatin;
}
public function getMinorFontEastAsian(): string
{
return $this->minorFontEastAsian;
}
public function getMinorFontComplexScript(): string
{
return $this->minorFontComplexScript;
}
/** @return string[] */
public function getMinorFontSubstitutions(): array
{
return $this->minorFontSubstitutions;
}
/** @param null|string[] $substitutions */
public function setMinorFontValues(?string $latin, ?string $eastAsian, ?string $complexScript, ?array $substitutions): self
{
if (!empty($latin)) {
$this->minorFontLatin = $latin;
}
if ($eastAsian !== null) {
$this->minorFontEastAsian = $eastAsian;
}
if ($complexScript !== null) {
$this->minorFontComplexScript = $complexScript;
}
if ($substitutions !== null) {
$this->minorFontSubstitutions = $substitutions;
}
return $this;
}
public function getThemeFontName(): string
{
return $this->themeFontName;
}
public function setThemeFontName(?string $name): self
{
if (!empty($name)) {
$this->themeFontName = $name;
}
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/NamedFormula.php | src/PhpSpreadsheet/NamedFormula.php | <?php
namespace PhpOffice\PhpSpreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class NamedFormula extends DefinedName
{
/**
* Create a new Named Formula.
*/
public function __construct(
string $name,
?Worksheet $worksheet = null,
?string $formula = null,
bool $localOnly = false,
?Worksheet $scope = null
) {
// Validate data
if (!isset($formula)) {
throw new Exception('You must specify a Formula value for a Named Formula');
}
parent::__construct($name, $worksheet, $formula, $localOnly, $scope);
}
/**
* Get the formula value.
*/
public function getFormula(): string
{
return $this->value;
}
/**
* Set the formula value.
*/
public function setFormula(string $formula): self
{
if (!empty($formula)) {
$this->value = $formula;
}
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Settings.php | src/PhpSpreadsheet/Settings.php | <?php
namespace PhpOffice\PhpSpreadsheet;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Chart\Renderer\IRenderer;
use PhpOffice\PhpSpreadsheet\Collection\Memory;
use Psr\SimpleCache\CacheInterface;
use ReflectionClass;
class Settings
{
/**
* Class name of the chart renderer used for rendering charts
* eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph.
*
* @var null|class-string<IRenderer>
*/
private static ?string $chartRenderer = null;
/**
* The cache implementation to be used for cell collection.
*/
private static ?CacheInterface $cache = null;
private static mixed $httpClient = null;
private static mixed $requestFactory = null;
/**
* Set the locale code to use for formula translations and any special formatting.
*
* @param string $locale The locale code to use (e.g. "fr" or "pt_br" or "en_uk")
*
* @return bool Success or failure
*/
public static function setLocale(string $locale): bool
{
return Calculation::getInstance()->setLocale($locale);
}
public static function getLocale(): string
{
return Calculation::getInstance()->getLocale();
}
/**
* Identify to PhpSpreadsheet the external library to use for rendering charts.
*
* @param class-string<IRenderer> $rendererClassName Class name of the chart renderer
* eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph
*/
public static function setChartRenderer(string $rendererClassName): void
{
// We want phpstan to validate caller, but still need this test
if (!is_a($rendererClassName, IRenderer::class, true)) { //* @phpstan-ignore-line
throw new Exception('Chart renderer must implement ' . IRenderer::class);
}
self::$chartRenderer = $rendererClassName;
}
public static function unsetChartRenderer(): void
{
self::$chartRenderer = null;
}
/**
* Return the Chart Rendering Library that PhpSpreadsheet is currently configured to use.
*
* @return null|class-string<IRenderer> Class name of the chart renderer
* eg: PhpOffice\PhpSpreadsheet\Chart\Renderer\JpGraph
*/
public static function getChartRenderer(): ?string
{
return self::$chartRenderer;
}
public static function htmlEntityFlags(): int
{
return ENT_COMPAT;
}
/**
* Sets the implementation of cache that should be used for cell collection.
*/
public static function setCache(?CacheInterface $cache): void
{
self::$cache = $cache;
}
/**
* Gets the implementation of cache that is being used for cell collection.
*/
public static function getCache(): CacheInterface
{
if (!self::$cache) {
self::$cache = self::useSimpleCacheVersion3() ? new Memory\SimpleCache3() : new Memory\SimpleCache1();
}
return self::$cache;
}
public static function useSimpleCacheVersion3(): bool
{
return (new ReflectionClass(CacheInterface::class))->getMethod('get')->getReturnType() !== null;
}
/**
* Set the HTTP client implementation to be used for network request.
*
* @deprecated 5.4.0 No replacement.
*
* @codeCoverageIgnore
*/
public static function setHttpClient(mixed $httpClient, mixed $requestFactory): void
{
self::$httpClient = $httpClient;
self::$requestFactory = $requestFactory;
}
/**
* Unset the HTTP client configuration.
*
* @deprecated 5.4.0 No replacement.
*
* @codeCoverageIgnore
*/
public static function unsetHttpClient(): void
{
self::$httpClient = null;
self::$requestFactory = null;
}
/**
* Get the HTTP client implementation to be used for network request.
*
* @deprecated 5.4.0 No replacement.
*
* @codeCoverageIgnore
*/
public static function getHttpClient(): mixed
{
return self::$httpClient;
}
/**
* Get the HTTP request factory.
*
* @deprecated 5.4.0 No replacement.
*
* @codeCoverageIgnore
*/
public static function getRequestFactory(): mixed
{
return self::$requestFactory;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/IOFactory.php | src/PhpSpreadsheet/IOFactory.php | <?php
namespace PhpOffice\PhpSpreadsheet;
use PhpOffice\PhpSpreadsheet\Reader\IReader;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Writer\IWriter;
/**
* Factory to create readers and writers easily.
*
* It is not required to use this class, but it should make it easier to read and write files.
* Especially for reading files with an unknown format.
*/
abstract class IOFactory
{
public const READER_XLSX = 'Xlsx';
public const READER_XLS = 'Xls';
public const READER_XML = 'Xml';
public const READER_ODS = 'Ods';
public const READER_SYLK = 'Slk';
public const READER_SLK = 'Slk';
public const READER_GNUMERIC = 'Gnumeric';
public const READER_HTML = 'Html';
public const READER_CSV = 'Csv';
public const WRITER_XLSX = 'Xlsx';
public const WRITER_XLS = 'Xls';
public const WRITER_ODS = 'Ods';
public const WRITER_CSV = 'Csv';
public const WRITER_HTML = 'Html';
/** @var array<string, class-string<IReader>> */
private static array $readers = [
self::READER_XLSX => Reader\Xlsx::class,
self::READER_XLS => Reader\Xls::class,
self::READER_XML => Reader\Xml::class,
self::READER_ODS => Reader\Ods::class,
self::READER_SLK => Reader\Slk::class,
self::READER_GNUMERIC => Reader\Gnumeric::class,
self::READER_HTML => Reader\Html::class,
self::READER_CSV => Reader\Csv::class,
];
/** @var array<string, class-string<IWriter>> */
private static array $writers = [
self::WRITER_XLS => Writer\Xls::class,
self::WRITER_XLSX => Writer\Xlsx::class,
self::WRITER_ODS => Writer\Ods::class,
self::WRITER_CSV => Writer\Csv::class,
self::WRITER_HTML => Writer\Html::class,
'Tcpdf' => Writer\Pdf\Tcpdf::class,
'Dompdf' => Writer\Pdf\Dompdf::class,
'Mpdf' => Writer\Pdf\Mpdf::class,
];
/** @internal */
public static function restoreDefaultReadersAndWriters(): void
{
self::$readers = [
self::READER_XLSX => Reader\Xlsx::class,
self::READER_XLS => Reader\Xls::class,
self::READER_XML => Reader\Xml::class,
self::READER_ODS => Reader\Ods::class,
self::READER_SLK => Reader\Slk::class,
self::READER_GNUMERIC => Reader\Gnumeric::class,
self::READER_HTML => Reader\Html::class,
self::READER_CSV => Reader\Csv::class,
];
self::$writers = [
self::WRITER_XLS => Writer\Xls::class,
self::WRITER_XLSX => Writer\Xlsx::class,
self::WRITER_ODS => Writer\Ods::class,
self::WRITER_CSV => Writer\Csv::class,
self::WRITER_HTML => Writer\Html::class,
'Tcpdf' => Writer\Pdf\Tcpdf::class,
'Dompdf' => Writer\Pdf\Dompdf::class,
'Mpdf' => Writer\Pdf\Mpdf::class,
];
}
/**
* Create Writer\IWriter.
*/
public static function createWriter(Spreadsheet $spreadsheet, string $writerType): IWriter
{
/** @var class-string<IWriter> */
$className = $writerType;
if (!in_array($writerType, self::$writers, true)) {
if (!isset(self::$writers[$writerType])) {
throw new Writer\Exception("No writer found for type $writerType");
}
// Instantiate writer
$className = self::$writers[$writerType];
}
return new $className($spreadsheet);
}
/**
* Create IReader.
*/
public static function createReader(string $readerType): IReader
{
/** @var class-string<IReader> */
$className = $readerType;
if (!in_array($readerType, self::$readers, true)) {
if (!isset(self::$readers[$readerType])) {
throw new Reader\Exception("No reader found for type $readerType");
}
// Instantiate reader
$className = self::$readers[$readerType];
}
return new $className();
}
/**
* Loads Spreadsheet from file using automatic Reader\IReader resolution.
*
* @param string $filename The name of the spreadsheet file
* @param int $flags the optional second parameter flags may be used to identify specific elements
* that should be loaded, but which won't be loaded by default, using these values:
* IReader::LOAD_WITH_CHARTS - Include any charts that are defined in the loaded file.
* IReader::READ_DATA_ONLY - Read cell values only, not formatting or merge structure.
* IReader::IGNORE_EMPTY_CELLS - Don't load empty cells into the model.
* @param string[] $readers An array of Readers to use to identify the file type. By default, load() will try
* all possible Readers until it finds a match; but this allows you to pass in a
* list of Readers so it will only try the subset that you specify here.
* Values in this list can be any of the constant values defined in the set
* IOFactory::READER_*.
*/
public static function load(string $filename, int $flags = 0, ?array $readers = null): Spreadsheet
{
$reader = self::createReaderForFile($filename, $readers);
return $reader->load($filename, $flags);
}
/**
* Identify file type using automatic IReader resolution.
*
* @param string[] $readers
*/
public static function identify(string $filename, ?array $readers = null, bool $fullClassName = false): string
{
$reader = self::createReaderForFile($filename, $readers);
$className = $reader::class;
if ($fullClassName) {
return $className;
}
$classType = explode('\\', $className);
return array_pop($classType);
}
/**
* Create Reader\IReader for file using automatic IReader resolution.
*
* @param string[] $readers An array of Readers to use to identify the file type. By default, load() will try
* all possible Readers until it finds a match; but this allows you to pass in a
* list of Readers so it will only try the subset that you specify here.
* Values in this list can be any of the constant values defined in the set
* IOFactory::READER_*.
*/
public static function createReaderForFile(string $filename, ?array $readers = null): IReader
{
File::assertFile($filename);
$testReaders = self::$readers;
if ($readers !== null) {
$readers = array_map('strtoupper', $readers);
$testReaders = array_filter(
self::$readers,
fn (string $readerType): bool => in_array(strtoupper($readerType), $readers, true),
ARRAY_FILTER_USE_KEY
);
}
// First, lucky guess by inspecting file extension
$guessedReader = self::getReaderTypeFromExtension($filename);
if (($guessedReader !== null) && array_key_exists($guessedReader, $testReaders)) {
$reader = self::createReader($guessedReader);
// Let's see if we are lucky
if ($reader->canRead($filename)) {
return $reader;
}
}
// If we reach here then "lucky guess" didn't give any result
// Try walking through all the options in self::$readers (or the selected subset)
foreach ($testReaders as $readerType => $class) {
// Ignore our original guess, we know that won't work
if ($readerType !== $guessedReader) {
$reader = self::createReader($readerType);
if ($reader->canRead($filename)) {
return $reader;
}
}
}
throw new Reader\Exception('Unable to identify a reader for this file');
}
/**
* Guess a reader type from the file extension, if any.
*/
private static function getReaderTypeFromExtension(string $filename): ?string
{
$pathinfo = pathinfo($filename);
if (!isset($pathinfo['extension'])) {
return null;
}
return match (strtolower($pathinfo['extension'])) {
// Excel (OfficeOpenXML) Spreadsheet
'xlsx',
// Excel (OfficeOpenXML) Macro Spreadsheet (macros will be discarded)
'xlsm',
// Excel (OfficeOpenXML) Template
'xltx',
// Excel (OfficeOpenXML) Macro Template (macros will be discarded)
'xltm' => 'Xlsx',
// Excel (BIFF) Spreadsheet
'xls',
// Excel (BIFF) Template
'xlt' => 'Xls',
// Open/Libre Offic Calc
'ods',
// Open/Libre Offic Calc Template
'ots' => 'Ods',
'slk' => 'Slk',
// Excel 2003 SpreadSheetML
'xml' => 'Xml',
'gnumeric' => 'Gnumeric',
'htm', 'html' => 'Html',
// Do nothing
// We must not try to use CSV reader since it loads
// all files including Excel files etc.
'csv' => null,
default => null,
};
}
/**
* Register a writer with its type and class name.
*
* @param class-string<IWriter> $writerClass
*/
public static function registerWriter(string $writerType, string $writerClass): void
{
// We want phpstan to validate caller, but still need this test
if (!is_a($writerClass, IWriter::class, true)) { //* @phpstan-ignore-line
throw new Writer\Exception('Registered writers must implement ' . IWriter::class);
}
self::$writers[$writerType] = $writerClass;
}
/**
* Register a reader with its type and class name.
*
* @param class-string<IReader> $readerClass
*/
public static function registerReader(string $readerType, string $readerClass): void
{
// We want phpstan to validate caller, but still need this test
if (!is_a($readerClass, IReader::class, true)) { //* @phpstan-ignore-line
throw new Reader\Exception('Registered readers must implement ' . IReader::class);
}
self::$readers[$readerType] = $readerClass;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/DefinedName.php | src/PhpSpreadsheet/DefinedName.php | <?php
namespace PhpOffice\PhpSpreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
abstract class DefinedName
{
protected const REGEXP_IDENTIFY_FORMULA = '[^_\p{N}\p{L}:, \$\'!]';
/**
* Name.
*/
protected string $name;
/**
* Worksheet on which the defined name can be resolved.
*/
protected ?Worksheet $worksheet;
/**
* Value of the named object.
*/
protected string $value;
/**
* Is the defined named local? (i.e. can only be used on $this->worksheet).
*/
protected bool $localOnly;
/**
* Scope.
*/
protected ?Worksheet $scope;
/**
* Whether this is a named range or a named formula.
*/
protected bool $isFormula;
/**
* Create a new Defined Name.
*/
public function __construct(
string $name,
?Worksheet $worksheet = null,
?string $value = null,
bool $localOnly = false,
?Worksheet $scope = null
) {
if ($worksheet === null) {
$worksheet = $scope;
}
// Set local members
$this->name = $name;
$this->worksheet = $worksheet;
$this->value = (string) $value;
$this->localOnly = $localOnly;
// If local only, then the scope will be set to worksheet unless a scope is explicitly set
$this->scope = ($localOnly === true) ? (($scope === null) ? $worksheet : $scope) : null;
// If the range string contains characters that aren't associated with the range definition (A-Z,1-9
// for cell references, and $, or the range operators (colon comma or space), quotes and ! for
// worksheet names
// then this is treated as a named formula, and not a named range
$this->isFormula = self::testIfFormula($this->value);
}
public function __destruct()
{
$this->worksheet = null;
$this->scope = null;
}
/**
* Create a new defined name, either a range or a formula.
*/
public static function createInstance(
string $name,
?Worksheet $worksheet = null,
?string $value = null,
bool $localOnly = false,
?Worksheet $scope = null
): self {
$value = (string) $value;
$isFormula = self::testIfFormula($value);
if ($isFormula) {
return new NamedFormula($name, $worksheet, $value, $localOnly, $scope);
}
return new NamedRange($name, $worksheet, $value, $localOnly, $scope);
}
public static function testIfFormula(string $value): bool
{
if (str_starts_with($value, '=')) {
$value = substr($value, 1);
}
if (is_numeric($value)) {
return true;
}
$segMatcher = false;
foreach (explode("'", $value) as $subVal) {
// Only test in alternate array entries (the non-quoted blocks)
$segMatcher = $segMatcher === false;
if (
$segMatcher
&& (preg_match('/' . self::REGEXP_IDENTIFY_FORMULA . '/miu', $subVal))
) {
return true;
}
}
return false;
}
/**
* Get name.
*/
public function getName(): string
{
return $this->name;
}
/**
* Set name.
*/
public function setName(string $name): self
{
if (!empty($name)) {
// Old title
$oldTitle = $this->name;
// Re-attach
if ($this->worksheet !== null) {
$this->worksheet->getParentOrThrow()->removeNamedRange($this->name, $this->worksheet);
}
$this->name = $name;
if ($this->worksheet !== null) {
$this->worksheet->getParentOrThrow()->addDefinedName($this);
}
if ($this->worksheet !== null) {
// New title
$newTitle = $this->name;
ReferenceHelper::getInstance()->updateNamedFormulae($this->worksheet->getParentOrThrow(), $oldTitle, $newTitle);
}
}
return $this;
}
/**
* Get worksheet.
*/
public function getWorksheet(): ?Worksheet
{
return $this->worksheet;
}
/**
* Set worksheet.
*/
public function setWorksheet(?Worksheet $worksheet): self
{
$this->worksheet = $worksheet;
return $this;
}
/**
* Get range or formula value.
*/
public function getValue(): string
{
return $this->value;
}
/**
* Set range or formula value.
*/
public function setValue(string $value): self
{
$this->value = $value;
return $this;
}
/**
* Get localOnly.
*/
public function getLocalOnly(): bool
{
return $this->localOnly;
}
/**
* Set localOnly.
*/
public function setLocalOnly(bool $localScope): self
{
$this->localOnly = $localScope;
$this->scope = $localScope ? $this->worksheet : null;
return $this;
}
/**
* Get scope.
*/
public function getScope(): ?Worksheet
{
return $this->scope;
}
/**
* Set scope.
*/
public function setScope(?Worksheet $worksheet): self
{
$this->scope = $worksheet;
$this->localOnly = $worksheet !== null;
return $this;
}
/**
* Identify whether this is a named range or a named formula.
*/
public function isFormula(): bool
{
return $this->isFormula;
}
/**
* Resolve a named range to a regular cell range or formula.
*/
public static function resolveName(string $definedName, Worksheet $worksheet, string $sheetName = ''): ?self
{
if ($sheetName === '') {
$worksheet2 = $worksheet;
} else {
$worksheet2 = $worksheet->getParentOrThrow()->getSheetByName($sheetName);
if ($worksheet2 === null) {
return null;
}
}
return $worksheet->getParentOrThrow()->getDefinedName($definedName, $worksheet2);
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Exception.php | src/PhpSpreadsheet/Exception.php | <?php
namespace PhpOffice\PhpSpreadsheet;
use RuntimeException;
class Exception extends RuntimeException
{
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/NamedRange.php | src/PhpSpreadsheet/NamedRange.php | <?php
namespace PhpOffice\PhpSpreadsheet;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class NamedRange extends DefinedName
{
/**
* Create a new Named Range.
*/
public function __construct(
string $name,
?Worksheet $worksheet = null,
string $range = 'A1',
bool $localOnly = false,
?Worksheet $scope = null
) {
if ($worksheet === null && $scope === null) {
throw new Exception('You must specify a worksheet or a scope for a Named Range');
}
parent::__construct($name, $worksheet, $range, $localOnly, $scope);
}
/**
* Get the range value.
*/
public function getRange(): string
{
return $this->value;
}
/**
* Set the range value.
*/
public function setRange(string $range): self
{
if (!empty($range)) {
$this->value = $range;
}
return $this;
}
/** @return string[] */
public function getCellsInRange(): array
{
$range = $this->value;
if (str_starts_with($range, '=')) {
$range = substr($range, 1);
}
return Coordinate::extractAllCellReferencesInRange($range);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Comment.php | src/PhpSpreadsheet/Comment.php | <?php
namespace PhpOffice\PhpSpreadsheet;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Helper\Size;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use Stringable;
class Comment implements IComparable, Stringable
{
/**
* Author.
*/
private string $author;
/**
* Rich text comment.
*/
private RichText $text;
/**
* Comment width (CSS style, i.e. XXpx or YYpt).
*/
private string $width = '96pt';
/**
* Left margin (CSS style, i.e. XXpx or YYpt).
*/
private string $marginLeft = '59.25pt';
/**
* Top margin (CSS style, i.e. XXpx or YYpt).
*/
private string $marginTop = '1.5pt';
/**
* Visible.
*/
private bool $visible = false;
/**
* Comment height (CSS style, i.e. XXpx or YYpt).
*/
private string $height = '55.5pt';
/**
* Comment fill color.
*/
private Color $fillColor;
/**
* Alignment.
*/
private string $alignment;
/**
* Background image in comment.
*/
private Drawing $backgroundImage;
public const TEXTBOX_DIRECTION_RTL = 'rtl';
public const TEXTBOX_DIRECTION_LTR = 'ltr';
// MS uses 'auto' in xml but 'context' in UI
public const TEXTBOX_DIRECTION_AUTO = 'auto';
public const TEXTBOX_DIRECTION_CONTEXT = 'auto';
private string $textboxDirection = '';
/**
* Create a new Comment.
*/
public function __construct()
{
// Initialise variables
$this->author = 'Author';
$this->text = new RichText();
$this->fillColor = new Color('FFFFFFE1');
$this->alignment = Alignment::HORIZONTAL_GENERAL;
$this->backgroundImage = new Drawing();
}
/**
* Get Author.
*/
public function getAuthor(): string
{
return $this->author;
}
/**
* Set Author.
*/
public function setAuthor(string $author): self
{
$this->author = $author;
return $this;
}
/**
* Get Rich text comment.
*/
public function getText(): RichText
{
return $this->text;
}
/**
* Set Rich text comment.
*/
public function setText(RichText $text): self
{
$this->text = $text;
return $this;
}
/**
* Get comment width (CSS style, i.e. XXpx or YYpt).
*/
public function getWidth(): string
{
return $this->width;
}
/**
* Set comment width (CSS style, i.e. XXpx or YYpt). Default unit is pt.
*/
public function setWidth(string $width): self
{
$width = new Size($width);
if ($width->valid()) {
$this->width = (string) $width;
}
return $this;
}
/**
* Get comment height (CSS style, i.e. XXpx or YYpt).
*/
public function getHeight(): string
{
return $this->height;
}
/**
* Set comment height (CSS style, i.e. XXpx or YYpt). Default unit is pt.
*/
public function setHeight(string $height): self
{
$height = new Size($height);
if ($height->valid()) {
$this->height = (string) $height;
}
return $this;
}
/**
* Get left margin (CSS style, i.e. XXpx or YYpt).
*/
public function getMarginLeft(): string
{
return $this->marginLeft;
}
/**
* Set left margin (CSS style, i.e. XXpx or YYpt). Default unit is pt.
*/
public function setMarginLeft(string $margin): self
{
$margin = new Size($margin);
if ($margin->valid()) {
$this->marginLeft = (string) $margin;
}
return $this;
}
/**
* Get top margin (CSS style, i.e. XXpx or YYpt).
*/
public function getMarginTop(): string
{
return $this->marginTop;
}
/**
* Set top margin (CSS style, i.e. XXpx or YYpt). Default unit is pt.
*/
public function setMarginTop(string $margin): self
{
$margin = new Size($margin);
if ($margin->valid()) {
$this->marginTop = (string) $margin;
}
return $this;
}
/**
* Is the comment visible by default?
*/
public function getVisible(): bool
{
return $this->visible;
}
/**
* Set comment default visibility.
*/
public function setVisible(bool $visibility): self
{
$this->visible = $visibility;
return $this;
}
/**
* Set fill color.
*/
public function setFillColor(Color $color): self
{
$this->fillColor = $color;
return $this;
}
/**
* Get fill color.
*/
public function getFillColor(): Color
{
return $this->fillColor;
}
public function setAlignment(string $alignment): self
{
$this->alignment = $alignment;
return $this;
}
public function getAlignment(): string
{
return $this->alignment;
}
public function setTextboxDirection(string $textboxDirection): self
{
$this->textboxDirection = $textboxDirection;
return $this;
}
public function getTextboxDirection(): string
{
return $this->textboxDirection;
}
/**
* Get hash code.
*/
public function getHashCode(): string
{
return md5(
$this->author
. $this->text->getHashCode()
. $this->width
. $this->height
. $this->marginLeft
. $this->marginTop
. ($this->visible ? 1 : 0)
. $this->fillColor->getHashCode()
. $this->alignment
. $this->textboxDirection
. ($this->hasBackgroundImage() ? $this->backgroundImage->getHashCode() : '')
. __CLASS__
);
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
/**
* Convert to string.
*/
public function __toString(): string
{
return $this->text->getPlainText();
}
/**
* Check is background image exists.
*/
public function hasBackgroundImage(): bool
{
$path = $this->backgroundImage->getPath();
if (empty($path)) {
return false;
}
return getimagesize($path) !== false;
}
/**
* Returns background image.
*/
public function getBackgroundImage(): Drawing
{
return $this->backgroundImage;
}
/**
* Sets background image.
*/
public function setBackgroundImage(Drawing $objDrawing): self
{
if (!array_key_exists($objDrawing->getType(), Drawing::IMAGE_TYPES_CONVERTION_MAP)) {
throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
}
$this->backgroundImage = $objDrawing;
return $this;
}
/**
* Sets size of comment as size of background image.
*/
public function setSizeAsBackgroundImage(): self
{
if ($this->hasBackgroundImage()) {
$this->setWidth(SharedDrawing::pixelsToPoints($this->backgroundImage->getWidth()) . 'pt');
$this->setHeight(SharedDrawing::pixelsToPoints($this->backgroundImage->getHeight()) . 'pt');
}
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/HashTable.php | src/PhpSpreadsheet/HashTable.php | <?php
namespace PhpOffice\PhpSpreadsheet;
/**
* @template T of IComparable
*/
class HashTable
{
/**
* HashTable elements.
*
* @var array<string, T>
*/
protected array $items = [];
/**
* HashTable key map.
*
* @var array<int, string>
*/
protected array $keyMap = [];
/**
* Create a new HashTable.
*
* @param T[] $source Optional source array to create HashTable from
*/
public function __construct(?array $source = [])
{
if ($source !== null) {
// Create HashTable
$this->addFromSource($source);
}
}
/**
* Add HashTable items from source.
*
* @param T[] $source Source array to create HashTable from
*/
public function addFromSource(?array $source = null): void
{
// Check if an array was passed
if ($source === null) {
return;
}
foreach ($source as $item) {
$this->add($item);
}
}
/**
* Add HashTable item.
*
* @param T $source Item to add
*/
public function add(IComparable $source): void
{
$hash = $source->getHashCode();
if (!isset($this->items[$hash])) {
$this->items[$hash] = $source;
$this->keyMap[count($this->items) - 1] = $hash;
}
}
/**
* Remove HashTable item.
*
* @param T $source Item to remove
*/
public function remove(IComparable $source): void
{
$hash = $source->getHashCode();
if (isset($this->items[$hash])) {
unset($this->items[$hash]);
$deleteKey = -1;
foreach ($this->keyMap as $key => $value) {
if ($deleteKey >= 0) {
$this->keyMap[$key - 1] = $value;
}
if ($value == $hash) {
$deleteKey = $key;
}
}
unset($this->keyMap[count($this->keyMap) - 1]);
}
}
/**
* Clear HashTable.
*/
public function clear(): void
{
$this->items = [];
$this->keyMap = [];
}
/**
* Count.
*/
public function count(): int
{
return count($this->items);
}
/**
* Get index for hash code.
*/
public function getIndexForHashCode(string $hashCode): false|int
{
return array_search($hashCode, $this->keyMap, true);
}
/**
* Get by index.
*
* @return null|T
*/
public function getByIndex(int $index): ?IComparable
{
if (isset($this->keyMap[$index])) {
return $this->getByHashCode($this->keyMap[$index]);
}
return null;
}
/**
* Get by hashcode.
*
* @return null|T
*/
public function getByHashCode(string $hashCode): ?IComparable
{
if (isset($this->items[$hashCode])) {
return $this->items[$hashCode];
}
return null;
}
/**
* HashTable to array.
*
* @return T[]
*/
public function toArray(): array
{
return $this->items;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
// each member of this class is an array
if (is_array($value)) {
$array1 = $value;
foreach ($array1 as $key1 => $value1) {
if (is_object($value1)) {
$array1[$key1] = clone $value1;
}
}
$this->$key = $array1;
}
}
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/IComparable.php | src/PhpSpreadsheet/IComparable.php | <?php
namespace PhpOffice\PhpSpreadsheet;
interface IComparable
{
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string;
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/CellReferenceHelper.php | src/PhpSpreadsheet/CellReferenceHelper.php | <?php
namespace PhpOffice\PhpSpreadsheet;
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
class CellReferenceHelper
{
protected string $beforeCellAddress;
protected int $beforeColumn;
protected bool $beforeColumnAbsolute = false;
protected string $beforeColumnString;
protected int $beforeRow;
protected bool $beforeRowAbsolute = false;
protected int $numberOfColumns;
protected int $numberOfRows;
public function __construct(string $beforeCellAddress = 'A1', int $numberOfColumns = 0, int $numberOfRows = 0)
{
$this->beforeColumnAbsolute = $beforeCellAddress[0] === '$';
$this->beforeRowAbsolute = strpos($beforeCellAddress, '$', 1) !== false;
$this->beforeCellAddress = str_replace('$', '', $beforeCellAddress);
$this->numberOfColumns = $numberOfColumns;
$this->numberOfRows = $numberOfRows;
// Get coordinate of $beforeCellAddress
[$beforeColumn, $beforeRow] = Coordinate::coordinateFromString($beforeCellAddress);
$this->beforeColumnString = $beforeColumn;
$this->beforeColumn = (int) Coordinate::columnIndexFromString($beforeColumn);
$this->beforeRow = (int) $beforeRow;
}
public function beforeCellAddress(): string
{
return $this->beforeCellAddress;
}
public function refreshRequired(string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): bool
{
return $this->beforeCellAddress !== $beforeCellAddress
|| $this->numberOfColumns !== $numberOfColumns
|| $this->numberOfRows !== $numberOfRows;
}
public function updateCellReference(string $cellReference = 'A1', bool $includeAbsoluteReferences = false, bool $onlyAbsoluteReferences = false, ?bool $topLeft = null): string
{
if (Coordinate::coordinateIsRange($cellReference)) {
throw new Exception('Only single cell references may be passed to this method.');
}
// Get coordinate of $cellReference
[$newColumn, $newRow] = Coordinate::coordinateFromString($cellReference);
$newColumnIndex = Coordinate::columnIndexFromString(str_replace('$', '', $newColumn));
$newRowIndex = (int) str_replace('$', '', $newRow);
$absoluteColumn = $newColumn[0] === '$' ? '$' : '';
$absoluteRow = $newRow[0] === '$' ? '$' : '';
// Verify which parts should be updated
if ($onlyAbsoluteReferences === true) {
$updateColumn = (($absoluteColumn === '$') && $newColumnIndex >= $this->beforeColumn);
$updateRow = (($absoluteRow === '$') && $newRowIndex >= $this->beforeRow);
} elseif ($includeAbsoluteReferences === false) {
$updateColumn = (($absoluteColumn !== '$') && $newColumnIndex >= $this->beforeColumn);
$updateRow = (($absoluteRow !== '$') && $newRowIndex >= $this->beforeRow);
} else {
$newColumnIndex = $this->computeNewColumnIndex($newColumnIndex, $topLeft);
$newColumn = $absoluteColumn . Coordinate::stringFromColumnIndex($newColumnIndex);
$updateColumn = false;
$newRowIndex = $this->computeNewRowIndex($newRowIndex, $topLeft);
$newRow = $absoluteRow . $newRowIndex;
$updateRow = false;
}
// Create new column reference
if ($updateColumn) {
$newColumn = $this->updateColumnReference($newColumnIndex, $absoluteColumn);
}
// Create new row reference
if ($updateRow) {
$newRow = $this->updateRowReference($newRowIndex, $absoluteRow);
}
// Return new reference
return "{$newColumn}{$newRow}";
}
public function computeNewColumnIndex(int $newColumnIndex, ?bool $topLeft): int
{
// A special case is removing the left/top or bottom/right edge of a range
// $topLeft is null if we aren't adjusting a range at all.
if (
$topLeft !== null
&& $this->numberOfColumns < 0
&& $newColumnIndex >= $this->beforeColumn + $this->numberOfColumns
&& $newColumnIndex <= $this->beforeColumn - 1
) {
if ($topLeft) {
$newColumnIndex = $this->beforeColumn + $this->numberOfColumns;
} else {
$newColumnIndex = $this->beforeColumn + $this->numberOfColumns - 1;
}
} elseif ($newColumnIndex >= $this->beforeColumn) {
// Create new column reference
$newColumnIndex += $this->numberOfColumns;
}
return $newColumnIndex;
}
public function computeNewRowIndex(int $newRowIndex, ?bool $topLeft): int
{
// A special case is removing the left/top or bottom/right edge of a range
// $topLeft is null if we aren't adjusting a range at all.
if (
$topLeft !== null
&& $this->numberOfRows < 0
&& $newRowIndex >= $this->beforeRow + $this->numberOfRows
&& $newRowIndex <= $this->beforeRow - 1
) {
if ($topLeft) {
$newRowIndex = $this->beforeRow + $this->numberOfRows;
} else {
$newRowIndex = $this->beforeRow + $this->numberOfRows - 1;
}
} elseif ($newRowIndex >= $this->beforeRow) {
$newRowIndex = $newRowIndex + $this->numberOfRows;
}
return $newRowIndex;
}
public function cellAddressInDeleteRange(string $cellAddress): bool
{
[$cellColumn, $cellRow] = Coordinate::coordinateFromString($cellAddress);
$cellColumnIndex = Coordinate::columnIndexFromString($cellColumn);
// Is cell within the range of rows/columns if we're deleting
if (
$this->numberOfRows < 0
&& ($cellRow >= ($this->beforeRow + $this->numberOfRows))
&& ($cellRow < $this->beforeRow)
) {
return true;
} elseif (
$this->numberOfColumns < 0
&& ($cellColumnIndex >= ($this->beforeColumn + $this->numberOfColumns))
&& ($cellColumnIndex < $this->beforeColumn)
) {
return true;
}
return false;
}
protected function updateColumnReference(int $newColumnIndex, string $absoluteColumn): string
{
$newColumn = Coordinate::stringFromColumnIndex(min($newColumnIndex + $this->numberOfColumns, AddressRange::MAX_COLUMN_INT));
return "{$absoluteColumn}{$newColumn}";
}
protected function updateRowReference(int $newRowIndex, string $absoluteRow): string
{
$newRow = $newRowIndex + $this->numberOfRows;
$newRow = ($newRow > AddressRange::MAX_ROW) ? AddressRange::MAX_ROW : $newRow;
return "{$absoluteRow}{$newRow}";
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Spreadsheet.php | src/PhpSpreadsheet/Spreadsheet.php | <?php
namespace PhpOffice\PhpSpreadsheet;
use JsonSerializable;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\IValueBinder;
use PhpOffice\PhpSpreadsheet\Document\Properties;
use PhpOffice\PhpSpreadsheet\Document\Security;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Shared\Font as SharedFont;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Style\Style;
use PhpOffice\PhpSpreadsheet\Worksheet\Iterator;
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class Spreadsheet implements JsonSerializable
{
// Allowable values for workbook window visibility
const VISIBILITY_VISIBLE = 'visible';
const VISIBILITY_HIDDEN = 'hidden';
const VISIBILITY_VERY_HIDDEN = 'veryHidden';
private const DEFINED_NAME_IS_RANGE = false;
private const DEFINED_NAME_IS_FORMULA = true;
private const WORKBOOK_VIEW_VISIBILITY_VALUES = [
self::VISIBILITY_VISIBLE,
self::VISIBILITY_HIDDEN,
self::VISIBILITY_VERY_HIDDEN,
];
protected int $excelCalendar = Date::CALENDAR_WINDOWS_1900;
/**
* Unique ID.
*/
private string $uniqueID;
/**
* Document properties.
*/
private Properties $properties;
/**
* Document security.
*/
private Security $security;
/**
* Collection of Worksheet objects.
*
* @var Worksheet[]
*/
private array $workSheetCollection;
/**
* Calculation Engine.
*/
private Calculation $calculationEngine;
/**
* Active sheet index.
*/
private int $activeSheetIndex;
/**
* Named ranges.
*
* @var DefinedName[]
*/
private array $definedNames;
/**
* CellXf supervisor.
*/
private Style $cellXfSupervisor;
/**
* CellXf collection.
*
* @var Style[]
*/
private array $cellXfCollection = [];
/**
* CellStyleXf collection.
*
* @var Style[]
*/
private array $cellStyleXfCollection = [];
/**
* hasMacros : this workbook have macros ?
*/
private bool $hasMacros = false;
/**
* macrosCode : all macros code as binary data (the vbaProject.bin file, this include form, code, etc.), null if no macro.
*/
private ?string $macrosCode = null;
/**
* macrosCertificate : if macros are signed, contains binary data vbaProjectSignature.bin file, null if not signed.
*/
private ?string $macrosCertificate = null;
/**
* ribbonXMLData : null if workbook isn't Excel 2007 or not contain a customized UI.
*
* @var null|array{target: string, data: string}
*/
private ?array $ribbonXMLData = null;
/**
* ribbonBinObjects : null if workbook isn't Excel 2007 or not contain embedded objects (picture(s)) for Ribbon Elements
* ignored if $ribbonXMLData is null.
*
* @var null|mixed[]
*/
private ?array $ribbonBinObjects = null;
/**
* List of unparsed loaded data for export to same format with better compatibility.
* It has to be minimized when the library start to support currently unparsed data.
*
* @var array<array<array<array<string>|string>>>
*/
private array $unparsedLoadedData = [];
/**
* Controls visibility of the horizonal scroll bar in the application.
*/
private bool $showHorizontalScroll = true;
/**
* Controls visibility of the horizonal scroll bar in the application.
*/
private bool $showVerticalScroll = true;
/**
* Controls visibility of the sheet tabs in the application.
*/
private bool $showSheetTabs = true;
/**
* Specifies a boolean value that indicates whether the workbook window
* is minimized.
*/
private bool $minimized = false;
/**
* Specifies a boolean value that indicates whether to group dates
* when presenting the user with filtering options in the user
* interface.
*/
private bool $autoFilterDateGrouping = true;
/**
* Specifies the index to the first sheet in the book view.
*/
private int $firstSheetIndex = 0;
/**
* Specifies the visible status of the workbook.
*/
private string $visibility = self::VISIBILITY_VISIBLE;
/**
* Specifies the ratio between the workbook tabs bar and the horizontal
* scroll bar. TabRatio is assumed to be out of 1000 of the horizontal
* window width.
*/
private int $tabRatio = 600;
private Theme $theme;
private ?IValueBinder $valueBinder = null;
/** @var array<string, int> */
private array $fontCharsets = [
'B Nazanin' => SharedFont::CHARSET_ANSI_ARABIC,
];
/**
* @param int $charset uses any value from Shared\Font,
* but defaults to ARABIC because that is the only known
* charset for which this declaration might be needed
*/
public function addFontCharset(string $fontName, int $charset = SharedFont::CHARSET_ANSI_ARABIC): void
{
$this->fontCharsets[$fontName] = $charset;
}
public function getFontCharset(string $fontName): int
{
return $this->fontCharsets[$fontName] ?? -1;
}
/**
* Return all fontCharsets.
*
* @return array<string, int>
*/
public function getFontCharsets(): array
{
return $this->fontCharsets;
}
public function getTheme(): Theme
{
return $this->theme;
}
/**
* The workbook has macros ?
*/
public function hasMacros(): bool
{
return $this->hasMacros;
}
/**
* Define if a workbook has macros.
*
* @param bool $hasMacros true|false
*/
public function setHasMacros(bool $hasMacros): void
{
$this->hasMacros = (bool) $hasMacros;
}
/**
* Set the macros code.
*/
public function setMacrosCode(?string $macroCode): void
{
$this->macrosCode = $macroCode;
$this->setHasMacros($macroCode !== null);
}
/**
* Return the macros code.
*/
public function getMacrosCode(): ?string
{
return $this->macrosCode;
}
/**
* Set the macros certificate.
*/
public function setMacrosCertificate(?string $certificate): void
{
$this->macrosCertificate = $certificate;
}
/**
* Is the project signed ?
*
* @return bool true|false
*/
public function hasMacrosCertificate(): bool
{
return $this->macrosCertificate !== null;
}
/**
* Return the macros certificate.
*/
public function getMacrosCertificate(): ?string
{
return $this->macrosCertificate;
}
/**
* Remove all macros, certificate from spreadsheet.
*/
public function discardMacros(): void
{
$this->hasMacros = false;
$this->macrosCode = null;
$this->macrosCertificate = null;
}
/**
* set ribbon XML data.
*/
public function setRibbonXMLData(mixed $target, mixed $xmlData): void
{
if (is_string($target) && is_string($xmlData)) {
$this->ribbonXMLData = ['target' => $target, 'data' => $xmlData];
} else {
$this->ribbonXMLData = null;
}
}
/**
* retrieve ribbon XML Data.
*
* @return mixed[]
*/
public function getRibbonXMLData(string $what = 'all'): null|array|string //we need some constants here...
{
$returnData = null;
$what = strtolower($what);
switch ($what) {
case 'all':
$returnData = $this->ribbonXMLData;
break;
case 'target':
case 'data':
if (is_array($this->ribbonXMLData)) {
$returnData = $this->ribbonXMLData[$what];
}
break;
}
return $returnData;
}
/**
* store binaries ribbon objects (pictures).
*/
public function setRibbonBinObjects(mixed $binObjectsNames, mixed $binObjectsData): void
{
if ($binObjectsNames !== null && $binObjectsData !== null) {
$this->ribbonBinObjects = ['names' => $binObjectsNames, 'data' => $binObjectsData];
} else {
$this->ribbonBinObjects = null;
}
}
/**
* List of unparsed loaded data for export to same format with better compatibility.
* It has to be minimized when the library start to support currently unparsed data.
*
* @internal
*
* @return mixed[]
*/
public function getUnparsedLoadedData(): array
{
return $this->unparsedLoadedData;
}
/**
* List of unparsed loaded data for export to same format with better compatibility.
* It has to be minimized when the library start to support currently unparsed data.
*
* @internal
*
* @param array<array<array<array<string>|string>>> $unparsedLoadedData
*/
public function setUnparsedLoadedData(array $unparsedLoadedData): void
{
$this->unparsedLoadedData = $unparsedLoadedData;
}
/**
* retrieve Binaries Ribbon Objects.
*
* @return mixed[]
*/
public function getRibbonBinObjects(string $what = 'all'): ?array
{
$ReturnData = null;
$what = strtolower($what);
switch ($what) {
case 'all':
return $this->ribbonBinObjects;
case 'names':
case 'data':
if (is_array($this->ribbonBinObjects) && is_array($this->ribbonBinObjects[$what] ?? null)) {
$ReturnData = $this->ribbonBinObjects[$what];
}
break;
case 'types':
if (
is_array($this->ribbonBinObjects)
&& isset($this->ribbonBinObjects['data']) && is_array($this->ribbonBinObjects['data'])
) {
$tmpTypes = array_keys($this->ribbonBinObjects['data']);
$ReturnData = array_unique(array_map(fn (string $path): string => pathinfo($path, PATHINFO_EXTENSION), $tmpTypes));
} else {
$ReturnData = []; // the caller want an array... not null if empty
}
break;
}
return $ReturnData;
}
/**
* This workbook have a custom UI ?
*/
public function hasRibbon(): bool
{
return $this->ribbonXMLData !== null;
}
/**
* This workbook have additional object for the ribbon ?
*/
public function hasRibbonBinObjects(): bool
{
return $this->ribbonBinObjects !== null;
}
/**
* Check if a sheet with a specified code name already exists.
*
* @param string $codeName Name of the worksheet to check
*/
public function sheetCodeNameExists(string $codeName): bool
{
return $this->getSheetByCodeName($codeName) !== null;
}
/**
* Get sheet by code name. Warning : sheet don't have always a code name !
*
* @param string $codeName Sheet name
*/
public function getSheetByCodeName(string $codeName): ?Worksheet
{
$worksheetCount = count($this->workSheetCollection);
for ($i = 0; $i < $worksheetCount; ++$i) {
if ($this->workSheetCollection[$i]->getCodeName() == $codeName) {
return $this->workSheetCollection[$i];
}
}
return null;
}
/**
* Create a new PhpSpreadsheet with one Worksheet.
*/
public function __construct()
{
$this->uniqueID = uniqid('', true);
$this->calculationEngine = new Calculation($this);
$this->theme = new Theme();
// Initialise worksheet collection and add one worksheet
$this->workSheetCollection = [];
$this->workSheetCollection[] = new Worksheet($this);
$this->activeSheetIndex = 0;
// Create document properties
$this->properties = new Properties();
// Create document security
$this->security = new Security();
// Set defined names
$this->definedNames = [];
// Create the cellXf supervisor
$this->cellXfSupervisor = new Style(true);
$this->cellXfSupervisor->bindParent($this);
// Create the default style
$this->addCellXf(new Style());
$this->addCellStyleXf(new Style());
}
/**
* Code to execute when this worksheet is unset().
*/
public function __destruct()
{
$this->disconnectWorksheets();
unset($this->calculationEngine);
$this->cellXfCollection = [];
$this->cellStyleXfCollection = [];
$this->definedNames = [];
}
/**
* Disconnect all worksheets from this PhpSpreadsheet workbook object,
* typically so that the PhpSpreadsheet object can be unset.
*/
public function disconnectWorksheets(): void
{
foreach ($this->workSheetCollection as $worksheet) {
$worksheet->disconnectCells();
unset($worksheet);
}
$this->workSheetCollection = [];
}
/**
* Return the calculation engine for this worksheet.
*/
public function getCalculationEngine(): Calculation
{
return $this->calculationEngine;
}
/**
* Intended for use only via a destructor.
*
* @internal
*/
public function getCalculationEngineOrNull(): ?Calculation
{
if (!isset($this->calculationEngine)) { //* @phpstan-ignore-line
return null;
}
return $this->calculationEngine;
}
/**
* Get properties.
*/
public function getProperties(): Properties
{
return $this->properties;
}
/**
* Set properties.
*/
public function setProperties(Properties $documentProperties): void
{
$this->properties = $documentProperties;
}
/**
* Get security.
*/
public function getSecurity(): Security
{
return $this->security;
}
/**
* Set security.
*/
public function setSecurity(Security $documentSecurity): void
{
$this->security = $documentSecurity;
}
/**
* Get active sheet.
*/
public function getActiveSheet(): Worksheet
{
return $this->getSheet($this->activeSheetIndex);
}
/**
* Create sheet and add it to this workbook.
*
* @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
*/
public function createSheet(?int $sheetIndex = null): Worksheet
{
$newSheet = new Worksheet($this);
$this->addSheet($newSheet, $sheetIndex, true);
return $newSheet;
}
/**
* Check if a sheet with a specified name already exists.
*
* @param string $worksheetName Name of the worksheet to check
*/
public function sheetNameExists(string $worksheetName): bool
{
return $this->getSheetByName($worksheetName) !== null;
}
public function duplicateWorksheetByTitle(string $title): Worksheet
{
$original = $this->getSheetByNameOrThrow($title);
$index = $this->getIndex($original) + 1;
$clone = clone $original;
return $this->addSheet($clone, $index, true);
}
/**
* Add sheet.
*
* @param Worksheet $worksheet The worksheet to add
* @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
*/
public function addSheet(Worksheet $worksheet, ?int $sheetIndex = null, bool $retitleIfNeeded = false): Worksheet
{
if ($retitleIfNeeded) {
$title = $worksheet->getTitle();
if ($this->sheetNameExists($title)) {
$i = 1;
$newTitle = "$title $i";
while ($this->sheetNameExists($newTitle)) {
++$i;
$newTitle = "$title $i";
}
$worksheet->setTitle($newTitle);
}
}
if ($this->sheetNameExists($worksheet->getTitle())) {
throw new Exception(
"Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename this worksheet first."
);
}
if ($sheetIndex === null) {
if ($this->activeSheetIndex < 0) {
$this->activeSheetIndex = 0;
}
$this->workSheetCollection[] = $worksheet;
} else {
// Insert the sheet at the requested index
array_splice(
$this->workSheetCollection,
$sheetIndex,
0,
[$worksheet]
);
// Adjust active sheet index if necessary
if ($this->activeSheetIndex >= $sheetIndex) {
++$this->activeSheetIndex;
}
if ($this->activeSheetIndex < 0) {
$this->activeSheetIndex = 0;
}
}
if ($worksheet->getParent() === null) {
$worksheet->rebindParent($this);
}
return $worksheet;
}
/**
* Remove sheet by index.
*
* @param int $sheetIndex Index position of the worksheet to remove
*/
public function removeSheetByIndex(int $sheetIndex): void
{
$numSheets = count($this->workSheetCollection);
if ($sheetIndex > $numSheets - 1) {
throw new Exception(
"You tried to remove a sheet by the out of bounds index: {$sheetIndex}. The actual number of sheets is {$numSheets}."
);
}
array_splice($this->workSheetCollection, $sheetIndex, 1);
// Adjust active sheet index if necessary
if (
($this->activeSheetIndex >= $sheetIndex)
&& ($this->activeSheetIndex > 0 || $numSheets <= 1)
) {
--$this->activeSheetIndex;
}
}
/**
* Get sheet by index.
*
* @param int $sheetIndex Sheet index
*/
public function getSheet(int $sheetIndex): Worksheet
{
if (!isset($this->workSheetCollection[$sheetIndex])) {
$numSheets = $this->getSheetCount();
throw new Exception(
"Your requested sheet index: {$sheetIndex} is out of bounds. The actual number of sheets is {$numSheets}."
);
}
return $this->workSheetCollection[$sheetIndex];
}
/**
* Get all sheets.
*
* @return Worksheet[]
*/
public function getAllSheets(): array
{
return $this->workSheetCollection;
}
/**
* Get sheet by name.
*
* @param string $worksheetName Sheet name
*/
public function getSheetByName(string $worksheetName): ?Worksheet
{
$trimWorksheetName = StringHelper::strToUpper(trim($worksheetName, "'"));
foreach ($this->workSheetCollection as $worksheet) {
if (StringHelper::strToUpper($worksheet->getTitle()) === $trimWorksheetName) {
return $worksheet;
}
}
return null;
}
/**
* Get sheet by name, throwing exception if not found.
*/
public function getSheetByNameOrThrow(string $worksheetName): Worksheet
{
$worksheet = $this->getSheetByName($worksheetName);
if ($worksheet === null) {
throw new Exception("Sheet $worksheetName does not exist.");
}
return $worksheet;
}
/**
* Get index for sheet.
*
* @return int index
*/
public function getIndex(Worksheet $worksheet, bool $noThrow = false): int
{
foreach ($this->workSheetCollection as $key => $value) {
if ($value === $worksheet) {
return $key;
}
}
if ($noThrow) {
return -1;
}
throw new Exception('Sheet does not exist.');
}
/**
* Set index for sheet by sheet name.
*
* @param string $worksheetName Sheet name to modify index for
* @param int $newIndexPosition New index for the sheet
*
* @return int New sheet index
*/
public function setIndexByName(string $worksheetName, int $newIndexPosition): int
{
$oldIndex = $this->getIndex($this->getSheetByNameOrThrow($worksheetName));
$worksheet = array_splice(
$this->workSheetCollection,
$oldIndex,
1
);
array_splice(
$this->workSheetCollection,
$newIndexPosition,
0,
$worksheet
);
return $newIndexPosition;
}
/**
* Get sheet count.
*/
public function getSheetCount(): int
{
return count($this->workSheetCollection);
}
/**
* Get active sheet index.
*
* @return int Active sheet index
*/
public function getActiveSheetIndex(): int
{
return $this->activeSheetIndex;
}
/**
* Set active sheet index.
*
* @param int $worksheetIndex Active sheet index
*/
public function setActiveSheetIndex(int $worksheetIndex): Worksheet
{
$numSheets = count($this->workSheetCollection);
if ($worksheetIndex > $numSheets - 1) {
throw new Exception(
"You tried to set a sheet active by the out of bounds index: {$worksheetIndex}. The actual number of sheets is {$numSheets}."
);
}
$this->activeSheetIndex = $worksheetIndex;
return $this->getActiveSheet();
}
/**
* Set active sheet index by name.
*
* @param string $worksheetName Sheet title
*/
public function setActiveSheetIndexByName(string $worksheetName): Worksheet
{
if (($worksheet = $this->getSheetByName($worksheetName)) instanceof Worksheet) {
$this->setActiveSheetIndex($this->getIndex($worksheet));
return $worksheet;
}
throw new Exception('Workbook does not contain sheet:' . $worksheetName);
}
/**
* Get sheet names.
*
* @return string[]
*/
public function getSheetNames(): array
{
$returnValue = [];
$worksheetCount = $this->getSheetCount();
for ($i = 0; $i < $worksheetCount; ++$i) {
$returnValue[] = $this->getSheet($i)->getTitle();
}
return $returnValue;
}
/**
* Add external sheet.
*
* @param Worksheet $worksheet External sheet to add
* @param null|int $sheetIndex Index where sheet should go (0,1,..., or null for last)
*/
public function addExternalSheet(Worksheet $worksheet, ?int $sheetIndex = null): Worksheet
{
if ($this->sheetNameExists($worksheet->getTitle())) {
throw new Exception("Workbook already contains a worksheet named '{$worksheet->getTitle()}'. Rename the external sheet first.");
}
// count how many cellXfs there are in this workbook currently, we will need this below
$countCellXfs = count($this->cellXfCollection);
// copy all the shared cellXfs from the external workbook and append them to the current
foreach ($worksheet->getParentOrThrow()->getCellXfCollection() as $cellXf) {
$this->addCellXf(clone $cellXf);
}
// move sheet to this workbook
$worksheet->rebindParent($this);
// update the cellXfs
foreach ($worksheet->getCoordinates(false) as $coordinate) {
$cell = $worksheet->getCell($coordinate);
$cell->setXfIndex($cell->getXfIndex() + $countCellXfs);
}
// update the column dimensions Xfs
foreach ($worksheet->getColumnDimensions() as $columnDimension) {
$columnDimension->setXfIndex($columnDimension->getXfIndex() + $countCellXfs);
}
// update the row dimensions Xfs
foreach ($worksheet->getRowDimensions() as $rowDimension) {
$xfIndex = $rowDimension->getXfIndex();
if ($xfIndex !== null) {
$rowDimension->setXfIndex($xfIndex + $countCellXfs);
}
}
return $this->addSheet($worksheet, $sheetIndex);
}
/**
* Get an array of all Named Ranges.
*
* @return DefinedName[]
*/
public function getNamedRanges(): array
{
return array_filter(
$this->definedNames,
fn (DefinedName $definedName): bool => $definedName->isFormula() === self::DEFINED_NAME_IS_RANGE
);
}
/**
* Get an array of all Named Formulae.
*
* @return DefinedName[]
*/
public function getNamedFormulae(): array
{
return array_filter(
$this->definedNames,
fn (DefinedName $definedName): bool => $definedName->isFormula() === self::DEFINED_NAME_IS_FORMULA
);
}
/**
* Get an array of all Defined Names (both named ranges and named formulae).
*
* @return DefinedName[]
*/
public function getDefinedNames(): array
{
return $this->definedNames;
}
/**
* Add a named range.
* If a named range with this name already exists, then this will replace the existing value.
*/
public function addNamedRange(NamedRange $namedRange): void
{
$this->addDefinedName($namedRange);
}
/**
* Add a named formula.
* If a named formula with this name already exists, then this will replace the existing value.
*/
public function addNamedFormula(NamedFormula $namedFormula): void
{
$this->addDefinedName($namedFormula);
}
/**
* Add a defined name (either a named range or a named formula).
* If a defined named with this name already exists, then this will replace the existing value.
*/
public function addDefinedName(DefinedName $definedName): void
{
$upperCaseName = StringHelper::strToUpper($definedName->getName());
if ($definedName->getScope() == null) {
// global scope
$this->definedNames[$upperCaseName] = $definedName;
} else {
// local scope
$this->definedNames[$definedName->getScope()->getTitle() . '!' . $upperCaseName] = $definedName;
}
}
/**
* Get named range.
*
* @param null|Worksheet $worksheet Scope. Use null for global scope
*/
public function getNamedRange(string $namedRange, ?Worksheet $worksheet = null): ?NamedRange
{
$returnValue = null;
if ($namedRange !== '') {
$namedRange = StringHelper::strToUpper($namedRange);
// first look for global named range
$returnValue = $this->getGlobalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE);
// then look for local named range (has priority over global named range if both names exist)
$returnValue = $this->getLocalDefinedNameByType($namedRange, self::DEFINED_NAME_IS_RANGE, $worksheet) ?: $returnValue;
}
return $returnValue instanceof NamedRange ? $returnValue : null;
}
/**
* Get named formula.
*
* @param null|Worksheet $worksheet Scope. Use null for global scope
*/
public function getNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): ?NamedFormula
{
$returnValue = null;
if ($namedFormula !== '') {
$namedFormula = StringHelper::strToUpper($namedFormula);
// first look for global named formula
$returnValue = $this->getGlobalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA);
// then look for local named formula (has priority over global named formula if both names exist)
$returnValue = $this->getLocalDefinedNameByType($namedFormula, self::DEFINED_NAME_IS_FORMULA, $worksheet) ?: $returnValue;
}
return $returnValue instanceof NamedFormula ? $returnValue : null;
}
private function getGlobalDefinedNameByType(string $name, bool $type): ?DefinedName
{
if (isset($this->definedNames[$name]) && $this->definedNames[$name]->isFormula() === $type) {
return $this->definedNames[$name];
}
return null;
}
private function getLocalDefinedNameByType(string $name, bool $type, ?Worksheet $worksheet = null): ?DefinedName
{
if (
($worksheet !== null) && isset($this->definedNames[$worksheet->getTitle() . '!' . $name])
&& $this->definedNames[$worksheet->getTitle() . '!' . $name]->isFormula() === $type
) {
return $this->definedNames[$worksheet->getTitle() . '!' . $name];
}
return null;
}
/**
* Get named range.
*
* @param null|Worksheet $worksheet Scope. Use null for global scope
*/
public function getDefinedName(string $definedName, ?Worksheet $worksheet = null): ?DefinedName
{
$returnValue = null;
if ($definedName !== '') {
$definedName = StringHelper::strToUpper($definedName);
// first look for global defined name
foreach ($this->definedNames as $dn) {
$upper = StringHelper::strToUpper($dn->getName());
if (
!$dn->getLocalOnly()
&& $definedName === $upper
) {
$returnValue = $dn;
break;
}
}
// then look for local defined name (has priority over global defined name if both names exist)
if ($worksheet !== null) {
$wsTitle = StringHelper::strToUpper($worksheet->getTitle());
$definedName = (string) preg_replace('/^.*!/', '', $definedName);
foreach ($this->definedNames as $dn) {
$sheet = $dn->getScope() ?? $dn->getWorksheet();
$upper = StringHelper::strToUpper($dn->getName());
$upperTitle = StringHelper::strToUpper((string) $sheet?->getTitle());
if (
$dn->getLocalOnly()
&& $upper === $definedName
&& $upperTitle === $wsTitle
) {
return $dn;
}
}
}
}
return $returnValue;
}
/**
* Remove named range.
*
* @param null|Worksheet $worksheet scope: use null for global scope
*
* @return $this
*/
public function removeNamedRange(string $namedRange, ?Worksheet $worksheet = null): self
{
if ($this->getNamedRange($namedRange, $worksheet) === null) {
return $this;
}
return $this->removeDefinedName($namedRange, $worksheet);
}
/**
* Remove named formula.
*
* @param null|Worksheet $worksheet scope: use null for global scope
*
* @return $this
*/
public function removeNamedFormula(string $namedFormula, ?Worksheet $worksheet = null): self
{
if ($this->getNamedFormula($namedFormula, $worksheet) === null) {
return $this;
}
return $this->removeDefinedName($namedFormula, $worksheet);
}
/**
* Remove defined name.
*
* @param null|Worksheet $worksheet scope: use null for global scope
*
* @return $this
*/
public function removeDefinedName(string $definedName, ?Worksheet $worksheet = null): self
{
$definedName = StringHelper::strToUpper($definedName);
if ($worksheet === null) {
if (isset($this->definedNames[$definedName])) {
unset($this->definedNames[$definedName]);
}
} else {
if (isset($this->definedNames[$worksheet->getTitle() . '!' . $definedName])) {
unset($this->definedNames[$worksheet->getTitle() . '!' . $definedName]);
} elseif (isset($this->definedNames[$definedName])) {
unset($this->definedNames[$definedName]);
}
}
return $this;
}
/**
* Get worksheet iterator.
*/
public function getWorksheetIterator(): Iterator
{
return new Iterator($this);
}
/**
* Copy workbook (!= clone!).
*/
public function copy(): self
{
return unserialize(serialize($this)); //* @phpstan-ignore-line
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$this->uniqueID = uniqid('', true);
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | true |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/ReferenceHelper.php | src/PhpSpreadsheet/ReferenceHelper.php | <?php
namespace PhpOffice\PhpSpreadsheet;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Cell\AddressRange;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Worksheet\AutoFilter;
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class ReferenceHelper
{
/** Constants */
/** Regular Expressions */
private const SHEETNAME_PART = '((\w*|\'[^!]*\')!)';
private const SHEETNAME_PART_WITH_SLASHES = '/' . self::SHEETNAME_PART . '/';
const REFHELPER_REGEXP_CELLREF = self::SHEETNAME_PART . '?(?<![:a-z1-9_\.\$])(\$?[a-z]{1,3}\$?\d+)(?=[^:!\d\'])';
const REFHELPER_REGEXP_CELLRANGE = self::SHEETNAME_PART . '?(\$?[a-z]{1,3}\$?\d+):(\$?[a-z]{1,3}\$?\d+)';
const REFHELPER_REGEXP_ROWRANGE = self::SHEETNAME_PART . '?(\$?\d+):(\$?\d+)';
const REFHELPER_REGEXP_COLRANGE = self::SHEETNAME_PART . '?(\$?[a-z]{1,3}):(\$?[a-z]{1,3})';
/**
* Instance of this class.
*/
private static ?ReferenceHelper $instance = null;
private ?CellReferenceHelper $cellReferenceHelper = null;
/**
* Get an instance of this class.
*/
public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Create a new ReferenceHelper.
*/
protected function __construct()
{
}
/**
* Compare two column addresses
* Intended for use as a Callback function for sorting column addresses by column.
*
* @param string $a First column to test (e.g. 'AA')
* @param string $b Second column to test (e.g. 'Z')
*/
public static function columnSort(string $a, string $b): int
{
return strcasecmp(strlen($a) . $a, strlen($b) . $b);
}
/**
* Compare two column addresses
* Intended for use as a Callback function for reverse sorting column addresses by column.
*
* @param string $a First column to test (e.g. 'AA')
* @param string $b Second column to test (e.g. 'Z')
*/
public static function columnReverseSort(string $a, string $b): int
{
return -strcasecmp(strlen($a) . $a, strlen($b) . $b);
}
/**
* Compare two cell addresses
* Intended for use as a Callback function for sorting cell addresses by column and row.
*
* @param string $a First cell to test (e.g. 'AA1')
* @param string $b Second cell to test (e.g. 'Z1')
*/
public static function cellSort(string $a, string $b): int
{
sscanf($a, '%[A-Z]%d', $ac, $ar);
/** @var int $ar */
/** @var string $ac */
sscanf($b, '%[A-Z]%d', $bc, $br);
/** @var int $br */
/** @var string $bc */
if ($ar === $br) {
return strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc);
}
return ($ar < $br) ? -1 : 1;
}
/**
* Compare two cell addresses
* Intended for use as a Callback function for sorting cell addresses by column and row.
*
* @param string $a First cell to test (e.g. 'AA1')
* @param string $b Second cell to test (e.g. 'Z1')
*/
public static function cellReverseSort(string $a, string $b): int
{
sscanf($a, '%[A-Z]%d', $ac, $ar);
/** @var int $ar */
/** @var string $ac */
sscanf($b, '%[A-Z]%d', $bc, $br);
/** @var int $br */
/** @var string $bc */
if ($ar === $br) {
return -strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc);
}
return ($ar < $br) ? 1 : -1;
}
/**
* Update page breaks when inserting/deleting rows/columns.
*
* @param Worksheet $worksheet The worksheet that we're editing
* @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
*/
protected function adjustPageBreaks(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void
{
$aBreaks = $worksheet->getBreaks();
($numberOfColumns > 0 || $numberOfRows > 0)
? uksort($aBreaks, [self::class, 'cellReverseSort'])
: uksort($aBreaks, [self::class, 'cellSort']);
foreach ($aBreaks as $cellAddress => $value) {
/** @var CellReferenceHelper */
$cellReferenceHelper = $this->cellReferenceHelper;
if ($cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === true) {
// If we're deleting, then clear any defined breaks that are within the range
// of rows/columns that we're deleting
$worksheet->setBreak($cellAddress, Worksheet::BREAK_NONE);
} else {
// Otherwise update any affected breaks by inserting a new break at the appropriate point
// and removing the old affected break
$newReference = $this->updateCellReference($cellAddress);
if ($cellAddress !== $newReference) {
$worksheet->setBreak($newReference, $value)
->setBreak($cellAddress, Worksheet::BREAK_NONE);
}
}
}
}
/**
* Update cell comments when inserting/deleting rows/columns.
*
* @param Worksheet $worksheet The worksheet that we're editing
*/
protected function adjustComments(Worksheet $worksheet): void
{
$aComments = $worksheet->getComments();
$aNewComments = []; // the new array of all comments
foreach ($aComments as $cellAddress => &$value) {
// Any comments inside a deleted range will be ignored
/** @var CellReferenceHelper */
$cellReferenceHelper = $this->cellReferenceHelper;
if ($cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === false) {
// Otherwise build a new array of comments indexed by the adjusted cell reference
$newReference = $this->updateCellReference($cellAddress);
$aNewComments[$newReference] = $value;
}
}
// Replace the comments array with the new set of comments
$worksheet->setComments($aNewComments);
}
/**
* Update hyperlinks when inserting/deleting rows/columns.
*
* @param Worksheet $worksheet The worksheet that we're editing
* @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
*/
protected function adjustHyperlinks(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void
{
$aHyperlinkCollection = $worksheet->getHyperlinkCollection();
($numberOfColumns > 0 || $numberOfRows > 0)
? uksort($aHyperlinkCollection, [self::class, 'cellReverseSort'])
: uksort($aHyperlinkCollection, [self::class, 'cellSort']);
foreach ($aHyperlinkCollection as $cellAddress => $value) {
$newReference = $this->updateCellReference($cellAddress);
/** @var CellReferenceHelper */
$cellReferenceHelper = $this->cellReferenceHelper;
if ($cellReferenceHelper->cellAddressInDeleteRange($cellAddress) === true) {
$worksheet->setHyperlink($cellAddress, null);
} elseif ($cellAddress !== $newReference) {
$worksheet->setHyperlink($cellAddress, null);
if ($newReference) {
$worksheet->setHyperlink($newReference, $value);
}
}
}
}
/**
* Update conditional formatting styles when inserting/deleting rows/columns.
*
* @param Worksheet $worksheet The worksheet that we're editing
* @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
*/
protected function adjustConditionalFormatting(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void
{
$aStyles = $worksheet->getConditionalStylesCollection();
($numberOfColumns > 0 || $numberOfRows > 0)
? uksort($aStyles, [self::class, 'cellReverseSort'])
: uksort($aStyles, [self::class, 'cellSort']);
foreach ($aStyles as $cellAddress => $cfRules) {
$worksheet->removeConditionalStyles($cellAddress);
$newReference = $this->updateCellReference($cellAddress);
foreach ($cfRules as &$cfRule) {
/** @var Conditional $cfRule */
$conditions = $cfRule->getConditions();
foreach ($conditions as &$condition) {
if (is_string($condition)) {
/** @var CellReferenceHelper */
$cellReferenceHelper = $this->cellReferenceHelper;
$condition = $this->updateFormulaReferences(
$condition,
$cellReferenceHelper->beforeCellAddress(),
$numberOfColumns,
$numberOfRows,
$worksheet->getTitle(),
true
);
}
}
$cfRule->setConditions($conditions);
}
$worksheet->setConditionalStyles($newReference, $cfRules);
}
}
/**
* Update data validations when inserting/deleting rows/columns.
*
* @param Worksheet $worksheet The worksheet that we're editing
* @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
*/
protected function adjustDataValidations(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows, string $beforeCellAddress): void
{
$aDataValidationCollection = $worksheet->getDataValidationCollection();
($numberOfColumns > 0 || $numberOfRows > 0)
? uksort($aDataValidationCollection, [self::class, 'cellReverseSort'])
: uksort($aDataValidationCollection, [self::class, 'cellSort']);
foreach ($aDataValidationCollection as $cellAddress => $dataValidation) {
$formula = $dataValidation->getFormula1();
if ($formula !== '') {
$dataValidation->setFormula1(
$this->updateFormulaReferences(
$formula,
$beforeCellAddress,
$numberOfColumns,
$numberOfRows,
$worksheet->getTitle(),
true
)
);
}
$formula = $dataValidation->getFormula2();
if ($formula !== '') {
$dataValidation->setFormula2(
$this->updateFormulaReferences(
$formula,
$beforeCellAddress,
$numberOfColumns,
$numberOfRows,
$worksheet->getTitle(),
true
)
);
}
$addressParts = explode(' ', $cellAddress);
$newReference = '';
$separator = '';
foreach ($addressParts as $addressPart) {
$newReference .= $separator . $this->updateCellReference($addressPart);
$separator = ' ';
}
if ($cellAddress !== $newReference) {
$worksheet->setDataValidation($newReference, $dataValidation);
$worksheet->setDataValidation($cellAddress, null);
if ($newReference) {
$worksheet->setDataValidation($newReference, $dataValidation);
}
}
}
}
/**
* Update merged cells when inserting/deleting rows/columns.
*
* @param Worksheet $worksheet The worksheet that we're editing
*/
protected function adjustMergeCells(Worksheet $worksheet): void
{
$aMergeCells = $worksheet->getMergeCells();
$aNewMergeCells = []; // the new array of all merge cells
foreach ($aMergeCells as $cellAddress => &$value) {
$newReference = $this->updateCellReference($cellAddress);
if ($newReference) {
$aNewMergeCells[$newReference] = $newReference;
}
}
$worksheet->setMergeCells($aNewMergeCells); // replace the merge cells array
}
/**
* Update protected cells when inserting/deleting rows/columns.
*
* @param Worksheet $worksheet The worksheet that we're editing
* @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
*/
protected function adjustProtectedCells(Worksheet $worksheet, int $numberOfColumns, int $numberOfRows): void
{
$aProtectedCells = $worksheet->getProtectedCellRanges();
/** @var CellReferenceHelper */
$cellReferenceHelper = $this->cellReferenceHelper;
if ($numberOfRows >= 0 && $numberOfColumns >= 0) {
foreach ($aProtectedCells as $key2 => $value) {
$ranges = $value->allRanges();
$newKey = $separator = '';
foreach ($ranges as $key => $range) {
$oldKey = $range[0] . (array_key_exists(1, $range) ? (':' . $range[1]) : '');
$newKey .= $separator . $this->updateCellReference($oldKey);
$separator = ' ';
}
if ($key2 !== $newKey) {
$worksheet->unprotectCells($key2);
$worksheet->protectCells($newKey, $value->getPassword(), true, $value->getName(), $value->getSecurityDescriptor());
}
}
} else {
foreach ($aProtectedCells as $key2 => $value) {
$range = str_replace([' ', ',', "\0"], ["\0", ' ', ','], $key2);
$extracted = Coordinate::extractAllCellReferencesInRange($range);
$outArray = [];
foreach ($extracted as $cellAddress) {
if (!$cellReferenceHelper->cellAddressInDeleteRange($cellAddress)) {
$outArray[$this->updateCellReference($cellAddress)] = 'x';
}
}
$outArray2 = Coordinate::mergeRangesInCollection($outArray);
$newKey = implode(' ', array_keys($outArray2));
if ($key2 !== $newKey) {
$worksheet->unprotectCells($key2);
$worksheet->protectCells($newKey, $value->getPassword(), true, $value->getName(), $value->getSecurityDescriptor());
}
}
}
}
/**
* Update column dimensions when inserting/deleting rows/columns.
*
* @param Worksheet $worksheet The worksheet that we're editing
*/
protected function adjustColumnDimensions(Worksheet $worksheet): void
{
$aColumnDimensions = array_reverse($worksheet->getColumnDimensions(), true);
if (!empty($aColumnDimensions)) {
foreach ($aColumnDimensions as $objColumnDimension) {
$newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1');
[$newReference] = Coordinate::coordinateFromString($newReference);
if ($objColumnDimension->getColumnIndex() !== $newReference) {
$objColumnDimension->setColumnIndex($newReference);
}
}
$worksheet->refreshColumnDimensions();
}
}
/**
* Update row dimensions when inserting/deleting rows/columns.
*
* @param Worksheet $worksheet The worksheet that we're editing
* @param int $beforeRow Number of the row we're inserting/deleting before
* @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
*/
protected function adjustRowDimensions(Worksheet $worksheet, int $beforeRow, int $numberOfRows): void
{
$aRowDimensions = array_reverse($worksheet->getRowDimensions(), true);
if (!empty($aRowDimensions)) {
foreach ($aRowDimensions as $objRowDimension) {
$newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex());
[, $newReference] = Coordinate::coordinateFromString($newReference);
$newRoweference = (int) $newReference;
if ($objRowDimension->getRowIndex() !== $newRoweference) {
$objRowDimension->setRowIndex($newRoweference);
}
}
$worksheet->refreshRowDimensions();
$copyDimension = $worksheet->getRowDimension($beforeRow - 1);
for ($i = $beforeRow; $i <= $beforeRow - 1 + $numberOfRows; ++$i) {
$newDimension = $worksheet->getRowDimension($i);
$newDimension->setRowHeight($copyDimension->getRowHeight());
$newDimension->setVisible($copyDimension->getVisible());
$newDimension->setOutlineLevel($copyDimension->getOutlineLevel());
$newDimension->setCollapsed($copyDimension->getCollapsed());
}
}
}
/**
* Insert a new column or row, updating all possible related data.
*
* @param string $beforeCellAddress Insert before this cell address (e.g. 'A1')
* @param int $numberOfColumns Number of columns to insert/delete (negative values indicate deletion)
* @param int $numberOfRows Number of rows to insert/delete (negative values indicate deletion)
* @param Worksheet $worksheet The worksheet that we're editing
*/
public function insertNewBefore(
string $beforeCellAddress,
int $numberOfColumns,
int $numberOfRows,
Worksheet $worksheet
): void {
$remove = ($numberOfColumns < 0 || $numberOfRows < 0);
if (
$this->cellReferenceHelper === null
|| $this->cellReferenceHelper->refreshRequired($beforeCellAddress, $numberOfColumns, $numberOfRows)
) {
$this->cellReferenceHelper = new CellReferenceHelper($beforeCellAddress, $numberOfColumns, $numberOfRows);
}
// Get coordinate of $beforeCellAddress
[$beforeColumn, $beforeRow, $beforeColumnString] = Coordinate::indexesFromString($beforeCellAddress);
// Clear cells if we are removing columns or rows
$highestColumn = $worksheet->getHighestColumn();
$highestDataColumn = $worksheet->getHighestDataColumn();
$highestRow = $worksheet->getHighestRow();
$highestDataRow = $worksheet->getHighestDataRow();
// 1. Clear column strips if we are removing columns
if ($numberOfColumns < 0 && $beforeColumn - 2 + $numberOfColumns > 0) {
$this->clearColumnStrips($highestRow, $beforeColumn, $numberOfColumns, $worksheet);
}
// 2. Clear row strips if we are removing rows
if ($numberOfRows < 0 && $beforeRow - 1 + $numberOfRows > 0) {
$this->clearRowStrips($highestColumn, $beforeColumn, $beforeRow, $numberOfRows, $worksheet);
}
// Find missing coordinates. This is important when inserting or deleting column before the last column
$startRow = $startCol = 1;
$startColString = 'A';
if ($numberOfRows === 0) {
$startCol = $beforeColumn;
$startColString = $beforeColumnString;
} elseif ($numberOfColumns === 0) {
$startRow = $beforeRow;
}
$highColumn = Coordinate::columnIndexFromString($highestDataColumn);
for ($row = $startRow; $row <= $highestDataRow; ++$row) {
for ($col = $startCol, $colString = $startColString; $col <= $highColumn; ++$col, StringHelper::stringIncrement($colString)) {
$worksheet->getCell("$colString$row"); // create cell if it doesn't exist
}
}
$allCoordinates = $worksheet->getCoordinates();
if ($remove) {
// It's faster to reverse and pop than to use unshift, especially with large cell collections
$allCoordinates = array_reverse($allCoordinates);
}
// Loop through cells, bottom-up, and change cell coordinate
while ($coordinate = array_pop($allCoordinates)) {
$cell = $worksheet->getCell($coordinate);
$cellIndex = Coordinate::columnIndexFromString($cell->getColumn());
// Don't update cells that are being removed
if ($numberOfColumns < 0 && $cellIndex >= $beforeColumn + $numberOfColumns && $cellIndex < $beforeColumn) {
continue;
}
// New coordinate
$newCoordinate = Coordinate::stringFromColumnIndex($cellIndex + $numberOfColumns) . ($cell->getRow() + $numberOfRows);
// Should the cell be updated? Move value and cellXf index from one cell to another.
if (($cellIndex >= $beforeColumn) && ($cell->getRow() >= $beforeRow)) {
// Update cell styles
$worksheet->getCell($newCoordinate)->setXfIndex($cell->getXfIndex());
// Insert this cell at its new location
if ($cell->getDataType() === DataType::TYPE_FORMULA) {
// Formula should be adjusted
$worksheet->getCell($newCoordinate)
->setValue($this->updateFormulaReferences($cell->getValueString(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true));
} else {
// Cell value should not be adjusted
$worksheet->getCell($newCoordinate)->setValueExplicit($cell->getValue(), $cell->getDataType());
}
// Clear the original cell
$worksheet->getCellCollection()->delete($coordinate);
} else {
/* We don't need to update styles for rows/columns before our insertion position,
but we do still need to adjust any formulae in those cells */
if ($cell->getDataType() === DataType::TYPE_FORMULA) {
// Formula should be adjusted
$cell->setValue($this->updateFormulaReferences($cell->getValueString(), $beforeCellAddress, $numberOfColumns, $numberOfRows, $worksheet->getTitle(), true));
}
}
}
// Duplicate styles for the newly inserted cells
$highestColumn = $worksheet->getHighestColumn();
$highestRow = $worksheet->getHighestRow();
if ($numberOfColumns > 0 && $beforeColumn > 1) {
$this->duplicateStylesByColumn($worksheet, $beforeColumn, $beforeRow, $highestRow, $numberOfColumns);
}
if ($numberOfRows > 0 && $beforeRow - 1 > 0) {
$this->duplicateStylesByRow($worksheet, $beforeColumn, $beforeRow, $highestColumn, $numberOfRows);
}
// Update worksheet: column dimensions
$this->adjustColumnDimensions($worksheet);
// Update worksheet: row dimensions
$this->adjustRowDimensions($worksheet, $beforeRow, $numberOfRows);
// Update worksheet: page breaks
$this->adjustPageBreaks($worksheet, $numberOfColumns, $numberOfRows);
// Update worksheet: comments
$this->adjustComments($worksheet);
// Update worksheet: hyperlinks
$this->adjustHyperlinks($worksheet, $numberOfColumns, $numberOfRows);
// Update worksheet: conditional formatting styles
$this->adjustConditionalFormatting($worksheet, $numberOfColumns, $numberOfRows);
// Update worksheet: data validations
$this->adjustDataValidations($worksheet, $numberOfColumns, $numberOfRows, $beforeCellAddress);
// Update worksheet: merge cells
$this->adjustMergeCells($worksheet);
// Update worksheet: protected cells
$this->adjustProtectedCells($worksheet, $numberOfColumns, $numberOfRows);
// Update worksheet: autofilter
$this->adjustAutoFilter($worksheet, $beforeCellAddress, $numberOfColumns);
// Update worksheet: table
$this->adjustTable($worksheet, $beforeCellAddress, $numberOfColumns);
// Update worksheet: freeze pane
if ($worksheet->getFreezePane()) {
$splitCell = $worksheet->getFreezePane();
$topLeftCell = $worksheet->getTopLeftCell() ?? '';
$splitCell = $this->updateCellReference($splitCell);
$topLeftCell = $this->updateCellReference($topLeftCell);
$worksheet->freezePane($splitCell, $topLeftCell);
}
$this->updatePrintAreas($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
// Update worksheet: drawings
$aDrawings = $worksheet->getDrawingCollection();
foreach ($aDrawings as $objDrawing) {
$newReference = $this->updateCellReference($objDrawing->getCoordinates());
if ($objDrawing->getCoordinates() != $newReference) {
$objDrawing->setCoordinates($newReference);
}
if ($objDrawing->getCoordinates2() !== '') {
$newReference = $this->updateCellReference($objDrawing->getCoordinates2());
if ($objDrawing->getCoordinates2() != $newReference) {
$objDrawing->setCoordinates2($newReference);
}
}
}
// Update workbook: define names
if (count($worksheet->getParentOrThrow()->getDefinedNames()) > 0) {
$this->updateDefinedNames($worksheet, $beforeCellAddress, $numberOfColumns, $numberOfRows);
}
// Garbage collect
$worksheet->garbageCollect();
}
private function updatePrintAreas(Worksheet $worksheet, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): void
{
$pageSetup = $worksheet->getPageSetup();
if (!$pageSetup->isPrintAreaSet()) {
return;
}
$printAreas = explode(',', $pageSetup->getPrintArea());
$newPrintAreas = [];
foreach ($printAreas as $printArea) {
$result = $this->updatePrintArea($printArea, $beforeCellAddress, $numberOfColumns, $numberOfRows);
if ($result !== '') {
$newPrintAreas[] = $result;
}
}
$result = implode(',', $newPrintAreas);
if ($result === '') {
$pageSetup->clearPrintArea();
} else {
$pageSetup->setPrintArea($result);
}
}
private function updatePrintArea(string $printArea, string $beforeCellAddress, int $numberOfColumns, int $numberOfRows): string
{
$coordinates = Coordinate::indexesFromString($beforeCellAddress);
if (preg_match('/^([A-Z]{1,3})(\d{1,7}):([A-Z]{1,3})(\d{1,7})$/i', $printArea, $matches) === 1) {
$firstRow = (int) $matches[2];
$lastRow = (int) $matches[4];
$firstColumnString = $matches[1];
$lastColumnString = $matches[3];
if ($numberOfRows < 0) {
$affectedRow = $coordinates[1] + $numberOfRows - 1;
$lastAffectedRow = $coordinates[1] - 1;
if ($affectedRow >= $firstRow && $affectedRow <= $lastRow) {
$newLastRow = max($affectedRow, $lastRow + $numberOfRows);
if ($newLastRow >= $firstRow) {
return $matches[1] . $matches[2] . ':' . $matches[3] . $newLastRow;
}
return '';
}
if ($lastAffectedRow >= $firstRow && $affectedRow <= $lastRow) {
$newFirstRow = $affectedRow + 1;
$newLastRow = $lastRow + $numberOfRows;
if ($newFirstRow >= 1 && $newLastRow >= $newFirstRow) {
return $matches[1] . $newFirstRow . ':' . $matches[3] . $newLastRow;
}
return '';
}
}
if ($numberOfColumns < 0) {
$firstColumnInt = Coordinate::columnIndexFromString($firstColumnString);
$lastColumnInt = Coordinate::columnIndexFromString($lastColumnString);
$affectedColumn = $coordinates[0] + $numberOfColumns - 1;
$lastAffectedColumn = $coordinates[0] - 1;
if ($affectedColumn >= $firstColumnInt && $affectedColumn <= $lastColumnInt) {
$newLastColumnInt = max($affectedColumn, $lastColumnInt + $numberOfColumns);
if ($newLastColumnInt >= $firstColumnInt) {
$newLastColumnString = Coordinate::stringFromColumnIndex($newLastColumnInt);
return $matches[1] . $matches[2] . ':' . $newLastColumnString . $matches[4];
}
return '';
}
if ($affectedColumn < $firstColumnInt && $lastAffectedColumn > $lastColumnInt) {
return '';
}
if ($lastAffectedColumn >= $firstColumnInt && $lastAffectedColumn <= $lastColumnInt) {
$newFirstColumn = $affectedColumn + 1;
$newLastColumn = $lastColumnInt + $numberOfColumns;
if ($newFirstColumn >= 1 && $newLastColumn >= $newFirstColumn) {
$firstString = Coordinate::stringFromColumnIndex($newFirstColumn);
$lastString = Coordinate::stringFromColumnIndex($newLastColumn);
return $firstString . $matches[2] . ':' . $lastString . $matches[4];
}
return '';
}
}
}
return $this->updateCellReference($printArea);
}
private static function matchSheetName(?string $match, string $worksheetName): bool
{
return $match === null || $match === '' || $match === "'\u{fffc}'" || $match === "'\u{fffb}'" || strcasecmp(trim($match, "'"), $worksheetName) === 0;
}
private static function sheetnameBeforeCells(string $match, string $worksheetName, string $cells): string
{
$toString = ($match > '') ? "$match!" : '';
return str_replace(["\u{fffc}", "'\u{fffb}'"], $worksheetName, $toString) . $cells;
}
/**
* Update references within formulas.
*
* @param string $formula Formula to update
* @param string $beforeCellAddress Insert before this one
* @param int $numberOfColumns Number of columns to insert
* @param int $numberOfRows Number of rows to insert
* @param string $worksheetName Worksheet name/title
*
* @return string Updated formula
*/
public function updateFormulaReferences(
string $formula = '',
string $beforeCellAddress = 'A1',
int $numberOfColumns = 0,
int $numberOfRows = 0,
string $worksheetName = '',
bool $includeAbsoluteReferences = false,
bool $onlyAbsoluteReferences = false
): string {
$callback = fn (array $matches): string => (strcasecmp(trim($matches[2], "'"), $worksheetName) === 0) ? (($matches[2][0] === "'") ? "'\u{fffc}'!" : "'\u{fffb}'!") : "'\u{fffd}'!";
if (
$this->cellReferenceHelper === null
|| $this->cellReferenceHelper->refreshRequired($beforeCellAddress, $numberOfColumns, $numberOfRows)
) {
$this->cellReferenceHelper = new CellReferenceHelper($beforeCellAddress, $numberOfColumns, $numberOfRows);
}
// Update cell references in the formula
$formulaBlocks = explode('"', $formula);
$i = false;
foreach ($formulaBlocks as &$formulaBlock) {
// Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode)
$i = $i === false;
if ($i) {
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | true |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/Font.php | src/PhpSpreadsheet/Style/Font.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style;
use PhpOffice\PhpSpreadsheet\Chart\ChartColor;
use PhpOffice\PhpSpreadsheet\Theme;
class Font extends Supervisor
{
// Underline types
const UNDERLINE_NONE = 'none';
const UNDERLINE_DOUBLE = 'double';
const UNDERLINE_DOUBLEACCOUNTING = 'doubleAccounting';
const UNDERLINE_SINGLE = 'single';
const UNDERLINE_SINGLEACCOUNTING = 'singleAccounting';
const CAP_ALL = 'all';
const CAP_SMALL = 'small';
const CAP_NONE = 'none';
private const VALID_CAPS = [self::CAP_ALL, self::CAP_SMALL, self::CAP_NONE];
protected ?string $cap = null;
public const DEFAULT_FONT_NAME = 'Calibri';
/**
* Font Name.
*/
protected ?string $name = self::DEFAULT_FONT_NAME;
/**
* The following 7 are used only for chart titles, I think.
*/
private string $latin = '';
private string $eastAsian = '';
private string $complexScript = '';
private int $baseLine = 0;
private string $strikeType = '';
private ?ChartColor $underlineColor = null;
private ?ChartColor $chartColor = null;
// end of chart title items
/**
* Font Size.
*/
protected ?float $size = 11;
/**
* Bold.
*/
protected ?bool $bold = false;
/**
* Italic.
*/
protected ?bool $italic = false;
/**
* Superscript.
*/
protected ?bool $superscript = false;
/**
* Subscript.
*/
protected ?bool $subscript = false;
/**
* Underline.
*/
protected ?string $underline = self::UNDERLINE_NONE;
/**
* Strikethrough.
*/
protected ?bool $strikethrough = false;
/**
* Foreground color.
*/
protected Color $color;
protected bool $autoColor = false;
public ?int $colorIndex = null;
protected string $scheme = '';
/**
* Create a new Font.
*
* @param bool $isSupervisor Flag indicating if this is a supervisor or not
* Leave this value at default unless you understand exactly what
* its ramifications are
* @param bool $isConditional Flag indicating if this is a conditional style or not
* Leave this value at default unless you understand exactly what
* its ramifications are
*/
public function __construct(bool $isSupervisor = false, bool $isConditional = false)
{
// Supervisor?
parent::__construct($isSupervisor);
// Initialise values
if ($isConditional) {
$this->name = null;
$this->size = null;
$this->bold = null;
$this->italic = null;
$this->superscript = null;
$this->subscript = null;
$this->underline = null;
$this->strikethrough = null;
$this->color = new Color(Color::COLOR_BLACK, $isSupervisor, $isConditional);
} else {
$this->color = new Color(Color::COLOR_BLACK, $isSupervisor);
}
// bind parent if we are a supervisor
if ($isSupervisor) {
$this->color->bindParent($this, 'color');
}
}
public function applyThemeFonts(Theme $theme): void
{
$this->setName($theme->getMinorFontLatin());
$this->setLatin($theme->getMinorFontLatin());
$this->setEastAsian($theme->getMinorFontEastAsian());
$this->setComplexScript($theme->getMinorFontComplexScript());
}
/**
* Get the shared style component for the currently active cell in currently active sheet.
* Only used for style supervisor.
*/
public function getSharedComponent(): self
{
/** @var Style $parent */
$parent = $this->parent;
return $parent->getSharedComponent()->getFont();
}
/**
* Build style array from subcomponents.
*
* @param mixed[] $array
*
* @return array{font: mixed[]}
*/
public function getStyleArray(array $array): array
{
return ['font' => $array];
}
/**
* Apply styles from array.
*
* <code>
* $spreadsheet->getActiveSheet()->getStyle('B2')->getFont()->applyFromArray(
* [
* 'name' => 'Arial',
* 'bold' => TRUE,
* 'italic' => FALSE,
* 'underline' => \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE,
* 'strikethrough' => FALSE,
* 'color' => [
* 'rgb' => '808080'
* ]
* ]
* );
* </code>
*
* @param array{name?: string, latin?: string, eastAsian?: string, complexScript?: string, bold?: bool, italic?: bool, superscript?: bool, subscript?: bool, underline?: bool|string, strikethrough?: bool, color?: string[], size?: ?int, chartColor?: ChartColor, scheme?: string, cap?: string, autoColor?: bool} $styleArray Array containing style information
*
* @return $this
*/
public function applyFromArray(array $styleArray): static
{
if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else {
if (isset($styleArray['name'])) {
$this->setName($styleArray['name']);
}
if (isset($styleArray['latin'])) {
$this->setLatin($styleArray['latin']);
}
if (isset($styleArray['eastAsian'])) {
$this->setEastAsian($styleArray['eastAsian']);
}
if (isset($styleArray['complexScript'])) {
$this->setComplexScript(
$styleArray['complexScript']
);
}
if (isset($styleArray['bold'])) {
$this->setBold($styleArray['bold']);
}
if (isset($styleArray['italic'])) {
$this->setItalic($styleArray['italic']);
}
if (isset($styleArray['superscript'])) {
$this->setSuperscript($styleArray['superscript']);
}
if (isset($styleArray['subscript'])) {
$this->setSubscript($styleArray['subscript']);
}
if (isset($styleArray['underline'])) {
$this->setUnderline($styleArray['underline']);
}
if (isset($styleArray['strikethrough'])) {
$this->setStrikethrough(
$styleArray['strikethrough']
);
}
if (isset($styleArray['color'])) {
/** @var array{rgb?: string, argb?: string, theme?: int} */
$temp = $styleArray['color'];
$this->getColor()
->applyFromArray($temp);
}
if (isset($styleArray['size'])) {
$this->setSize($styleArray['size']);
}
if (isset($styleArray['chartColor'])) {
$this->chartColor = $styleArray['chartColor'];
}
if (isset($styleArray['scheme'])) {
$this->setScheme($styleArray['scheme']);
}
if (isset($styleArray['cap'])) {
$this->setCap($styleArray['cap']);
}
if (isset($styleArray['autoColor'])) {
$this->setAutoColor($styleArray['autoColor']);
}
}
return $this;
}
/**
* Get Name.
*/
public function getName(): ?string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getName();
}
return $this->name;
}
public function getLatin(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getLatin();
}
return $this->latin;
}
public function getEastAsian(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getEastAsian();
}
return $this->eastAsian;
}
public function getComplexScript(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getComplexScript();
}
return $this->complexScript;
}
/**
* Set Name and turn off Scheme.
*/
public function setName(string $fontname): self
{
if ($fontname == '') {
$fontname = 'Calibri';
}
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['name' => $fontname]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->name = $fontname;
}
return $this->setScheme('');
}
public function setLatin(string $fontname): self
{
if ($fontname == '') {
$fontname = 'Calibri';
}
if (!$this->isSupervisor) {
$this->latin = $fontname;
} else {
// should never be true
// @codeCoverageIgnoreStart
$styleArray = $this->getStyleArray(['latin' => $fontname]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
// @codeCoverageIgnoreEnd
}
return $this;
}
public function setEastAsian(string $fontname): self
{
if ($fontname == '') {
$fontname = 'Calibri';
}
if (!$this->isSupervisor) {
$this->eastAsian = $fontname;
} else {
// should never be true
// @codeCoverageIgnoreStart
$styleArray = $this->getStyleArray(['eastAsian' => $fontname]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
// @codeCoverageIgnoreEnd
}
return $this;
}
public function setComplexScript(string $fontname): self
{
if ($fontname == '') {
$fontname = 'Calibri';
}
if (!$this->isSupervisor) {
$this->complexScript = $fontname;
} else {
// should never be true
// @codeCoverageIgnoreStart
$styleArray = $this->getStyleArray(['complexScript' => $fontname]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
// @codeCoverageIgnoreEnd
}
return $this;
}
/**
* Get Size.
*/
public function getSize(): ?float
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getSize();
}
return $this->size;
}
/**
* Set Size.
*
* @param mixed $sizeInPoints A float representing the value of a positive measurement in points (1/72 of an inch)
*
* @return $this
*/
public function setSize(mixed $sizeInPoints, bool $nullOk = false): static
{
if (is_string($sizeInPoints) || is_int($sizeInPoints)) {
$sizeInPoints = (float) $sizeInPoints; // $pValue = 0 if given string is not numeric
}
// Size must be a positive floating point number
// ECMA-376-1:2016, part 1, chapter 18.4.11 sz (Font Size), p. 1536
if (!is_float($sizeInPoints) || !($sizeInPoints > 0)) {
if (!$nullOk || $sizeInPoints !== null) {
$sizeInPoints = 10.0;
}
}
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['size' => $sizeInPoints]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->size = $sizeInPoints;
}
return $this;
}
/**
* Get Bold.
*/
public function getBold(): ?bool
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getBold();
}
return $this->bold;
}
/**
* Set Bold.
*
* @return $this
*/
public function setBold(bool $bold): static
{
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['bold' => $bold]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->bold = $bold;
}
return $this;
}
/**
* Get Italic.
*/
public function getItalic(): ?bool
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getItalic();
}
return $this->italic;
}
/**
* Set Italic.
*
* @return $this
*/
public function setItalic(bool $italic): static
{
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['italic' => $italic]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->italic = $italic;
}
return $this;
}
/**
* Get Superscript.
*/
public function getSuperscript(): ?bool
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getSuperscript();
}
return $this->superscript;
}
/**
* Set Superscript.
*
* @return $this
*/
public function setSuperscript(bool $superscript): static
{
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['superscript' => $superscript]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->superscript = $superscript;
if ($this->superscript) {
$this->subscript = false;
}
}
return $this;
}
/**
* Get Subscript.
*/
public function getSubscript(): ?bool
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getSubscript();
}
return $this->subscript;
}
/**
* Set Subscript.
*
* @return $this
*/
public function setSubscript(bool $subscript): static
{
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['subscript' => $subscript]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->subscript = $subscript;
if ($this->subscript) {
$this->superscript = false;
}
}
return $this;
}
public function getBaseLine(): int
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getBaseLine();
}
return $this->baseLine;
}
public function setBaseLine(int $baseLine): self
{
if (!$this->isSupervisor) {
$this->baseLine = $baseLine;
} else {
// should never be true
// @codeCoverageIgnoreStart
$styleArray = $this->getStyleArray(['baseLine' => $baseLine]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
// @codeCoverageIgnoreEnd
}
return $this;
}
public function getStrikeType(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getStrikeType();
}
return $this->strikeType;
}
public function setStrikeType(string $strikeType): self
{
if (!$this->isSupervisor) {
$this->strikeType = $strikeType;
} else {
// should never be true
// @codeCoverageIgnoreStart
$styleArray = $this->getStyleArray(['strikeType' => $strikeType]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
// @codeCoverageIgnoreEnd
}
return $this;
}
public function getUnderlineColor(): ?ChartColor
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getUnderlineColor();
}
return $this->underlineColor;
}
/** @param array{value: null|string, alpha: null|int|string, brightness?: null|int|string, type: null|string} $colorArray */
public function setUnderlineColor(array $colorArray): self
{
if (!$this->isSupervisor) {
$this->underlineColor = new ChartColor($colorArray);
} else {
// should never be true
// @codeCoverageIgnoreStart
$styleArray = $this->getStyleArray(['underlineColor' => $colorArray]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
// @codeCoverageIgnoreEnd
}
return $this;
}
public function getChartColor(): ?ChartColor
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getChartColor();
}
return $this->chartColor;
}
/** @param array{value: null|string, alpha: null|int|string, brightness?: null|int|string, type: null|string} $colorArray */
public function setChartColor(array $colorArray): self
{
if (!$this->isSupervisor) {
$this->chartColor = new ChartColor($colorArray);
} else {
// should never be true
// @codeCoverageIgnoreStart
$styleArray = $this->getStyleArray(['chartColor' => $colorArray]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
// @codeCoverageIgnoreEnd
}
return $this;
}
public function setChartColorFromObject(?ChartColor $chartColor): self
{
$this->chartColor = $chartColor;
return $this;
}
/**
* Get Underline.
*/
public function getUnderline(): ?string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getUnderline();
}
return $this->underline;
}
/**
* Set Underline.
*
* @param bool|string $underlineStyle \PhpOffice\PhpSpreadsheet\Style\Font underline type
* If a boolean is passed, then TRUE equates to UNDERLINE_SINGLE,
* false equates to UNDERLINE_NONE
*
* @return $this
*/
public function setUnderline($underlineStyle): static
{
if (is_bool($underlineStyle)) {
$underlineStyle = ($underlineStyle) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE;
} elseif ($underlineStyle == '') {
$underlineStyle = self::UNDERLINE_NONE;
}
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['underline' => $underlineStyle]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->underline = $underlineStyle;
}
return $this;
}
/**
* Get Strikethrough.
*/
public function getStrikethrough(): ?bool
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getStrikethrough();
}
return $this->strikethrough;
}
/**
* Set Strikethrough.
*
* @return $this
*/
public function setStrikethrough(bool $strikethru): static
{
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['strikethrough' => $strikethru]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->strikethrough = $strikethru;
}
return $this;
}
/**
* Get Color.
*/
public function getColor(): Color
{
return $this->color;
}
/**
* Set Color.
*
* @return $this
*/
public function setColor(Color $color): static
{
// make sure parameter is a real color and not a supervisor
$color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color;
if ($this->isSupervisor) {
$styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->color = $color;
}
return $this;
}
private function hashChartColor(?ChartColor $underlineColor): string
{
if ($underlineColor === null) {
return '';
}
return
$underlineColor->getValue()
. $underlineColor->getType()
. (string) $underlineColor->getAlpha();
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getHashCode();
}
return md5(
$this->name
. $this->size
. ($this->bold ? 't' : 'f')
. ($this->italic ? 't' : 'f')
. ($this->superscript ? 't' : 'f')
. ($this->subscript ? 't' : 'f')
. $this->underline
. ($this->strikethrough ? 't' : 'f')
. ($this->autoColor ? 't' : 'f')
. $this->color->getHashCode()
. $this->scheme
. implode(
'*',
[
$this->latin,
$this->eastAsian,
$this->complexScript,
$this->strikeType,
$this->hashChartColor($this->chartColor),
$this->hashChartColor($this->underlineColor),
(string) $this->baseLine,
(string) $this->cap,
]
)
. __CLASS__
);
}
/** @return mixed[] */
protected function exportArray1(): array
{
$exportedArray = [];
$this->exportArray2($exportedArray, 'baseLine', $this->getBaseLine());
$this->exportArray2($exportedArray, 'bold', $this->getBold());
$this->exportArray2($exportedArray, 'cap', $this->getCap());
$this->exportArray2($exportedArray, 'chartColor', $this->getChartColor());
$this->exportArray2($exportedArray, 'color', $this->getColor());
$this->exportArray2($exportedArray, 'complexScript', $this->getComplexScript());
$this->exportArray2($exportedArray, 'eastAsian', $this->getEastAsian());
$this->exportArray2($exportedArray, 'italic', $this->getItalic());
$this->exportArray2($exportedArray, 'latin', $this->getLatin());
$this->exportArray2($exportedArray, 'name', $this->getName());
$this->exportArray2($exportedArray, 'scheme', $this->getScheme());
$this->exportArray2($exportedArray, 'size', $this->getSize());
$this->exportArray2($exportedArray, 'strikethrough', $this->getStrikethrough());
$this->exportArray2($exportedArray, 'strikeType', $this->getStrikeType());
$this->exportArray2($exportedArray, 'subscript', $this->getSubscript());
$this->exportArray2($exportedArray, 'superscript', $this->getSuperscript());
$this->exportArray2($exportedArray, 'underline', $this->getUnderline());
$this->exportArray2($exportedArray, 'underlineColor', $this->getUnderlineColor());
$this->exportArray2($exportedArray, 'autoColor', $this->getAutoColor());
return $exportedArray;
}
public function getScheme(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getScheme();
}
return $this->scheme;
}
public function setScheme(string $scheme): self
{
if ($scheme === '' || $scheme === 'major' || $scheme === 'minor') {
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['scheme' => $scheme]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->scheme = $scheme;
}
}
return $this;
}
/**
* Set capitalization attribute. If not one of the permitted
* values (all, small, or none), set it to null.
* This will be honored only for the font for chart titles.
* None is distinguished from null because null will inherit
* the current value, whereas 'none' will override it.
*/
public function setCap(string $cap): self
{
$this->cap = in_array($cap, self::VALID_CAPS, true) ? $cap : null;
return $this;
}
public function getCap(): ?string
{
return $this->cap;
}
public function setHyperlinkTheme(): self
{
$this->color->setHyperlinkTheme();
$this->setUnderline(self::UNDERLINE_SINGLE);
return $this;
}
public function setAutoColor(bool $autoColor): self
{
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['autoColor' => $autoColor]);
$this->getActiveSheet()
->getStyle($this->getSelectedCells())
->applyFromArray($styleArray);
} else {
$this->autoColor = $autoColor;
}
return $this;
}
public function getAutoColor(): bool
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getAutoColor();
}
return $this->autoColor;
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$this->color = clone $this->color;
$this->chartColor = ($this->chartColor === null) ? null : clone $this->chartColor;
$this->underlineColor = ($this->underlineColor === null) ? null : clone $this->underlineColor;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/RgbTint.php | src/PhpSpreadsheet/Style/RgbTint.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style;
/**
* Class to handle tint applied to color.
* Code borrows heavily from some Python projects.
*
* @see https://docs.python.org/3/library/colorsys.html
* @see https://gist.github.com/Mike-Honey/b36e651e9a7f1d2e1d60ce1c63b9b633
*/
class RgbTint
{
private const ONE_THIRD = 1.0 / 3.0;
private const ONE_SIXTH = 1.0 / 6.0;
private const TWO_THIRD = 2.0 / 3.0;
private const RGBMAX = 255.0;
/**
* MS Excel's tint function expects that HLS is base 240.
*
* @see https://social.msdn.microsoft.com/Forums/en-US/e9d8c136-6d62-4098-9b1b-dac786149f43/excel-color-tint-algorithm-incorrect?forum=os_binaryfile#d3c2ac95-52e0-476b-86f1-e2a697f24969
*/
private const HLSMAX = 240.0;
/**
* Convert red/green/blue to hue/luminance/saturation.
*
* @param float $red 0.0 through 1.0
* @param float $green 0.0 through 1.0
* @param float $blue 0.0 through 1.0
*
* @return float[]
*/
private static function rgbToHls(float $red, float $green, float $blue): array
{
$maxc = max($red, $green, $blue);
$minc = min($red, $green, $blue);
$luminance = ($minc + $maxc) / 2.0;
if ($minc === $maxc) {
return [0.0, $luminance, 0.0];
}
$maxMinusMin = $maxc - $minc;
if ($luminance <= 0.5) {
$s = $maxMinusMin / ($maxc + $minc);
} else {
$s = $maxMinusMin / (2.0 - $maxc - $minc);
}
$rc = ($maxc - $red) / $maxMinusMin;
$gc = ($maxc - $green) / $maxMinusMin;
$bc = ($maxc - $blue) / $maxMinusMin;
if ($red === $maxc) {
$h = $bc - $gc;
} elseif ($green === $maxc) {
$h = 2.0 + $rc - $bc;
} else {
$h = 4.0 + $gc - $rc;
}
$h = self::positiveDecimalPart($h / 6.0);
return [$h, $luminance, $s];
}
/**
* Convert hue/luminance/saturation to red/green/blue.
*
* @param float $hue 0.0 through 1.0
* @param float $luminance 0.0 through 1.0
* @param float $saturation 0.0 through 1.0
*
* @return float[]
*/
private static function hlsToRgb(float $hue, float $luminance, float $saturation): array
{
if ($saturation === 0.0) {
return [$luminance, $luminance, $luminance];
}
if ($luminance <= 0.5) {
$m2 = $luminance * (1.0 + $saturation);
} else {
$m2 = $luminance + $saturation - ($luminance * $saturation);
}
$m1 = 2.0 * $luminance - $m2;
return [
self::vFunction($m1, $m2, $hue + self::ONE_THIRD),
self::vFunction($m1, $m2, $hue),
self::vFunction($m1, $m2, $hue - self::ONE_THIRD),
];
}
private static function vFunction(float $m1, float $m2, float $hue): float
{
$hue = self::positiveDecimalPart($hue);
if ($hue < self::ONE_SIXTH) {
return $m1 + ($m2 - $m1) * $hue * 6.0;
}
if ($hue < 0.5) {
return $m2;
}
if ($hue < self::TWO_THIRD) {
return $m1 + ($m2 - $m1) * (self::TWO_THIRD - $hue) * 6.0;
}
return $m1;
}
private static function positiveDecimalPart(float $hue): float
{
$hue = fmod($hue, 1.0);
return ($hue >= 0.0) ? $hue : (1.0 + $hue);
}
/**
* Convert red/green/blue to HLSMAX-based hue/luminance/saturation.
*
* @return int[]
*/
private static function rgbToMsHls(int $red, int $green, int $blue): array
{
$red01 = $red / self::RGBMAX;
$green01 = $green / self::RGBMAX;
$blue01 = $blue / self::RGBMAX;
[$hue, $luminance, $saturation] = self::rgbToHls($red01, $green01, $blue01);
return [
(int) round($hue * self::HLSMAX),
(int) round($luminance * self::HLSMAX),
(int) round($saturation * self::HLSMAX),
];
}
/**
* Converts HLSMAX based HLS values to rgb values in the range (0,1).
*
* @return float[]
*/
private static function msHlsToRgb(int $hue, int $lightness, int $saturation): array
{
return self::hlsToRgb($hue / self::HLSMAX, $lightness / self::HLSMAX, $saturation / self::HLSMAX);
}
/**
* Tints HLSMAX based luminance.
*
* @see http://ciintelligence.blogspot.co.uk/2012/02/converting-excel-theme-color-and-tint.html
*/
private static function tintLuminance(float $tint, float $luminance): int
{
if ($tint < 0) {
return (int) round($luminance * (1.0 + $tint));
}
return (int) round($luminance * (1.0 - $tint) + (self::HLSMAX - self::HLSMAX * (1.0 - $tint)));
}
/**
* Return result of tinting supplied rgb as 6 hex digits.
*/
public static function rgbAndTintToRgb(int $red, int $green, int $blue, float $tint): string
{
[$hue, $luminance, $saturation] = self::rgbToMsHls($red, $green, $blue);
[$red, $green, $blue] = self::msHlsToRgb($hue, self::tintLuminance($tint, $luminance), $saturation);
return sprintf(
'%02X%02X%02X',
(int) round($red * self::RGBMAX),
(int) round($green * self::RGBMAX),
(int) round($blue * self::RGBMAX)
);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/Protection.php | src/PhpSpreadsheet/Style/Protection.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style;
class Protection extends Supervisor
{
/** Protection styles */
const PROTECTION_INHERIT = 'inherit';
const PROTECTION_PROTECTED = 'protected';
const PROTECTION_UNPROTECTED = 'unprotected';
/**
* Locked.
*/
protected ?string $locked = null;
/**
* Hidden.
*/
protected ?string $hidden = null;
/**
* Create a new Protection.
*
* @param bool $isSupervisor Flag indicating if this is a supervisor or not
* Leave this value at default unless you understand exactly what
* its ramifications are
* @param bool $isConditional Flag indicating if this is a conditional style or not
* Leave this value at default unless you understand exactly what
* its ramifications are
*/
public function __construct(bool $isSupervisor = false, bool $isConditional = false)
{
// Supervisor?
parent::__construct($isSupervisor);
// Initialise values
if (!$isConditional) {
$this->locked = self::PROTECTION_INHERIT;
$this->hidden = self::PROTECTION_INHERIT;
}
}
/**
* Get the shared style component for the currently active cell in currently active sheet.
* Only used for style supervisor.
*/
public function getSharedComponent(): self
{
/** @var Style $parent */
$parent = $this->parent;
return $parent->getSharedComponent()->getProtection();
}
/**
* Build style array from subcomponents.
*
* @param mixed[] $array
*
* @return array{protection: mixed[]}
*/
public function getStyleArray(array $array): array
{
return ['protection' => $array];
}
/**
* Apply styles from array.
*
* <code>
* $spreadsheet->getActiveSheet()->getStyle('B2')->getLocked()->applyFromArray(
* [
* 'locked' => TRUE,
* 'hidden' => FALSE
* ]
* );
* </code>
*
* @param array{locked?: string, hidden?: string} $styleArray Array containing style information
*
* @return $this
*/
public function applyFromArray(array $styleArray): static
{
if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else {
if (isset($styleArray['locked'])) {
$this->setLocked($styleArray['locked']);
}
if (isset($styleArray['hidden'])) {
$this->setHidden($styleArray['hidden']);
}
}
return $this;
}
/**
* Get locked.
*/
public function getLocked(): ?string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getLocked();
}
return $this->locked;
}
/**
* Set locked.
*
* @param string $lockType see self::PROTECTION_*
*
* @return $this
*/
public function setLocked(string $lockType): static
{
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['locked' => $lockType]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->locked = $lockType;
}
return $this;
}
/**
* Get hidden.
*/
public function getHidden(): ?string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getHidden();
}
return $this->hidden;
}
/**
* Set hidden.
*
* @param string $hiddenType see self::PROTECTION_*
*
* @return $this
*/
public function setHidden(string $hiddenType): static
{
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['hidden' => $hiddenType]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->hidden = $hiddenType;
}
return $this;
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getHashCode();
}
return md5(
$this->locked
. $this->hidden
. __CLASS__
);
}
/** @return mixed[] */
protected function exportArray1(): array
{
$exportedArray = [];
$this->exportArray2($exportedArray, 'locked', $this->getLocked());
$this->exportArray2($exportedArray, 'hidden', $this->getHidden());
return $exportedArray;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/Supervisor.php | src/PhpSpreadsheet/Style/Supervisor.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style;
use PhpOffice\PhpSpreadsheet\IComparable;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
abstract class Supervisor implements IComparable
{
/**
* Supervisor?
*/
protected bool $isSupervisor;
/**
* Parent. Only used for supervisor.
*
* @var Spreadsheet|Supervisor
*/
protected $parent;
/**
* Parent property name.
*/
protected ?string $parentPropertyName = null;
/**
* Create a new Supervisor.
*
* @param bool $isSupervisor Flag indicating if this is a supervisor or not
* Leave this value at default unless you understand exactly what
* its ramifications are
*/
public function __construct(bool $isSupervisor = false)
{
// Supervisor?
$this->isSupervisor = $isSupervisor;
}
/**
* Bind parent. Only used for supervisor.
*
* @return $this
*/
public function bindParent(Spreadsheet|self $parent, ?string $parentPropertyName = null)
{
$this->parent = $parent;
$this->parentPropertyName = $parentPropertyName;
return $this;
}
/**
* Is this a supervisor or a cell style component?
*/
public function getIsSupervisor(): bool
{
return $this->isSupervisor;
}
/**
* Get the currently active sheet. Only used for supervisor.
*/
public function getActiveSheet(): Worksheet
{
return $this->parent->getActiveSheet();
}
/**
* Get the currently active cell coordinate in currently active sheet.
* Only used for supervisor.
*
* @return string E.g. 'A1'
*/
public function getSelectedCells(): string
{
return $this->getActiveSheet()->getSelectedCells();
}
/**
* Get the currently active cell coordinate in currently active sheet.
* Only used for supervisor.
*
* @return string E.g. 'A1'
*/
public function getActiveCell(): string
{
return $this->getActiveSheet()->getActiveCell();
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if ((is_object($value)) && ($key != 'parent')) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
/**
* Export style as array.
*
* Available to anything which extends this class:
* Alignment, Border, Borders, Color, Fill, Font,
* NumberFormat, Protection, and Style.
*
* @return mixed[]
*/
final public function exportArray(): array
{
return $this->exportArray1();
}
/**
* Abstract method to be implemented in anything which
* extends this class.
*
* This method invokes exportArray2 with the names and values
* of all properties to be included in output array,
* returning that array to exportArray, then to caller.
*
* @return mixed[]
*/
abstract protected function exportArray1(): array;
/**
* Populate array from exportArray1.
* This method is available to anything which extends this class.
* The parameter index is the key to be added to the array.
* The parameter objOrValue is either a primitive type,
* which is the value added to the array,
* or a Style object to be recursively added via exportArray.
*
* @param mixed[] $exportedArray
*/
final protected function exportArray2(array &$exportedArray, string $index, mixed $objOrValue): void
{
if ($objOrValue instanceof self) {
$exportedArray[$index] = $objOrValue->exportArray();
} else {
$exportedArray[$index] = $objOrValue;
}
}
/**
* Get the shared style component for the currently active cell in currently active sheet.
* Only used for style supervisor.
*/
abstract public function getSharedComponent(): mixed;
/**
* Build style array from subcomponents.
*
* @param mixed[] $array
*
* @return mixed[]
*/
abstract public function getStyleArray(array $array): array;
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/Borders.php | src/PhpSpreadsheet/Style/Borders.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
class Borders extends Supervisor
{
// Diagonal directions
const DIAGONAL_NONE = 0;
const DIAGONAL_UP = 1;
const DIAGONAL_DOWN = 2;
const DIAGONAL_BOTH = 3;
/**
* Left.
*/
protected Border $left;
/**
* Right.
*/
protected Border $right;
/**
* Top.
*/
protected Border $top;
/**
* Bottom.
*/
protected Border $bottom;
/**
* Diagonal.
*/
protected Border $diagonal;
/**
* DiagonalDirection.
*/
protected int $diagonalDirection;
/**
* All borders pseudo-border. Only applies to supervisor.
*/
protected Border $allBorders;
/**
* Outline pseudo-border. Only applies to supervisor.
*/
protected Border $outline;
/**
* Inside pseudo-border. Only applies to supervisor.
*/
protected Border $inside;
/**
* Vertical pseudo-border. Only applies to supervisor.
*/
protected Border $vertical;
/**
* Horizontal pseudo-border. Only applies to supervisor.
*/
protected Border $horizontal;
/**
* Create a new Borders.
*
* @param bool $isSupervisor Flag indicating if this is a supervisor or not
* Leave this value at default unless you understand exactly what
* its ramifications are
*/
public function __construct(bool $isSupervisor = false, bool $isConditional = false)
{
// Supervisor?
parent::__construct($isSupervisor);
// Initialise values
$this->left = new Border($isSupervisor, $isConditional);
$this->right = new Border($isSupervisor, $isConditional);
$this->top = new Border($isSupervisor, $isConditional);
$this->bottom = new Border($isSupervisor, $isConditional);
$this->diagonal = new Border($isSupervisor, $isConditional);
$this->diagonalDirection = self::DIAGONAL_NONE;
// Specially for supervisor
if ($isSupervisor) {
// Initialize pseudo-borders
$this->allBorders = new Border(true, $isConditional);
$this->outline = new Border(true, $isConditional);
$this->inside = new Border(true, $isConditional);
$this->vertical = new Border(true, $isConditional);
$this->horizontal = new Border(true, $isConditional);
// bind parent if we are a supervisor
$this->left->bindParent($this, 'left');
$this->right->bindParent($this, 'right');
$this->top->bindParent($this, 'top');
$this->bottom->bindParent($this, 'bottom');
$this->diagonal->bindParent($this, 'diagonal');
$this->allBorders->bindParent($this, 'allBorders');
$this->outline->bindParent($this, 'outline');
$this->inside->bindParent($this, 'inside');
$this->vertical->bindParent($this, 'vertical');
$this->horizontal->bindParent($this, 'horizontal');
}
}
/**
* Get the shared style component for the currently active cell in currently active sheet.
* Only used for style supervisor.
*/
public function getSharedComponent(): self
{
/** @var Style $parent */
$parent = $this->parent;
return $parent->getSharedComponent()->getBorders();
}
/**
* Build style array from subcomponents.
*
* @param mixed[] $array
*
* @return array{borders: mixed[]}
*/
public function getStyleArray(array $array): array
{
return ['borders' => $array];
}
/**
* Apply styles from array.
*
* <code>
* $spreadsheet->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray(
* [
* 'bottom' => [
* 'borderStyle' => Border::BORDER_DASHDOT,
* 'color' => [
* 'rgb' => '808080'
* ]
* ],
* 'top' => [
* 'borderStyle' => Border::BORDER_DASHDOT,
* 'color' => [
* 'rgb' => '808080'
* ]
* ]
* ]
* );
* </code>
*
* <code>
* $spreadsheet->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray(
* [
* 'allBorders' => [
* 'borderStyle' => Border::BORDER_DASHDOT,
* 'color' => [
* 'rgb' => '808080'
* ]
* ]
* ]
* );
* </code>
*
* @param mixed[] $styleArray Array containing style information
*
* @return $this
*/
public function applyFromArray(array $styleArray): static
{
if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else {
/** @var array{left?: float[], right?: float[], top?: float[], bottom?: float[], diagonal?: mixed[], diagonalDirection?: int, allBorders?: mixed[][]} $styleArray */
if (isset($styleArray['left'])) {
$this->getLeft()->applyFromArray($styleArray['left']);
}
if (isset($styleArray['right'])) {
$this->getRight()->applyFromArray($styleArray['right']);
}
if (isset($styleArray['top'])) {
$this->getTop()->applyFromArray($styleArray['top']);
}
if (isset($styleArray['bottom'])) {
$this->getBottom()->applyFromArray($styleArray['bottom']);
}
if (isset($styleArray['diagonal'])) {
$this->getDiagonal()->applyFromArray($styleArray['diagonal']);
}
if (isset($styleArray['diagonalDirection'])) {
$this->setDiagonalDirection($styleArray['diagonalDirection']);
}
if (isset($styleArray['allBorders'])) {
$this->getLeft()->applyFromArray($styleArray['allBorders']);
$this->getRight()->applyFromArray($styleArray['allBorders']);
$this->getTop()->applyFromArray($styleArray['allBorders']);
$this->getBottom()->applyFromArray($styleArray['allBorders']);
}
}
return $this;
}
/**
* Get Left.
*/
public function getLeft(): Border
{
return $this->left;
}
/**
* Get Right.
*/
public function getRight(): Border
{
return $this->right;
}
/**
* Get Top.
*/
public function getTop(): Border
{
return $this->top;
}
/**
* Get Bottom.
*/
public function getBottom(): Border
{
return $this->bottom;
}
/**
* Get Diagonal.
*/
public function getDiagonal(): Border
{
return $this->diagonal;
}
/**
* Get AllBorders (pseudo-border). Only applies to supervisor.
*/
public function getAllBorders(): Border
{
if (!$this->isSupervisor) {
throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.');
}
return $this->allBorders;
}
/**
* Get Outline (pseudo-border). Only applies to supervisor.
*/
public function getOutline(): Border
{
if (!$this->isSupervisor) {
throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.');
}
return $this->outline;
}
/**
* Get Inside (pseudo-border). Only applies to supervisor.
*/
public function getInside(): Border
{
if (!$this->isSupervisor) {
throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.');
}
return $this->inside;
}
/**
* Get Vertical (pseudo-border). Only applies to supervisor.
*/
public function getVertical(): Border
{
if (!$this->isSupervisor) {
throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.');
}
return $this->vertical;
}
/**
* Get Horizontal (pseudo-border). Only applies to supervisor.
*/
public function getHorizontal(): Border
{
if (!$this->isSupervisor) {
throw new PhpSpreadsheetException('Can only get pseudo-border for supervisor.');
}
return $this->horizontal;
}
/**
* Get DiagonalDirection.
*/
public function getDiagonalDirection(): int
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getDiagonalDirection();
}
return $this->diagonalDirection;
}
/**
* Set DiagonalDirection.
*
* @param int $direction see self::DIAGONAL_*
*
* @return $this
*/
public function setDiagonalDirection(int $direction): static
{
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['diagonalDirection' => $direction]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->diagonalDirection = $direction;
}
return $this;
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getHashcode();
}
return md5(
$this->getLeft()->getHashCode()
. $this->getRight()->getHashCode()
. $this->getTop()->getHashCode()
. $this->getBottom()->getHashCode()
. $this->getDiagonal()->getHashCode()
. $this->getDiagonalDirection()
. __CLASS__
);
}
/** @return mixed[][] */
protected function exportArray1(): array
{
$exportedArray = [];
$this->exportArray2($exportedArray, 'bottom', $this->getBottom());
$this->exportArray2($exportedArray, 'diagonal', $this->getDiagonal());
$this->exportArray2($exportedArray, 'diagonalDirection', $this->getDiagonalDirection());
$this->exportArray2($exportedArray, 'left', $this->getLeft());
$this->exportArray2($exportedArray, 'right', $this->getRight());
$this->exportArray2($exportedArray, 'top', $this->getTop());
/** @var mixed[][] $exportedArray */
return $exportedArray;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/Fill.php | src/PhpSpreadsheet/Style/Fill.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style;
class Fill extends Supervisor
{
// Fill types
const FILL_NONE = 'none';
const FILL_SOLID = 'solid';
const FILL_GRADIENT_LINEAR = 'linear';
const FILL_GRADIENT_PATH = 'path';
const FILL_PATTERN_DARKDOWN = 'darkDown';
const FILL_PATTERN_DARKGRAY = 'darkGray';
const FILL_PATTERN_DARKGRID = 'darkGrid';
const FILL_PATTERN_DARKHORIZONTAL = 'darkHorizontal';
const FILL_PATTERN_DARKTRELLIS = 'darkTrellis';
const FILL_PATTERN_DARKUP = 'darkUp';
const FILL_PATTERN_DARKVERTICAL = 'darkVertical';
const FILL_PATTERN_GRAY0625 = 'gray0625';
const FILL_PATTERN_GRAY125 = 'gray125';
const FILL_PATTERN_LIGHTDOWN = 'lightDown';
const FILL_PATTERN_LIGHTGRAY = 'lightGray';
const FILL_PATTERN_LIGHTGRID = 'lightGrid';
const FILL_PATTERN_LIGHTHORIZONTAL = 'lightHorizontal';
const FILL_PATTERN_LIGHTTRELLIS = 'lightTrellis';
const FILL_PATTERN_LIGHTUP = 'lightUp';
const FILL_PATTERN_LIGHTVERTICAL = 'lightVertical';
const FILL_PATTERN_MEDIUMGRAY = 'mediumGray';
public ?int $startcolorIndex = null;
public ?int $endcolorIndex = null;
/**
* Fill type.
*/
protected ?string $fillType = self::FILL_NONE;
/**
* Rotation.
*/
protected float $rotation = 0.0;
/**
* Start color.
*/
protected Color $startColor;
/**
* End color.
*/
protected Color $endColor;
private bool $colorChanged = false;
/**
* Create a new Fill.
*
* @param bool $isSupervisor Flag indicating if this is a supervisor or not
* Leave this value at default unless you understand exactly what
* its ramifications are
* @param bool $isConditional Flag indicating if this is a conditional style or not
* Leave this value at default unless you understand exactly what
* its ramifications are
*/
public function __construct(bool $isSupervisor = false, bool $isConditional = false)
{
// Supervisor?
parent::__construct($isSupervisor);
// Initialise values
if ($isConditional) {
$this->fillType = null;
}
$this->startColor = new Color(Color::COLOR_WHITE, $isSupervisor, $isConditional);
$this->endColor = new Color(Color::COLOR_BLACK, $isSupervisor, $isConditional);
// bind parent if we are a supervisor
if ($isSupervisor) {
$this->startColor->bindParent($this, 'startColor');
$this->endColor->bindParent($this, 'endColor');
}
}
/**
* Get the shared style component for the currently active cell in currently active sheet.
* Only used for style supervisor.
*/
public function getSharedComponent(): self
{
/** @var Style $parent */
$parent = $this->parent;
return $parent->getSharedComponent()->getFill();
}
/**
* Build style array from subcomponents.
*
* @param mixed[] $array
*
* @return array{fill: mixed[]}
*/
public function getStyleArray(array $array): array
{
return ['fill' => $array];
}
/**
* Apply styles from array.
*
* <code>
* $spreadsheet->getActiveSheet()->getStyle('B2')->getFill()->applyFromArray(
* [
* 'fillType' => Fill::FILL_GRADIENT_LINEAR,
* 'rotation' => 0.0,
* 'startColor' => [
* 'rgb' => '000000'
* ],
* 'endColor' => [
* 'argb' => 'FFFFFFFF'
* ]
* ]
* );
* </code>
*
* @param array{fillType?: string, rotation?: float, startColor?: array{rgb?: string, argb?: string}, endColor?: array{rgb?: string, argb?: string}, color?: array{rgb?: string, argb?: string}} $styleArray Array containing style information
*
* @return $this
*/
public function applyFromArray(array $styleArray): static
{
if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else {
if (isset($styleArray['fillType'])) {
$this->setFillType($styleArray['fillType']);
}
if (isset($styleArray['rotation'])) {
$this->setRotation($styleArray['rotation']);
}
if (isset($styleArray['startColor'])) {
$this->getStartColor()
->applyFromArray($styleArray['startColor']);
}
if (isset($styleArray['endColor'])) {
$this->getEndColor()
->applyFromArray($styleArray['endColor']);
}
if (isset($styleArray['color'])) {
$this->getStartColor()
->applyFromArray($styleArray['color']);
$this->getEndColor()
->applyFromArray($styleArray['color']);
}
}
return $this;
}
/**
* Get Fill Type.
*/
public function getFillType(): ?string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getFillType();
}
return $this->fillType;
}
/**
* Set Fill Type.
*
* @param string $fillType Fill type, see self::FILL_*
*
* @return $this
*/
public function setFillType(string $fillType): static
{
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['fillType' => $fillType]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->fillType = $fillType;
}
return $this;
}
/**
* Get Rotation.
*/
public function getRotation(): float
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getRotation();
}
return $this->rotation;
}
/**
* Set Rotation.
*
* @return $this
*/
public function setRotation(float $angleInDegrees): static
{
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['rotation' => $angleInDegrees]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->rotation = $angleInDegrees;
}
return $this;
}
/**
* Get Start Color.
*/
public function getStartColor(): Color
{
return $this->startColor;
}
/**
* Set Start Color.
*
* @return $this
*/
public function setStartColor(Color $color): static
{
$this->colorChanged = true;
// make sure parameter is a real color and not a supervisor
$color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color;
if ($this->isSupervisor) {
$styleArray = $this->getStartColor()->getStyleArray(['argb' => $color->getARGB()]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->startColor = $color;
}
return $this;
}
/**
* Get End Color.
*/
public function getEndColor(): Color
{
return $this->endColor;
}
/**
* Set End Color.
*
* @return $this
*/
public function setEndColor(Color $color): static
{
$this->colorChanged = true;
// make sure parameter is a real color and not a supervisor
$color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color;
if ($this->isSupervisor) {
$styleArray = $this->getEndColor()->getStyleArray(['argb' => $color->getARGB()]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->endColor = $color;
}
return $this;
}
public function getColorsChanged(): bool
{
if ($this->isSupervisor) {
$changed = $this->getSharedComponent()->colorChanged;
} else {
$changed = $this->colorChanged;
}
return $changed || $this->startColor->getHasChanged() || $this->endColor->getHasChanged();
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getHashCode();
}
// Note that we don't care about colours for fill type NONE, but could have duplicate NONEs with
// different hashes if we don't explicitly prevent this
return md5(
$this->getFillType()
. $this->getRotation()
. ($this->getFillType() !== self::FILL_NONE ? $this->getStartColor()->getHashCode() : '')
. ($this->getFillType() !== self::FILL_NONE ? $this->getEndColor()->getHashCode() : '')
. ((string) $this->getColorsChanged())
. __CLASS__
);
}
/** @return mixed[] */
protected function exportArray1(): array
{
$exportedArray = [];
$this->exportArray2($exportedArray, 'fillType', $this->getFillType());
$this->exportArray2($exportedArray, 'rotation', $this->getRotation());
if ($this->getColorsChanged()) {
$this->exportArray2($exportedArray, 'endColor', $this->getEndColor());
$this->exportArray2($exportedArray, 'startColor', $this->getStartColor());
}
return $exportedArray;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/Style.php | src/PhpSpreadsheet/Style/Style.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style;
use PhpOffice\PhpSpreadsheet\Calculation\Functions;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Chart\ChartColor;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class Style extends Supervisor
{
/**
* Font.
*/
protected Font $font;
/**
* Fill.
*/
protected Fill $fill;
/**
* Borders.
*/
protected Borders $borders;
/**
* Alignment.
*/
protected Alignment $alignment;
/**
* Number Format.
*/
protected NumberFormat $numberFormat;
/**
* Protection.
*/
protected Protection $protection;
/**
* Index of style in collection. Only used for real style.
*/
protected int $index;
/**
* Use Quote Prefix when displaying in cell editor. Only used for real style.
*/
protected bool $quotePrefix = false;
/**
* Internal cache for styles
* Used when applying style on range of cells (column or row) and cleared when
* all cells in range is styled.
*
* PhpSpreadsheet will always minimize the amount of styles used. So cells with
* same styles will reference the same Style instance. To check if two styles
* are similar Style::getHashCode() is used. This call is expensive. To minimize
* the need to call this method we can cache the internal PHP object id of the
* Style in the range. Style::getHashCode() will then only be called when we
* encounter a unique style.
*
* @see Style::applyFromArray()
* @see Style::getHashCode()
*
* @var null|array<string, mixed[]>
*/
private static ?array $cachedStyles = null;
/**
* Create a new Style.
*
* @param bool $isSupervisor Flag indicating if this is a supervisor or not
* Leave this value at default unless you understand exactly what
* its ramifications are
* @param bool $isConditional Flag indicating if this is a conditional style or not
* Leave this value at default unless you understand exactly what
* its ramifications are
*/
public function __construct(bool $isSupervisor = false, bool $isConditional = false)
{
parent::__construct($isSupervisor);
// Initialise values
$this->font = new Font($isSupervisor, $isConditional);
$this->fill = new Fill($isSupervisor, $isConditional);
$this->borders = new Borders($isSupervisor, $isConditional);
$this->alignment = new Alignment($isSupervisor, $isConditional);
$this->numberFormat = new NumberFormat($isSupervisor, $isConditional);
$this->protection = new Protection($isSupervisor, $isConditional);
// bind parent if we are a supervisor
if ($isSupervisor) {
$this->font->bindParent($this);
$this->fill->bindParent($this);
$this->borders->bindParent($this);
$this->alignment->bindParent($this);
$this->numberFormat->bindParent($this);
$this->protection->bindParent($this);
}
}
/**
* Get the shared style component for the currently active cell in currently active sheet.
* Only used for style supervisor.
*/
public function getSharedComponent(): self
{
$activeSheet = $this->getActiveSheet();
$selectedCell = Functions::trimSheetFromCellReference($this->getActiveCell()); // e.g. 'A1'
if ($activeSheet->cellExists($selectedCell)) {
$xfIndex = $activeSheet->getCell($selectedCell)->getXfIndex();
} else {
$xfIndex = 0;
}
return $activeSheet->getParentOrThrow()->getCellXfByIndex($xfIndex);
}
/**
* Get parent. Only used for style supervisor.
*/
public function getParent(): Spreadsheet
{
return $this->getActiveSheet()->getParentOrThrow();
}
/**
* Build style array from subcomponents.
*
* @param mixed[] $array
*
* @return array{quotePrefix: mixed[]}
*/
public function getStyleArray(array $array): array
{
return ['quotePrefix' => $array];
}
/**
* Apply styles from array.
*
* <code>
* $spreadsheet->getActiveSheet()->getStyle('B2')->applyFromArray(
* [
* 'font' => [
* 'name' => 'Arial',
* 'bold' => true,
* 'italic' => false,
* 'underline' => Font::UNDERLINE_DOUBLE,
* 'strikethrough' => false,
* 'color' => [
* 'rgb' => '808080'
* ]
* ],
* 'borders' => [
* 'bottom' => [
* 'borderStyle' => Border::BORDER_DASHDOT,
* 'color' => [
* 'rgb' => '808080'
* ]
* ],
* 'top' => [
* 'borderStyle' => Border::BORDER_DASHDOT,
* 'color' => [
* 'rgb' => '808080'
* ]
* ]
* ],
* 'alignment' => [
* 'horizontal' => Alignment::HORIZONTAL_CENTER,
* 'vertical' => Alignment::VERTICAL_CENTER,
* 'wrapText' => true,
* ],
* 'quotePrefix' => true
* ]
* );
* </code>
*
* @param mixed[] $styleArray Array containing style information
* @param bool $advancedBorders advanced mode for setting borders
*
* @return $this
*/
public function applyFromArray(array $styleArray, bool $advancedBorders = true): static
{
if ($this->isSupervisor) {
$pRange = $this->getSelectedCells();
// Uppercase coordinate and strip any Worksheet reference from the selected range
$pRange = strtoupper($pRange);
if (str_contains($pRange, '!')) {
$pRangeWorksheet = StringHelper::strToUpper(substr($pRange, 0, (int) strrpos($pRange, '!')));
$pRangeWorksheet = Worksheet::unApostrophizeTitle($pRangeWorksheet);
if ($pRangeWorksheet !== '' && StringHelper::strToUpper($this->getActiveSheet()->getTitle()) !== $pRangeWorksheet) {
throw new Exception('Invalid Worksheet for specified Range');
}
$pRange = strtoupper(Functions::trimSheetFromCellReference($pRange));
}
// Is it a cell range or a single cell?
if (!str_contains($pRange, ':')) {
$rangeA = $pRange;
$rangeB = $pRange;
} else {
[$rangeA, $rangeB] = explode(':', $pRange);
}
// Calculate range outer borders
$rangeStart = Coordinate::coordinateFromString($rangeA);
$rangeEnd = Coordinate::coordinateFromString($rangeB);
$rangeStartIndexes = Coordinate::indexesFromString($rangeA);
$rangeEndIndexes = Coordinate::indexesFromString($rangeB);
$columnStart = $rangeStart[0];
$columnEnd = $rangeEnd[0];
// Make sure we can loop upwards on rows and columns
if ($rangeStartIndexes[0] > $rangeEndIndexes[0] && $rangeStartIndexes[1] > $rangeEndIndexes[1]) {
$tmp = $rangeStartIndexes;
$rangeStartIndexes = $rangeEndIndexes;
$rangeEndIndexes = $tmp;
}
// ADVANCED MODE:
if ($advancedBorders && isset($styleArray['borders'])) {
// 'allBorders' is a shorthand property for 'outline' and 'inside' and
// it applies to components that have not been set explicitly
/** @var mixed[][] $styleArray */
if (isset($styleArray['borders']['allBorders'])) {
foreach (['outline', 'inside'] as $component) {
if (!isset($styleArray['borders'][$component])) {
$styleArray['borders'][$component] = $styleArray['borders']['allBorders'];
}
}
unset($styleArray['borders']['allBorders']); // not needed any more
}
// 'outline' is a shorthand property for 'top', 'right', 'bottom', 'left'
// it applies to components that have not been set explicitly
if (isset($styleArray['borders']['outline'])) {
foreach (['top', 'right', 'bottom', 'left'] as $component) {
if (!isset($styleArray['borders'][$component])) {
$styleArray['borders'][$component] = $styleArray['borders']['outline'];
}
}
unset($styleArray['borders']['outline']); // not needed any more
}
// 'inside' is a shorthand property for 'vertical' and 'horizontal'
// it applies to components that have not been set explicitly
if (isset($styleArray['borders']['inside'])) {
foreach (['vertical', 'horizontal'] as $component) {
if (!isset($styleArray['borders'][$component])) {
$styleArray['borders'][$component] = $styleArray['borders']['inside'];
}
}
unset($styleArray['borders']['inside']); // not needed any more
}
// width and height characteristics of selection, 1, 2, or 3 (for 3 or more)
$xMax = min($rangeEndIndexes[0] - $rangeStartIndexes[0] + 1, 3);
$yMax = min($rangeEndIndexes[1] - $rangeStartIndexes[1] + 1, 3);
// loop through up to 3 x 3 = 9 regions
for ($x = 1; $x <= $xMax; ++$x) {
// start column index for region
$colStart = ($x == 3)
? Coordinate::stringFromColumnIndex($rangeEndIndexes[0])
: Coordinate::stringFromColumnIndex($rangeStartIndexes[0] + $x - 1);
// end column index for region
$colEnd = ($x == 1)
? Coordinate::stringFromColumnIndex($rangeStartIndexes[0])
: Coordinate::stringFromColumnIndex($rangeEndIndexes[0] - $xMax + $x);
for ($y = 1; $y <= $yMax; ++$y) {
// which edges are touching the region
$edges = [];
if ($x == 1) {
// are we at left edge
$edges[] = 'left';
}
if ($x == $xMax) {
// are we at right edge
$edges[] = 'right';
}
if ($y == 1) {
// are we at top edge?
$edges[] = 'top';
}
if ($y == $yMax) {
// are we at bottom edge?
$edges[] = 'bottom';
}
// start row index for region
$rowStart = ($y == 3)
? $rangeEndIndexes[1] : $rangeStartIndexes[1] + $y - 1;
// end row index for region
$rowEnd = ($y == 1)
? $rangeStartIndexes[1] : $rangeEndIndexes[1] - $yMax + $y;
// build range for region
$range = $colStart . $rowStart . ':' . $colEnd . $rowEnd;
// retrieve relevant style array for region
$regionStyles = $styleArray;
unset($regionStyles['borders']['inside']);
// what are the inner edges of the region when looking at the selection
$innerEdges = array_diff(['top', 'right', 'bottom', 'left'], $edges);
// inner edges that are not touching the region should take the 'inside' border properties if they have been set
foreach ($innerEdges as $innerEdge) {
switch ($innerEdge) {
case 'top':
case 'bottom':
/** @var mixed[][] $styleArray */
// should pick up 'horizontal' border property if set
if (isset($styleArray['borders']['horizontal'])) {
/** @var mixed[][] $regionStyles */
$regionStyles['borders'][$innerEdge]
= $styleArray['borders']['horizontal'];
} else {
/** @var mixed[][] $regionStyles */
unset($regionStyles['borders'][$innerEdge]);
}
break;
case 'left':
case 'right':
// should pick up 'vertical' border property if set
if (isset($styleArray['borders']['vertical'])) {
$regionStyles['borders'][$innerEdge] = $styleArray['borders']['vertical'];
} else {
unset($regionStyles['borders'][$innerEdge]);
}
break;
}
}
// apply region style to region by calling applyFromArray() in simple mode
$this->getActiveSheet()->getStyle($range)->applyFromArray($regionStyles, false);
}
}
// restore initial cell selection range
$this->getActiveSheet()->getStyle($pRange);
return $this;
}
// SIMPLE MODE:
// Selection type, inspect
if (preg_match('/^[A-Z]+1:[A-Z]+1048576$/', $pRange)) {
$selectionType = 'COLUMN';
// Enable caching of styles
self::$cachedStyles = ['hashByObjId' => [], 'styleByHash' => []];
} elseif (preg_match('/^A\d+:XFD\d+$/', $pRange)) {
$selectionType = 'ROW';
// Enable caching of styles
self::$cachedStyles = ['hashByObjId' => [], 'styleByHash' => []];
} else {
$selectionType = 'CELL';
}
// First loop through columns, rows, or cells to find out which styles are affected by this operation
$oldXfIndexes = $this->getOldXfIndexes($selectionType, $rangeStartIndexes, $rangeEndIndexes, $columnStart, $columnEnd, $styleArray);
// clone each of the affected styles, apply the style array, and add the new styles to the workbook
$workbook = $this->getActiveSheet()->getParentOrThrow();
$newXfIndexes = [];
foreach ($oldXfIndexes as $oldXfIndex => $dummy) {
$style = $workbook->getCellXfByIndex($oldXfIndex);
// $cachedStyles is set when applying style for a range of cells, either column or row
if (self::$cachedStyles === null) {
// Clone the old style and apply style-array
$newStyle = clone $style;
$newStyle->applyFromArray($styleArray);
// Look for existing style we can use instead (reduce memory usage)
$existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode());
} else {
// Style cache is stored by Style::getHashCode(). But calling this method is
// expensive. So we cache the php obj id -> hash.
$objId = spl_object_id($style);
// Look for the original HashCode
$styleHash = self::$cachedStyles['hashByObjId'][$objId] ?? null;
if ($styleHash === null) {
// This object_id is not cached, store the hashcode in case encounter again
$styleHash = self::$cachedStyles['hashByObjId'][$objId] = $style->getHashCode();
}
// Find existing style by hash.
/** @var string $styleHash */
$existingStyle = self::$cachedStyles['styleByHash'][$styleHash] ?? null;
if (!$existingStyle) {
// The old style combined with the new style array is not cached, so we create it now
$newStyle = clone $style;
$newStyle->applyFromArray($styleArray);
// Look for similar style in workbook to reduce memory usage
$existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode());
// Cache the new style by original hashcode
self::$cachedStyles['styleByHash'][$styleHash] = $existingStyle instanceof self ? $existingStyle : $newStyle;
}
}
if ($existingStyle) {
// there is already such cell Xf in our collection
/** @var Style $existingStyle */
$newXfIndexes[$oldXfIndex] = $existingStyle->getIndex();
} else {
if (!isset($newStyle)) {
// Handle bug in PHPStan, see https://github.com/phpstan/phpstan/issues/5805
// $newStyle should always be defined.
// This block might not be needed in the future
// @codeCoverageIgnoreStart
$newStyle = clone $style;
$newStyle->applyFromArray($styleArray);
// @codeCoverageIgnoreEnd
}
// we don't have such a cell Xf, need to add
$workbook->addCellXf($newStyle);
$newXfIndexes[$oldXfIndex] = $newStyle->getIndex();
}
}
// Loop through columns, rows, or cells again and update the XF index
switch ($selectionType) {
case 'COLUMN':
for ($col = $rangeStartIndexes[0]; $col <= $rangeEndIndexes[0]; ++$col) {
$columnDimension = $this->getActiveSheet()->getColumnDimensionByColumn($col);
$oldXfIndex = $columnDimension->getXfIndex();
/** @var int[] $newXfIndexes */
$columnDimension->setXfIndex($newXfIndexes[$oldXfIndex]);
}
// Disable caching of styles
self::$cachedStyles = null;
break;
case 'ROW':
for ($row = $rangeStartIndexes[1]; $row <= $rangeEndIndexes[1]; ++$row) {
$rowDimension = $this->getActiveSheet()->getRowDimension($row);
// row without explicit style should be formatted based on default style
$oldXfIndex = $rowDimension->getXfIndex() ?? 0;
/** @var int[] $newXfIndexes */
$rowDimension->setXfIndex($newXfIndexes[$oldXfIndex]);
}
// Disable caching of styles
self::$cachedStyles = null;
break;
case 'CELL':
for ($col = $rangeStartIndexes[0]; $col <= $rangeEndIndexes[0]; ++$col) {
for ($row = $rangeStartIndexes[1]; $row <= $rangeEndIndexes[1]; ++$row) {
$cell = $this->getActiveSheet()->getCell([$col, $row]);
$oldXfIndex = $cell->getXfIndex();
$cell->setXfIndex($newXfIndexes[$oldXfIndex]);
}
}
break;
}
} else {
// not a supervisor, just apply the style array directly on style object
/** @var array{
* alignment?: mixed[],
* fill?: array{fillType?: string, rotation?: float, startColor?: array{rgb?: string, argb?: string}, endColor?: array{rgb?: string, argb?: string}, color?: array{rgb?: string, argb?: string}},
* font?: array{name?: string, latin?: string, eastAsian?: string, complexScript?: string, bold?: bool, italic?: bool, superscript?: bool, subscript?: bool, underline?: bool|string, strikethrough?: bool, color?: string[], size?: ?int, chartColor?: ChartColor, scheme?: string, cap?: string},
* borders?: mixed[][],
* numberFormat?: string[],
* protection?: array{locked?: string, hidden?: string},
* quotePrefix?: bool} $styleArray */
if (isset($styleArray['fill'])) {
$this->getFill()
->applyFromArray($styleArray['fill']);
}
if (isset($styleArray['font'])) {
$this->getFont()
->applyFromArray($styleArray['font']);
}
if (isset($styleArray['borders'])) {
$this->getBorders()
->applyFromArray($styleArray['borders']);
}
if (isset($styleArray['alignment'])) {
$temp = $styleArray['alignment'];
$this->getAlignment()
->applyFromArray($temp);
}
if (isset($styleArray['numberFormat'])) {
$this->getNumberFormat()
->applyFromArray($styleArray['numberFormat']);
}
if (isset($styleArray['protection'])) {
$this->getProtection()
->applyFromArray($styleArray['protection']);
}
if (isset($styleArray['quotePrefix'])) {
$this->quotePrefix = $styleArray['quotePrefix'];
}
}
return $this;
}
/**
* @param mixed[] $rangeStart
* @param mixed[] $rangeEnd
* @param mixed[] $styleArray
*
* @return mixed[]
*/
private function getOldXfIndexes(string $selectionType, array $rangeStart, array $rangeEnd, string $columnStart, string $columnEnd, array $styleArray): array
{
$oldXfIndexes = [];
switch ($selectionType) {
case 'COLUMN':
for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
/** @var int $col */
$oldXfIndexes[$this->getActiveSheet()->getColumnDimensionByColumn($col)->getXfIndex()] = true;
}
foreach ($this->getActiveSheet()->getColumnIterator($columnStart, $columnEnd) as $columnIterator) {
$cellIterator = $columnIterator->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $columnCell) {
$columnCell->getStyle()
->applyFromArray($styleArray);
}
}
break;
case 'ROW':
for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
/** @var int $row */
if ($this->getActiveSheet()->getRowDimension($row)->getXfIndex() === null) {
$oldXfIndexes[0] = true; // row without explicit style should be formatted based on default style
} else {
$oldXfIndexes[$this->getActiveSheet()->getRowDimension($row)->getXfIndex()] = true;
}
}
/** @var float|int */
$temp1 = $rangeStart[1];
/** @var float|int */
$temp2 = $rangeEnd[1];
foreach ($this->getActiveSheet()->getRowIterator((int) $temp1, (int) $temp2) as $rowIterator) {
$cellIterator = $rowIterator->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $rowCell) {
$rowCell->getStyle()
->applyFromArray($styleArray);
}
}
break;
case 'CELL':
for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) {
/** @var int $col */
for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) {
/** @var int $row */
$oldXfIndexes[$this->getActiveSheet()->getCell([$col, $row])->getXfIndex()] = true;
}
}
break;
}
return $oldXfIndexes;
}
/**
* Get Fill.
*/
public function getFill(): Fill
{
return $this->fill;
}
/**
* Get Font.
*/
public function getFont(): Font
{
return $this->font;
}
/**
* Set font.
*
* @return $this
*/
public function setFont(Font $font): static
{
$this->font = $font;
return $this;
}
/**
* Get Borders.
*/
public function getBorders(): Borders
{
return $this->borders;
}
/**
* Get Alignment.
*/
public function getAlignment(): Alignment
{
return $this->alignment;
}
/**
* Get Number Format.
*/
public function getNumberFormat(): NumberFormat
{
return $this->numberFormat;
}
/**
* Get Conditional Styles. Only used on supervisor.
*
* @return Conditional[]
*/
public function getConditionalStyles(): array
{
return $this->getActiveSheet()->getConditionalStyles($this->getActiveCell());
}
/**
* Set Conditional Styles. Only used on supervisor.
*
* @param Conditional[] $conditionalStyleArray Array of conditional styles
*
* @return $this
*/
public function setConditionalStyles(array $conditionalStyleArray): static
{
$this->getActiveSheet()->setConditionalStyles($this->getSelectedCells(), $conditionalStyleArray);
return $this;
}
/**
* Get Protection.
*/
public function getProtection(): Protection
{
return $this->protection;
}
/**
* Get quote prefix.
*/
public function getQuotePrefix(): bool
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getQuotePrefix();
}
return $this->quotePrefix;
}
/**
* Set quote prefix.
*
* @return $this
*/
public function setQuotePrefix(bool $quotePrefix): static
{
if ($quotePrefix == '') {
$quotePrefix = false;
}
if ($this->isSupervisor) {
$styleArray = ['quotePrefix' => $quotePrefix];
$this->getActiveSheet()
->getStyle($this->getSelectedCells())
->applyFromArray($styleArray);
} else {
$this->quotePrefix = (bool) $quotePrefix;
}
return $this;
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
return md5(
$this->fill->getHashCode()
. $this->font->getHashCode()
. $this->borders->getHashCode()
. $this->alignment->getHashCode()
. $this->numberFormat->getHashCode()
. $this->protection->getHashCode()
. ($this->quotePrefix ? 't' : 'f')
. __CLASS__
);
}
/**
* Get own index in style collection.
*/
public function getIndex(): int
{
return $this->index;
}
/**
* Set own index in style collection.
*/
public function setIndex(int $index): void
{
$this->index = $index;
}
/** @return mixed[] */
protected function exportArray1(): array
{
$exportedArray = [];
$this->exportArray2($exportedArray, 'alignment', $this->getAlignment());
$this->exportArray2($exportedArray, 'borders', $this->getBorders());
$this->exportArray2($exportedArray, 'fill', $this->getFill());
$this->exportArray2($exportedArray, 'font', $this->getFont());
$this->exportArray2($exportedArray, 'numberFormat', $this->getNumberFormat());
$this->exportArray2($exportedArray, 'protection', $this->getProtection());
$this->exportArray2($exportedArray, 'quotePrefix', $this->getQuotePrefix());
return $exportedArray;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/Border.php | src/PhpSpreadsheet/Style/Border.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
class Border extends Supervisor
{
// Border style
const BORDER_NONE = 'none';
const BORDER_DASHDOT = 'dashDot';
const BORDER_DASHDOTDOT = 'dashDotDot';
const BORDER_DASHED = 'dashed';
const BORDER_DOTTED = 'dotted';
const BORDER_DOUBLE = 'double';
const BORDER_HAIR = 'hair';
const BORDER_MEDIUM = 'medium';
const BORDER_MEDIUMDASHDOT = 'mediumDashDot';
const BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot';
const BORDER_MEDIUMDASHED = 'mediumDashed';
const BORDER_SLANTDASHDOT = 'slantDashDot';
const BORDER_THICK = 'thick';
const BORDER_THIN = 'thin';
const BORDER_OMIT = 'omit'; // should be used only for Conditional
/**
* Border style.
*/
protected string $borderStyle = self::BORDER_NONE;
/**
* Border color.
*/
protected Color $color;
public ?int $colorIndex = null;
/**
* Create a new Border.
*
* @param bool $isSupervisor Flag indicating if this is a supervisor or not
* Leave this value at default unless you understand exactly what
* its ramifications are
*/
public function __construct(bool $isSupervisor = false, bool $isConditional = false)
{
// Supervisor?
parent::__construct($isSupervisor);
// Initialise values
$this->color = new Color(Color::COLOR_BLACK, $isSupervisor);
// bind parent if we are a supervisor
if ($isSupervisor) {
$this->color->bindParent($this, 'color');
}
if ($isConditional) {
$this->borderStyle = self::BORDER_OMIT;
}
}
/**
* Get the shared style component for the currently active cell in currently active sheet.
* Only used for style supervisor.
*/
public function getSharedComponent(): self
{
/** @var Style $parent */
$parent = $this->parent;
/** @var Borders $sharedComponent */
$sharedComponent = $parent->getSharedComponent();
return match ($this->parentPropertyName) {
'bottom' => $sharedComponent->getBottom(),
'diagonal' => $sharedComponent->getDiagonal(),
'left' => $sharedComponent->getLeft(),
'right' => $sharedComponent->getRight(),
'top' => $sharedComponent->getTop(),
default => throw new PhpSpreadsheetException('Cannot get shared component for a pseudo-border.'),
};
}
/**
* Build style array from subcomponents.
*
* @param mixed[] $array
*
* @return mixed[]
*/
public function getStyleArray(array $array): array
{
/** @var Style $parent */
$parent = $this->parent;
return $parent->getStyleArray([$this->parentPropertyName => $array]);
}
/**
* Apply styles from array.
*
* <code>
* $spreadsheet->getActiveSheet()->getStyle('B2')->getBorders()->getTop()->applyFromArray(
* [
* 'borderStyle' => Border::BORDER_DASHDOT,
* 'color' => [
* 'rgb' => '808080'
* ]
* ]
* );
* </code>
*
* @param mixed[] $styleArray Array containing style information
*
* @return $this
*/
public function applyFromArray(array $styleArray): static
{
if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else {
/** @var array{borderStyle?: string, color?: array{rgb?: string, argb?: string}} $styleArray */
if (isset($styleArray['borderStyle'])) {
$this->setBorderStyle($styleArray['borderStyle']);
}
if (isset($styleArray['color'])) {
$this->getColor()
->applyFromArray($styleArray['color']);
}
}
return $this;
}
/**
* Get Border style.
*/
public function getBorderStyle(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getBorderStyle();
}
return $this->borderStyle;
}
/**
* Set Border style.
*
* @param bool|string $style When passing a boolean, FALSE equates Border::BORDER_NONE
* and TRUE to Border::BORDER_MEDIUM
*
* @return $this
*/
public function setBorderStyle(bool|string $style): static
{
if (empty($style)) {
$style = self::BORDER_NONE;
} elseif (is_bool($style)) {
$style = self::BORDER_MEDIUM;
}
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['borderStyle' => $style]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->borderStyle = $style;
}
return $this;
}
/**
* Get Border Color.
*/
public function getColor(): Color
{
return $this->color;
}
/**
* Set Border Color.
*
* @return $this
*/
public function setColor(Color $color): static
{
// make sure parameter is a real color and not a supervisor
$color = $color->getIsSupervisor() ? $color->getSharedComponent() : $color;
if ($this->isSupervisor) {
$styleArray = $this->getColor()->getStyleArray(['argb' => $color->getARGB()]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->color = $color;
}
return $this;
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getHashCode();
}
return md5(
$this->borderStyle
. $this->color->getHashCode()
. __CLASS__
);
}
/** @return mixed[] */
protected function exportArray1(): array
{
$exportedArray = [];
$this->exportArray2($exportedArray, 'borderStyle', $this->getBorderStyle());
$this->exportArray2($exportedArray, 'color', $this->getColor());
return $exportedArray;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/Alignment.php | src/PhpSpreadsheet/Style/Alignment.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
class Alignment extends Supervisor
{
// Horizontal alignment styles
const HORIZONTAL_GENERAL = 'general';
const HORIZONTAL_LEFT = 'left';
const HORIZONTAL_RIGHT = 'right';
const HORIZONTAL_CENTER = 'center';
const HORIZONTAL_CENTER_CONTINUOUS = 'centerContinuous';
const HORIZONTAL_JUSTIFY = 'justify';
const HORIZONTAL_FILL = 'fill';
const HORIZONTAL_DISTRIBUTED = 'distributed'; // Excel2007 only
private const HORIZONTAL_CENTER_CONTINUOUS_LC = 'centercontinuous';
// Mapping for horizontal alignment
const HORIZONTAL_ALIGNMENT_FOR_XLSX = [
self::HORIZONTAL_LEFT => self::HORIZONTAL_LEFT,
self::HORIZONTAL_RIGHT => self::HORIZONTAL_RIGHT,
self::HORIZONTAL_CENTER => self::HORIZONTAL_CENTER,
self::HORIZONTAL_CENTER_CONTINUOUS => self::HORIZONTAL_CENTER_CONTINUOUS,
self::HORIZONTAL_JUSTIFY => self::HORIZONTAL_JUSTIFY,
self::HORIZONTAL_FILL => self::HORIZONTAL_FILL,
self::HORIZONTAL_DISTRIBUTED => self::HORIZONTAL_DISTRIBUTED,
];
// Mapping for horizontal alignment CSS
const HORIZONTAL_ALIGNMENT_FOR_HTML = [
self::HORIZONTAL_LEFT => self::HORIZONTAL_LEFT,
self::HORIZONTAL_RIGHT => self::HORIZONTAL_RIGHT,
self::HORIZONTAL_CENTER => self::HORIZONTAL_CENTER,
self::HORIZONTAL_CENTER_CONTINUOUS => self::HORIZONTAL_CENTER,
self::HORIZONTAL_JUSTIFY => self::HORIZONTAL_JUSTIFY,
//self::HORIZONTAL_FILL => self::HORIZONTAL_FILL, // no reasonable equivalent for fill
self::HORIZONTAL_DISTRIBUTED => self::HORIZONTAL_JUSTIFY,
];
// Vertical alignment styles
const VERTICAL_BOTTOM = 'bottom';
const VERTICAL_TOP = 'top';
const VERTICAL_CENTER = 'center';
const VERTICAL_JUSTIFY = 'justify';
const VERTICAL_DISTRIBUTED = 'distributed'; // Excel2007 only
// Vertical alignment CSS
private const VERTICAL_BASELINE = 'baseline';
private const VERTICAL_MIDDLE = 'middle';
private const VERTICAL_SUB = 'sub';
private const VERTICAL_SUPER = 'super';
private const VERTICAL_TEXT_BOTTOM = 'text-bottom';
private const VERTICAL_TEXT_TOP = 'text-top';
// Mapping for vertical alignment
const VERTICAL_ALIGNMENT_FOR_XLSX = [
self::VERTICAL_BOTTOM => self::VERTICAL_BOTTOM,
self::VERTICAL_TOP => self::VERTICAL_TOP,
self::VERTICAL_CENTER => self::VERTICAL_CENTER,
self::VERTICAL_JUSTIFY => self::VERTICAL_JUSTIFY,
self::VERTICAL_DISTRIBUTED => self::VERTICAL_DISTRIBUTED,
// css settings that aren't in sync with Excel
self::VERTICAL_BASELINE => self::VERTICAL_BOTTOM,
self::VERTICAL_MIDDLE => self::VERTICAL_CENTER,
self::VERTICAL_SUB => self::VERTICAL_BOTTOM,
self::VERTICAL_SUPER => self::VERTICAL_TOP,
self::VERTICAL_TEXT_BOTTOM => self::VERTICAL_BOTTOM,
self::VERTICAL_TEXT_TOP => self::VERTICAL_TOP,
];
// Mapping for vertical alignment for Html
const VERTICAL_ALIGNMENT_FOR_HTML = [
self::VERTICAL_BOTTOM => self::VERTICAL_BOTTOM,
self::VERTICAL_TOP => self::VERTICAL_TOP,
self::VERTICAL_CENTER => self::VERTICAL_MIDDLE,
self::VERTICAL_JUSTIFY => self::VERTICAL_MIDDLE,
self::VERTICAL_DISTRIBUTED => self::VERTICAL_MIDDLE,
// css settings that aren't in sync with Excel
self::VERTICAL_BASELINE => self::VERTICAL_BASELINE,
self::VERTICAL_MIDDLE => self::VERTICAL_MIDDLE,
self::VERTICAL_SUB => self::VERTICAL_SUB,
self::VERTICAL_SUPER => self::VERTICAL_SUPER,
self::VERTICAL_TEXT_BOTTOM => self::VERTICAL_TEXT_BOTTOM,
self::VERTICAL_TEXT_TOP => self::VERTICAL_TEXT_TOP,
];
// Read order
const READORDER_CONTEXT = 0;
const READORDER_LTR = 1;
const READORDER_RTL = 2;
// Special value for Text Rotation
const TEXTROTATION_STACK_EXCEL = 255;
const TEXTROTATION_STACK_PHPSPREADSHEET = -165; // 90 - 255
public const INDENT_UNITS_TO_PIXELS = 9;
/**
* Horizontal alignment.
*/
protected ?string $horizontal = self::HORIZONTAL_GENERAL;
/**
* Justify Last Line alignment.
*/
protected ?bool $justifyLastLine = null;
/**
* Vertical alignment.
*/
protected ?string $vertical = self::VERTICAL_BOTTOM;
/**
* Text rotation.
*/
protected ?int $textRotation = 0;
/**
* Wrap text.
*/
protected bool $wrapText = false;
/**
* Shrink to fit.
*/
protected bool $shrinkToFit = false;
/**
* Indent - only possible with horizontal alignment left and right.
*/
protected int $indent = 0;
/**
* Read order.
*/
protected int $readOrder = 0;
/**
* Create a new Alignment.
*
* @param bool $isSupervisor Flag indicating if this is a supervisor or not
* Leave this value at default unless you understand exactly what
* its ramifications are
* @param bool $isConditional Flag indicating if this is a conditional style or not
* Leave this value at default unless you understand exactly what
* its ramifications are
*/
public function __construct(bool $isSupervisor = false, bool $isConditional = false)
{
// Supervisor?
parent::__construct($isSupervisor);
if ($isConditional) {
$this->horizontal = null;
$this->vertical = null;
$this->textRotation = null;
}
}
/**
* Get the shared style component for the currently active cell in currently active sheet.
* Only used for style supervisor.
*/
public function getSharedComponent(): self
{
/** @var Style $parent */
$parent = $this->parent;
return $parent->getSharedComponent()->getAlignment();
}
/**
* Build style array from subcomponents.
*
* @param mixed[] $array
*
* @return array{alignment: mixed[]}
*/
public function getStyleArray(array $array): array
{
return ['alignment' => $array];
}
/**
* Apply styles from array.
*
* <code>
* $spreadsheet->getActiveSheet()->getStyle('B2')->getAlignment()->applyFromArray(
* [
* 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
* 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
* 'textRotation' => 0,
* 'wrapText' => TRUE
* ]
* );
* </code>
*
* @param mixed[] $styleArray Array containing style information
*
* @return $this
*/
public function applyFromArray(array $styleArray): static
{
if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells())
->applyFromArray($this->getStyleArray($styleArray));
} else {
/** @var array{horizontal?: string, vertical?: string, justifyLastLine?: bool, textRotation?: int, wrapText?: bool, shrinkToFit?: bool, readOrder?: int, indent?: int} $styleArray */
if (isset($styleArray['horizontal'])) {
$this->setHorizontal($styleArray['horizontal']);
}
if (isset($styleArray['justifyLastLine'])) {
$this->setJustifyLastLine($styleArray['justifyLastLine']);
}
if (isset($styleArray['vertical'])) {
$this->setVertical($styleArray['vertical']);
}
if (isset($styleArray['textRotation'])) {
$this->setTextRotation($styleArray['textRotation']);
}
if (isset($styleArray['wrapText'])) {
$this->setWrapText($styleArray['wrapText']);
}
if (isset($styleArray['shrinkToFit'])) {
$this->setShrinkToFit($styleArray['shrinkToFit']);
}
if (isset($styleArray['indent'])) {
$this->setIndent($styleArray['indent']);
}
if (isset($styleArray['readOrder'])) {
$this->setReadOrder($styleArray['readOrder']);
}
}
return $this;
}
/**
* Get Horizontal.
*/
public function getHorizontal(): null|string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getHorizontal();
}
return $this->horizontal;
}
/**
* Set Horizontal.
*
* @param string $horizontalAlignment see self::HORIZONTAL_*
*
* @return $this
*/
public function setHorizontal(string $horizontalAlignment): static
{
$horizontalAlignment = strtolower($horizontalAlignment);
if ($horizontalAlignment === self::HORIZONTAL_CENTER_CONTINUOUS_LC) {
$horizontalAlignment = self::HORIZONTAL_CENTER_CONTINUOUS;
}
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['horizontal' => $horizontalAlignment]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->horizontal = $horizontalAlignment;
}
return $this;
}
/**
* Get Justify Last Line.
*/
public function getJustifyLastLine(): ?bool
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getJustifyLastLine();
}
return $this->justifyLastLine;
}
/**
* Set Justify Last Line.
*
* @return $this
*/
public function setJustifyLastLine(bool $justifyLastLine): static
{
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['justifyLastLine' => $justifyLastLine]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->justifyLastLine = $justifyLastLine;
}
return $this;
}
/**
* Get Vertical.
*/
public function getVertical(): null|string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getVertical();
}
return $this->vertical;
}
/**
* Set Vertical.
*
* @param string $verticalAlignment see self::VERTICAL_*
*
* @return $this
*/
public function setVertical(string $verticalAlignment): static
{
$verticalAlignment = strtolower($verticalAlignment);
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['vertical' => $verticalAlignment]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->vertical = $verticalAlignment;
}
return $this;
}
/**
* Get TextRotation.
*/
public function getTextRotation(): null|int
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getTextRotation();
}
return $this->textRotation;
}
/**
* Set TextRotation.
*
* @return $this
*/
public function setTextRotation(int $angleInDegrees): static
{
// Excel2007 value 255 => PhpSpreadsheet value -165
if ($angleInDegrees == self::TEXTROTATION_STACK_EXCEL) {
$angleInDegrees = self::TEXTROTATION_STACK_PHPSPREADSHEET;
}
// Set rotation
if (($angleInDegrees >= -90 && $angleInDegrees <= 90) || $angleInDegrees == self::TEXTROTATION_STACK_PHPSPREADSHEET) {
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['textRotation' => $angleInDegrees]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->textRotation = $angleInDegrees;
}
} else {
throw new PhpSpreadsheetException('Text rotation should be a value between -90 and 90.');
}
return $this;
}
/**
* Get Wrap Text.
*/
public function getWrapText(): bool
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getWrapText();
}
return $this->wrapText;
}
/**
* Set Wrap Text.
*
* @return $this
*/
public function setWrapText(bool $wrapped): static
{
if ($wrapped == '') {
$wrapped = false;
}
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['wrapText' => $wrapped]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->wrapText = $wrapped;
}
return $this;
}
/**
* Get Shrink to fit.
*/
public function getShrinkToFit(): bool
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getShrinkToFit();
}
return $this->shrinkToFit;
}
/**
* Set Shrink to fit.
*
* @return $this
*/
public function setShrinkToFit(bool $shrink): static
{
if ($shrink == '') {
$shrink = false;
}
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['shrinkToFit' => $shrink]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->shrinkToFit = $shrink;
}
return $this;
}
/**
* Get indent.
*/
public function getIndent(): int
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getIndent();
}
return $this->indent;
}
/**
* Set indent.
*
* @return $this
*/
public function setIndent(int $indent): static
{
if ($indent > 0) {
if (
$this->getHorizontal() != self::HORIZONTAL_GENERAL
&& $this->getHorizontal() != self::HORIZONTAL_LEFT
&& $this->getHorizontal() != self::HORIZONTAL_RIGHT
&& $this->getHorizontal() != self::HORIZONTAL_DISTRIBUTED
) {
$indent = 0; // indent not supported
}
}
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['indent' => $indent]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->indent = $indent;
}
return $this;
}
/**
* Get read order.
*/
public function getReadOrder(): int
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getReadOrder();
}
return $this->readOrder;
}
/**
* Set read order.
*
* @return $this
*/
public function setReadOrder(int $readOrder): static
{
if ($readOrder < 0 || $readOrder > 2) {
$readOrder = 0;
}
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['readOrder' => $readOrder]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->readOrder = $readOrder;
}
return $this;
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getHashCode();
}
return md5(
$this->horizontal
. (($this->justifyLastLine === null) ? 'null' : ($this->justifyLastLine ? 't' : 'f'))
. $this->vertical
. $this->textRotation
. ($this->wrapText ? 't' : 'f')
. ($this->shrinkToFit ? 't' : 'f')
. $this->indent
. $this->readOrder
. __CLASS__
);
}
/** @return mixed[] */
protected function exportArray1(): array
{
$exportedArray = [];
$this->exportArray2($exportedArray, 'horizontal', $this->getHorizontal());
$this->exportArray2($exportedArray, 'justifyLastLine', $this->getJustifyLastLine());
$this->exportArray2($exportedArray, 'indent', $this->getIndent());
$this->exportArray2($exportedArray, 'readOrder', $this->getReadOrder());
$this->exportArray2($exportedArray, 'shrinkToFit', $this->getShrinkToFit());
$this->exportArray2($exportedArray, 'textRotation', $this->getTextRotation());
$this->exportArray2($exportedArray, 'vertical', $this->getVertical());
$this->exportArray2($exportedArray, 'wrapText', $this->getWrapText());
return $exportedArray;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/NumberFormat.php | src/PhpSpreadsheet/Style/NumberFormat.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
class NumberFormat extends Supervisor
{
// Pre-defined formats
const FORMAT_GENERAL = 'General';
const FORMAT_TEXT = '@';
const FORMAT_NUMBER = '0';
const FORMAT_NUMBER_0 = '0.0';
const FORMAT_NUMBER_00 = '0.00';
const FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00';
const FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-';
const FORMAT_PERCENTAGE = '0%';
const FORMAT_PERCENTAGE_0 = '0.0%';
const FORMAT_PERCENTAGE_00 = '0.00%';
const FORMAT_DATE_YYYYMMDD = 'yyyy-mm-dd';
const FORMAT_DATE_DDMMYYYY = 'dd/mm/yyyy';
const FORMAT_DATE_DMYSLASH = 'd/m/yy';
const FORMAT_DATE_DMYMINUS = 'd-m-yy';
const FORMAT_DATE_DMMINUS = 'd-m';
const FORMAT_DATE_MYMINUS = 'm-yy';
const FORMAT_DATE_XLSX14 = 'mm-dd-yy';
const FORMAT_DATE_XLSX14_ACTUAL = 'm/d/yyyy';
const FORMAT_DATE_XLSX15 = 'd-mmm-yy';
const FORMAT_DATE_XLSX16 = 'd-mmm';
const FORMAT_DATE_XLSX17 = 'mmm-yy';
const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm';
const FORMAT_DATE_XLSX22_ACTUAL = 'm/d/yyyy h:mm';
const FORMAT_DATE_DATETIME = 'd/m/yy h:mm';
const FORMAT_DATE_TIME1 = 'h:mm AM/PM';
const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM';
const FORMAT_DATE_TIME3 = 'h:mm';
const FORMAT_DATE_TIME4 = 'h:mm:ss';
const FORMAT_DATE_TIME5 = 'mm:ss';
const FORMAT_DATE_TIME6 = 'h:mm:ss';
const FORMAT_DATE_TIME7 = 'i:s.S';
const FORMAT_DATE_TIME8 = 'h:mm:ss;@';
const FORMAT_DATE_YYYYMMDDSLASH = 'yyyy/mm/dd;@';
const FORMAT_DATE_LONG_DATE = 'dddd, mmmm d, yyyy';
const DATE_TIME_OR_DATETIME_ARRAY = [
self::FORMAT_DATE_YYYYMMDD,
self::FORMAT_DATE_DDMMYYYY,
self::FORMAT_DATE_DMYSLASH,
self::FORMAT_DATE_DMYMINUS,
self::FORMAT_DATE_DMMINUS,
self::FORMAT_DATE_MYMINUS,
self::FORMAT_DATE_XLSX14,
self::FORMAT_DATE_XLSX14_ACTUAL,
self::FORMAT_DATE_XLSX15,
self::FORMAT_DATE_XLSX16,
self::FORMAT_DATE_XLSX17,
self::FORMAT_DATE_XLSX22,
self::FORMAT_DATE_XLSX22_ACTUAL,
self::FORMAT_DATE_DATETIME,
self::FORMAT_DATE_TIME1,
self::FORMAT_DATE_TIME2,
self::FORMAT_DATE_TIME3,
self::FORMAT_DATE_TIME4,
self::FORMAT_DATE_TIME5,
self::FORMAT_DATE_TIME6,
self::FORMAT_DATE_TIME7,
self::FORMAT_DATE_TIME8,
self::FORMAT_DATE_YYYYMMDDSLASH,
self::FORMAT_DATE_LONG_DATE,
];
const TIME_OR_DATETIME_ARRAY = [
self::FORMAT_DATE_XLSX22,
self::FORMAT_DATE_DATETIME,
self::FORMAT_DATE_TIME1,
self::FORMAT_DATE_TIME2,
self::FORMAT_DATE_TIME3,
self::FORMAT_DATE_TIME4,
self::FORMAT_DATE_TIME5,
self::FORMAT_DATE_TIME6,
self::FORMAT_DATE_TIME7,
self::FORMAT_DATE_TIME8,
];
const FORMAT_CURRENCY_USD_INTEGER = '$#,##0_-';
const FORMAT_CURRENCY_USD = '$#,##0.00_-';
const FORMAT_CURRENCY_EUR_INTEGER = '#,##0_-[$€]';
const FORMAT_CURRENCY_EUR = '#,##0.00_-[$€]';
const FORMAT_ACCOUNTING_USD = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)';
const FORMAT_ACCOUNTING_EUR = '_("€"* #,##0.00_);_("€"* \(#,##0.00\);_("€"* "-"??_);_(@_)';
const SHORT_DATE_INDEX = 14;
const DATE_TIME_INDEX = 22;
const FORMAT_SYSDATE_X = '[$-x-sysdate]';
const FORMAT_SYSDATE_F800 = '[$-F800]';
const FORMAT_SYSTIME_X = '[$-x-systime]';
const FORMAT_SYSTIME_F400 = '[$-F400]';
protected static string $shortDateFormat = self::FORMAT_DATE_XLSX14_ACTUAL;
protected static string $longDateFormat = self::FORMAT_DATE_LONG_DATE;
protected static string $dateTimeFormat = self::FORMAT_DATE_XLSX22_ACTUAL;
protected static string $timeFormat = self::FORMAT_DATE_TIME2;
/**
* Excel built-in number formats.
*
* @var string[]
*/
protected static array $builtInFormats;
/**
* Excel built-in number formats (flipped, for faster lookups).
*
* @var int[]
*/
protected static array $flippedBuiltInFormats;
/**
* Format Code.
*/
protected ?string $formatCode = self::FORMAT_GENERAL;
/**
* Built-in format Code.
*
* @var false|int
*/
protected $builtInFormatCode = 0;
/**
* Create a new NumberFormat.
*
* @param bool $isSupervisor Flag indicating if this is a supervisor or not
* Leave this value at default unless you understand exactly what
* its ramifications are
* @param bool $isConditional Flag indicating if this is a conditional style or not
* Leave this value at default unless you understand exactly what
* its ramifications are
*/
public function __construct(bool $isSupervisor = false, bool $isConditional = false)
{
// Supervisor?
parent::__construct($isSupervisor);
if ($isConditional) {
$this->formatCode = null;
$this->builtInFormatCode = false;
}
}
/**
* Get the shared style component for the currently active cell in currently active sheet.
* Only used for style supervisor.
*/
public function getSharedComponent(): self
{
/** @var Style $parent */
$parent = $this->parent;
return $parent->getSharedComponent()->getNumberFormat();
}
/**
* Build style array from subcomponents.
*
* @param mixed[] $array
*
* @return array{numberFormat: mixed[]}
*/
public function getStyleArray(array $array): array
{
return ['numberFormat' => $array];
}
/**
* Apply styles from array.
*
* <code>
* $spreadsheet->getActiveSheet()->getStyle('B2')->getNumberFormat()->applyFromArray(
* [
* 'formatCode' => NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE
* ]
* );
* </code>
*
* @param string[] $styleArray Array containing style information
*
* @return $this
*/
public function applyFromArray(array $styleArray): static
{
if ($this->isSupervisor) {
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($styleArray));
} else {
if (isset($styleArray['formatCode'])) {
$this->setFormatCode($styleArray['formatCode']);
}
}
return $this;
}
/**
* Get Format Code.
*/
public function getFormatCode(bool $extended = false): ?string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getFormatCode($extended);
}
$builtin = $this->getBuiltInFormatCode();
if (is_int($builtin)) {
if ($extended) {
if ($builtin === self::SHORT_DATE_INDEX) {
return self::$shortDateFormat;
}
if ($builtin === self::DATE_TIME_INDEX) {
return self::$dateTimeFormat;
}
}
return self::builtInFormatCode($builtin);
}
return $extended ? self::convertSystemFormats($this->formatCode) : $this->formatCode;
}
public static function convertSystemFormats(?string $formatCode): ?string
{
if (is_string($formatCode)) {
if (stripos($formatCode, self::FORMAT_SYSDATE_F800) !== false || stripos($formatCode, self::FORMAT_SYSDATE_X) !== false) {
return self::$longDateFormat;
}
if (stripos($formatCode, self::FORMAT_SYSTIME_F400) !== false || stripos($formatCode, self::FORMAT_SYSTIME_X) !== false) {
return self::$timeFormat;
}
}
return $formatCode;
}
/**
* Set Format Code.
*
* @param string $formatCode see self::FORMAT_*
*
* @return $this
*/
public function setFormatCode(string $formatCode): static
{
if ($formatCode == '') {
$formatCode = self::FORMAT_GENERAL;
}
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['formatCode' => $formatCode]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->formatCode = $formatCode;
$this->builtInFormatCode = self::builtInFormatCodeIndex($formatCode);
}
return $this;
}
/**
* Get Built-In Format Code.
*
* @return false|int
*/
public function getBuiltInFormatCode()
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getBuiltInFormatCode();
}
return $this->builtInFormatCode;
}
/**
* Set Built-In Format Code.
*
* @param int $formatCodeIndex Id of the built-in format code to use
*
* @return $this
*/
public function setBuiltInFormatCode(int $formatCodeIndex): static
{
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['formatCode' => self::builtInFormatCode($formatCodeIndex)]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->builtInFormatCode = $formatCodeIndex;
$this->formatCode = self::builtInFormatCode($formatCodeIndex);
}
return $this;
}
/**
* Fill built-in format codes.
*/
private static function fillBuiltInFormatCodes(): void
{
// [MS-OI29500: Microsoft Office Implementation Information for ISO/IEC-29500 Standard Compliance]
// 18.8.30. numFmt (Number Format)
//
// The ECMA standard defines built-in format IDs
// 14: "mm-dd-yy"
// 22: "m/d/yy h:mm"
// 37: "#,##0 ;(#,##0)"
// 38: "#,##0 ;[Red](#,##0)"
// 39: "#,##0.00;(#,##0.00)"
// 40: "#,##0.00;[Red](#,##0.00)"
// 47: "mmss.0"
// KOR fmt 55: "yyyy-mm-dd"
// Excel defines built-in format IDs
// 14: "m/d/yyyy"
// 22: "m/d/yyyy h:mm"
// 37: "#,##0_);(#,##0)"
// 38: "#,##0_);[Red](#,##0)"
// 39: "#,##0.00_);(#,##0.00)"
// 40: "#,##0.00_);[Red](#,##0.00)"
// 47: "mm:ss.0"
// KOR fmt 55: "yyyy/mm/dd"
// Built-in format codes
if (empty(self::$builtInFormats)) {
self::$builtInFormats = [];
// General
self::$builtInFormats[0] = self::FORMAT_GENERAL;
self::$builtInFormats[1] = '0';
self::$builtInFormats[2] = '0.00';
self::$builtInFormats[3] = '#,##0';
self::$builtInFormats[4] = '#,##0.00';
self::$builtInFormats[9] = '0%';
self::$builtInFormats[10] = '0.00%';
self::$builtInFormats[11] = '0.00E+00';
self::$builtInFormats[12] = '# ?/?';
self::$builtInFormats[13] = '# ??/??';
self::$builtInFormats[14] = self::FORMAT_DATE_XLSX14_ACTUAL; // Despite ECMA 'mm-dd-yy';
self::$builtInFormats[15] = self::FORMAT_DATE_XLSX15;
self::$builtInFormats[16] = 'd-mmm';
self::$builtInFormats[17] = 'mmm-yy';
self::$builtInFormats[18] = 'h:mm AM/PM';
self::$builtInFormats[19] = 'h:mm:ss AM/PM';
self::$builtInFormats[20] = 'h:mm';
self::$builtInFormats[21] = 'h:mm:ss';
self::$builtInFormats[22] = self::FORMAT_DATE_XLSX22_ACTUAL; // Despite ECMA 'm/d/yy h:mm';
self::$builtInFormats[37] = '#,##0_);(#,##0)'; // Despite ECMA '#,##0 ;(#,##0)';
self::$builtInFormats[38] = '#,##0_);[Red](#,##0)'; // Despite ECMA '#,##0 ;[Red](#,##0)';
self::$builtInFormats[39] = '#,##0.00_);(#,##0.00)'; // Despite ECMA '#,##0.00;(#,##0.00)';
self::$builtInFormats[40] = '#,##0.00_);[Red](#,##0.00)'; // Despite ECMA '#,##0.00;[Red](#,##0.00)';
self::$builtInFormats[44] = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)';
self::$builtInFormats[45] = 'mm:ss';
self::$builtInFormats[46] = '[h]:mm:ss';
self::$builtInFormats[47] = 'mm:ss.0'; // Despite ECMA 'mmss.0';
self::$builtInFormats[48] = '##0.0E+0';
self::$builtInFormats[49] = '@';
// CHT
self::$builtInFormats[27] = '[$-404]e/m/d';
self::$builtInFormats[30] = 'm/d/yy';
self::$builtInFormats[36] = '[$-404]e/m/d';
self::$builtInFormats[50] = '[$-404]e/m/d';
self::$builtInFormats[57] = '[$-404]e/m/d';
// THA
self::$builtInFormats[59] = 't0';
self::$builtInFormats[60] = 't0.00';
self::$builtInFormats[61] = 't#,##0';
self::$builtInFormats[62] = 't#,##0.00';
self::$builtInFormats[67] = 't0%';
self::$builtInFormats[68] = 't0.00%';
self::$builtInFormats[69] = 't# ?/?';
self::$builtInFormats[70] = 't# ??/??';
// JPN
self::$builtInFormats[28] = '[$-411]ggge"年"m"月"d"日"';
self::$builtInFormats[29] = '[$-411]ggge"年"m"月"d"日"';
self::$builtInFormats[31] = 'yyyy"年"m"月"d"日"';
self::$builtInFormats[32] = 'h"時"mm"分"';
self::$builtInFormats[33] = 'h"時"mm"分"ss"秒"';
self::$builtInFormats[34] = 'yyyy"年"m"月"';
self::$builtInFormats[35] = 'm"月"d"日"';
self::$builtInFormats[51] = '[$-411]ggge"年"m"月"d"日"';
self::$builtInFormats[52] = 'yyyy"年"m"月"';
self::$builtInFormats[53] = 'm"月"d"日"';
self::$builtInFormats[54] = '[$-411]ggge"年"m"月"d"日"';
self::$builtInFormats[55] = 'yyyy"年"m"月"';
self::$builtInFormats[56] = 'm"月"d"日"';
self::$builtInFormats[58] = '[$-411]ggge"年"m"月"d"日"';
// Flip array (for faster lookups)
self::$flippedBuiltInFormats = array_flip(self::$builtInFormats);
}
}
/**
* Get built-in format code.
*/
public static function builtInFormatCode(int $index): string
{
// Clean parameter
$index = (int) $index;
// Ensure built-in format codes are available
self::fillBuiltInFormatCodes();
// Lookup format code
if (isset(self::$builtInFormats[$index])) {
return self::$builtInFormats[$index];
}
return '';
}
/**
* Get built-in format code index.
*
* @return false|int
*/
public static function builtInFormatCodeIndex(string $formatCodeIndex)
{
// Ensure built-in format codes are available
self::fillBuiltInFormatCodes();
// Lookup format code
if (array_key_exists($formatCodeIndex, self::$flippedBuiltInFormats)) {
return self::$flippedBuiltInFormats[$formatCodeIndex];
}
return false;
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getHashCode();
}
return md5(
$this->formatCode
. $this->builtInFormatCode
. __CLASS__
);
}
/**
* Convert a value in a pre-defined format to a PHP string.
*
* @param null|bool|float|int|RichText|string $value Value to format
* @param string $format Format code: see = self::FORMAT_* for predefined values;
* or can be any valid MS Excel custom format string
* @param ?mixed[] $callBack Callback function for additional formatting of string
* @param bool $lessFloatPrecision If true, unstyled floats will be converted to a more human-friendly but less computationally accurate value
*
* @return string Formatted string
*/
public static function toFormattedString(mixed $value, string $format, ?array $callBack = null, bool $lessFloatPrecision = false): string
{
return NumberFormat\Formatter::toFormattedString($value, $format, $callBack, $lessFloatPrecision);
}
/** @return mixed[] */
protected function exportArray1(): array
{
$exportedArray = [];
$this->exportArray2($exportedArray, 'formatCode', $this->getFormatCode());
return $exportedArray;
}
public static function getShortDateFormat(): string
{
return self::$shortDateFormat;
}
public static function setShortDateFormat(string $shortDateFormat): void
{
self::$shortDateFormat = $shortDateFormat;
}
public static function getLongDateFormat(): string
{
return self::$longDateFormat;
}
public static function setLongDateFormat(string $longDateFormat): void
{
self::$longDateFormat = $longDateFormat;
}
public static function getDateTimeFormat(): string
{
return self::$dateTimeFormat;
}
public static function setDateTimeFormat(string $dateTimeFormat): void
{
self::$dateTimeFormat = $dateTimeFormat;
}
public static function getTimeFormat(): string
{
return self::$timeFormat;
}
public static function setTimeFormat(string $timeFormat): void
{
self::$timeFormat = $timeFormat;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/Color.php | src/PhpSpreadsheet/Style/Color.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style;
use PhpOffice\PhpSpreadsheet\Theme;
class Color extends Supervisor
{
const NAMED_COLORS = [
'Black',
'White',
'Red',
'Green',
'Blue',
'Yellow',
'Magenta',
'Cyan',
];
// Colors
const COLOR_BLACK = 'FF000000';
const COLOR_WHITE = 'FFFFFFFF';
const COLOR_RED = 'FFFF0000';
const COLOR_DARKRED = 'FF800000';
const COLOR_BLUE = 'FF0000FF';
const COLOR_DARKBLUE = 'FF000080';
const COLOR_GREEN = 'FF00FF00';
const COLOR_DARKGREEN = 'FF008000';
const COLOR_YELLOW = 'FFFFFF00';
const COLOR_DARKYELLOW = 'FF808000';
const COLOR_MAGENTA = 'FFFF00FF';
const COLOR_CYAN = 'FF00FFFF';
const NAMED_COLOR_TRANSLATIONS = [
'Black' => self::COLOR_BLACK,
'White' => self::COLOR_WHITE,
'Red' => self::COLOR_RED,
'Green' => self::COLOR_GREEN,
'Blue' => self::COLOR_BLUE,
'Yellow' => self::COLOR_YELLOW,
'Magenta' => self::COLOR_MAGENTA,
'Cyan' => self::COLOR_CYAN,
];
const VALIDATE_ARGB_SIZE = 8;
const VALIDATE_RGB_SIZE = 6;
const VALIDATE_COLOR_6 = '/^[A-F0-9]{6}$/i';
const VALIDATE_COLOR_8 = '/^[A-F0-9]{8}$/i';
private const INDEXED_COLORS = [
1 => 'FF000000', // System Colour #1 - Black
2 => 'FFFFFFFF', // System Colour #2 - White
3 => 'FFFF0000', // System Colour #3 - Red
4 => 'FF00FF00', // System Colour #4 - Green
5 => 'FF0000FF', // System Colour #5 - Blue
6 => 'FFFFFF00', // System Colour #6 - Yellow
7 => 'FFFF00FF', // System Colour #7- Magenta
8 => 'FF00FFFF', // System Colour #8- Cyan
9 => 'FF800000', // Standard Colour #9
10 => 'FF008000', // Standard Colour #10
11 => 'FF000080', // Standard Colour #11
12 => 'FF808000', // Standard Colour #12
13 => 'FF800080', // Standard Colour #13
14 => 'FF008080', // Standard Colour #14
15 => 'FFC0C0C0', // Standard Colour #15
16 => 'FF808080', // Standard Colour #16
17 => 'FF9999FF', // Chart Fill Colour #17
18 => 'FF993366', // Chart Fill Colour #18
19 => 'FFFFFFCC', // Chart Fill Colour #19
20 => 'FFCCFFFF', // Chart Fill Colour #20
21 => 'FF660066', // Chart Fill Colour #21
22 => 'FFFF8080', // Chart Fill Colour #22
23 => 'FF0066CC', // Chart Fill Colour #23
24 => 'FFCCCCFF', // Chart Fill Colour #24
25 => 'FF000080', // Chart Line Colour #25
26 => 'FFFF00FF', // Chart Line Colour #26
27 => 'FFFFFF00', // Chart Line Colour #27
28 => 'FF00FFFF', // Chart Line Colour #28
29 => 'FF800080', // Chart Line Colour #29
30 => 'FF800000', // Chart Line Colour #30
31 => 'FF008080', // Chart Line Colour #31
32 => 'FF0000FF', // Chart Line Colour #32
33 => 'FF00CCFF', // Standard Colour #33
34 => 'FFCCFFFF', // Standard Colour #34
35 => 'FFCCFFCC', // Standard Colour #35
36 => 'FFFFFF99', // Standard Colour #36
37 => 'FF99CCFF', // Standard Colour #37
38 => 'FFFF99CC', // Standard Colour #38
39 => 'FFCC99FF', // Standard Colour #39
40 => 'FFFFCC99', // Standard Colour #40
41 => 'FF3366FF', // Standard Colour #41
42 => 'FF33CCCC', // Standard Colour #42
43 => 'FF99CC00', // Standard Colour #43
44 => 'FFFFCC00', // Standard Colour #44
45 => 'FFFF9900', // Standard Colour #45
46 => 'FFFF6600', // Standard Colour #46
47 => 'FF666699', // Standard Colour #47
48 => 'FF969696', // Standard Colour #48
49 => 'FF003366', // Standard Colour #49
50 => 'FF339966', // Standard Colour #50
51 => 'FF003300', // Standard Colour #51
52 => 'FF333300', // Standard Colour #52
53 => 'FF993300', // Standard Colour #53
54 => 'FF993366', // Standard Colour #54
55 => 'FF333399', // Standard Colour #55
56 => 'FF333333', // Standard Colour #56
];
/**
* ARGB - Alpha RGB.
*/
protected ?string $argb = null;
private bool $hasChanged = false;
private int $theme = -1;
/**
* Create a new Color.
*
* @param string $colorValue ARGB value for the colour, or named colour
* @param bool $isSupervisor Flag indicating if this is a supervisor or not
* Leave this value at default unless you understand exactly what
* its ramifications are
* @param bool $isConditional Flag indicating if this is a conditional style or not
* Leave this value at default unless you understand exactly what
* its ramifications are
*/
public function __construct(string $colorValue = self::COLOR_BLACK, bool $isSupervisor = false, bool $isConditional = false)
{
// Supervisor?
parent::__construct($isSupervisor);
// Initialise values
if (!$isConditional) {
$this->argb = $this->validateColor($colorValue) ?: self::COLOR_BLACK;
}
}
/**
* Get the shared style component for the currently active cell in currently active sheet.
* Only used for style supervisor.
*/
public function getSharedComponent(): self
{
/** @var Style $parent */
$parent = $this->parent;
/** @var Border|Fill $sharedComponent */
$sharedComponent = $parent->getSharedComponent();
if ($sharedComponent instanceof Fill) {
if ($this->parentPropertyName === 'endColor') {
return $sharedComponent->getEndColor();
}
return $sharedComponent->getStartColor();
}
return $sharedComponent->getColor();
}
/**
* Build style array from subcomponents.
*
* @param mixed[] $array
*
* @return mixed[]
*/
public function getStyleArray(array $array): array
{
/** @var Style $parent */
$parent = $this->parent;
return $parent->getStyleArray([$this->parentPropertyName => $array]);
}
/**
* Apply styles from array.
*
* <code>
* $spreadsheet->getActiveSheet()->getStyle('B2')->getFont()->getColor()->applyFromArray(['rgb' => '808080']);
* </code>
*
* @param array{rgb?: string, argb?: string, theme?: int} $styleArray Array containing style information
*
* @return $this
*/
public function applyFromArray(array $styleArray): static
{
if ($this->isSupervisor) {
$this->getActiveSheet()
->getStyle($this->getSelectedCells())
->applyFromArray(
$this->getStyleArray($styleArray)
);
} else {
if (isset($styleArray['rgb'])) {
$this->setRGB($styleArray['rgb']);
}
if (isset($styleArray['argb'])) {
$this->setARGB($styleArray['argb']);
}
if (isset($styleArray['theme'])) {
$this->setTheme($styleArray['theme']);
}
}
return $this;
}
private function validateColor(?string $colorValue): string
{
if ($colorValue === null || $colorValue === '') {
return self::COLOR_BLACK;
}
$named = ucfirst(strtolower($colorValue));
if (array_key_exists($named, self::NAMED_COLOR_TRANSLATIONS)) {
return self::NAMED_COLOR_TRANSLATIONS[$named];
}
if (preg_match(self::VALIDATE_COLOR_8, $colorValue) === 1) {
return $colorValue;
}
if (preg_match(self::VALIDATE_COLOR_6, $colorValue) === 1) {
return 'FF' . $colorValue;
}
return '';
}
/**
* Get ARGB.
*/
public function getARGB(): ?string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getARGB();
}
return $this->argb;
}
/**
* Set ARGB.
*
* @param ?string $colorValue ARGB value, or a named color
*
* @return $this
*/
public function setARGB(?string $colorValue = self::COLOR_BLACK, bool $nullStringOkay = false): static
{
$this->hasChanged = true;
$this->setTheme(-1);
if (!$nullStringOkay || $colorValue !== '') {
$colorValue = $this->validateColor($colorValue);
if ($colorValue === '') {
return $this;
}
}
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['argb' => $colorValue]);
$this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
} else {
$this->argb = $colorValue;
}
return $this;
}
/**
* Get RGB.
*/
public function getRGB(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getRGB();
}
return substr($this->argb ?? '', 2);
}
/**
* Set RGB.
*
* @param ?string $colorValue RGB value, or a named color
*
* @return $this
*/
public function setRGB(?string $colorValue = self::COLOR_BLACK): static
{
return $this->setARGB($colorValue);
}
/**
* Get a specified colour component of an RGB value.
*
* @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE
* @param int $offset Position within the RGB value to extract
* @param bool $hex Flag indicating whether the component should be returned as a hex or a
* decimal value
*
* @return int|string The extracted colour component
*/
private static function getColourComponent(string $rgbValue, int $offset, bool $hex = true): string|int
{
$colour = substr($rgbValue, $offset, 2) ?: '';
if (preg_match('/^[0-9a-f]{2}$/i', $colour) !== 1) {
$colour = '00';
}
return ($hex) ? $colour : (int) hexdec($colour);
}
/**
* Get the red colour component of an RGB value.
*
* @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE
* @param bool $hex Flag indicating whether the component should be returned as a hex or a
* decimal value
*
* @return int|string The red colour component
*/
public static function getRed(string $rgbValue, bool $hex = true)
{
return self::getColourComponent($rgbValue, strlen($rgbValue) - 6, $hex);
}
/**
* Get the green colour component of an RGB value.
*
* @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE
* @param bool $hex Flag indicating whether the component should be returned as a hex or a
* decimal value
*
* @return int|string The green colour component
*/
public static function getGreen(string $rgbValue, bool $hex = true)
{
return self::getColourComponent($rgbValue, strlen($rgbValue) - 4, $hex);
}
/**
* Get the blue colour component of an RGB value.
*
* @param string $rgbValue The colour as an RGB value (e.g. FF00CCCC or CCDDEE
* @param bool $hex Flag indicating whether the component should be returned as a hex or a
* decimal value
*
* @return int|string The blue colour component
*/
public static function getBlue(string $rgbValue, bool $hex = true)
{
return self::getColourComponent($rgbValue, strlen($rgbValue) - 2, $hex);
}
/**
* Adjust the brightness of a color.
*
* @param string $hexColourValue The colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE)
* @param float $adjustPercentage The percentage by which to adjust the colour as a float from -1 to 1
*
* @return string The adjusted colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE)
*/
public static function changeBrightness(string $hexColourValue, float $adjustPercentage): string
{
$rgba = (strlen($hexColourValue) === 8);
$adjustPercentage = max(-1.0, min(1.0, $adjustPercentage));
/** @var int $red */
$red = self::getRed($hexColourValue, false);
/** @var int $green */
$green = self::getGreen($hexColourValue, false);
/** @var int $blue */
$blue = self::getBlue($hexColourValue, false);
return (($rgba) ? 'FF' : '') . RgbTint::rgbAndTintToRgb($red, $green, $blue, $adjustPercentage);
}
/**
* Get indexed color.
*
* @param int $colorIndex Index entry point into the colour array
* @param bool $background Flag to indicate whether default background or foreground colour
* should be returned if the indexed colour doesn't exist
* @param null|string[] $palette
*/
public static function indexedColor(int $colorIndex, bool $background = false, ?array $palette = null): self
{
// Clean parameter
$colorIndex = (int) $colorIndex;
if (empty($palette)) {
if (isset(self::INDEXED_COLORS[$colorIndex])) {
return new self(self::INDEXED_COLORS[$colorIndex]);
}
} else {
if (isset($palette[$colorIndex])) {
return new self($palette[$colorIndex]);
}
}
return ($background) ? new self(self::COLOR_WHITE) : new self(self::COLOR_BLACK);
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getHashCode();
}
return md5(
$this->argb
. (string) $this->theme
. __CLASS__
);
}
/** @return mixed[] */
protected function exportArray1(): array
{
$exportedArray = [];
$this->exportArray2($exportedArray, 'argb', $this->getARGB());
$this->exportArray2($exportedArray, 'theme', $this->getTheme());
return $exportedArray;
}
public function getHasChanged(): bool
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->hasChanged;
}
return $this->hasChanged;
}
public function getTheme(): int
{
if ($this->isSupervisor) {
return $this->getSharedComponent()->getTheme();
}
return $this->theme;
}
public function setTheme(int $theme): self
{
$this->hasChanged = true;
if ($this->isSupervisor) {
$styleArray = $this->getStyleArray(['theme' => $theme]);
$this->getActiveSheet()
->getStyle($this->getSelectedCells())
->applyFromArray($styleArray);
} else {
$this->theme = $theme;
}
return $this;
}
public function setHyperlinkTheme(): self
{
$rgb = $this->getActiveSheet()
->getParent()
?->getTheme()
->getThemeColors();
if (is_array($rgb) && array_key_exists('hlink', $rgb)) {
$this->setRGB($rgb['hlink']);
}
return $this->setTheme(Theme::HYPERLINK_THEME);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/Conditional.php | src/PhpSpreadsheet/Style/Conditional.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style;
use PhpOffice\PhpSpreadsheet\IComparable;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalColorScale;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalDataBar;
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\ConditionalIconSet;
class Conditional implements IComparable
{
// Condition types
const CONDITION_NONE = 'none';
const CONDITION_BEGINSWITH = 'beginsWith';
const CONDITION_CELLIS = 'cellIs';
const CONDITION_COLORSCALE = 'colorScale';
const CONDITION_CONTAINSBLANKS = 'containsBlanks';
const CONDITION_CONTAINSERRORS = 'containsErrors';
const CONDITION_CONTAINSTEXT = 'containsText';
const CONDITION_DATABAR = 'dataBar';
const CONDITION_ENDSWITH = 'endsWith';
const CONDITION_EXPRESSION = 'expression';
const CONDITION_NOTCONTAINSBLANKS = 'notContainsBlanks';
const CONDITION_NOTCONTAINSERRORS = 'notContainsErrors';
const CONDITION_NOTCONTAINSTEXT = 'notContainsText';
const CONDITION_TIMEPERIOD = 'timePeriod';
const CONDITION_DUPLICATES = 'duplicateValues';
const CONDITION_UNIQUE = 'uniqueValues';
const CONDITION_ICONSET = 'iconSet';
private const CONDITION_TYPES = [
self::CONDITION_BEGINSWITH,
self::CONDITION_CELLIS,
self::CONDITION_COLORSCALE,
self::CONDITION_CONTAINSBLANKS,
self::CONDITION_CONTAINSERRORS,
self::CONDITION_CONTAINSTEXT,
self::CONDITION_DATABAR,
self::CONDITION_DUPLICATES,
self::CONDITION_ENDSWITH,
self::CONDITION_EXPRESSION,
self::CONDITION_NONE,
self::CONDITION_NOTCONTAINSBLANKS,
self::CONDITION_NOTCONTAINSERRORS,
self::CONDITION_NOTCONTAINSTEXT,
self::CONDITION_TIMEPERIOD,
self::CONDITION_UNIQUE,
self::CONDITION_ICONSET,
];
// Operator types
const OPERATOR_NONE = '';
const OPERATOR_BEGINSWITH = 'beginsWith';
const OPERATOR_ENDSWITH = 'endsWith';
const OPERATOR_EQUAL = 'equal';
const OPERATOR_GREATERTHAN = 'greaterThan';
const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual';
const OPERATOR_LESSTHAN = 'lessThan';
const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual';
const OPERATOR_NOTEQUAL = 'notEqual';
const OPERATOR_CONTAINSTEXT = 'containsText';
const OPERATOR_NOTCONTAINS = 'notContains';
const OPERATOR_BETWEEN = 'between';
const OPERATOR_NOTBETWEEN = 'notBetween';
const TIMEPERIOD_TODAY = 'today';
const TIMEPERIOD_YESTERDAY = 'yesterday';
const TIMEPERIOD_TOMORROW = 'tomorrow';
const TIMEPERIOD_LAST_7_DAYS = 'last7Days';
const TIMEPERIOD_LAST_WEEK = 'lastWeek';
const TIMEPERIOD_THIS_WEEK = 'thisWeek';
const TIMEPERIOD_NEXT_WEEK = 'nextWeek';
const TIMEPERIOD_LAST_MONTH = 'lastMonth';
const TIMEPERIOD_THIS_MONTH = 'thisMonth';
const TIMEPERIOD_NEXT_MONTH = 'nextMonth';
/**
* Condition type.
*/
private string $conditionType = self::CONDITION_NONE;
/**
* Operator type.
*/
private string $operatorType = self::OPERATOR_NONE;
/**
* Text.
*/
private string $text = '';
/**
* Stop on this condition, if it matches.
*/
private bool $stopIfTrue = false;
/**
* Condition.
*
* @var (bool|float|int|string)[]
*/
private array $condition = [];
private ?ConditionalDataBar $dataBar = null;
private ?ConditionalColorScale $colorScale = null;
private ?ConditionalIconSet $iconSet = null;
private Style $style;
private bool $noFormatSet = false;
private int $priority = 0;
/**
* Create a new Conditional.
*/
public function __construct()
{
// Initialise values
$this->style = new Style(false, true);
}
public function getPriority(): int
{
return $this->priority;
}
public function setPriority(int $priority): self
{
$this->priority = $priority;
return $this;
}
public function getNoFormatSet(): bool
{
return $this->noFormatSet;
}
public function setNoFormatSet(bool $noFormatSet): self
{
$this->noFormatSet = $noFormatSet;
return $this;
}
/**
* Get Condition type.
*/
public function getConditionType(): string
{
return $this->conditionType;
}
/**
* Set Condition type.
*
* @param string $type Condition type, see self::CONDITION_*
*
* @return $this
*/
public function setConditionType(string $type): static
{
$this->conditionType = $type;
return $this;
}
/**
* Get Operator type.
*/
public function getOperatorType(): string
{
return $this->operatorType;
}
/**
* Set Operator type.
*
* @param string $type Conditional operator type, see self::OPERATOR_*
*
* @return $this
*/
public function setOperatorType(string $type): static
{
$this->operatorType = $type;
return $this;
}
/**
* Get text.
*/
public function getText(): string
{
return $this->text;
}
/**
* Set text.
*
* @return $this
*/
public function setText(string $text): static
{
$this->text = $text;
return $this;
}
/**
* Get StopIfTrue.
*/
public function getStopIfTrue(): bool
{
return $this->stopIfTrue;
}
/**
* Set StopIfTrue.
*
* @return $this
*/
public function setStopIfTrue(bool $stopIfTrue): static
{
$this->stopIfTrue = $stopIfTrue;
return $this;
}
/**
* Get Conditions.
*
* @return (bool|float|int|string)[]
*/
public function getConditions(): array
{
return $this->condition;
}
/**
* Set Conditions.
*
* @param bool|(bool|float|int|string)[]|float|int|string $conditions Condition
*
* @return $this
*/
public function setConditions($conditions): static
{
if (!is_array($conditions)) {
$conditions = [$conditions];
}
$this->condition = $conditions;
return $this;
}
/**
* Add Condition.
*
* @param bool|float|int|string $condition Condition
*
* @return $this
*/
public function addCondition($condition): static
{
$this->condition[] = $condition;
return $this;
}
/**
* Get Style.
*/
public function getStyle(mixed $cellData = null): Style
{
if ($this->conditionType === self::CONDITION_COLORSCALE && $cellData !== null && $this->colorScale !== null && is_numeric($cellData)) {
$style = new Style(isConditional: true);
$style->getFill()->setFillType(Fill::FILL_SOLID);
$style->getFill()->getStartColor()->setARGB($this->colorScale->getColorForValue((float) $cellData));
return $style;
}
return $this->style;
}
/**
* Set Style.
*
* @return $this
*/
public function setStyle(Style $style): static
{
$this->style = $style;
return $this;
}
public function getDataBar(): ?ConditionalDataBar
{
return $this->dataBar;
}
public function setDataBar(ConditionalDataBar $dataBar): static
{
$this->dataBar = $dataBar;
return $this;
}
public function getColorScale(): ?ConditionalColorScale
{
return $this->colorScale;
}
public function setColorScale(ConditionalColorScale $colorScale): static
{
$this->colorScale = $colorScale;
return $this;
}
public function getIconSet(): ?ConditionalIconSet
{
return $this->iconSet;
}
public function setIconSet(ConditionalIconSet $iconSet): static
{
$this->iconSet = $iconSet;
return $this;
}
/**
* Get hash code.
*
* @return string Hash code
*/
public function getHashCode(): string
{
return md5(
$this->conditionType
. $this->operatorType
. implode(';', $this->condition)
. $this->style->getHashCode()
. __CLASS__
);
}
/**
* Implement PHP __clone to create a deep clone, not just a shallow copy.
*/
public function __clone()
{
$vars = get_object_vars($this);
foreach ($vars as $key => $value) {
if (is_object($value)) {
$this->$key = clone $value;
} else {
$this->$key = $value;
}
}
}
/**
* Verify if param is valid condition type.
*/
public static function isValidConditionType(string $type): bool
{
return in_array($type, self::CONDITION_TYPES);
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalColorScale.php | src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalColorScale.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting;
use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Percentiles;
use PhpOffice\PhpSpreadsheet\Style\Color;
class ConditionalColorScale
{
private ?ConditionalFormatValueObject $minimumConditionalFormatValueObject = null;
private ?ConditionalFormatValueObject $midpointConditionalFormatValueObject = null;
private ?ConditionalFormatValueObject $maximumConditionalFormatValueObject = null;
private ?Color $minimumColor = null;
private ?Color $midpointColor = null;
private ?Color $maximumColor = null;
private ?string $sqref = null;
/** @var mixed[] */
private array $valueArray = [];
private float $minValue = 0;
private float $maxValue = 0;
private float $midValue = 0;
private ?\PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet = null;
public function getMinimumConditionalFormatValueObject(): ?ConditionalFormatValueObject
{
return $this->minimumConditionalFormatValueObject;
}
public function setMinimumConditionalFormatValueObject(ConditionalFormatValueObject $minimumConditionalFormatValueObject): self
{
$this->minimumConditionalFormatValueObject = $minimumConditionalFormatValueObject;
return $this;
}
public function getMidpointConditionalFormatValueObject(): ?ConditionalFormatValueObject
{
return $this->midpointConditionalFormatValueObject;
}
public function setMidpointConditionalFormatValueObject(ConditionalFormatValueObject $midpointConditionalFormatValueObject): self
{
$this->midpointConditionalFormatValueObject = $midpointConditionalFormatValueObject;
return $this;
}
public function getMaximumConditionalFormatValueObject(): ?ConditionalFormatValueObject
{
return $this->maximumConditionalFormatValueObject;
}
public function setMaximumConditionalFormatValueObject(ConditionalFormatValueObject $maximumConditionalFormatValueObject): self
{
$this->maximumConditionalFormatValueObject = $maximumConditionalFormatValueObject;
return $this;
}
public function getMinimumColor(): ?Color
{
return $this->minimumColor;
}
public function setMinimumColor(Color $minimumColor): self
{
$this->minimumColor = $minimumColor;
return $this;
}
public function getMidpointColor(): ?Color
{
return $this->midpointColor;
}
public function setMidpointColor(Color $midpointColor): self
{
$this->midpointColor = $midpointColor;
return $this;
}
public function getMaximumColor(): ?Color
{
return $this->maximumColor;
}
public function setMaximumColor(Color $maximumColor): self
{
$this->maximumColor = $maximumColor;
return $this;
}
public function getSqRef(): ?string
{
return $this->sqref;
}
public function setSqRef(string $sqref, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $worksheet): self
{
$this->sqref = $sqref;
$this->worksheet = $worksheet;
return $this;
}
public function setScaleArray(): self
{
if ($this->sqref !== null && $this->worksheet !== null) {
$values = $this->worksheet->rangesToArray($this->sqref, null, true, true, true);
$this->valueArray = [];
foreach ($values as $key => $value) {
/** @var array<float|int|string> $value */
foreach ($value as $k => $v) {
$this->valueArray[] = (float) $v;
}
}
$this->prepareColorScale();
}
return $this;
}
public function getColorForValue(float $value): string
{
if ($this->minimumColor === null || $this->midpointColor === null || $this->maximumColor === null) {
return 'FF000000';
}
$minColor = $this->minimumColor->getARGB();
$midColor = $this->midpointColor->getARGB();
$maxColor = $this->maximumColor->getARGB();
if ($minColor === null || $midColor === null || $maxColor === null) {
return 'FF000000';
}
if ($value <= $this->minValue) {
return $minColor;
}
if ($value >= $this->maxValue) {
return $maxColor;
}
if ($value == $this->midValue) {
return $midColor;
}
if ($value < $this->midValue) {
$blend = ($value - $this->minValue) / ($this->midValue - $this->minValue);
$alpha1 = hexdec(substr($minColor, 0, 2));
$alpha2 = hexdec(substr($midColor, 0, 2));
$red1 = hexdec(substr($minColor, 2, 2));
$red2 = hexdec(substr($midColor, 2, 2));
$green1 = hexdec(substr($minColor, 4, 2));
$green2 = hexdec(substr($midColor, 4, 2));
$blue1 = hexdec(substr($minColor, 6, 2));
$blue2 = hexdec(substr($midColor, 6, 2));
return strtoupper(dechex((int) ($alpha2 * $blend + $alpha1 * (1 - $blend))) . '' . dechex((int) ($red2 * $blend + $red1 * (1 - $blend))) . '' . dechex((int) ($green2 * $blend + $green1 * (1 - $blend))) . '' . dechex((int) ($blue2 * $blend + $blue1 * (1 - $blend))));
}
$blend = ($value - $this->midValue) / ($this->maxValue - $this->midValue);
$alpha1 = hexdec(substr($midColor, 0, 2));
$alpha2 = hexdec(substr($maxColor, 0, 2));
$red1 = hexdec(substr($midColor, 2, 2));
$red2 = hexdec(substr($maxColor, 2, 2));
$green1 = hexdec(substr($midColor, 4, 2));
$green2 = hexdec(substr($maxColor, 4, 2));
$blue1 = hexdec(substr($midColor, 6, 2));
$blue2 = hexdec(substr($maxColor, 6, 2));
return strtoupper(dechex((int) ($alpha2 * $blend + $alpha1 * (1 - $blend))) . '' . dechex((int) ($red2 * $blend + $red1 * (1 - $blend))) . '' . dechex((int) ($green2 * $blend + $green1 * (1 - $blend))) . '' . dechex((int) ($blue2 * $blend + $blue1 * (1 - $blend))));
}
private function getLimitValue(string $type, float $value = 0, float $formula = 0): float
{
if (count($this->valueArray) === 0) {
return 0;
}
switch ($type) {
case 'min':
/** @var float|int */
$temp = min($this->valueArray);
return (float) $temp;
case 'max':
/** @var float|int */
$temp = max($this->valueArray);
return (float) $temp;
case 'percentile':
return (float) Percentiles::PERCENTILE($this->valueArray, (float) ($value / 100));
case 'formula':
return $formula;
case 'percent':
/** @var float|int */
$min = min($this->valueArray);
$min = (float) $min;
/** @var float|int */
$max = max($this->valueArray);
$max = (float) $max;
return $min + (float) ($value / 100) * ($max - $min);
default:
return 0;
}
}
/**
* Prepares color scale for execution, see the first if for variables that must be set beforehand.
*/
public function prepareColorScale(): self
{
if ($this->minimumConditionalFormatValueObject !== null && $this->maximumConditionalFormatValueObject !== null && $this->minimumColor !== null && $this->maximumColor !== null) {
if ($this->midpointConditionalFormatValueObject !== null && $this->midpointConditionalFormatValueObject->getType() !== 'None') {
$this->minValue = $this->getLimitValue($this->minimumConditionalFormatValueObject->getType(), (float) $this->minimumConditionalFormatValueObject->getValue(), (float) $this->minimumConditionalFormatValueObject->getCellFormula());
$this->midValue = $this->getLimitValue($this->midpointConditionalFormatValueObject->getType(), (float) $this->midpointConditionalFormatValueObject->getValue(), (float) $this->midpointConditionalFormatValueObject->getCellFormula());
$this->maxValue = $this->getLimitValue($this->maximumConditionalFormatValueObject->getType(), (float) $this->maximumConditionalFormatValueObject->getValue(), (float) $this->maximumConditionalFormatValueObject->getCellFormula());
} else {
$this->minValue = $this->getLimitValue($this->minimumConditionalFormatValueObject->getType(), (float) $this->minimumConditionalFormatValueObject->getValue(), (float) $this->minimumConditionalFormatValueObject->getCellFormula());
$this->maxValue = $this->getLimitValue($this->maximumConditionalFormatValueObject->getType(), (float) $this->maximumConditionalFormatValueObject->getValue(), (float) $this->maximumConditionalFormatValueObject->getCellFormula());
$this->midValue = (float) ($this->minValue + $this->maxValue) / 2;
$blend = 0.5;
$minColor = $this->minimumColor->getARGB();
$maxColor = $this->maximumColor->getARGB();
if ($minColor !== null && $maxColor !== null) {
$alpha1 = hexdec(substr($minColor, 0, 2));
$alpha2 = hexdec(substr($maxColor, 0, 2));
$red1 = hexdec(substr($minColor, 2, 2));
$red2 = hexdec(substr($maxColor, 2, 2));
$green1 = hexdec(substr($minColor, 4, 2));
$green2 = hexdec(substr($maxColor, 4, 2));
$blue1 = hexdec(substr($minColor, 6, 2));
$blue2 = hexdec(substr($maxColor, 6, 2));
$this->midpointColor = new Color(strtoupper(dechex((int) ($alpha2 * $blend + $alpha1 * (1 - $blend))) . '' . dechex((int) ($red2 * $blend + $red1 * (1 - $blend))) . '' . dechex((int) ($green2 * $blend + $green1 * (1 - $blend))) . '' . dechex((int) ($blue2 * $blend + $blue1 * (1 - $blend)))));
} else {
$this->midpointColor = null;
}
}
}
return $this;
}
/**
* Checks that all needed color scale data is in place.
*/
public function colorScaleReadyForUse(): bool
{
if ($this->minimumColor === null || $this->midpointColor === null || $this->maximumColor === null) {
return false;
}
return true;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/CellMatcher.php | src/PhpSpreadsheet/Style/ConditionalFormatting/CellMatcher.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting;
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Calculation\Exception;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class CellMatcher
{
public const COMPARISON_OPERATORS = [
Conditional::OPERATOR_EQUAL => '=',
Conditional::OPERATOR_GREATERTHAN => '>',
Conditional::OPERATOR_GREATERTHANOREQUAL => '>=',
Conditional::OPERATOR_LESSTHAN => '<',
Conditional::OPERATOR_LESSTHANOREQUAL => '<=',
Conditional::OPERATOR_NOTEQUAL => '<>',
];
public const COMPARISON_RANGE_OPERATORS = [
Conditional::OPERATOR_BETWEEN => 'IF(AND(A1>=%s,A1<=%s),TRUE,FALSE)',
Conditional::OPERATOR_NOTBETWEEN => 'IF(AND(A1>=%s,A1<=%s),FALSE,TRUE)',
];
public const COMPARISON_DUPLICATES_OPERATORS = [
Conditional::CONDITION_DUPLICATES => "COUNTIF('%s'!%s,%s)>1",
Conditional::CONDITION_UNIQUE => "COUNTIF('%s'!%s,%s)=1",
];
protected Cell $cell;
protected int $cellRow;
protected Worksheet $worksheet;
protected int $cellColumn;
protected string $conditionalRange;
protected string $referenceCell;
protected int $referenceRow;
protected int $referenceColumn;
protected Calculation $engine;
public function __construct(Cell $cell, string $conditionalRange)
{
$this->cell = $cell;
$this->worksheet = $cell->getWorksheet();
[$this->cellColumn, $this->cellRow] = Coordinate::indexesFromString($this->cell->getCoordinate());
$this->setReferenceCellForExpressions($conditionalRange);
$this->engine = Calculation::getInstance($this->worksheet->getParent());
}
protected function setReferenceCellForExpressions(string $conditionalRange): void
{
$conditionalRange = Coordinate::splitRange(str_replace('$', '', strtoupper($conditionalRange)));
[$this->referenceCell] = $conditionalRange[0];
[$this->referenceColumn, $this->referenceRow] = Coordinate::indexesFromString($this->referenceCell);
// Convert our conditional range to an absolute conditional range, so it can be used "pinned" in formulae
$rangeSets = [];
foreach ($conditionalRange as $rangeSet) {
$absoluteRangeSet = array_map(
[Coordinate::class, 'absoluteCoordinate'],
$rangeSet
);
$rangeSets[] = implode(':', $absoluteRangeSet);
}
$this->conditionalRange = implode(',', $rangeSets);
}
public function evaluateConditional(Conditional $conditional): bool
{
// Some calculations may modify the stored cell; so reset it before every evaluation.
$cellColumn = Coordinate::stringFromColumnIndex($this->cellColumn);
$cellAddress = "{$cellColumn}{$this->cellRow}";
$this->cell = $this->worksheet->getCell($cellAddress);
return match ($conditional->getConditionType()) {
Conditional::CONDITION_CELLIS => $this->processOperatorComparison($conditional),
Conditional::CONDITION_DUPLICATES, Conditional::CONDITION_UNIQUE => $this->processDuplicatesComparison($conditional),
// Expression is NOT(ISERROR(SEARCH("<TEXT>",<Cell Reference>)))
Conditional::CONDITION_CONTAINSTEXT,
// Expression is ISERROR(SEARCH("<TEXT>",<Cell Reference>))
Conditional::CONDITION_NOTCONTAINSTEXT,
// Expression is LEFT(<Cell Reference>,LEN("<TEXT>"))="<TEXT>"
Conditional::CONDITION_BEGINSWITH,
// Expression is RIGHT(<Cell Reference>,LEN("<TEXT>"))="<TEXT>"
Conditional::CONDITION_ENDSWITH,
// Expression is LEN(TRIM(<Cell Reference>))=0
Conditional::CONDITION_CONTAINSBLANKS,
// Expression is LEN(TRIM(<Cell Reference>))>0
Conditional::CONDITION_NOTCONTAINSBLANKS,
// Expression is ISERROR(<Cell Reference>)
Conditional::CONDITION_CONTAINSERRORS,
// Expression is NOT(ISERROR(<Cell Reference>))
Conditional::CONDITION_NOTCONTAINSERRORS,
// Expression varies, depending on specified timePeriod value, e.g.
// Yesterday FLOOR(<Cell Reference>,1)=TODAY()-1
// Today FLOOR(<Cell Reference>,1)=TODAY()
// Tomorrow FLOOR(<Cell Reference>,1)=TODAY()+1
// Last 7 Days AND(TODAY()-FLOOR(<Cell Reference>,1)<=6,FLOOR(<Cell Reference>,1)<=TODAY())
Conditional::CONDITION_TIMEPERIOD,
Conditional::CONDITION_EXPRESSION => $this->processExpression($conditional),
Conditional::CONDITION_COLORSCALE => $this->processColorScale($conditional),
default => false,
};
}
protected function wrapValue(mixed $value): float|int|string
{
if (!is_numeric($value)) {
if (is_bool($value)) {
return $value ? 'TRUE' : 'FALSE';
} elseif ($value === null) {
return 'NULL';
}
return '"' . StringHelper::convertToString($value) . '"';
}
return $value;
}
protected function wrapCellValue(): float|int|string
{
$this->cell = $this->worksheet->getCell([$this->cellColumn, $this->cellRow]);
return $this->wrapValue($this->cell->getCalculatedValue());
}
/** @param string[] $matches */
protected function conditionCellAdjustment(array $matches): float|int|string
{
$column = $matches[6];
$row = $matches[7];
if (!str_contains($column, '$')) {
// $column = Coordinate::stringFromColumnIndex($this->cellColumn);
$column = Coordinate::columnIndexFromString($column);
$column += $this->cellColumn - $this->referenceColumn;
$column = Coordinate::stringFromColumnIndex($column);
}
if (!str_contains($row, '$')) {
$row = (int) $row + $this->cellRow - $this->referenceRow;
}
if (!empty($matches[4])) {
$worksheet = $this->worksheet->getParentOrThrow()->getSheetByName(trim($matches[4], "'"));
if ($worksheet === null) {
return $this->wrapValue(null);
}
return $this->wrapValue(
$worksheet
->getCell(str_replace('$', '', "{$column}{$row}"))
->getCalculatedValue()
);
}
return $this->wrapValue(
$this->worksheet
->getCell(str_replace('$', '', "{$column}{$row}"))
->getCalculatedValue()
);
}
protected function cellConditionCheck(string $condition): string
{
$splitCondition = explode(Calculation::FORMULA_STRING_QUOTE, $condition);
$i = false;
foreach ($splitCondition as &$value) {
// Only count/replace in alternating array entries (ie. not in quoted strings)
$i = $i === false;
if ($i) {
$value = (string) preg_replace_callback(
'/' . Calculation::CALCULATION_REGEXP_CELLREF_RELATIVE . '/i',
[$this, 'conditionCellAdjustment'],
$value
);
}
}
unset($value);
// Then rebuild the condition string to return it
return implode(Calculation::FORMULA_STRING_QUOTE, $splitCondition);
}
/**
* @param mixed[] $conditions
*
* @return mixed[]
*/
protected function adjustConditionsForCellReferences(array $conditions): array
{
return array_map(
[$this, 'cellConditionCheck'],
$conditions
);
}
protected function processOperatorComparison(Conditional $conditional): bool
{
if (array_key_exists($conditional->getOperatorType(), self::COMPARISON_RANGE_OPERATORS)) {
return $this->processRangeOperator($conditional);
}
$operator = self::COMPARISON_OPERATORS[$conditional->getOperatorType()];
$conditions = $this->adjustConditionsForCellReferences($conditional->getConditions());
/** @var float|int|string */
$temp1 = $this->wrapCellValue();
/** @var scalar */
$temp2 = array_pop($conditions);
$expression = sprintf('%s%s%s', (string) $temp1, $operator, (string) $temp2);
return $this->evaluateExpression($expression);
}
protected function processColorScale(Conditional $conditional): bool
{
if (is_numeric($this->wrapCellValue()) && $conditional->getColorScale()?->colorScaleReadyForUse()) {
return true;
}
return false;
}
protected function processRangeOperator(Conditional $conditional): bool
{
$conditions = $this->adjustConditionsForCellReferences($conditional->getConditions());
sort($conditions);
$expression = sprintf(
(string) preg_replace(
'/\bA1\b/i',
(string) $this->wrapCellValue(),
self::COMPARISON_RANGE_OPERATORS[$conditional->getOperatorType()]
),
...$conditions //* @phpstan-ignore-line
);
return $this->evaluateExpression($expression);
}
protected function processDuplicatesComparison(Conditional $conditional): bool
{
$worksheetName = $this->cell->getWorksheet()->getTitle();
$expression = sprintf(
self::COMPARISON_DUPLICATES_OPERATORS[$conditional->getConditionType()],
$worksheetName,
$this->conditionalRange,
$this->cellConditionCheck($this->cell->getCalculatedValueString())
);
return $this->evaluateExpression($expression);
}
protected function processExpression(Conditional $conditional): bool
{
$conditions = $this->adjustConditionsForCellReferences($conditional->getConditions());
/** @var string */
$expression = array_pop($conditions);
/** @var float|int|string */
$temp = $this->wrapCellValue();
$expression = (string) preg_replace(
'/\b' . $this->referenceCell . '\b/i',
(string) $temp,
$expression
);
return $this->evaluateExpression($expression);
}
protected function evaluateExpression(string $expression): bool
{
$expression = "={$expression}";
try {
$this->engine->flushInstance();
$result = (bool) $this->engine->calculateFormula($expression);
} catch (Exception) {
return false;
}
return $result;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php | src/PhpSpreadsheet/Style/ConditionalFormatting/ConditionalDataBarExtension.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting;
class ConditionalDataBarExtension
{
/** <dataBar> attributes */
private int $minLength;
private int $maxLength;
private ?bool $border = null;
private ?bool $gradient = null;
private ?string $direction = null;
private ?bool $negativeBarBorderColorSameAsPositive = null;
private ?string $axisPosition = null;
// <dataBar> children
private ConditionalFormatValueObject $maximumConditionalFormatValueObject;
private ConditionalFormatValueObject $minimumConditionalFormatValueObject;
private ?string $borderColor = null;
private ?string $negativeFillColor = null;
private ?string $negativeBorderColor = null;
/** @var array{rgb: ?string, theme: ?string, tint: ?string} */
private array $axisColor = [
'rgb' => null,
'theme' => null,
'tint' => null,
];
/** @return mixed[] */
public function getXmlAttributes(): array
{
$ret = [];
foreach (['minLength', 'maxLength', 'direction', 'axisPosition'] as $attrKey) {
if (null !== $this->{$attrKey}) {
$ret[$attrKey] = $this->{$attrKey};
}
}
foreach (['border', 'gradient', 'negativeBarBorderColorSameAsPositive'] as $attrKey) {
if (null !== $this->{$attrKey}) {
$ret[$attrKey] = $this->{$attrKey} ? '1' : '0';
}
}
return $ret;
}
/** @return mixed[] */
public function getXmlElements(): array
{
$ret = [];
$elms = ['borderColor', 'negativeFillColor', 'negativeBorderColor'];
foreach ($elms as $elmKey) {
if (null !== $this->{$elmKey}) {
$ret[$elmKey] = ['rgb' => $this->{$elmKey}];
}
}
foreach (array_filter($this->axisColor) as $attrKey => $axisColorAttr) {
if (!isset($ret['axisColor'])) {
$ret['axisColor'] = [];
}
$ret['axisColor'][$attrKey] = $axisColorAttr;
}
return $ret;
}
public function getMinLength(): int
{
return $this->minLength;
}
public function setMinLength(int $minLength): self
{
$this->minLength = $minLength;
return $this;
}
public function getMaxLength(): int
{
return $this->maxLength;
}
public function setMaxLength(int $maxLength): self
{
$this->maxLength = $maxLength;
return $this;
}
public function getBorder(): ?bool
{
return $this->border;
}
public function setBorder(bool $border): self
{
$this->border = $border;
return $this;
}
public function getGradient(): ?bool
{
return $this->gradient;
}
public function setGradient(bool $gradient): self
{
$this->gradient = $gradient;
return $this;
}
public function getDirection(): ?string
{
return $this->direction;
}
public function setDirection(string $direction): self
{
$this->direction = $direction;
return $this;
}
public function getNegativeBarBorderColorSameAsPositive(): ?bool
{
return $this->negativeBarBorderColorSameAsPositive;
}
public function setNegativeBarBorderColorSameAsPositive(bool $negativeBarBorderColorSameAsPositive): self
{
$this->negativeBarBorderColorSameAsPositive = $negativeBarBorderColorSameAsPositive;
return $this;
}
public function getAxisPosition(): ?string
{
return $this->axisPosition;
}
public function setAxisPosition(string $axisPosition): self
{
$this->axisPosition = $axisPosition;
return $this;
}
public function getMaximumConditionalFormatValueObject(): ConditionalFormatValueObject
{
return $this->maximumConditionalFormatValueObject;
}
public function setMaximumConditionalFormatValueObject(ConditionalFormatValueObject $maximumConditionalFormatValueObject): self
{
$this->maximumConditionalFormatValueObject = $maximumConditionalFormatValueObject;
return $this;
}
public function getMinimumConditionalFormatValueObject(): ConditionalFormatValueObject
{
return $this->minimumConditionalFormatValueObject;
}
public function setMinimumConditionalFormatValueObject(ConditionalFormatValueObject $minimumConditionalFormatValueObject): self
{
$this->minimumConditionalFormatValueObject = $minimumConditionalFormatValueObject;
return $this;
}
public function getBorderColor(): ?string
{
return $this->borderColor;
}
public function setBorderColor(string $borderColor): self
{
$this->borderColor = $borderColor;
return $this;
}
public function getNegativeFillColor(): ?string
{
return $this->negativeFillColor;
}
public function setNegativeFillColor(string $negativeFillColor): self
{
$this->negativeFillColor = $negativeFillColor;
return $this;
}
public function getNegativeBorderColor(): ?string
{
return $this->negativeBorderColor;
}
public function setNegativeBorderColor(string $negativeBorderColor): self
{
$this->negativeBorderColor = $negativeBorderColor;
return $this;
}
/** @return array{rgb: ?string, theme: ?string, tint: ?string} */
public function getAxisColor(): array
{
return $this->axisColor;
}
public function setAxisColor(?string $rgb, ?string $theme = null, ?string $tint = null): self
{
$this->axisColor = [
'rgb' => $rgb,
'theme' => $theme,
'tint' => $tint,
];
return $this;
}
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
PHPOffice/PhpSpreadsheet | https://github.com/PHPOffice/PhpSpreadsheet/blob/e33834b4ea2a02088becbb41fb8954d915b46b12/src/PhpSpreadsheet/Style/ConditionalFormatting/IconSetValues.php | src/PhpSpreadsheet/Style/ConditionalFormatting/IconSetValues.php | <?php
namespace PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting;
enum IconSetValues: string
{
case ThreeArrows = '3Arrows';
case ThreeArrowsGray = '3ArrowsGray';
case ThreeFlags = '3Flags';
case ThreeTrafficLights1 = '3TrafficLights1';
case ThreeTrafficLights2 = '3TrafficLights2';
case ThreeSigns = '3Signs';
case ThreeSymbols = '3Symbols';
case ThreeSymbols2 = '3Symbols2';
case FourArrows = '4Arrows';
case FourArrowsGray = '4ArrowsGray';
case FourRedToBlack = '4RedToBlack';
case FourRating = '4Rating';
case FourTrafficLights = '4TrafficLights';
case FiveArrows = '5Arrows';
case FiveArrowsGray = '5ArrowsGray';
case FiveRating = '5Rating';
case FiveQuarters = '5Quarters';
// The following icon sets are not implemented yet:
// case ThreeStars = "3Stars";
// case ThreeTriangles = "3Triangles";
// case FiveBoxes = "5Boxes";
}
| php | MIT | e33834b4ea2a02088becbb41fb8954d915b46b12 | 2026-01-04T15:02:44.305364Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.