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
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Model/EditableFormField/EditableDateField/FormField.php
code/Model/EditableFormField/EditableDateField/FormField.php
<?php namespace SilverStripe\UserForms\Model\EditableFormField\EditableDateField; use SilverStripe\Forms\DateField; /** * @package userforms */ class FormField extends DateField { public function Type() { return 'date-alt text'; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Extension/UserFormFieldEditorExtension.php
code/Extension/UserFormFieldEditorExtension.php
<?php namespace SilverStripe\UserForms\Extension; use SilverStripe\Admin\AdminRootController; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\GridField\GridFieldPaginator; use SilverStripe\Forms\Tab; use SilverStripe\Forms\GridField\GridField; use SilverStripe\Forms\GridField\GridFieldButtonRow; use SilverStripe\Forms\GridField\GridFieldConfig; use SilverStripe\Forms\GridField\GridFieldEditButton; use SilverStripe\Forms\GridField\GridFieldDeleteAction; use SilverStripe\Forms\GridField\GridFieldDetailForm; use SilverStripe\Forms\GridField\GridFieldToolbarHeader; use SilverStripe\Core\Extension; use SilverStripe\ORM\DataList; use SilverStripe\ORM\DataObject; use SilverStripe\ORM\HasManyList; use SilverStripe\UserForms\Form\GridFieldAddClassesButton; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroup; use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd; use SilverStripe\UserForms\Model\EditableFormField\EditableFileField; use SilverStripe\UserForms\Model\EditableFormField\EditableFormStep; use SilverStripe\UserForms\Model\EditableFormField\EditableTextField; use SilverStripe\Versioned\Versioned; use SilverStripe\View\Requirements; use Symbiote\GridFieldExtensions\GridFieldEditableColumns; use Symbiote\GridFieldExtensions\GridFieldOrderableRows; /** * @method HasManyList<EditableFormField> Fields() */ class UserFormFieldEditorExtension extends Extension { /** * @var array */ private static $has_many = array( 'Fields' => EditableFormField::class ); private static $owns = [ // Note we explicitly cannot use $cascade_duplicates to duplicate this relation. // See onAfterDuplicate() 'Fields' ]; private static $cascade_deletes = [ 'Fields' ]; private static array $scaffold_cms_fields_settings = [ 'ignoreRelations' => [ 'Fields', ], ]; /** * Adds the field editor to the page. * * @return FieldList */ protected function updateCMSFields(FieldList $fields) { $fieldEditor = $this->getFieldEditorGrid(); $fields->insertAfter('Main', Tab::create('FormFields', _t(__CLASS__.'.FORMFIELDS', 'Form Fields'))); $fields->addFieldToTab('Root.FormFields', $fieldEditor); return $fields; } /** * Gets the field editor, for adding and removing EditableFormFields. * * @return GridField */ public function getFieldEditorGrid() { Requirements::javascript('silverstripe/admin:client/dist/js/vendor.js'); Requirements::javascript('silverstripe/admin:client/dist/js/bundle.js'); Requirements::javascript('silverstripe/userforms:client/dist/js/userforms-cms.js'); $fields = $this->owner->Fields(); $this->createInitialFormStep(true); $editableColumns = GridFieldEditableColumns::create(); $fieldClasses = singleton(EditableFormField::class)->getEditableFieldClasses(); $editableColumns->setDisplayFields([ 'ClassName' => function ($record, $column, $grid) use ($fieldClasses) { if ($record instanceof EditableFormField) { $field = $record->getInlineClassnameField($column, $fieldClasses); if ($record instanceof EditableFileField) { $field->setAttribute('data-folderconfirmed', $record->FolderConfirmed ? 1 : 0); } return $field; } }, 'Title' => function ($record, $column, $grid) { if ($record instanceof EditableFormField) { return $record->getInlineTitleField($column); } } ]); $config = GridFieldConfig::create() ->addComponents( $editableColumns, GridFieldButtonRow::create(), (new GridFieldAddClassesButton(EditableTextField::class)) ->setButtonName(_t(__CLASS__.'.ADD_NEW_FIELD', 'Add new Field')) ->setButtonClass('btn-primary'), (new GridFieldAddClassesButton(EditableFormStep::class)) ->setButtonName(_t(__CLASS__.'.ADD_NEW_PAGE_BREAK', 'Add new Page Break')) ->setButtonClass('btn-secondary'), (new GridFieldAddClassesButton([EditableFieldGroup::class, EditableFieldGroupEnd::class])) ->setButtonName(_t(__CLASS__.'.ADD_NEW_FIELD_GROUP', 'Add new Field Group')) ->setButtonClass('btn-secondary'), $editButton = GridFieldEditButton::create(), GridFieldDeleteAction::create(), GridFieldToolbarHeader::create(), GridFieldOrderableRows::create('Sort'), GridFieldDetailForm::create(), // Betterbuttons prev and next is enabled by adding a GridFieldPaginator component GridFieldPaginator::create(999) ); $editButton->removeExtraClass('grid-field__icon-action--hidden-on-hover'); $fieldEditor = GridField::create( 'Fields', '', $fields, $config ) ->addExtraClass('uf-field-editor'); return $fieldEditor; } /** * A UserForm must have at least one step. * If no steps exist, create an initial step, and put all fields inside it. * * @param bool $force * @return void */ public function createInitialFormStep($force = false) { // Only invoke once saved if (!$this->owner->exists()) { return; } // Check if first field is a step $fields = $this->owner->Fields(); $firstField = $fields->first(); if ($firstField instanceof EditableFormStep) { return; } // Don't create steps on write if there are no formfields, as this // can create duplicate first steps during publish of new records if (!$force && !$firstField) { return; } // Re-apply sort to each field starting at 2 $next = 2; foreach ($fields as $field) { $field->Sort = $next++; $field->write(); } // Add step $step = EditableFormStep::create(); $step->Title = _t('SilverStripe\\UserForms\\Model\\EditableFormField\\EditableFormStep.TITLE_FIRST', 'First Page'); $step->Sort = 1; $step->write(); $fields->add($step); } /** * Ensure that at least one page exists at the start */ protected function onAfterWrite() { $this->createInitialFormStep(); } /** * Remove any orphaned child records on publish */ protected function onAfterPublish() { // store IDs of fields we've published $seenIDs = []; foreach ($this->owner->Fields() as $field) { // store any IDs of fields we publish so we don't unpublish them $seenIDs[] = $field->ID; $field->publishRecursive(); $field->destroy(); } // fetch any orphaned live records $live = Versioned::get_by_stage(EditableFormField::class, Versioned::LIVE) ->filter([ 'ParentID' => $this->owner->ID, 'ParentClass' => get_class($this->owner), ]); if (!empty($seenIDs)) { $live = $live->exclude([ 'ID' => $seenIDs, ]); } // delete orphaned records foreach ($live as $field) { $field->deleteFromStage(Versioned::LIVE); $field->destroy(); } } /** * Remove all fields from the live stage when unpublishing the page */ protected function onAfterUnpublish() { foreach ($this->owner->Fields() as $field) { $field->deleteFromStage(Versioned::LIVE); } } /** * Duplicate the Fields() relation. * When duplicating a UserDefinedForm, ensure the group ends aren't duplicated twice, * but also ensure they are connected to the correct duplicated Group. * * @see DataObject::duplicate * @param DataObject $oldPage * @param bool $doWrite * @param null|array $manyMany */ protected function onAfterDuplicate($oldPage, $doWrite, $manyMany) { // List of EditableFieldGroups, where the key of the array is the ID of the old end group $fieldGroups = []; foreach ($oldPage->Fields() as $field) { /** @var EditableFormField $newField */ $newField = $field->duplicate(false); $this->getOwner()->Fields()->add($newField); // If we encounter a group start, record it for later use if ($field instanceof EditableFieldGroup) { $fieldGroups[$field->EndID] = $newField; } // If we encounter an end group, link it back to the group start if ($field instanceof EditableFieldGroupEnd && isset($fieldGroups[$field->ID])) { $groupStart = $fieldGroups[$field->ID]; $groupStart->EndID = $newField->ID; $groupStart->write(); } } } /** * Checks child fields to see if any are modified in draft as well. The owner of this extension will still * use the Versioned method to determine its own status. * * @see Versioned::isModifiedOnDraft * * @return boolean|null */ public function isModifiedOnDraft() { foreach ($this->owner->Fields() as $field) { if ($field->isModifiedOnDraft()) { return true; } } } /** * @see Versioned::doRevertToLive */ protected function onAfterRevertToLive() { foreach ($this->owner->Fields() as $field) { $field->copyVersionToStage(Versioned::LIVE, Versioned::DRAFT); $field->writeWithoutVersion(); } } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Extension/UserFormValidator.php
code/Extension/UserFormValidator.php
<?php namespace SilverStripe\UserForms\Extension; use SilverStripe\Forms\Validation\RequiredFieldsValidator; use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroup; use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\Model\EditableFormField\EditableFormStep; class UserFormValidator extends RequiredFieldsValidator { public function php($data) { if (!parent::php($data)) { return false; } // Skip unsaved records if (empty($data['ID']) || !is_numeric($data['ID'])) { return true; } $fields = EditableFormField::get()->filter('ParentID', $data['ID'])->sort('"Sort" ASC'); // Current nesting $stack = array(); $conditionalStep = false; // Is the current step conditional? foreach ($fields as $field) { if ($field instanceof EditableFormStep) { // Page at top level, or after another page is ok if (empty($stack) || (count($stack ?? []) === 1 && $stack[0] instanceof EditableFormStep)) { $stack = array($field); $conditionalStep = $field->DisplayRules()->count() > 0; continue; } $this->validationError( 'FormFields', _t( __CLASS__.".UNEXPECTED_BREAK", "Unexpected page break '{name}' inside nested field '{group}'", array( 'name' => $field->CMSTitle, 'group' => end($stack)->CMSTitle ) ), 'error' ); return false; } // Validate no pages if (empty($stack)) { $this->validationError( 'FormFields', _t( __CLASS__.".NO_PAGE", "Field '{name}' found before any pages", array( 'name' => $field->CMSTitle ) ), 'error' ); return false; } // Nest field group if ($field instanceof EditableFieldGroup) { $stack[] = $field; continue; } // Unnest field group if ($field instanceof EditableFieldGroupEnd) { $top = end($stack); // Check that the top is a group at all if (!$top instanceof EditableFieldGroup) { $this->validationError( 'FormFields', _t( __CLASS__.".UNEXPECTED_GROUP_END", "'{name}' found without a matching group", array( 'name' => $field->CMSTitle ) ), 'error' ); return false; } // Check that the top is the right group if ($top->EndID != $field->ID) { $this->validationError( 'FormFields', _t( __CLASS__.".WRONG_GROUP_END", "'{name}' found closes the wrong group '{group}'", array( 'name' => $field->CMSTitle, 'group' => $top->CMSTitle ) ), 'error' ); return false; } // Unnest group array_pop($stack); } // Normal field type if ($conditionalStep && $field->Required) { $this->validationError( 'FormFields', _t( __CLASS__.".CONDITIONAL_REQUIRED", "Required field '{name}' cannot be placed within a conditional page", array( 'name' => $field->CMSTitle ) ), 'error' ); return false; } } return true; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Extension/UserFormFileExtension.php
code/Extension/UserFormFileExtension.php
<?php namespace SilverStripe\UserForms\Extension; use SilverStripe\Assets\File; use SilverStripe\Assets\Folder; use SilverStripe\Core\Convert; use SilverStripe\Core\Extension; use SilverStripe\ORM\DataObject; use SilverStripe\ORM\Queries\SQLUpdate; use SilverStripe\UserForms\Control\UserDefinedFormController; use SilverStripe\UserForms\Model\Submission\SubmittedFileField; /** * @property string $UserFormUpload * @method SubmittedFileField SubmittedFileField() * * @extends Extension<File&static> */ class UserFormFileExtension extends Extension { public const USER_FORM_UPLOAD_UNKNOWN = null; public const USER_FORM_UPLOAD_FALSE = 'f'; public const USER_FORM_UPLOAD_TRUE = 't'; private static $db = [ 'UserFormUpload' => "Enum('f, t', null)", ]; private static $belongs_to = [ 'SubmittedFileField' => SubmittedFileField::class ]; /** * Check if the file is associated with a userform submission * Save the result in the database as a tri-state for two reasons: * a) performance - prevent the need for an extra DB query * b) if in the future the UserForm submission is deleted and the uploaded file is not (file is orphaned), * then it is still recorded that the file was originally uploaded from a userform submission * * @param bool $value * @see File::isTrackedFormUpload(), UserDefinedFormController::process() */ protected function updateTrackedFormUpload(&$value): void { $file = $this->owner; if ($file->UserFormUpload != UserFormFileExtension::USER_FORM_UPLOAD_UNKNOWN) { $value = $file->UserFormUpload == UserFormFileExtension::USER_FORM_UPLOAD_TRUE; return; } if ($file->ClassName == Folder::class) { $value = false; } else { $value = $file->SubmittedFileField()->exists(); } $this->updateDB($value); } /** * Update File.UserFormUpload draft table without altering File.LastEdited * * @param bool $value */ private function updateDB(bool $value): void { if (!$this->owner->isInDB()) { return; } $tableName = Convert::raw2sql(DataObject::getSchema()->tableName(File::class)); $column = 'UserFormUpload'; $enumVal = $value ? UserFormFileExtension::USER_FORM_UPLOAD_TRUE : UserFormFileExtension::USER_FORM_UPLOAD_FALSE; SQLUpdate::create() ->setTable(sprintf('"%s"', $tableName)) ->addWhere(['"ID" = ?' => [$this->owner->ID]]) ->addAssignments([sprintf('"%s"', $column) => $enumVal]) ->execute(); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Extension/UpgradePolymorphicExtension.php
code/Extension/UpgradePolymorphicExtension.php
<?php namespace SilverStripe\UserForms\Extension; use SilverStripe\Control\Director; use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Extension; use SilverStripe\ORM\DataList; use SilverStripe\ORM\DataObject; use SilverStripe\Core\Validation\ValidationException; use SilverStripe\Dev\Deprecation; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\Model\Recipient\EmailRecipient; use SilverStripe\UserForms\Model\Submission\SubmittedForm; use SilverStripe\UserForms\Model\UserDefinedForm; use SilverStripe\UserForms\UserForm; /** * This extension provides a hook that runs when building the db which will check for existing data in various * polymorphic relationship fields for userforms models, and ensure that the data is correct. * * Various `Parent` relationships in silverstripe/userforms for SilverStripe 3 were mapped directly to UserDefinedForm * instances, and were made polymorphic in SilverStripe 4 (which also requires a class name). This means that a * certain amount of manual checking is required to ensure that upgrades are performed smoothly. * * @extends Extension<UserDefinedForm> * @deprecated 6.1.0 Will be removed without equivalent functionality to replace it in a future major release. */ class UpgradePolymorphicExtension extends Extension { /** * A list of userforms classes that have had polymorphic relationships added in SilverStripe 4, and the fields * on them that are polymorphic * * @var array */ protected $targets = [ EditableFormField::class => ['ParentClass'], EmailRecipient::class => ['FormClass'], SubmittedForm::class => ['ParentClass'], ]; /** * The default class name that will be used to replace values with * * @var string */ protected $defaultReplacement = UserDefinedForm::class; public function __construct() { Deprecation::noticeWithNoReplacment('6.1.0'); } protected function onRequireDefaultRecords() { if (!Deprecation::withSuppressedNotice(fn () => UserDefinedForm::config()->get('upgrade_on_build'))) { return; } $updated = 0; foreach ($this->targets as $className => $fieldNames) { foreach ($fieldNames as $fieldName) { /** @var DataList $list */ $list = $className::get(); foreach ($list as $entry) { /** @var DataObject $relationshipObject */ $relationshipObject = Injector::inst()->get($entry->$fieldName); if (!$relationshipObject) { continue; } // If the defined data class doesn't have the UserForm trait applied, it's probably wrong. Re-map // it to a default value that does $classTraits = class_uses($relationshipObject); if (in_array(UserForm::class, $classTraits ?? [])) { continue; } // Don't rewrite class values when an existing value is set and is an instance of UserDefinedForm if ($relationshipObject instanceof UserDefinedForm) { continue; } $entry->$fieldName = $this->defaultReplacement; try { $entry->write(); $updated++; } catch (ValidationException $ex) { // no-op, allow the rest of the db build to continue. There may be an error indicating that the // object's class doesn't exist, which can be fixed by {@link DatabaseAdmin::doBuild} and this // logic will work the next time the db is built. } } } } if ($updated) { $message = "Corrected {$updated} default polymorphic class names to {$this->defaultReplacement}"; if (Director::is_cli()) { echo sprintf(" * %s\n", $message); } else { echo sprintf("<li>%s</li>\n", $message); } } } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/FormField/UserFormsCheckboxSetField.php
code/FormField/UserFormsCheckboxSetField.php
<?php namespace SilverStripe\UserForms\FormField; use SilverStripe\Core\Validation\ValidationResult; use SilverStripe\Forms\CheckboxSetField; /** * @package userforms */ class UserFormsCheckboxSetField extends CheckboxSetField { /** * If your project uses a custom UserFormsCheckboxSetField template, ensure that it includes * `$Top.getValidationAttributesHTML().RAW` so that custom validation messages work * For further details see * templates/SilverStripe/UserForms/FormField/UserFormsCheckboxSetField template * * Use on a template with .RAW - single and double quoted strings will be safely escaped * * @return string * @see EditableFormField::updateFormField() */ public function getValidationAttributesHTML() { $attrs = array_filter(array_keys($this->getAttributes() ?? []), function ($attr) { return !in_array($attr, ['data-rule-required', 'data-msg-required']); }); return $this->getAttributesHTML(...$attrs); } /** * jQuery validate requires that the value of the option does not contain * the actual value of the input. */ public function getOptions() { $options = parent::getOptions(); foreach ($options as $option) { $option->Name = "{$this->name}[]"; } return $options; } public function getValueForValidation(): mixed { $value = $this->getValue(); if (is_iterable($value) || is_null($value)) { return $value; } // Value may contain a comma-delimited list of values if (is_string($value) && strstr($value, ',')) { return explode(',', $value); } return [$value]; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/FormField/UserFormsStepField.php
code/FormField/UserFormsStepField.php
<?php namespace SilverStripe\UserForms\FormField; /** * Represents a page step in a form, which may contain form fields or other groups */ class UserFormsStepField extends UserFormsCompositeField { private static $casting = [ 'StepNumber' => 'Int' ]; /** * Numeric index (1 based) of this step * * Null if unassigned * * @var int|null */ protected $number = null; public function FieldHolder($properties = []) { return $this->Field($properties); } /** * Get the step number * * @return int|null */ public function getStepNumber() { return $this->number; } /** * Re-assign this step to another number * * @param type $number * @return $this */ public function setStepNumber($number) { $this->number = $number; return $this; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/FormField/UserFormsOptionSetField.php
code/FormField/UserFormsOptionSetField.php
<?php namespace SilverStripe\UserForms\FormField; use SilverStripe\Forms\OptionsetField; use SilverStripe\UserForms\Model\EditableFormField; /** * @package userforms */ class UserFormsOptionSetField extends OptionsetField { /** * If your project uses a custom UserFormsCheckboxSetField template, ensure that it includes * `$Top.getValidationAttributesHTML().RAW` so that custom validation messages work * For further details see * templates/SilverStripe/UserForms/FormField/UserFormsCheckboxSetField template * * Use on a template with .RAW - single and double quoted strings will be safely escaped * * @return string * @see EditableFormField::updateFormField() */ public function getValidationAttributesHTML() { $attrs = array_filter(array_keys($this->getAttributes() ?? []), function ($attr) { return !in_array($attr, ['data-rule-required', 'data-msg-required']); }); return $this->getAttributesHTML(...$attrs); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/FormField/UserFormsCompositeField.php
code/FormField/UserFormsCompositeField.php
<?php namespace SilverStripe\UserForms\FormField; use SilverStripe\Forms\CompositeField; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\Model\EditableFormField\EditableFormStep; /** * Represents a composite field group, which may contain other groups */ abstract class UserFormsCompositeField extends CompositeField implements UserFormsFieldContainer { /** * Parent field * * @var UserFormsFieldContainer */ protected $parent = null; public function getParent() { return $this->parent; } public function setParent(UserFormsFieldContainer $parent) { $this->parent = $parent; return $this; } public function processNext(EditableFormField $field) { // When we find a step, bubble up to the top if ($field instanceof EditableFormStep) { return $this->getParent()->processNext($field); } // Skip over fields that don't generate formfields if (get_class($field) === EditableFormField::class || !$field->getFormField()) { return $this; } $formField = $field->getFormField(); // Save this field $this->push($formField); // Nest fields that are containers if ($formField instanceof UserFormsFieldContainer) { return $formField->setParent($this); } // Add any subsequent fields to this return $this; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/FormField/UserFormsFieldContainer.php
code/FormField/UserFormsFieldContainer.php
<?php namespace SilverStripe\UserForms\FormField; use SilverStripe\UserForms\Model\EditableFormField; /** * Represents a field container which can iteratively process nested fields, converting it into a fieldset */ interface UserFormsFieldContainer { /** * Process the next field in the list, returning the container to add the next field to. * * @param EditableFormField $field * @return EditableContainerField */ public function processNext(EditableFormField $field); /** * Set the parent * * @param UserFormsFieldContainer $parent * @return $this */ public function setParent(UserFormsFieldContainer $parent); /** * Get the parent * * @return UserFormsFieldContainer */ public function getParent(); }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/FormField/UserFormsGroupField.php
code/FormField/UserFormsGroupField.php
<?php namespace SilverStripe\UserForms\FormField; use SilverStripe\UserForms\Model\EditableFormField\EditableFieldGroupEnd; use SilverStripe\UserForms\Model\EditableFormField; /** * Front end composite field for userforms */ class UserFormsGroupField extends UserFormsCompositeField { public function __construct($children = null) { parent::__construct($children); $this->setTag('fieldset'); } public function getLegend() { // Legend defaults to title return parent::getLegend() ?: $this->Title(); } public function processNext(EditableFormField $field) { // When ending a group, jump up one level if ($field instanceof EditableFieldGroupEnd) { return $this->getParent(); } // Otherwise behave as per normal composite field return parent::processNext($field); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/FormField/UserFormsFieldList.php
code/FormField/UserFormsFieldList.php
<?php namespace SilverStripe\UserForms\FormField; use SilverStripe\Forms\FieldList; use SilverStripe\UserForms\Model\EditableFormField; /** * A list of formfields which allows for iterative processing of nested composite fields */ class UserFormsFieldList extends FieldList implements UserFormsFieldContainer { public function processNext(EditableFormField $field) { $formField = $field->getFormField(); if (!$formField) { return $this; } $this->push($formField); if ($formField instanceof UserFormsFieldContainer) { return $formField->setParent($this); } return $this; } public function getParent() { // Field list does not have a parent return null; } public function setParent(UserFormsFieldContainer $parent) { return $this; } /** * Remove all empty steps */ public function clearEmptySteps() { foreach ($this as $field) { if ($field instanceof UserFormsStepField && count($field->getChildren() ?? []) === 0) { $this->remove($field); } } } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Form/UserForm.php
code/Form/UserForm.php
<?php namespace SilverStripe\UserForms\Form; use ResetFormAction; use SilverStripe\Control\Controller; use SilverStripe\Control\Session; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\Form; use SilverStripe\Forms\FormAction; use SilverStripe\UserForms\FormField\UserFormsStepField; use SilverStripe\UserForms\FormField\UserFormsFieldList; /** * @package userforms */ class UserForm extends Form { /** * @config * @var string */ private static $button_text = ''; /** * @param Controller $controller * @param string $name */ public function __construct(Controller $controller, $name = Form::class) { $this->controller = $controller; $this->setRedirectToFormOnValidationError(true); parent::__construct( $controller, $name, new FieldList(), new FieldList() ); $this->setFields($fields = $this->getFormFields()); $fields->setForm($this); $this->setActions($actions = $this->getFormActions()); $actions->setForm($this); $this->setValidator($this->getRequiredFields()); // This needs to be re-evaluated since fields have been assigned $this->restoreFormState(); // Number each page $stepNumber = 1; foreach ($this->getSteps() as $step) { $step->setStepNumber($stepNumber++); } if ($controller->DisableCsrfSecurityToken) { $this->disableSecurityToken(); } $data = $this->getRequest()->getSession()->get("FormInfo.{$this->FormName()}.data"); if (is_array($data)) { $this->loadDataFrom($data); } $this->extend('updateForm'); } public function restoreFormState() { // Suppress restoreFormState if fields haven't been bootstrapped if ($this->fields && $this->fields->exists()) { return parent::restoreFormState(); } return $this; } /** * Used for partial caching in the template. * * @return string */ public function getLastEdited() { return $this->controller->LastEdited; } /** * @return bool */ public function getDisplayErrorMessagesAtTop() { return (bool)$this->controller->DisplayErrorMessagesAtTop; } /** * Return the fieldlist, filtered to only contain steps * * @return \SilverStripe\Model\List\ArrayList */ public function getSteps() { return $this->Fields()->filterByCallback(function ($field) { return $field instanceof UserFormsStepField; }); } /** * Get the form fields for the form on this page. Can modify this FieldSet * by using {@link updateFormFields()} on an {@link Extension} subclass which * is applied to this controller. * * This will be a list of top level composite steps * * @return FieldList */ public function getFormFields() { $fields = UserFormsFieldList::create(); $target = $fields; foreach ($this->controller->data()->Fields() as $field) { $target = $target->processNext($field); } $fields->clearEmptySteps(); $this->extend('updateFormFields', $fields); $fields->setForm($this); return $fields; } /** * Generate the form actions for the UserDefinedForm. You * can manipulate these by using {@link updateFormActions()} on * a decorator. * * @return FieldList */ public function getFormActions() { $submitText = ($this->controller->SubmitButtonText) ? $this->controller->SubmitButtonText : _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.SUBMITBUTTON', 'Submit'); $clearText = ($this->controller->ClearButtonText) ? $this->controller->ClearButtonText : _t('SilverStripe\\UserForms\\Model\\UserDefinedForm.CLEARBUTTON', 'Clear'); $actions = FieldList::create(FormAction::create('process', $submitText)); if ($this->controller->ShowClearButton) { $actions->push(FormAction::create('clearForm', $clearText)->setAttribute('type', 'reset')); } $this->extend('updateFormActions', $actions); $actions->setForm($this); return $actions; } /** * Get the required form fields for this form. * * @return RequiredFieldsValidator */ public function getRequiredFields() { // Generate required field validator $requiredNames = $this ->getController() ->data() ->Fields() ->filter('Required', true) ->column('Name'); $requiredNames = array_merge($requiredNames, $this->getEmailRecipientRequiredFields()); $required = UserFormsRequiredFieldsValidator::create($requiredNames); $this->extend('updateRequiredFields', $required); $required->setForm($this); return $required; } /** * Override some we can add UserForm specific attributes to the form. * * @return array */ public function getAttributes() { $attrs = parent::getAttributes(); $attrs['class'] = $attrs['class'] . ' userform'; $attrs['data-livevalidation'] = (bool)$this->controller->EnableLiveValidation; $attrs['data-toperrors'] = (bool)$this->controller->DisplayErrorMessagesAtTop; return $attrs; } /** * @return string */ public function getButtonText() { return $this->config()->get('button_text'); } /** * Push fields into the RequiredFieldsValidator array if they are used by any Email recipients. * Ignore if there is a backup i.e. the plain string field is set * * @return array required fields names */ protected function getEmailRecipientRequiredFields() { $requiredFields = []; $recipientFieldsMap = [ 'EmailAddress' => 'SendEmailToField', 'EmailSubject' => 'SendEmailSubjectField', 'EmailReplyTo' => 'SendEmailFromField' ]; foreach ($this->getController()->data()->EmailRecipients() as $recipient) { foreach ($recipientFieldsMap as $textField => $dynamicFormField) { if (empty($recipient->$textField) && $recipient->getComponent($dynamicFormField)->exists()) { $requiredFields[] = $recipient->getComponent($dynamicFormField)->Name; } } } return $requiredFields; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Form/UserFormsRequiredFieldsValidator.php
code/Form/UserFormsRequiredFieldsValidator.php
<?php namespace SilverStripe\UserForms\Form; use InvalidArgumentException; use SilverStripe\Dev\Debug; use SilverStripe\Forms\FileField; use SilverStripe\Forms\FormField; use SilverStripe\Forms\Validation\RequiredFieldsValidator; use SilverStripe\Core\ArrayLib; use SilverStripe\UserForms\Model\EditableFormField; /** * An extension of RequiredFieldsValidator which handles conditionally required fields. * * A conditionally required is a field that is required, but can be hidden by display rules. * When it is visible, (according to the submitted form data) it will be validated as required. * When it is hidden, it will skip required validation. * * Required fields will be validated as usual. * Conditionally required fields will be validated IF the display rules are satisfied in the submitted dataset. */ class UserFormsRequiredFieldsValidator extends RequiredFieldsValidator { /** * Allows validation of fields via specification of a php function for * validation which is executed after the form is submitted. * * @param array $data * * @return bool */ public function php($data) { $valid = true; $fields = $this->form->Fields(); if (empty($this->required)) { return $valid; } foreach ($this->required as $fieldName) { if (!$fieldName) { continue; } // get form field if ($fieldName instanceof FormField) { $formField = $fieldName; $fieldName = $fieldName->getName(); } else { $formField = $fields->dataFieldByName($fieldName); } // get editable form field - owns display rules for field $editableFormField = $this->getEditableFormFieldByName($fieldName); // Validate if the field is displayed $error = $editableFormField->isDisplayed($data) && $this->validateRequired($formField, $data); // handle error case if ($formField && $error) { $this->handleError($formField, $fieldName); $valid = false; } } return $valid; } /** * Retrieve an Editable Form field by its name. * @param string $name * @return EditableFormField */ private function getEditableFormFieldByName($name) { $field = EditableFormField::get()->filter(['Name' => $name])->first(); if ($field) { return $field; } // This should happen if form field data got corrupted throw new InvalidArgumentException(sprintf( 'Could not find EditableFormField with name `%s`', $name )); } /** * Check if the validation rules for the specified field are met by the provided data. * * @note Logic replicated from php() method of parent class `SilverStripe\Forms\Validation\RequiredFieldsValidator` * @param EditableFormField $field * @param array $data * @return bool */ private function validateRequired(FormField $field, array $data) { $error = false; $fieldName = $field->getName(); // submitted data for file upload fields come back as an array $value = isset($data[$fieldName]) ? $data[$fieldName] : null; if (is_array($value)) { if ($field instanceof FileField && isset($value['error']) && $value['error']) { $error = true; } else { $error = (count($value ?? [])) ? false : true; } } else { // assume a string or integer $error = (strlen($value ?? '')) ? false : true; } return $error; } /** * Register an error for the provided field. * @param FormField $formField * @param string $fieldName * @return void */ private function handleError(FormField $formField, $fieldName) { $errorMessage = _t( 'SilverStripe\\Forms\\Form.FIELDISREQUIRED', '{name} is required', [ 'name' => strip_tags( '"' . ($formField->Title() ? $formField->Title() : $fieldName) . '"' ) ] ); if ($msg = $formField->getCustomValidationMessage()) { $errorMessage = $msg; } $this->validationError($fieldName, $errorMessage, "required"); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Form/GridFieldAddClassesButton.php
code/Form/GridFieldAddClassesButton.php
<?php namespace SilverStripe\UserForms\Form; use SilverStripe\Control\HTTPResponse_Exception; use SilverStripe\Forms\GridField\GridField; use SilverStripe\Forms\GridField\GridField_ActionProvider; use SilverStripe\Forms\GridField\GridField_FormAction; use SilverStripe\Forms\GridField\GridField_HTMLProvider; use SilverStripe\UserForms\Model\EditableFormField; use Symbiote\GridFieldExtensions\GridFieldEditableColumns; /** * A button which allows objects to be created with a specified classname(s) */ class GridFieldAddClassesButton implements GridField_HTMLProvider, GridField_ActionProvider { /** * Name of fragment to insert into * * @var string */ protected $targetFragment; /** * Button title * * @var string */ protected $buttonName; /** * Additonal CSS classes for the button * * @var string */ protected $buttonClass = null; /** * Class names * * @var array */ protected $modelClasses = null; /** * @param array $classes Class or list of classes to create. * If you enter more than one class, each click of the "add" button will create one of each * @param string $targetFragment The fragment to render the button into */ public function __construct($classes, $targetFragment = 'buttons-before-left') { $this->setClasses($classes); $this->setFragment($targetFragment); } /** * Change the button name * * @param string $name * @return $this */ public function setButtonName($name) { $this->buttonName = $name; return $this; } /** * Get the button name * * @return string */ public function getButtonName() { return $this->buttonName; } /** * Gets the fragment name this button is rendered into. * * @return string */ public function getFragment() { return $this->targetFragment; } /** * Sets the fragment name this button is rendered into. * * @param string $fragment * @return GridFieldAddNewInlineButton $this */ public function setFragment($fragment) { $this->targetFragment = $fragment; return $this; } /** * Get extra button class * * @return string */ public function getButtonClass() { return $this->buttonClass; } /** * Sets extra CSS classes for this button * * @param string $buttonClass * @return $this */ public function setButtonClass($buttonClass) { $this->buttonClass = $buttonClass; return $this; } /** * Get the classes of the objects to create * * @return array */ public function getClasses() { return $this->modelClasses; } /** * Gets the list of classes which can be created, with checks for permissions. * Will fallback to the default model class for the given DataGrid * * @param DataGrid $grid * @return array */ public function getClassesCreate($grid) { // Get explicit or fallback class list $classes = $this->getClasses(); if (empty($classes) && $grid) { $classes = array($grid->getModelClass()); } // Filter out classes without permission return array_filter($classes ?? [], function ($class) { return singleton($class)->canCreate(); }); } /** * Specify the classes to create * * @param array $classes */ public function setClasses($classes) { if (!is_array($classes)) { $classes = $classes ? array($classes) : array(); } $this->modelClasses = $classes; } public function getHTMLFragments($grid) { // Check create permission $singleton = singleton($grid->getModelClass()); if (!$singleton->canCreate()) { return array(); } // Get button name $buttonName = $this->getButtonName(); if (!$buttonName) { // provide a default button name, can be changed by calling {@link setButtonName()} on this component $objectName = $singleton->i18n_singular_name(); $buttonName = _t(GridField::class . '.AddNew', 'Add new {name}', ['name' => $objectName]); } $addAction = GridField_FormAction::create( $grid, $this->getAction(), $buttonName, $this->getAction(), array() ); $addAction->addExtraClass('btn')->setIcon('plus'); if ($this->getButtonClass()) { $addAction->addExtraClass($this->getButtonClass()); } return array( $this->targetFragment => $addAction->forTemplate() ); } /** * {@inheritDoc} */ public function getActions($gridField) { return array( $this->getAction() ); } /** * Get the action suburl for this component * * @return string */ protected function getAction() { return 'add-classes-' . strtolower(implode('-', $this->getClasses())); } public function handleAction(GridField $gridField, $actionName, $arguments, $data) { switch (strtolower($actionName ?? '')) { case $this->getAction(): return $this->handleAdd($gridField); default: return null; } } /** * Handles adding a new instance of a selected class. * * @param GridField $grid * @return null */ public function handleAdd($grid) { $classes = $this->getClassesCreate($grid); if (empty($classes)) { throw new HTTPResponse_Exception(400); } // Add item to gridfield $list = $grid->getList(); foreach ($classes as $class) { $item = $class::create(); $item->write(); $list->add($item); } $this->writeModifiedFieldData($grid); // Should trigger a simple reload return null; } /** * Write any existing form field data that was modified before clicking add button */ private function writeModifiedFieldData(GridField $gridField): void { $vars = $gridField->getRequest()->requestVars(); $data = $vars['Fields'][GridFieldEditableColumns::POST_KEY] ?? []; $ids = array_keys($data); if (empty($ids)) { return; } $list = EditableFormField::get()->filter(['ID' => $ids]); foreach ($ids as $id) { $row = $data[$id]; $field = $list->byID($id); if (!$field) { continue; } $update = false; foreach ($row as $name => $value) { if ($field->{$name} !== $value) { $field->{$name} = $value; $update = true; } } if ($update) { $field->write(); } } } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Form/UserFormsGridFieldFilterHeader.php
code/Form/UserFormsGridFieldFilterHeader.php
<?php namespace SilverStripe\UserForms\Form; use SilverStripe\Core\Convert; use SilverStripe\Forms\CompositeField; use SilverStripe\Forms\DateField; use SilverStripe\Forms\DropdownField; use SilverStripe\Forms\FieldGroup; use SilverStripe\Forms\GridField\GridField; use SilverStripe\Forms\GridField\GridField_FormAction; use SilverStripe\Forms\GridField\GridFieldDataColumns; use SilverStripe\Forms\GridField\GridFieldFilterHeader; use SilverStripe\Forms\TextField; use SilverStripe\Model\List\ArrayList; use SilverStripe\ORM\FieldType\DBDate; use SilverStripe\Model\List\SS_List; use SilverStripe\Model\ArrayData; /** * Extension to the build in SilverStripe {@link GridField} to allow for * filtering {@link SubmittedForm} objects in the submissions tab by * entering the value of a field * * @package userforms */ class UserFormsGridFieldFilterHeader extends GridFieldFilterHeader { /** * A map of name => value of columns from all submissions * @var array */ protected $columns; public function setColumns($columns) { $this->columns = $columns; } public function handleAction(GridField $gridField, $actionName, $arguments, $data) { if (!$this->checkDataType($gridField->getList())) { return; } if ($actionName === 'filter') { $gridField->State->UserFormsGridField = array( 'filter' => isset($data['FieldNameFilter']) ? $data['FieldNameFilter'] : null, 'value' => isset($data['FieldValue']) ? $data['FieldValue'] : null, 'start' => isset($data['StartFilter']) ? $data['StartFilter'] : null, 'end' => isset($data['EndFilter']) ? $data['EndFilter'] : null ); } } public function getHTMLFragments($gridField) { $fields = ArrayList::create(); $state = $gridField->State->UserFormsGridField; $selectedField = $state->filter; $selectedValue = $state->value; // show dropdown of all the fields available from the submitted form fields // that have been saved. Takes the titles from the currently live form. $columnField = DropdownField::create('FieldNameFilter', ''); $columnField->setSource($this->columns); $columnField->setEmptyString(_t(__CLASS__.'.FILTERSUBMISSIONS', 'Filter Submissions..')); $columnField->setHasEmptyDefault(true); $columnField->setValue($selectedField); $valueField = TextField::create('FieldValue', '', $selectedValue); $columnField->addExtraClass('ss-gridfield-sort'); $columnField->addExtraClass('no-change-track'); $valueField->addExtraClass('ss-gridfield-sort'); $valueField->addExtraClass('no-change-track'); $valueField->setAttribute( 'placeholder', _t(__CLASS__.'.WHEREVALUEIS', 'where value is..') ); $fields->push(FieldGroup::create(CompositeField::create( $columnField, $valueField ))); $fields->push(FieldGroup::create(CompositeField::create( $start = DateField::create('StartFilter', _t(__CLASS__.'.FROM', 'From')), $end = DateField::create('EndFilter', _t(__CLASS__.'.TILL', 'Till')) ))); foreach (array($start, $end) as $date) { $date->setDateFormat(DBDate::ISO_DATE); $date->addExtraClass('no-change-track'); } if ($state->end) { $end->setValue($state->end); } if ($state->start) { $start->setValue($state->start); } $fields->push($actions = FieldGroup::create( GridField_FormAction::create($gridField, 'filter', false, 'filter', null) ->addExtraClass('ss-gridfield-button-filter btn btn-primary') ->setTitle(_t(__CLASS__.'.FILTER', "Filter")) ->setAttribute('title', _t(__CLASS__.'.FILTER', "Filter")) ->setAttribute('id', 'action_filter_' . $gridField->getModelClass() . '_' . $columnField), GridField_FormAction::create($gridField, 'reset', false, 'reset', null) ->addExtraClass('ss-gridfield-button-close btn ') ->setTitle(_t(__CLASS__.'.RESET', "Reset")) ->setAttribute('title', _t(__CLASS__.'.RESET', "Reset")) ->setAttribute('id', 'action_reset_' . $gridField->getModelClass() . '_' . $columnField) )); $actions->addExtraClass('filter-buttons'); $actions->addExtraClass('no-change-track'); $colSpan = 2 + count($gridField->getConfig()->getComponentByType(GridFieldDataColumns::class) ->getDisplayFields($gridField) ?? []); $forTemplate = ArrayData::create(array( 'Fields' => $fields, 'ColSpan' => $colSpan )); return array( 'header' => $forTemplate->renderWith(UserFormsGridFieldFilterHeader::class . '_Row') ); } public function getManipulatedData(GridField $gridField, SS_List $dataList) { $state = $gridField->State; if ($filter = $state->UserFormsGridField->toArray()) { if (isset($filter['filter']) && $filter['filter'] && isset($filter['value']) && $filter['value']) { $dataList = $dataList->where(sprintf( " SELECT COUNT(*) FROM SubmittedFormField WHERE ( ParentID = SubmittedForm.ID AND Name = '%s' AND Value LIKE '%s' ) > 0", Convert::raw2sql($filter['filter']), Convert::raw2sql($filter['value']) )); } if (isset($filter['start']) && $filter['start']) { $dataList = $dataList->filter(array( 'Created:GreaterThan' => $filter['start'] )); } if (isset($filter['end']) && $filter['end']) { $dataList = $dataList->filter(array( 'Created:LessThan' => $filter['end'] )); } } return $dataList; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Task/RecoverUploadLocationsHelper.php
code/Task/RecoverUploadLocationsHelper.php
<?php namespace SilverStripe\UserForms\Task; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; use RuntimeException; use SilverStripe\Assets\File; use SilverStripe\Assets\Folder; use SilverStripe\Core\Config\Configurable; use SilverStripe\Core\Convert; use SilverStripe\Core\Environment; use SilverStripe\Core\Injector\Injectable; use SilverStripe\Core\Injector\Injector; use SilverStripe\ORM\DataList; use SilverStripe\ORM\DataObject; use SilverStripe\ORM\Queries\SQLSelect; use SilverStripe\Security\InheritedPermissions; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\Model\EditableFormField\EditableFileField; use SilverStripe\UserForms\Model\Submission\SubmittedFileField; use SilverStripe\UserForms\Model\Submission\SubmittedForm; use SilverStripe\UserForms\Model\Submission\SubmittedFormField; use SilverStripe\UserForms\Model\UserDefinedForm; use SilverStripe\Versioned\Versioned; /** * A helper to recover the UserForm uploads targeting folders incorrectly migrated from Silverstripe CMS 3 * * In short, the migrated folders do not have Live version records in the database, as such * all the files uploaded through UserForms EditableFileField end up in a default fallback folder (/Uploads by default) * * If your project has not been migrated from Silverstripe CMS 3, you do not need this helper. * For more details see CVE-2020-9280 * * @internal This class is not a part of Silverstripe CMS public API */ class RecoverUploadLocationsHelper { use Injectable; use Configurable; private static $dependencies = [ 'logger' => '%$' . LoggerInterface::class . '.quiet', ]; /** * @var LoggerInterface */ private $logger; /** * @var Versioned */ private $versionedExtension; /** * Whether File class has Versioned extension installed * * @var bool */ private $filesVersioned; /** * Cache of the EditableFileField versions * * @var EditableFileField */ private $fieldFolderCache = array(); public function __construct() { $this->logger = new NullLogger(); // Set up things before going into the loop $this->versionedExtension = Injector::inst()->get(Versioned::class); $this->filesVersioned = $this->versionedExtension->canBeVersioned(File::class); } /** * @param LoggerInterface $logger * @return $this */ public function setLogger(LoggerInterface $logger) { $this->logger = $logger; return $this; } /** * Process the UserForm uplodas * * @return int Number of files processed */ public function run() { // Set max time and memory limit Environment::increaseTimeLimitTo(); Environment::setMemoryLimitMax(-1); Environment::increaseMemoryLimitTo(-1); $this->logger->notice('Begin UserForm uploaded files destination folders recovery'); if (!class_exists(Versioned::class)) { $this->logger->warning('Versioned extension is not installed. Skipping recovery.'); return 0; } if (!$this->versionedExtension->canBeVersioned(UserDefinedForm::class)) { $this->logger->warning('Versioned extension is not set up for UserForms. Skipping recovery.'); return 0; } return $this->process(); } /** * Process all the files and return the number * * @return int Number of files processed */ protected function process() { // Check if we have folders to migrate $totalCount = $this->getCountQuery()->count(); if (!$totalCount) { $this->logger->warning('No UserForm uploads found'); return 0; } $this->logger->notice(sprintf('Processing %d file records', $totalCount)); $processedCount = 0; $recoveryCount = 0; $errorsCount = 0; // Loop over the files to process foreach ($this->chunk() as $uploadRecord) { ++$processedCount; $fileId = $uploadRecord['UploadedFileID']; $fieldId = $uploadRecord['FieldID']; $fieldVersion = $uploadRecord['FieldVersion']; try { $expectedFolderId = $this->getExpectedUploadFolderId($fieldId, $fieldVersion); if ($expectedFolderId == 0) { $this->logger->warning(sprintf( 'The upload folder was not set for the file %d, SKIPPING', $fileId )); continue; } $recoveryCount += $this->recover($fileId, $expectedFolderId); } catch (\Exception $e) { $this->logger->error(sprintf('Could not process the file: %d', $fileId), ['exception' => $e]); ++$errorsCount; } } // Show summary of results if ($processedCount > 0) { $this->logger->notice(sprintf('%d file records have been processed.', $processedCount)); $this->logger->notice(sprintf('%d files recovered', $recoveryCount)); $this->logger->notice(sprintf('%d errors', $errorsCount)); } else { $this->logger->notice('No files found'); } return $processedCount; } /** * Fetches the EditableFileField version from cache and returns its FolderID * * @param int $fieldId EditableFileField.ID * @param int EditableFileField Version * * @return int */ protected function getExpectedUploadFolderId($fieldId, $fieldVersion) { // return if cache is warm if (isset($this->fieldFolderCache[$fieldId][$fieldVersion])) { return $this->fieldFolderCache[$fieldId][$fieldVersion]->FolderID; } // fetch the version $editableFileField = Versioned::get_version(EditableFileField::class, $fieldId, $fieldVersion); // populate the cache $this->fieldFolderCache[$fieldId][$fieldVersion] = $editableFileField; return $editableFileField->FolderID; } /** * Fetches a Folder by its ID, gracefully handling * deleted folders * * @param int $id Folder.ID * * @return Folder * * @throws RuntimeException when folder could not be found */ protected function getFolder($id) { $folder = Folder::get()->byID($id); if (!$folder && $this->filesVersioned) { // The folder might have been deleted, let's look up its latest version $folder = Versioned::get_latest_version(Folder::class, $id); if ($folder) { $this->logger->warning(sprintf('Restoring (as protected) a deleted folder: "%s"', $folder->Filename)); if ($folder->CanViewType === InheritedPermissions::INHERIT) { // enforce restored top level folders to be protected $folder->CanViewType = InheritedPermissions::ONLY_THESE_USERS; } $folder->publishSingle(); } } if (!$folder) { throw new RuntimeException(sprintf('Could not fetch the folder with id "%d"', $id)); } return $folder; } /** * Recover an uploaded file location * * @param int $fileId File.ID * @param int $expectedFolderId ID of the folder where the file should have end up * * @return int Number of files recovered */ protected function recover($fileId, $expectedFolderId) { /* @var File */ $draft = null; /* @var File */ $live = null; if ($this->filesVersioned) { $draftVersion = Versioned::get_versionnumber_by_stage(File::class, Versioned::DRAFT, $fileId); $liveVersion = Versioned::get_versionnumber_by_stage(File::class, Versioned::LIVE, $fileId); if ($draftVersion && $draftVersion != $liveVersion) { $draft = Versioned::get_version(File::class, $fileId, $draftVersion); } else { $draft = null; } if ($liveVersion) { $live = Versioned::get_version(File::class, $fileId, $liveVersion); } } else { $live = File::get()->byID($fileId); } if (!$live) { $this->logger->notice(sprintf('Could not find file with id %d (perhaps it has been deleted)', $fileId)); return 0; } // Check whether the file has been modified (moved) after the upload if ($live->Version > 1) { if ($live->ParentID != $expectedFolderId) { // The file was updated after upload (perhaps was moved) // We should assume that was intentional and do not process // it, but rather make a warning here $this->logger->notice(sprintf( 'The file was updated after initial upload, skipping! "%s"', $live->getField('FileFilename') )); } // check for residual files in the original folder return $this->checkResidual($fileId, $live, $draft); } if ($live->ParentID == $expectedFolderId) { $this->logger->info(sprintf('OK: "%s"', $live->getField('FileFilename'))); return 0; } $this->logger->warning(sprintf('Found a misplaced file: "%s"', $live->getField('FileFilename'))); $expectedFolder = $this->getFolder($expectedFolderId); if ($draft) { return $this->recoverWithDraft($live, $draft, $expectedFolder); } else { return $this->recoverLiveOnly($live, $expectedFolder); } } /** * Handles gracefully a bug in UserForms that prevents * some uploaded files from being removed on the filesystem level * when manually moving them to another folder through CMS * * @see https://github.com/silverstripe/silverstripe-userforms/issues/944 * * @param int $fileId File.ID * @param File $file The live version of the file * @param File|null $draft The draft version of the file * * @return int Number of files recovered */ protected function checkResidual($fileId, File $file, ?File $draft = null) { if (!$this->filesVersioned) { return 0; } $upload = Versioned::get_version(File::class, $fileId, 1); if ($upload->ParentID == $file->ParentID) { // The file is published in the original folder, so we're good return 0; } if ($draft && $upload->ParentID == $draft->ParentID) { // The file draft is residing in the same folder where it // has been uploaded originally. It's under the draft's control now return 0; } $deleted = 0; $dbFile = $upload->File; if ($dbFile->exists()) { // Find if another file record refer to the same physical location $another = Versioned::get_by_stage(File::class, Versioned::LIVE, [ '"ID" != ?' => $fileId, '"FileFilename"' => $dbFile->Filename, '"FileHash"' => $dbFile->Hash, '"FileVariant"' => $dbFile->Variant ])->exists(); // A lazy check for draft (no check if we already found live) $another = $another || Versioned::get_by_stage(File::class, Versioned::DRAFT, [ '"ID" != ?' => $fileId, '"FileFilename"' => $dbFile->Filename, '"FileHash"' => $dbFile->Hash, '"FileVariant"' => $dbFile->Variant ])->exists(); if (!$another) { $this->logger->warning(sprintf('Found a residual file on the filesystem, going to delete it: "%s"', $dbFile->Filename)); if ($dbFile->deleteFile()) { $this->logger->warning(sprintf('DELETE: "%s"', $dbFile->Filename)); ++$deleted; } else { $this->logger->warning(sprintf('FAILED TO DELETE: "%s"', $dbFile->Filename)); } } } return $deleted; } /** * Recover a file with only Live version (with no draft) * * @param File $file the file instance * @param int $expectedFolder The expected folder * * @return int How many files have been recovered */ protected function recoverLiveOnly(File $file, Folder $expectedFolder) { $this->logger->warning(sprintf('MOVE: "%s" to %s', $file->Filename, $expectedFolder->Filename)); return $this->moveFileToFolder($file, $expectedFolder); } /** * Recover a live version of the file preserving the draft * * @param File $live Live version of the file * @param File $draft Draft version of the file * @param Folder $expectedFolder The expected folder * * @return int How many files have been recovered */ protected function recoverWithDraft(File $live, File $draft, Folder $expectedFolder) { $this->logger->warning(sprintf( 'MOVE: "%s" to "%s", preserving draft "%s"', $live->Filename, $expectedFolder->Filename, $draft->Filename )); $result = $this->moveFileToFolder($live, $expectedFolder); // Restore the DB record of the draft deleted after publishing $draft->writeToStage(Versioned::DRAFT); // This hack makes it copy the file on the filesystem level. // The file under the Filename link of the draft has been removed // when we published the updated live version of the file. $draft->File->Filename = $live->File->Filename; // If the draft parent folder has been deleted (e.g. the draft file was alone there) // we explicitly restore it here, otherwise it // will be lost and saved in the root directory $draft->Parent = $this->getFolder($draft->ParentID); // Save the draft and copy over the file from the Live version // on the filesystem level $draft->write(); return $result; } protected function moveFileToFolder(File $file, Folder $folder) { $file->Parent = $folder; $file->write(); $file->publishSingle(); return 1; } /** * Split queries into smaller chunks to avoid using too much memory * @param int $chunkSize * @return Generator */ private function chunk($chunkSize = 100) { $greaterThanID = 0; do { $count = 0; $chunk = $this->getQuery() ->setLimit($chunkSize) ->addWhere([ '"SubmittedFileFieldTable"."UploadedFileID" > ?' => $greaterThanID ])->execute(); foreach ($chunk as $item) { yield $item; $greaterThanID = $item['UploadedFileID']; ++$count; } } while ($count > 0); } /** * Returns SQLQuery instance * select SubmittedFileField.UploadedFileID, EditableFileField_Versions.RecordID as FieldID, MAX(EditableFileField_Versions.Version) as FieldVersion from SubmittedFileField left join SubmittedFormField on SubmittedFormField.ID = SubmittedFileField.ID left join SubmittedForm on SubmittedForm.ID = SubmittedFormField.ParentID left join EditableFormField_Versions on EditableFormField_Versions.ParentID = SubmittedForm.ParentID and EditableFormField_Versions.Name = SubmittedFormField.Name and EditableFormField_Versions.LastEdited < SubmittedForm.Created inner join EditableFileField_Versions on EditableFileField_Versions.RecordID = EditableFormField_Versions.RecordID and EditableFileField_Versions.Version = EditableFormField_Versions.Version where SubmittedFileField.UploadedFileID != 0 group by SubmittedFileField.UploadedFileID, EditableFileField_Versions.RecordID order by SubmittedFileField.UploadedFileID limit 100 */ private function getQuery() { $schema = DataObject::getSchema(); $submittedFileFieldTable = $schema->tableName(SubmittedFileField::class); $submittedFormFieldTable = $schema->tableName(SubmittedFormField::class); $submittedFormTable = $schema->tableName(SubmittedForm::class); $editableFileFieldTable = $schema->tableName(EditableFileField::class); $editableFileFieldVersionsTable = sprintf('%s_Versions', $editableFileFieldTable); $editableFormFieldTable = $schema->tableName(EditableFormField::class); $editableFormFieldVersionsTable = sprintf('%s_Versions', $editableFormFieldTable); return SQLSelect::create() ->setSelect([ '"SubmittedFileFieldTable"."UploadedFileID"', '"EditableFileFieldVersions"."RecordID" as "FieldID"', 'MAX("EditableFileFieldVersions"."Version") as "FieldVersion"' ]) ->setFrom(sprintf('%s as "SubmittedFileFieldTable"', Convert::symbol2sql($submittedFileFieldTable))) ->setWhere([ '"SubmittedFileFieldTable"."UploadedFileID" != 0' ]) ->setGroupBy([ '"SubmittedFileFieldTable"."UploadedFileID"', '"EditableFileFieldVersions"."RecordID"' ]) ->addLeftJoin( $submittedFormFieldTable, '"SubmittedFormFieldTable"."ID" = "SubmittedFileFieldTable"."ID"', 'SubmittedFormFieldTable' ) ->addLeftJoin( $submittedFormTable, '"SubmittedFormTable"."ID" = "SubmittedFormFieldTable"."ParentID"', 'SubmittedFormTable' ) ->addLeftJoin( $editableFormFieldVersionsTable, sprintf( '%s AND %s AND %s', '"EditableFormFieldVersions"."ParentID" = "SubmittedFormTable"."ParentID"', '"EditableFormFieldVersions"."Name" = "SubmittedFormFieldTable"."Name"', '"EditableFormFieldVersions"."LastEdited" < "SubmittedFormTable"."Created"' ), 'EditableFormFieldVersions' ) ->addInnerJoin( $editableFileFieldVersionsTable, sprintf( '%s AND %s', '"EditableFileFieldVersions"."RecordID" = "EditableFormFieldVersions"."RecordID"', '"EditableFileFieldVersions"."Version" = "EditableFormFieldVersions"."Version"' ), 'EditableFileFieldVersions' ) ->addOrderBy('"SubmittedFileFieldTable"."UploadedFileID"', 'ASC') ; } /** * Returns DataList object containing every * uploaded file record * * @return DataList<SubmittedFileField> */ private function getCountQuery() { return SubmittedFileField::get()->filter(['UploadedFileID:NOT' => 0]); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Control/UserDefinedFormAdmin.php
code/Control/UserDefinedFormAdmin.php
<?php namespace SilverStripe\UserForms\Control; use SilverStripe\Admin\FormSchemaController; use SilverStripe\Assets\Folder; use SilverStripe\Control\HTTPRequest; use SilverStripe\Control\HTTPResponse; use SilverStripe\Control\HTTPResponse_Exception; use SilverStripe\Forms\FieldList; use SilverStripe\Forms\Form; use SilverStripe\Forms\FormAction; use SilverStripe\Forms\HiddenField; use SilverStripe\Forms\LiteralField; use SilverStripe\Forms\OptionsetField; use SilverStripe\Forms\Validation\RequiredFieldsValidator; use SilverStripe\Forms\Schema\FormSchema; use SilverStripe\Forms\TextField; use SilverStripe\Forms\TreeDropdownField; use SilverStripe\Core\Validation\ValidationException; use SilverStripe\Security\Group; use SilverStripe\Security\InheritedPermissions; use SilverStripe\Security\Permission; use SilverStripe\Security\PermissionFailureException; use SilverStripe\Security\Security; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\Model\EditableFormField\EditableFileField; use SilverStripe\UserForms\Model\UserDefinedForm; use SilverStripe\Versioned\Versioned; /** * Provides a few endpoints the user form CMS UI targets with some AJAX request. */ class UserDefinedFormAdmin extends FormSchemaController { private static $allowed_actions = [ 'confirmfolderformschema', 'ConfirmFolderForm', 'confirmfolder', 'getfoldergrouppermissions', ]; private static $required_permission_codes = 'CMS_ACCESS_CMSMain'; private static $url_segment = 'user-forms'; /** * @var string The name of the folder where form submissions will be placed by default */ private static $form_submissions_folder = 'Form-submissions'; /** * Returns a TextField for entering a folder name. * @param string $folder The current folder to set the field to * @param string $title The title of the text field * @return TextField */ private static function getRestrictedAccessField(string $folder, string $title) { $textField = TextField::create('CreateFolder', ''); /** @var Folder $formSubmissionsFolder */ $formSubmissionsFolder = Folder::find($folder); $textField->setDescription(EditableFileField::getFolderPermissionString($formSubmissionsFolder)); $textField->addExtraClass('pt-2 userform-confirm-folder'); $textField->setSchemaData([ 'data' => [ 'prefix' => static::config()->get('form_submissions_folder') . '/', ], 'attributes' => [ 'placeholder' => $title ] ]); return $textField; } public function index(HTTPRequest $request): HTTPResponse { // Don't serve anythign under the main URL. return $this->httpError(404); } /** * This returns a Confirm Folder form schema used to verify the upload folder for EditableFileFields * @param HTTPRequest $request * @return HTTPResponse */ public function confirmfolderformschema(HTTPRequest $request) { // Retrieve editable form field by its ID $id = $request->requestVar('ID'); if (!$id) { throw new HTTPResponse_Exception(_t(__CLASS__.'.INVALID_REQUEST', 'This request was invalid.'), 400); } $editableFormField = EditableFormField::get()->byID($id); if (!$editableFormField) { $editableFormField = Versioned::get_by_stage(EditableFormField::class, Versioned::DRAFT) ->byID($id); } if (!$editableFormField) { throw new HTTPResponse_Exception(_t(__CLASS__.'.INVALID_REQUEST', 'This request was invalid.'), 400); } // Retrieve the editable form fields Parent $userForm = $editableFormField->Parent(); if (!$userForm) { throw new HTTPResponse_Exception(_t(__CLASS__.'.INVALID_REQUEST', 'This request was invalid.'), 400); } if (!$userForm->canEdit()) { throw new PermissionFailureException(); } // Get the folder we want to associate to this EditableFileField $folderId = 0; if ($editableFormField instanceof EditableFileField) { $folderId = $editableFormField->FolderID; } $folder = Folder::get()->byID($folderId); if (!$folder) { $folder = $this->getFormSubmissionFolder(); $folderId = $folder->ID; } $form = $this->buildConfirmFolderForm( $userForm->Title ?: '', EditableFileField::getFolderPermissionString($folder) ); $form->loadDataFrom(['FolderID' => $folderId, 'ID' => $id]); // Convert the EditableFormField to an EditableFileField if it's not already one. if (!$editableFormField instanceof EditableFileField) { $editableFormField = $editableFormField->newClassInstance(EditableFileField::class); $editableFormField->write(); } // create the schema response $parts = $this->getRequest()->getHeader(FormSchema::SCHEMA_HEADER); $schemaID = $this->getRequest()->getURL(); $data = FormSchema::singleton()->getMultipartSchema($parts, $schemaID, $form); // return the schema response $response = HTTPResponse::create(json_encode($data)); $response->addHeader('Content-Type', 'application/json'); return $response; } /** * Return the ConfirmFolderForm. This is only exposed so the treeview has somewhere to direct it's AJAX calss. * @return Form */ public function ConfirmFolderForm(): Form { return $this->buildConfirmFolderForm(); } /** * Build the ConfirmFolderForm * @param string $suggestedFolderName Suggested name for the folder name field * @param string $permissionFolderString Description to append to the treeview field * @return Form */ private function buildConfirmFolderForm(string $suggestedFolderName = '', string $permissionFolderString = ''): Form { // Build our Field list for the Form we will return to the front end. $fields = FieldList::create( LiteralField::create( 'LabelA', _t(__CLASS__.'.CONFIRM_FOLDER_LABEL_A', 'Files that your users upload should be stored carefully to reduce the risk of exposing sensitive data. Ensure the folder you select can only be viewed by appropriate parties. Folder permissions can be managed within the Files area.') )->addExtraClass(' mb-2'), LiteralField::create( 'LabelB', _t(__CLASS__.'.CONFIRM_FOLDER_LABEL_B', 'The folder selected will become the default for this form. This can be changed on an individual basis in the <i>File upload field.</i>') )->addExtraClass(' mb-3'), static::getRestrictedAccessField($this->config()->get('form_submissions_folder'), $suggestedFolderName), OptionsetField::create('FolderOptions', _t(__CLASS__.'.FOLDER_OPTIONS_TITLE', 'Form folder options'), [ "new" => _t(__CLASS__.'.FOLDER_OPTIONS_NEW', 'Create a new folder (recommended)'), "existing" => _t(__CLASS__.'.FOLDER_OPTIONS_EXISTING', 'Use an existing folder') ], "new"), TreeDropdownField::create('FolderID', '', Folder::class) ->addExtraClass('pt-1') ->setDescription($permissionFolderString), HiddenField::create('ID') ); $actions = FieldList::create( FormAction::create('confirmfolder', _t(__CLASS__.'.FORM_ACTION_CONFIRM', 'Save and continue')) ->setUseButtonTag(false) ->addExtraClass('btn btn-primary'), FormAction::create("cancel", _t(__CLASS__ . '.CANCEL', "Cancel")) ->addExtraClass('btn btn-secondary') ->setUseButtonTag(true) ); return Form::create($this, 'ConfirmFolderForm', $fields, $actions, RequiredFieldsValidator::create('ID')) ->setFormAction($this->Link('ConfirmFolderForm')) ->addExtraClass('form--no-dividers'); } /** * Sets the selected folder as the upload folder for an EditableFileField * @param array $data * @param Form $form * @param HTTPRequest $request * @return HTTPResponse * @throws ValidationException */ public function confirmfolder(array $data, Form $form, HTTPRequest $request) { if (!Permission::checkMember(null, "CMS_ACCESS_AssetAdmin")) { throw new PermissionFailureException(); } // retrieve the EditableFileField $id = $data['ID']; if (!$id) { throw new HTTPResponse_Exception(_t(__CLASS__.'.INVALID_REQUEST', 'This request was invalid.'), 400); } $editableFormField = EditableFormField::get()->byID($id); if (!$editableFormField) { $editableFormField = Versioned::get_by_stage(EditableFormField::class, Versioned::DRAFT)->byID($id); } if (!$editableFormField) { throw new HTTPResponse_Exception(_t(__CLASS__.'.INVALID_REQUEST', 'This request was invalid.'), 400); } // change the class if it is incorrect if (!$editableFormField instanceof EditableFileField) { $editableFormField = $editableFormField->newClassInstance(EditableFileField::class); } if (!$editableFormField) { throw new HTTPResponse_Exception(_t(__CLASS__.'.INVALID_REQUEST', 'This request was invalid.'), 400); } $editableFileField = $editableFormField; if (!$editableFileField->canEdit()) { throw new PermissionFailureException(); } // check if we're creating a new folder or using an existing folder $option = isset($data['FolderOptions']) ? $data['FolderOptions'] : ''; if ($option === 'existing') { // set existing folder $folderID = $data['FolderID']; if ($folderID != 0) { $folder = Folder::get()->byID($folderID); if (!$folder) { throw new HTTPResponse_Exception(_t(__CLASS__.'.INVALID_REQUEST', 'This request was invalid.'), 400); } } } else { // create the folder $createFolder = isset($data['CreateFolder']) ? $data['CreateFolder'] : $editableFormField->Parent()->Title; $folder = $this->getFormSubmissionFolder($createFolder); } // assign the folder $editableFileField->FolderID = isset($folder) ? $folder->ID : 0; $editableFileField->write(); // respond return HTTPResponse::create(json_encode([]))->addHeader('Content-Type', 'application/json'); } /** * Get the permission for a specific folder * @return HTTPResponse */ public function getfoldergrouppermissions() { $folderID = $this->getRequest()->requestVar('FolderID'); if ($folderID) { $folder = Folder::get()->byID($folderID); if (!$folder) { throw new HTTPResponse_Exception(_t(__CLASS__.'.INVALID_REQUEST', 'This request was invalid.'), 400); } if (!$folder->canView()) { throw new PermissionFailureException(); } } else { $folder = null; } // respond $response = HTTPResponse::create(json_encode(EditableFileField::getFolderPermissionString($folder))); $response->addHeader('Content-Type', 'application/json'); return $response; } /** * Set the permission for the default submisison folder. * @throws ValidationException */ private static function updateFormSubmissionFolderPermissions() { // ensure the FormSubmissions folder is only accessible to Administrators $formSubmissionsFolder = Folder::find(static::config()->get('form_submissions_folder')); $formSubmissionsFolder->CanViewType = InheritedPermissions::ONLY_THESE_USERS; $formSubmissionsFolder->ViewerGroups()->removeAll(); $formSubmissionsFolder->ViewerGroups()->add(Group::get()->setUseCache(true)->find('Code', 'administrators')); $formSubmissionsFolder->write(); } /** * Returns the form submission folder or a sub folder if provided. * Creates the form submission folder if it doesn't exist. * Updates the form submission folder permissions if it is created. * @param string $subFolder Sub-folder to be created or returned. * @return Folder * @throws ValidationException */ public static function getFormSubmissionFolder(?string $subFolder = null): ?Folder { $folderPath = static::config()->get('form_submissions_folder'); if ($subFolder) { $folderPath .= '/' . $subFolder; } $formSubmissionsFolderExists = !!Folder::find(static::config()->get('form_submissions_folder')); $folder = Folder::find_or_make($folderPath); // Set default permissions if this is the first time we create the form submission folder if (!$formSubmissionsFolderExists) { UserDefinedFormAdmin::updateFormSubmissionFolderPermissions(); // Make sure we return the folder with the latest permission $folder = Folder::find($folderPath); } return $folder; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Control/UserDefinedFormController.php
code/Control/UserDefinedFormController.php
<?php namespace SilverStripe\UserForms\Control; use Exception; use PageController; use Psr\Log\LoggerInterface; use SilverStripe\AssetAdmin\Controller\AssetAdmin; use SilverStripe\Assets\File; use SilverStripe\Assets\Upload; use SilverStripe\Control\Controller; use SilverStripe\Control\Email\Email; use SilverStripe\Control\HTTPRequest; use SilverStripe\Control\HTTPResponse; use SilverStripe\Core\Injector\Injector; use SilverStripe\Core\Manifest\ModuleLoader; use SilverStripe\Forms\Form; use SilverStripe\i18n\i18n; use SilverStripe\Model\List\ArrayList; use SilverStripe\ORM\FieldType\DBField; use SilverStripe\Core\Validation\ValidationException; use SilverStripe\Core\Validation\ValidationResult; use SilverStripe\Security\Security; use SilverStripe\UserForms\Extension\UserFormFileExtension; use SilverStripe\UserForms\Form\UserForm; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\Model\EditableFormField\EditableFileField; use SilverStripe\UserForms\Model\Submission\SubmittedForm; use SilverStripe\UserForms\Model\Submission\SubmittedFileField; use SilverStripe\UserForms\Model\UserDefinedForm; use SilverStripe\Versioned\Versioned; use SilverStripe\Model\ArrayData; use SilverStripe\View\Requirements; use SilverStripe\Model\ModelData; use SilverStripe\View\TemplateEngine; use SilverStripe\View\ViewLayerData; use Symfony\Component\Mime\Exception\RfcComplianceException; /** * Controller for the {@link UserDefinedForm} page type. * * @extends PageController<UserDefinedForm> */ class UserDefinedFormController extends PageController { private static $finished_anchor = '#uff'; private static $allowed_actions = [ 'index', 'ping', 'Form', 'finished', ]; /** @var string The name of the folder where form submissions will be placed by default */ private static $form_submissions_folder = 'Form-submissions'; private static string $file_upload_stage = Versioned::DRAFT; /** * Size that an uploaded file must not excede for it to be attached to an email * Follows PHP "shorthand bytes" definition rules. * @see UserDefinedFormController::parseByteSizeString() * * @var int * @config */ private static $maximum_email_attachment_size = '1M'; protected function init() { parent::init(); $page = $this->data(); // load the css if (!$page->config()->get('block_default_userforms_css')) { Requirements::css('silverstripe/userforms:client/dist/styles/userforms.css'); } // load the jquery if (!$page->config()->get('block_default_userforms_js')) { Requirements::javascript('silverstripe/userforms:client/dist/js/jquery.min.js'); Requirements::javascript( 'silverstripe/userforms:client/dist/js/jquery-validation/jquery.validate.min.js' ); Requirements::javascript('silverstripe/admin:client/dist/js/i18n.js'); Requirements::add_i18n_javascript('silverstripe/userforms:client/lang'); Requirements::javascript('silverstripe/userforms:client/dist/js/userforms.js'); $this->addUserFormsValidatei18n(); // Bind a confirmation message when navigating away from a partially completed form. if ($page::config()->get('enable_are_you_sure')) { Requirements::javascript( 'silverstripe/userforms:client/dist/js/jquery.are-you-sure/jquery.are-you-sure.js' ); } } } /** * Add the necessary jQuery validate i18n translation files, either by locale or by langauge, * e.g. 'en_NZ' or 'en'. This adds "methods_abc.min.js" as well as "messages_abc.min.js" from the * jQuery validate thirdparty library from dist/js. */ protected function addUserFormsValidatei18n() { $module = ModuleLoader::getModule('silverstripe/userforms'); $candidates = [ i18n::getData()->langFromLocale(i18n::config()->get('default_locale')), i18n::config()->get('default_locale'), i18n::getData()->langFromLocale(i18n::get_locale()), i18n::get_locale(), ]; foreach ($candidates as $candidate) { foreach (['messages', 'methods'] as $candidateType) { $localisationCandidate = "client/dist/js/jquery-validation/localization/{$candidateType}_{$candidate}.min.js"; $resource = $module->getResource($localisationCandidate); if ($resource->exists()) { Requirements::javascript($resource->getRelativePath()); } } } } /** * Using $UserDefinedForm in the Content area of the page shows * where the form should be rendered into. If it does not exist * then default back to $Form. * * @return array */ public function index(?HTTPRequest $request = null) { $form = $this->Form(); if ($this->Content && $form && !$this->config()->disable_form_content_shortcode) { $hasLocation = stristr($this->Content ?? '', '$UserDefinedForm'); if ($hasLocation) { /** @see Requirements_Backend::escapeReplacement */ $formEscapedForRegex = addcslashes($form->forTemplate() ?? '', '\\$'); $content = preg_replace( '/(<p[^>]*>)?\\$UserDefinedForm(<\\/p>)?/i', $formEscapedForRegex ?? '', $this->Content ?? '' ); return [ 'Content' => DBField::create_field('HTMLText', $content), 'Form' => '' ]; } } return [ 'Content' => DBField::create_field('HTMLText', $this->Content), 'Form' => $this->Form() ]; } /** * Keep the session alive for the user. * * @return int */ public function ping() { return 1; } /** * Get the form for the page. Form can be modified by calling {@link updateForm()} * on a UserDefinedForm extension. * * @return Form */ public function Form() { $form = UserForm::create($this, 'Form_' . $this->ID); $form->setFormAction(Controller::join_links($this->Link(), 'Form')); $this->generateConditionalJavascript(); return $form; } /** * Generate the javascript for the conditional field show / hiding logic. * * @return void */ public function generateConditionalJavascript() { $rules = ''; $form = $this->data(); if (!$form) { return; } $formFields = $form->Fields(); $watch = []; if ($formFields) { foreach ($formFields as $field) { if ($result = $field->formatDisplayRules()) { $watch[] = $result; } } } if ($watch) { $rules .= $this->buildWatchJS($watch); } // Only add customScript if $default or $rules is defined if ($rules) { Requirements::customScript(<<<JS (function($) { $(document).ready(function() { {$rules} }); })(jQuery); JS , 'UserFormsConditional-' . $form->ID); } } /** * Returns the maximum size uploaded files can be before they're excluded from CMS configured recipient emails * * @return int size in megabytes */ public function getMaximumAllowedEmailAttachmentSize() { return $this->parseByteSizeString($this->config()->get('maximum_email_attachment_size')); } /** * Convert file sizes with a single character for unit size to true byte count. * Just as with php.ini and e.g. 128M -> 1024 * 1024 * 128 bytes. * @see https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes * * @param string $byteSize * @return int bytes */ protected function parseByteSizeString($byteSize) { // kilo, mega, giga $validUnits = 'kmg'; $valid = preg_match("/^(?<number>\d+)((?<unit>[$validUnits])b?)?$/i", $byteSize, $matches); if (!$valid) { throw new \InvalidArgumentException( "Expected a positive integer followed optionally by K, M, or G. Found '$byteSize' instead" ); } $power = 0; // prepend b for bytes to $validUnits to give correct mapping of ordinal position to exponent if (isset($matches['unit'])) { $power = stripos("b$validUnits", $matches['unit']); } return intval($matches['number']) * pow(1024, $power); } /** * Process the form that is submitted through the site * * {@see UserForm::validate()} for validation step prior to processing * * @param array $data * @param Form $form * * @return HTTPResponse */ public function process($data, $form) { $submittedForm = SubmittedForm::create(); $submittedForm->SubmittedByID = Security::getCurrentUser() ? Security::getCurrentUser()->ID : 0; $submittedForm->ParentClass = get_class($this->data()); $submittedForm->ParentID = $this->ID; // if saving is not disabled save now to generate the ID if (!$this->DisableSaveSubmissions) { $submittedForm->write(); } $attachments = []; $submittedFields = ArrayList::create(); foreach ($this->data()->Fields() as $field) { if (!$field->showInReports()) { continue; } $submittedField = $field->getSubmittedFormField(); $submittedField->ParentID = $submittedForm->ID; $submittedField->Name = $field->Name; $submittedField->Title = $field->getField('Title'); // save the value from the data if ($field->hasMethod('getValueFromData')) { $submittedField->Value = $field->getValueFromData($data); } else { if (isset($data[$field->Name])) { $submittedField->Value = $data[$field->Name]; } } // set visibility flag according to display rules $submittedField->Displayed = $field->isDisplayed($data); if (!empty($data[$field->Name])) { if (in_array(EditableFileField::class, $field->getClassAncestry() ?? [])) { if (!empty($_FILES[$field->Name]['name'])) { if (!$field->getFolderExists()) { $field->createProtectedFolder(); } $file = Versioned::withVersionedMode(function () use ($field, $form) { $stage = Injector::inst()->get(UserDefinedFormController::class)->config()->get('file_upload_stage'); Versioned::set_stage($stage); $foldername = $field->getFormField()->getFolderName(); // create the file from post data $upload = Upload::create(); try { $upload->loadIntoFile($_FILES[$field->Name], null, $foldername); } catch (ValidationException $e) { $validationResult = $e->getResult(); foreach ($validationResult->getMessages() as $message) { $form->sessionMessage($message['message'], ValidationResult::TYPE_ERROR); } Controller::curr()->redirectBack(); return null; } /** @var AssetContainer|File $file */ $file = $upload->getFile(); $file->ShowInSearch = 0; $file->UserFormUpload = UserFormFileExtension::USER_FORM_UPLOAD_TRUE; $file->write(); return $file; }); if (is_null($file)) { return; } // generate image thumbnail to show in asset-admin // you can run userforms without asset-admin, so need to ensure asset-admin is installed if (class_exists(AssetAdmin::class)) { AssetAdmin::singleton()->generateThumbnails($file); } // write file to form field $submittedField->UploadedFileID = $file->ID; // attach a file to recipient email only if lower than configured size if ($file->getAbsoluteSize() <= $this->getMaximumAllowedEmailAttachmentSize()) { // using the field name as array index is fine as file upload field only allows one file $attachments[$field->Name] = $file; } } } } $submittedField->extend('onPopulationFromField', $field); if (!$this->DisableSaveSubmissions) { $submittedField->write(); } $submittedFields->push($submittedField); } $visibleSubmittedFields = $submittedFields->filter('Displayed', true); $emailData = [ 'Sender' => Security::getCurrentUser(), 'HideFormData' => false, 'SubmittedForm' => $submittedForm, 'Fields' => $submittedFields, 'Body' => '', ]; $this->extend('updateEmailData', $emailData, $attachments); // email users on submit. if ($recipients = $this->FilteredEmailRecipients($data, $form)) { foreach ($recipients as $recipient) { $email = Email::create() ->setHTMLTemplate('email/SubmittedFormEmail') ->setPlainTemplate('email/SubmittedFormEmailPlain'); // Merge fields are used for CMS authors to reference specific form fields in email content $mergeFields = $this->getMergeFieldsMap($emailData['Fields']); if ($attachments && (bool) $recipient->HideFormData === false) { foreach ($attachments as $uploadFieldName => $file) { /** @var File $file */ if ((int) $file->ID === 0) { continue; } $canAttachFileForRecipient = true; $this->extend('updateCanAttachFileForRecipient', $canAttachFileForRecipient, $recipient, $uploadFieldName, $file); if ($canAttachFileForRecipient) { $email->addAttachmentFromData( $file->getString(), $file->getFilename(), $file->getMimeType() ); } } } if (!$recipient->SendPlain && $recipient->emailTemplateExists()) { $email->setHTMLTemplate($recipient->EmailTemplate); } // Add specific template data for the current recipient $emailData['HideFormData'] = (bool) $recipient->HideFormData; // Include any parsed merge field references from the CMS editor - this is already escaped // This string substitution works for both HTML and plain text emails. // $recipient->getEmailBodyContent() will retrieve the relevant version of the email $engine = Injector::inst()->create(TemplateEngine::class); $emailData['Body'] = $engine->renderString($recipient->getEmailBodyContent(), ViewLayerData::create($mergeFields)); // only include visible fields if recipient visibility flag is set if ((bool) $recipient->HideInvisibleFields) { $emailData['Fields'] = $visibleSubmittedFields; } // Push the template data to the Email's data foreach ($emailData as $key => $value) { $email->addData($key, $value); } // check to see if they are a dynamic reply to. eg based on a email field a user selected $emailFrom = $recipient->SendEmailFromField(); if ($emailFrom && $emailFrom->exists()) { $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailFromField()->Name); if ($submittedFormField && $submittedFormField->Value && is_string($submittedFormField->Value)) { $emailSendTo = $this->validEmailsToArray($submittedFormField->Value); $email->addReplyTo(...$emailSendTo); } } elseif ($recipient->EmailReplyTo) { $emailReplyTo = $this->validEmailsToArray($recipient->EmailReplyTo); $email->addReplyTo(...$emailReplyTo); } // check for a specified from; otherwise fall back to server defaults if ($recipient->EmailFrom) { $email->setFrom($this->validEmailsToArray($recipient->EmailFrom)); } // check to see if they are a dynamic reciever eg based on a dropdown field a user selected $emailTo = $recipient->SendEmailToField(); try { if ($emailTo && $emailTo->exists()) { $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailToField()->Name); if ($submittedFormField && is_string($submittedFormField->Value)) { $email->setTo($this->validEmailsToArray($submittedFormField->Value)); } else { $email->setTo($this->validEmailsToArray($recipient->EmailAddress)); } } else { $email->setTo($this->validEmailsToArray($recipient->EmailAddress)); } } catch (RfcComplianceException $e) { // The sending address is empty and/or invalid. Log and skip sending. $error = sprintf( 'Failed to set sender for userform submission %s: %s', $submittedForm->ID, $e->getMessage() ); Injector::inst()->get(LoggerInterface::class)->notice($error); continue; } // check to see if there is a dynamic subject $emailSubject = $recipient->SendEmailSubjectField(); if ($emailSubject && $emailSubject->exists()) { $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailSubjectField()->Name); if ($submittedFormField && trim($submittedFormField->Value ?? '')) { $email->setSubject($submittedFormField->Value); } else { $email->setSubject($engine->renderString($recipient->EmailSubject, ViewLayerData::create($mergeFields))); } } else { $email->setSubject($engine->renderString($recipient->EmailSubject, ViewLayerData::create($mergeFields))); } $this->extend('updateEmail', $email, $recipient, $emailData); if ((bool)$recipient->SendPlain) { // decode previously encoded html tags because the email is being sent as text/plain $body = html_entity_decode($emailData['Body'] ?? '') . "\n"; if (isset($emailData['Fields']) && !$emailData['HideFormData']) { foreach ($emailData['Fields'] as $field) { if ($field instanceof SubmittedFileField) { $body .= $field->Title . ': ' . $field->ExportValue ." \n"; } else { $body .= $field->Title . ': ' . $field->Value . " \n"; } } } $email->setBody($body); try { $email->sendPlain(); } catch (Exception $e) { Injector::inst()->get(LoggerInterface::class)->error($e); } } else { try { $email->send(); } catch (Exception $e) { Injector::inst()->get(LoggerInterface::class)->error($e); } } } } $submittedForm->extend('updateAfterProcess', $emailData, $attachments); $session = $this->getRequest()->getSession(); $session->clear("FormInfo.{$form->FormName()}.errors"); $session->clear("FormInfo.{$form->FormName()}.data"); $referrer = (isset($data['Referrer'])) ? '?referrer=' . urlencode($data['Referrer']) : ""; // set a session variable from the security ID to stop people accessing // the finished method directly. if (!$this->DisableAuthenicatedFinishAction) { if (isset($data['SecurityID'])) { $session->set('FormProcessed', $data['SecurityID']); } else { // if the form has had tokens disabled we still need to set FormProcessed // to allow us to get through the finshed method if (!$this->Form()->getSecurityToken()->isEnabled()) { $randNum = rand(1, 1000); $randHash = md5($randNum ?? ''); $session->set('FormProcessed', $randHash); $session->set('FormProcessedNum', $randNum); } } } if (!$this->DisableSaveSubmissions) { $session->set('userformssubmission'. $this->ID, $submittedForm->ID); } return $this->redirect($this->Link('finished') . $referrer . $this->config()->get('finished_anchor')); } /** * Allows the use of field values in email body. * * @param ArrayList $fields * @return ArrayData */ protected function getMergeFieldsMap($fields = []) { $data = ArrayData::create([]); foreach ($fields as $field) { $data->setField($field->Name, DBField::create_field('Text', $field->Value)); } return $data; } /** * This action handles rendering the "finished" message, which is * customizable by editing the ReceivedFormSubmission template. * * @return ModelData */ public function finished() { $submission = $this->getRequest()->getSession()->get('userformssubmission'. $this->ID); if ($submission) { $submission = SubmittedForm::get()->byId($submission); } $referrer = isset($_GET['referrer']) ? urldecode($_GET['referrer']) : null; if (!$this->DisableAuthenicatedFinishAction) { $formProcessed = $this->getRequest()->getSession()->get('FormProcessed'); if (!isset($formProcessed)) { return $this->redirect($this->Link() . $referrer); } else { $securityID = $this->getRequest()->getSession()->get('SecurityID'); // make sure the session matches the SecurityID and is not left over from another form if ($formProcessed != $securityID) { // they may have disabled tokens on the form $securityID = md5($this->getRequest()->getSession()->get('FormProcessedNum') ?? ''); if ($formProcessed != $securityID) { return $this->redirect($this->Link() . $referrer); } } } $this->getRequest()->getSession()->clear('FormProcessed'); } $data = [ 'Submission' => $submission, 'Link' => $referrer ]; $this->extend('updateReceivedFormSubmissionData', $data); return $this->customise([ 'Content' => $this->customise($data)->renderWith(__CLASS__ . '_ReceivedFormSubmission'), 'Form' => '', ]); } /** * Outputs the required JS from the $watch input * * @param array $watch * * @return string */ protected function buildWatchJS($watch) { $result = ''; foreach ($watch as $key => $rule) { $events = implode(' ', $rule['events']); $selectors = implode(', ', $rule['selectors']); $conjunction = $rule['conjunction']; $operations = implode(" {$conjunction} ", $rule['operations']); $target = $rule['targetFieldID']; $holder = $rule['holder']; $isFormStep = strpos($target ?? '', 'EditableFormStep') !== false; $result .= <<<EOS \n $('.userform').on('{$events}', "{$selectors}", function (){ if ({$operations}) { $('{$target}').{$rule['view']}; {$holder}.{$rule['view']}.trigger('{$rule['holder_event']}'); } else { $('{$target}').{$rule['opposite']}; {$holder}.{$rule['opposite']}.trigger('{$rule['holder_event_opposite']}'); } }); EOS; if ($isFormStep) { // Hide the step jump button if the FormStep has is initially hidden. // This is particularly important beacause the next/prev page buttons logic is controlled by // the visibility of the FormStep buttons // The HTML for the FormStep buttons is defined in the UserFormProgress template $id = str_replace('#', '', $target ?? ''); $result .= <<<EOS $('.step-button-wrapper[data-for="{$id}"]').addClass('hide'); EOS; } else { // If a field's initial state is set to be hidden, a '.hide' class will be added to the field as well // as the fieldholder. Afterwards, JS only removes it from the fieldholder, thus the field stays hidden. // We'll update update the JS so that the '.hide' class is removed from the field from the beginning, // though we need to ensure we don't do this on FormSteps (page breaks) otherwise we'll mistakenly // target fields contained within the formstep $result .= <<<EOS $("{$target}").find('.hide').removeClass('hide'); EOS; } } return $result; } /** * Check validity of email and return array of valid emails */ private function validEmailsToArray(?string $emails): array { $emailsArray = []; $emails = explode(',', $emails ?? ''); foreach ($emails as $email) { $email = trim($email); if (Email::is_valid_address($email)) { $emailsArray[] = $email; } } return $emailsArray; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Extensions/UsedOnTableExtension.php
code/Extensions/UsedOnTableExtension.php
<?php namespace SilverStripe\UserForms\Extensions; use SilverStripe\Admin\Forms\UsedOnTable; use SilverStripe\Core\Extension; use SilverStripe\ORM\DataObject; use SilverStripe\UserForms\Model\EditableFormField; use SilverStripe\UserForms\Model\Submission\SubmittedFileField; use SilverStripe\UserForms\Model\Submission\SubmittedForm; use SilverStripe\UserForms\Model\UserDefinedForm; /** * Update DataObjects on the file "Used On" table * * @extends Extension<UsedOnTable> */ class UsedOnTableExtension extends Extension { /** * Link submitted file fields to their parent page * * @param array $ancestorDataObjects * @param DataObject $dataObject|null */ protected function updateUsageDataObject(?DataObject &$dataObject) { if (!($dataObject instanceof SubmittedFileField)) { return; } $submittedForm = $dataObject->Parent(); if (!$submittedForm) { $dataObject = null; return; } // Display the submitted form instead of the submitted file field $dataObject = $submittedForm; } /** * @param array $ancestorDataObjects * @param DataObject $dataObject */ protected function updateUsageAncestorDataObjects(array &$ancestorDataObjects, DataObject $dataObject) { // SubmittedFileField was changed to a Submitted Form in updateUsageModifyOrExcludeDataObject() if (!($dataObject instanceof SubmittedForm)) { return; } /** @var UserDefinedForm $page */ $page = $dataObject->Parent(); if (!$page) { return; } // Use an un-persisted DataObject with a 'Title' field to display the word 'Submissions' $submissions = new EditableFormField(); $submissions->Title = 'Submissions'; $ancestorDataObjects[] = $submissions; $ancestorDataObjects[] = $page; } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Modifier/UnderscoreSegmentFieldModifier.php
code/Modifier/UnderscoreSegmentFieldModifier.php
<?php namespace SilverStripe\UserForms\Modifier; use SilverStripe\Forms\SegmentFieldModifier\SlugSegmentFieldModifier; class UnderscoreSegmentFieldModifier extends SlugSegmentFieldModifier { public function getPreview($value) { return str_replace('-', '_', parent::getPreview($value) ?? ''); } public function getSuggestion($value) { return str_replace('-', '_', parent::getSuggestion($value) ?? ''); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
silverstripe/silverstripe-userforms
https://github.com/silverstripe/silverstripe-userforms/blob/e33fff165d33a077ec4b20c2eef2ef8bca25d15a/code/Modifier/DisambiguationSegmentFieldModifier.php
code/Modifier/DisambiguationSegmentFieldModifier.php
<?php namespace SilverStripe\UserForms\Modifier; use SilverStripe\Forms\Form; use SilverStripe\Forms\SegmentFieldModifier\AbstractSegmentFieldModifier; use SilverStripe\UserForms\Model\EditableFormField; class DisambiguationSegmentFieldModifier extends AbstractSegmentFieldModifier { public function getPreview($value) { if ($this->form instanceof Form && $record = $this->form->getRecord()) { $parent = $record->Parent(); $try = $value; $sibling = EditableFormField::get() ->filter('ParentID', $parent->ID) ->filter('Name', $try) ->where('"ID" != ' . $record->ID) ->first(); $counter = 1; while ($sibling !== null) { $try = $value . '_' . $counter++; $sibling = EditableFormField::get() ->filter('ParentID', $parent->ID) ->filter('Name', $try) ->first(); } if ($try !== $value) { return $try; } } return $value; } public function getSuggestion($value) { return $this->getPreview($value); } }
php
BSD-3-Clause
e33fff165d33a077ec4b20c2eef2ef8bca25d15a
2026-01-05T05:22:58.009669Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Traits/CanVerifyEmail.php
src/Traits/CanVerifyEmail.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Traits; trait CanVerifyEmail { /** * {@inheritdoc} */ public function getEmailForVerification(): string { return $this->email; } /** * {@inheritdoc} */ public function hasVerifiedEmail(): bool { return ! is_null($this->email_verified_at); } /** * {@inheritdoc} */ public function sendEmailVerificationNotification(string $token, int $expiration): void { ! $this->emailVerificationNotificationClass || $this->notify(new $this->emailVerificationNotificationClass($token, $expiration)); } }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Traits/CanVerifyPhone.php
src/Traits/CanVerifyPhone.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Traits; trait CanVerifyPhone { /** * {@inheritdoc} */ public function getPhoneForVerification(): ?string { return $this->phone; } /** * {@inheritdoc} */ public function getCountryForVerification(): ?string { return $this->country_code ? country($this->country_code)->getCallingCode() : null; } /** * {@inheritdoc} */ public function hasVerifiedPhone(): bool { return ! is_null($this->phone_verified_at); } /** * {@inheritdoc} */ public function sendPhoneVerificationNotification(string $method, bool $force): void { ! $this->phoneVerificationNotificationClass || $this->notify(new $this->phoneVerificationNotificationClass($method, $force)); } }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Traits/CanResetPassword.php
src/Traits/CanResetPassword.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Traits; trait CanResetPassword { /** * {@inheritdoc} */ public function getEmailForPasswordReset(): string { return $this->email; } /** * {@inheritdoc} */ public function sendPasswordResetNotification(string $token, int $expiration): void { ! $this->passwordResetNotificationClass || $this->notify(new $this->passwordResetNotificationClass($token, $expiration)); } }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Traits/AuthenticatableTwoFactor.php
src/Traits/AuthenticatableTwoFactor.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Traits; trait AuthenticatableTwoFactor { /** * Get the TwoFactor options. * * @return array|null */ public function getTwoFactor(): ?array { return $this->two_factor; } }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Traits/HasHashables.php
src/Traits/HasHashables.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Traits; trait HasHashables { /** * Get the current hashables for the model. * * @return array|null */ public function getHashables(): ?array { return $this->hashables ?? null; } /** * Set the hashables associated with the model. * * @param array $hashables * * @return $this */ public function setHashables(array $hashables) { $this->hashables = $hashables; return $this; } }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Support/helpers.php
src/Support/helpers.php
<?php declare(strict_types=1); if (! function_exists('get_login_field')) { /** * Get the login field to be used. * * @param string $loginfield * * @return string */ function get_login_field($loginfield) { return ! $loginfield || filter_var($loginfield, FILTER_VALIDATE_EMAIL) ? 'email' : 'username'; } }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Services/PasswordResetBrokerManager.php
src/Services/PasswordResetBrokerManager.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Services; use InvalidArgumentException; use Illuminate\Contracts\Auth\PasswordBrokerFactory; use Rinvex\Auth\Contracts\PasswordResetBrokerContract; class PasswordResetBrokerManager implements PasswordBrokerFactory { /** * The application instance. * * @var \Illuminate\Foundation\Application */ protected $app; /** * The array of created "drivers". * * @var array */ protected $brokers = []; /** * Create a new PasswordResetBroker manager instance. * * @param \Illuminate\Foundation\Application $app */ public function __construct($app) { $this->app = $app; } /** * Attempt to get the broker from the local cache. * * @param string $name * * @return \Rinvex\Auth\Contracts\PasswordResetBrokerContract */ public function broker($name = null): PasswordResetBrokerContract { $name = $name ?: $this->getDefaultDriver(); return $this->brokers[$name] ?? $this->brokers[$name] = $this->resolve($name); } /** * Resolve the given broker. * * @param string $name * * @throws \InvalidArgumentException * * @return \Rinvex\Auth\Contracts\PasswordResetBrokerContract */ protected function resolve($name): PasswordResetBrokerContract { $config = $this->getConfig($name); if (is_null($config)) { throw new InvalidArgumentException("Password resetter [{$name}] is not defined."); } return new PasswordResetBroker( $this->app['auth']->createUserProvider($config['provider']), $this->app['config']['app.key'], $config['expire'] ); } /** * Get the password reset broker configuration. * * @param string $name * * @return array */ protected function getConfig($name): array { return $this->app['config']["auth.passwords.{$name}"]; } /** * Get the default password reset broker name. * * @return string */ public function getDefaultDriver(): string { return $this->app['config']['auth.defaults.passwords']; } /** * Set the default password reset broker name. * * @param string $name * * @return void */ public function setDefaultDriver($name): void { $this->app['config']['auth.defaults.passwords'] = $name; } /** * Dynamically call the default driver instance. * * @param string $method * @param array $parameters * * @return mixed */ public function __call($method, $parameters) { return $this->broker()->{$method}(...$parameters); } }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Services/PasswordResetBroker.php
src/Services/PasswordResetBroker.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Services; use Closure; use Illuminate\Support\Carbon; use Illuminate\Support\Arr; use Illuminate\Support\Str; use UnexpectedValueException; use Illuminate\Contracts\Auth\UserProvider; use Rinvex\Auth\Contracts\CanResetPasswordContract; use Rinvex\Auth\Contracts\PasswordResetBrokerContract; class PasswordResetBroker implements PasswordResetBrokerContract { /** * The application key. * * @var string */ protected $key; /** * The user provider implementation. * * @var \Illuminate\Contracts\Auth\UserProvider */ protected $users; /** * The number of minutes that the reset token should be considered valid. * * @var int */ protected $expiration; /** * Create a new verification broker instance. * * @param \Illuminate\Contracts\Auth\UserProvider $users * @param string $key * @param int $expiration */ public function __construct(UserProvider $users, $key, $expiration) { $this->key = $key; $this->users = $users; $this->expiration = $expiration; } /** * Send a password reset link to a user. * * @param array $credentials * @param \Closure|null $callback * * @return string */ public function sendResetLink(array $credentials, Closure $callback = null) { // First we will check to see if we found a user at the given credentials and // if we did not we will redirect back to this current URI with a piece of // "flash" data in the session to indicate to the developers the errors. $user = $this->getUser($credentials); if (is_null($user)) { return static::INVALID_USER; } $expiration = Carbon::now()->addMinutes($this->expiration)->timestamp; // Once we have the reset token, we are ready to send the message out to this // user with a link to reset their password. We will then redirect back to // the current URI having nothing set in the session to indicate errors. $user->sendPasswordResetNotification($this->createToken($user, $expiration), $expiration); return static::RESET_LINK_SENT; } /** * Reset the password for the given token. * * @param array $credentials * @param \Closure $callback * * @return mixed */ public function reset(array $credentials, Closure $callback) { $user = $this->validateReset($credentials); // If the responses from the validate method is not a user instance, we will // assume that it is a redirect and simply return it from this method and // the user is properly redirected having an error message on the post. if (! $user instanceof CanResetPasswordContract) { return $user; } $password = $credentials['password']; // Once the reset has been validated, we'll call the given callback with the // new password. This gives the user an opportunity to store the password // in their persistent storage. $callback($user, $password); return static::PASSWORD_RESET; } /** * Get the user for the given credentials. * * @param array $credentials * * @throws \UnexpectedValueException * * @return \Rinvex\Auth\Contracts\CanResetPasswordContract|null */ public function getUser(array $credentials): ?CanResetPasswordContract { $user = $this->users->retrieveByCredentials(Arr::only($credentials, ['email'])); if ($user && ! $user instanceof CanResetPasswordContract) { throw new UnexpectedValueException('User must implement CanResetPassword interface.'); } return $user; } /** * Create a new password reset token for the given user. * * @param \Rinvex\Auth\Contracts\CanResetPasswordContract $user * @param int $expiration * * @return string */ public function createToken(CanResetPasswordContract $user, $expiration): string { $payload = $this->buildPayload($user, $user->getEmailForPasswordReset(), $expiration); return hash_hmac('sha256', $payload, $this->getKey()); } /** * Validate the given password reset token. * * @param \Rinvex\Auth\Contracts\CanResetPasswordContract $user * @param array $credentials * * @return bool */ public function validateToken(CanResetPasswordContract $user, array $credentials): bool { $payload = $this->buildPayload($user, $credentials['email'], $credentials['expiration']); return hash_equals($credentials['token'], hash_hmac('sha256', $payload, $this->getKey())); } /** * Validate the given expiration timestamp. * * @param int $expiration * * @return bool */ public function validateTimestamp($expiration): bool { return Carbon::now()->createFromTimestamp($expiration)->isFuture(); } /** * Return the application key. * * @return string */ public function getKey(): string { if (Str::startsWith($this->key, 'base64:')) { return base64_decode(mb_substr($this->key, 7)); } return $this->key; } /** * Returns the payload string containing. * * @param \Rinvex\Auth\Contracts\CanResetPasswordContract $user * @param string $email * @param int $expiration * * @return string */ protected function buildPayload(CanResetPasswordContract $user, $email, $expiration): string { return implode(';', [ $email, $expiration, $user->getKey(), $user->password, ]); } /** * Validate a password reset for the given credentials. * * @param array $credentials * * @return \Illuminate\Contracts\Auth\CanResetPassword|string */ protected function validateReset(array $credentials) { if (is_null($user = $this->getUser($credentials))) { return static::INVALID_USER; } if (! $this->validateToken($user, $credentials)) { return static::INVALID_TOKEN; } if (! $this->validateTimestamp($credentials['expiration'])) { return static::EXPIRED_TOKEN; } return $user; } }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Services/EmailVerificationBroker.php
src/Services/EmailVerificationBroker.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Services; use Closure; use Illuminate\Support\Carbon; use Illuminate\Support\Arr; use Illuminate\Support\Str; use UnexpectedValueException; use Illuminate\Contracts\Auth\UserProvider; use Rinvex\Auth\Contracts\CanVerifyEmailContract; use Rinvex\Auth\Contracts\EmailVerificationBrokerContract; class EmailVerificationBroker implements EmailVerificationBrokerContract { /** * The application key. * * @var string */ protected $key; /** * The user provider implementation. * * @var \Illuminate\Contracts\Auth\UserProvider */ protected $users; /** * The number of minutes that the reset token should be considered valid. * * @var int */ protected $expiration; /** * Create a new verification broker instance. * * @param \Illuminate\Contracts\Auth\UserProvider $users * @param string $key * @param int $expiration */ public function __construct(UserProvider $users, $key, $expiration) { $this->key = $key; $this->users = $users; $this->expiration = $expiration; } /** * {@inheritdoc} */ public function sendVerificationLink(array $credentials): string { // First we will check to see if we found a user at the given credentials and // if we did not we will redirect back to this current URI with a piece of // "flash" data in the session to indicate to the developers the errors. if (is_null($user = $this->getUser($credentials))) { return static::INVALID_USER; } $expiration = Carbon::now()->addMinutes($this->expiration)->timestamp; // Once we have the verification token, we are ready to send the message out to // this user with a link to verify their email. We will then redirect back to // the current URI having nothing set in the session to indicate any errors $user->sendEmailVerificationNotification($this->createToken($user, $expiration), $expiration); return static::LINK_SENT; } /** * {@inheritdoc} */ public function verify(array $credentials, Closure $callback) { // If the responses from the validate method is not a user instance, we will // assume that it is a redirect and simply return it from this method and // the user is properly redirected having an error message on the post. $user = $this->validateVerification($credentials); if (! $user instanceof CanVerifyEmailContract) { return $user; } // Once the email has been verified, we'll call the given // callback, then we'll delete the token and return. // in their persistent storage. $callback($user); return static::EMAIL_VERIFIED; } /** * Get the user for the given credentials. * * @param array $credentials * * @throws \UnexpectedValueException * * @return \Rinvex\Auth\Contracts\CanVerifyEmailContract|null */ public function getUser(array $credentials): ?CanVerifyEmailContract { $user = $this->users->retrieveByCredentials(Arr::only($credentials, ['email'])); if ($user && ! $user instanceof CanVerifyEmailContract) { throw new UnexpectedValueException('User must implement CanVerifyEmailContract interface.'); } return $user; } /** * Create a new email verification token for the given user. * * @param \Rinvex\Auth\Contracts\CanVerifyEmailContract $user * @param int $expiration * * @return string */ public function createToken(CanVerifyEmailContract $user, $expiration): string { $payload = $this->buildPayload($user, $user->getEmailForVerification(), $expiration); return hash_hmac('sha256', $payload, $this->getKey()); } /** * Validate the given email verification token. * * @param \Rinvex\Auth\Contracts\CanVerifyEmailContract $user * @param array $credentials * * @return bool */ public function validateToken(CanVerifyEmailContract $user, array $credentials): bool { $payload = $this->buildPayload($user, $credentials['email'], $credentials['expiration']); return hash_equals($credentials['token'], hash_hmac('sha256', $payload, $this->getKey())); } /** * Validate the given expiration timestamp. * * @param int $expiration * * @return bool */ public function validateTimestamp($expiration): bool { return Carbon::now()->createFromTimestamp($expiration)->isFuture(); } /** * Return the application key. * * @return string */ public function getKey(): string { if (Str::startsWith($this->key, 'base64:')) { return base64_decode(mb_substr($this->key, 7)); } return $this->key; } /** * Returns the payload string containing. * * @param \Rinvex\Auth\Contracts\CanVerifyEmailContract $user * @param string $email * @param int $expiration * * @return string */ protected function buildPayload(CanVerifyEmailContract $user, $email, $expiration): string { return implode(';', [ $email, $expiration, $user->getKey(), $user->password, ]); } /** * Validate an email verification for the given credentials. * * @param array $credentials * * @return \Rinvex\Auth\Contracts\CanVerifyEmailContract|string */ protected function validateVerification(array $credentials) { if (is_null($user = $this->getUser($credentials))) { return static::INVALID_USER; } if (! $this->validateToken($user, $credentials)) { return static::INVALID_TOKEN; } if (! $this->validateTimestamp($credentials['expiration'])) { return static::EXPIRED_TOKEN; } return $user; } }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Services/EmailVerificationBrokerManager.php
src/Services/EmailVerificationBrokerManager.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Services; use InvalidArgumentException; use Rinvex\Auth\Contracts\EmailVerificationBrokerContract; use Rinvex\Auth\Contracts\EmailVerificationBrokerFactoryContract; class EmailVerificationBrokerManager implements EmailVerificationBrokerFactoryContract { /** * The application instance. * * @var \Illuminate\Foundation\Application */ protected $app; /** * The array of created "drivers". * * @var array */ protected $brokers = []; /** * Create a new EmailVerificationBroker manager instance. * * @param \Illuminate\Foundation\Application $app */ public function __construct($app) { $this->app = $app; } /** * Attempt to get the broker from the local cache. * * @param string $name * * @return \Rinvex\Auth\Contracts\EmailVerificationBrokerContract */ public function broker($name = null): EmailVerificationBrokerContract { $name = $name ?: $this->getDefaultDriver(); return $this->brokers[$name] ?? $this->brokers[$name] = $this->resolve($name); } /** * Resolve the given broker. * * @param string $name * * @throws \InvalidArgumentException * * @return \Rinvex\Auth\Contracts\EmailVerificationBrokerContract */ protected function resolve($name): EmailVerificationBrokerContract { $config = $this->getConfig($name); if (is_null($config)) { throw new InvalidArgumentException("Email verification broker [{$name}] is not defined."); } return new EmailVerificationBroker( $this->app['auth']->createUserProvider($config['provider']), $this->app['config']['app.key'], $config['expire'] ); } /** * Get the email verification broker configuration. * * @param string $name * * @return array */ protected function getConfig($name): array { return $this->app['config']["auth.emails.{$name}"]; } /** * Get the default email verification broker name. * * @return string */ public function getDefaultDriver(): string { return $this->app['config']['auth.defaults.emails']; } /** * Set the default email verification broker name. * * @param string $name * * @return void */ public function setDefaultDriver($name): void { $this->app['config']['auth.defaults.emails'] = $name; } /** * Dynamically call the default driver instance. * * @param string $method * @param array $parameters * * @return mixed */ public function __call($method, $parameters) { return $this->broker()->{$method}(...$parameters); } }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Contracts/AuthenticatableTwoFactorContract.php
src/Contracts/AuthenticatableTwoFactorContract.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Contracts; interface AuthenticatableTwoFactorContract { /** * Get the TwoFactor options. * * @return array|null */ public function getTwoFactor(): ?array; }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Contracts/CanVerifyPhoneContract.php
src/Contracts/CanVerifyPhoneContract.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Contracts; interface CanVerifyPhoneContract { /** * Get the phone for verification. * * @return string|null */ public function getPhoneForVerification(): ?string; /** * Get the country for verification. * * @return string|null */ public function getCountryForVerification(): ?string; /** * Determine if the user has verified their phone number. * * @return bool */ public function hasVerifiedPhone(): bool; /** * Send the phone verification notification. * * @param string $method * @param bool $force * * @return void */ public function sendPhoneVerificationNotification(string $method, bool $force): void; }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Contracts/PasswordResetBrokerContract.php
src/Contracts/PasswordResetBrokerContract.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Contracts; use Illuminate\Contracts\Auth\PasswordBroker; interface PasswordResetBrokerContract extends PasswordBroker { /** * Constant representing an expired token. * * @var string */ const EXPIRED_TOKEN = 'passwords.expired'; }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Contracts/EmailVerificationBrokerContract.php
src/Contracts/EmailVerificationBrokerContract.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Contracts; use Closure; interface EmailVerificationBrokerContract { /** * Constant representing a successfully sent verification email. * * @var string */ const LINK_SENT = 'messages.verification.email.link_sent'; /** * Constant representing a successfully verified email. * * @var string */ const EMAIL_VERIFIED = 'messages.verification.email.verified'; /** * Constant representing an invalid user. * * @var string */ const INVALID_USER = 'messages.verification.email.invalid_user'; /** * Constant representing an invalid token. * * @var string */ const INVALID_TOKEN = 'messages.verification.email.invalid_token'; /** * Constant representing an expired token. * * @var string */ const EXPIRED_TOKEN = 'messages.verification.email.expired_token'; /** * Send a user email verification. * * @param array $credentials * * @return string */ public function sendVerificationLink(array $credentials): string; /** * Verify given account. * * @param array $credentials * @param \Closure|null $callback * * @return mixed */ public function verify(array $credentials, Closure $callback); }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Contracts/CanResetPasswordContract.php
src/Contracts/CanResetPasswordContract.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Contracts; interface CanResetPasswordContract { /** * Get the email address where password reset links are sent. * * @return string */ public function getEmailForPasswordReset(): string; /** * Send the password reset notification. * * @param string $token * @param int $expiration * * @return void */ public function sendPasswordResetNotification(string $token, int $expiration): void; }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Contracts/EmailVerificationBrokerFactoryContract.php
src/Contracts/EmailVerificationBrokerFactoryContract.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Contracts; interface EmailVerificationBrokerFactoryContract { /** * Get a broker instance by name. * * @param string $name * * @return \Rinvex\Auth\Contracts\EmailVerificationBrokerContract */ public function broker($name = null); }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Contracts/CanVerifyEmailContract.php
src/Contracts/CanVerifyEmailContract.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Contracts; interface CanVerifyEmailContract { /** * Get the email for verification sending. * * @return string */ public function getEmailForVerification(): string; /** * Determine if the user has verified their email address. * * @return bool */ public function hasVerifiedEmail(): bool; /** * Send the email verification notification. * * @param string $token * @param int $expiration * * @return void */ public function sendEmailVerificationNotification(string $token, int $expiration): void; }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Console/Commands/PublishCommand.php
src/Console/Commands/PublishCommand.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Console\Commands; use Illuminate\Console\Command; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand(name: 'rinvex:publish:auth')] class PublishCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'rinvex:publish:auth {--f|force : Overwrite any existing files.} {--r|resource=* : Specify which resources to publish.}'; /** * The console command description. * * @var string */ protected $description = 'Publish Rinvex Auth Resources.'; /** * Execute the console command. * * @return void */ public function handle(): void { $this->alert($this->description); collect($this->option('resource') ?: ['config'])->each(function ($resource) { $this->call('vendor:publish', ['--tag' => "rinvex/auth::{$resource}", '--force' => $this->option('force')]); }); $this->line(''); } }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
rinvex/laravel-auth
https://github.com/rinvex/laravel-auth/blob/b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327/src/Providers/AuthServiceProvider.php
src/Providers/AuthServiceProvider.php
<?php declare(strict_types=1); namespace Rinvex\Auth\Providers; use Illuminate\Support\ServiceProvider; use Rinvex\Support\Traits\ConsoleTools; use Rinvex\Auth\Console\Commands\PublishCommand; use Rinvex\Auth\Services\PasswordResetBrokerManager; use Rinvex\Auth\Services\EmailVerificationBrokerManager; class AuthServiceProvider extends ServiceProvider { use ConsoleTools; /** * The commands to be registered. * * @var array */ protected $commands = [ PublishCommand::class, ]; /** * {@inheritdoc} */ public function register() { // Register console commands $this->commands($this->commands); // Register the password reset broker manager $this->app->singleton('auth.password', function ($app) { return new PasswordResetBrokerManager($app); }); // Register the verification broker manager $this->app->singleton('rinvex.auth.emailverification', function ($app) { return new EmailVerificationBrokerManager($app); }); } }
php
MIT
b39c6cc4e22c261b245aa282d5c0e9ac6f0bb327
2026-01-05T05:23:26.001935Z
false
fabiofdsantos/laracountries
https://github.com/fabiofdsantos/laracountries/blob/2fc577f080f713f7896a42afa6749c3e24d5f62f/database/seeds/CountriesTableSeeder.php
database/seeds/CountriesTableSeeder.php
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; class CountriesTableSeeder extends Seeder { /** * Run the seeder. * * @return void */ public function run() { Schema::disableForeignKeyConstraints(); DB::table('countries')->truncate(); Schema::enableForeignKeyConstraints(); $countries = [ ['name' => 'Afghanistan', 'code' => 'AF'], ['name' => 'Åland Islands', 'code' => 'AX'], ['name' => 'Albania', 'code' => 'AL'], ['name' => 'Algeria', 'code' => 'DZ'], ['name' => 'American Samoa', 'code' => 'AS'], ['name' => 'Andorra', 'code' => 'AD'], ['name' => 'Angola', 'code' => 'AO'], ['name' => 'Anguilla', 'code' => 'AI'], ['name' => 'Antarctica', 'code' => 'AQ'], ['name' => 'Antigua and Barbuda', 'code' => 'AG'], ['name' => 'Argentina', 'code' => 'AR'], ['name' => 'Armenia', 'code' => 'AM'], ['name' => 'Aruba', 'code' => 'AW'], ['name' => 'Australia', 'code' => 'AU'], ['name' => 'Austria', 'code' => 'AT'], ['name' => 'Azerbaijan', 'code' => 'AZ'], ['name' => 'Bahamas', 'code' => 'BS'], ['name' => 'Bahrain', 'code' => 'BH'], ['name' => 'Bangladesh', 'code' => 'BD'], ['name' => 'Barbados', 'code' => 'BB'], ['name' => 'Belarus', 'code' => 'BY'], ['name' => 'Belgium', 'code' => 'BE'], ['name' => 'Belize', 'code' => 'BZ'], ['name' => 'Benin', 'code' => 'BJ'], ['name' => 'Bermuda', 'code' => 'BM'], ['name' => 'Bhutan', 'code' => 'BT'], ['name' => 'Bolivia, Plurinational State of', 'code' => 'BO'], ['name' => 'Bonaire, Sint Eustatius and Saba', 'code' => 'BQ'], ['name' => 'Bosnia and Herzegovina', 'code' => 'BA'], ['name' => 'Botswana', 'code' => 'BW'], ['name' => 'Bouvet Island', 'code' => 'BV'], ['name' => 'Brazil', 'code' => 'BR'], ['name' => 'British Indian Ocean Territory', 'code' => 'IO'], ['name' => 'Brunei Darussalam', 'code' => 'BN'], ['name' => 'Bulgaria', 'code' => 'BG'], ['name' => 'Burkina Faso', 'code' => 'BF'], ['name' => 'Burundi', 'code' => 'BI'], ['name' => 'Cambodia', 'code' => 'KH'], ['name' => 'Cameroon', 'code' => 'CM'], ['name' => 'Canada', 'code' => 'CA'], ['name' => 'Cape Verde', 'code' => 'CV'], ['name' => 'Cayman Islands', 'code' => 'KY'], ['name' => 'Central African Republic', 'code' => 'CF'], ['name' => 'Chad', 'code' => 'TD'], ['name' => 'Chile', 'code' => 'CL'], ['name' => 'China', 'code' => 'CN'], ['name' => 'Christmas Island', 'code' => 'CX'], ['name' => 'Cocos (Keeling) Islands', 'code' => 'CC'], ['name' => 'Colombia', 'code' => 'CO'], ['name' => 'Comoros', 'code' => 'KM'], ['name' => 'Congo', 'code' => 'CG'], ['name' => 'Congo, the Democratic Republic of the', 'code' => 'CD'], ['name' => 'Cook Islands', 'code' => 'CK'], ['name' => 'Costa Rica', 'code' => 'CR'], ['name' => 'Côte d\'Ivoire', 'code' => 'CI'], ['name' => 'Croatia', 'code' => 'HR'], ['name' => 'Cuba', 'code' => 'CU'], ['name' => 'Curaçao', 'code' => 'CW'], ['name' => 'Cyprus', 'code' => 'CY'], ['name' => 'Czech Republic', 'code' => 'CZ'], ['name' => 'Denmark', 'code' => 'DK'], ['name' => 'Djibouti', 'code' => 'DJ'], ['name' => 'Dominica', 'code' => 'DM'], ['name' => 'Dominican Republic', 'code' => 'DO'], ['name' => 'Ecuador', 'code' => 'EC'], ['name' => 'Egypt', 'code' => 'EG'], ['name' => 'El Salvador', 'code' => 'SV'], ['name' => 'Equatorial Guinea', 'code' => 'GQ'], ['name' => 'Eritrea', 'code' => 'ER'], ['name' => 'Estonia', 'code' => 'EE'], ['name' => 'Ethiopia', 'code' => 'ET'], ['name' => 'Falkland Islands (Malvinas)', 'code' => 'FK'], ['name' => 'Faroe Islands', 'code' => 'FO'], ['name' => 'Fiji', 'code' => 'FJ'], ['name' => 'Finland', 'code' => 'FI'], ['name' => 'France', 'code' => 'FR'], ['name' => 'French Guiana', 'code' => 'GF'], ['name' => 'French Polynesia', 'code' => 'PF'], ['name' => 'French Southern Territories', 'code' => 'TF'], ['name' => 'Gabon', 'code' => 'GA'], ['name' => 'Gambia', 'code' => 'GM'], ['name' => 'Georgia', 'code' => 'GE'], ['name' => 'Germany', 'code' => 'DE'], ['name' => 'Ghana', 'code' => 'GH'], ['name' => 'Gibraltar', 'code' => 'GI'], ['name' => 'Greece', 'code' => 'GR'], ['name' => 'Greenland', 'code' => 'GL'], ['name' => 'Grenada', 'code' => 'GD'], ['name' => 'Guadeloupe', 'code' => 'GP'], ['name' => 'Guam', 'code' => 'GU'], ['name' => 'Guatemala', 'code' => 'GT'], ['name' => 'Guernsey', 'code' => 'GG'], ['name' => 'Guinea', 'code' => 'GN'], ['name' => 'Guinea-Bissau', 'code' => 'GW'], ['name' => 'Guyana', 'code' => 'GY'], ['name' => 'Haiti', 'code' => 'HT'], ['name' => 'Heard Island and McDonald Mcdonald Islands', 'code' => 'HM'], ['name' => 'Holy See (Vatican City State)', 'code' => 'VA'], ['name' => 'Honduras', 'code' => 'HN'], ['name' => 'Hong Kong', 'code' => 'HK'], ['name' => 'Hungary', 'code' => 'HU'], ['name' => 'Iceland', 'code' => 'IS'], ['name' => 'India', 'code' => 'IN'], ['name' => 'Indonesia', 'code' => 'ID'], ['name' => 'Iran, Islamic Republic of', 'code' => 'IR'], ['name' => 'Iraq', 'code' => 'IQ'], ['name' => 'Ireland', 'code' => 'IE'], ['name' => 'Isle of Man', 'code' => 'IM'], ['name' => 'Israel', 'code' => 'IL'], ['name' => 'Italy', 'code' => 'IT'], ['name' => 'Jamaica', 'code' => 'JM'], ['name' => 'Japan', 'code' => 'JP'], ['name' => 'Jersey', 'code' => 'JE'], ['name' => 'Jordan', 'code' => 'JO'], ['name' => 'Kazakhstan', 'code' => 'KZ'], ['name' => 'Kenya', 'code' => 'KE'], ['name' => 'Kiribati', 'code' => 'KI'], ['name' => 'Korea, Democratic People\'s Republic of', 'code' => 'KP'], ['name' => 'Korea, Republic of', 'code' => 'KR'], ['name' => 'Kuwait', 'code' => 'KW'], ['name' => 'Kyrgyzstan', 'code' => 'KG'], ['name' => 'Lao People\'s Democratic Republic', 'code' => 'LA'], ['name' => 'Latvia', 'code' => 'LV'], ['name' => 'Lebanon', 'code' => 'LB'], ['name' => 'Lesotho', 'code' => 'LS'], ['name' => 'Liberia', 'code' => 'LR'], ['name' => 'Libya', 'code' => 'LY'], ['name' => 'Liechtenstein', 'code' => 'LI'], ['name' => 'Lithuania', 'code' => 'LT'], ['name' => 'Luxembourg', 'code' => 'LU'], ['name' => 'Macao', 'code' => 'MO'], ['name' => 'Macedonia, the Former Yugoslav Republic of', 'code' => 'MK'], ['name' => 'Madagascar', 'code' => 'MG'], ['name' => 'Malawi', 'code' => 'MW'], ['name' => 'Malaysia', 'code' => 'MY'], ['name' => 'Maldives', 'code' => 'MV'], ['name' => 'Mali', 'code' => 'ML'], ['name' => 'Malta', 'code' => 'MT'], ['name' => 'Marshall Islands', 'code' => 'MH'], ['name' => 'Martinique', 'code' => 'MQ'], ['name' => 'Mauritania', 'code' => 'MR'], ['name' => 'Mauritius', 'code' => 'MU'], ['name' => 'Mayotte', 'code' => 'YT'], ['name' => 'Mexico', 'code' => 'MX'], ['name' => 'Micronesia, Federated States of', 'code' => 'FM'], ['name' => 'Moldova, Republic of', 'code' => 'MD'], ['name' => 'Monaco', 'code' => 'MC'], ['name' => 'Mongolia', 'code' => 'MN'], ['name' => 'Montenegro', 'code' => 'ME'], ['name' => 'Montserrat', 'code' => 'MS'], ['name' => 'Morocco', 'code' => 'MA'], ['name' => 'Mozambique', 'code' => 'MZ'], ['name' => 'Myanmar', 'code' => 'MM'], ['name' => 'Namibia', 'code' => 'NA'], ['name' => 'Nauru', 'code' => 'NR'], ['name' => 'Nepal', 'code' => 'NP'], ['name' => 'Netherlands', 'code' => 'NL'], ['name' => 'New Caledonia', 'code' => 'NC'], ['name' => 'New Zealand', 'code' => 'NZ'], ['name' => 'Nicaragua', 'code' => 'NI'], ['name' => 'Niger', 'code' => 'NE'], ['name' => 'Nigeria', 'code' => 'NG'], ['name' => 'Niue', 'code' => 'NU'], ['name' => 'Norfolk Island', 'code' => 'NF'], ['name' => 'Northern Mariana Islands', 'code' => 'MP'], ['name' => 'Norway', 'code' => 'NO'], ['name' => 'Oman', 'code' => 'OM'], ['name' => 'Pakistan', 'code' => 'PK'], ['name' => 'Palau', 'code' => 'PW'], ['name' => 'Palestine, State of', 'code' => 'PS'], ['name' => 'Panama', 'code' => 'PA'], ['name' => 'Papua New Guinea', 'code' => 'PG'], ['name' => 'Paraguay', 'code' => 'PY'], ['name' => 'Peru', 'code' => 'PE'], ['name' => 'Philippines', 'code' => 'PH'], ['name' => 'Pitcairn', 'code' => 'PN'], ['name' => 'Poland', 'code' => 'PL'], ['name' => 'Portugal', 'code' => 'PT'], ['name' => 'Puerto Rico', 'code' => 'PR'], ['name' => 'Qatar', 'code' => 'QA'], ['name' => 'Réunion', 'code' => 'RE'], ['name' => 'Romania', 'code' => 'RO'], ['name' => 'Russian Federation', 'code' => 'RU'], ['name' => 'Rwanda', 'code' => 'RW'], ['name' => 'Saint Barthélemy', 'code' => 'BL'], ['name' => 'Saint Helena, Ascension and Tristan da Cunha', 'code' => 'SH'], ['name' => 'Saint Kitts and Nevis', 'code' => 'KN'], ['name' => 'Saint Lucia', 'code' => 'LC'], ['name' => 'Saint Martin (French part)', 'code' => 'MF'], ['name' => 'Saint Pierre and Miquelon', 'code' => 'PM'], ['name' => 'Saint Vincent and the Grenadines', 'code' => 'VC'], ['name' => 'Samoa', 'code' => 'WS'], ['name' => 'San Marino', 'code' => 'SM'], ['name' => 'Sao Tome and Principe', 'code' => 'ST'], ['name' => 'Saudi Arabia', 'code' => 'SA'], ['name' => 'Senegal', 'code' => 'SN'], ['name' => 'Serbia', 'code' => 'RS'], ['name' => 'Seychelles', 'code' => 'SC'], ['name' => 'Sierra Leone', 'code' => 'SL'], ['name' => 'Singapore', 'code' => 'SG'], ['name' => 'Sint Maarten (Dutch part)', 'code' => 'SX'], ['name' => 'Slovakia', 'code' => 'SK'], ['name' => 'Slovenia', 'code' => 'SI'], ['name' => 'Solomon Islands', 'code' => 'SB'], ['name' => 'Somalia', 'code' => 'SO'], ['name' => 'South Africa', 'code' => 'ZA'], ['name' => 'South Georgia and the South Sandwich Islands', 'code' => 'GS'], ['name' => 'South Sudan', 'code' => 'SS'], ['name' => 'Spain', 'code' => 'ES'], ['name' => 'Sri Lanka', 'code' => 'LK'], ['name' => 'Sudan', 'code' => 'SD'], ['name' => 'Suriname', 'code' => 'SR'], ['name' => 'Svalbard and Jan Mayen', 'code' => 'SJ'], ['name' => 'Swaziland', 'code' => 'SZ'], ['name' => 'Sweden', 'code' => 'SE'], ['name' => 'Switzerland', 'code' => 'CH'], ['name' => 'Syrian Arab Republic', 'code' => 'SY'], ['name' => 'Taiwan', 'code' => 'TW'], ['name' => 'Tajikistan', 'code' => 'TJ'], ['name' => 'Tanzania, United Republic of', 'code' => 'TZ'], ['name' => 'Thailand', 'code' => 'TH'], ['name' => 'Timor-Leste', 'code' => 'TL'], ['name' => 'Togo', 'code' => 'TG'], ['name' => 'Tokelau', 'code' => 'TK'], ['name' => 'Tonga', 'code' => 'TO'], ['name' => 'Trinidad and Tobago', 'code' => 'TT'], ['name' => 'Tunisia', 'code' => 'TN'], ['name' => 'Turkey', 'code' => 'TR'], ['name' => 'Turkmenistan', 'code' => 'TM'], ['name' => 'Turks and Caicos Islands', 'code' => 'TC'], ['name' => 'Tuvalu', 'code' => 'TV'], ['name' => 'Uganda', 'code' => 'UG'], ['name' => 'Ukraine', 'code' => 'UA'], ['name' => 'United Arab Emirates', 'code' => 'AE'], ['name' => 'United Kingdom', 'code' => 'GB'], ['name' => 'United States', 'code' => 'US'], ['name' => 'United States Minor Outlying Islands', 'code' => 'UM'], ['name' => 'Uruguay', 'code' => 'UY'], ['name' => 'Uzbekistan', 'code' => 'UZ'], ['name' => 'Vanuatu', 'code' => 'VU'], ['name' => 'Venezuela, Bolivarian Republic of', 'code' => 'VE'], ['name' => 'Viet Nam', 'code' => 'VN'], ['name' => 'Virgin Islands, British', 'code' => 'VG'], ['name' => 'Virgin Islands, U.S.', 'code' => 'VI'], ['name' => 'Wallis and Futuna', 'code' => 'WF'], ['name' => 'Western Sahara', 'code' => 'EH'], ['name' => 'Yemen', 'code' => 'YE'], ['name' => 'Zambia', 'code' => 'ZM'], ['name' => 'Zimbabwe', 'code' => 'ZW'], ]; DB::table('countries')->insert($countries); } }
php
MIT
2fc577f080f713f7896a42afa6749c3e24d5f62f
2026-01-05T05:23:32.611162Z
false
fabiofdsantos/laracountries
https://github.com/fabiofdsantos/laracountries/blob/2fc577f080f713f7896a42afa6749c3e24d5f62f/database/migrations/create_countries_table.php
database/migrations/create_countries_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateCountriesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('countries', function (Blueprint $table) { $table->increments('id'); $table->string('code', 2) ->index(); $table->string('name', 75); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('countries'); } }
php
MIT
2fc577f080f713f7896a42afa6749c3e24d5f62f
2026-01-05T05:23:32.611162Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/phpunit.php
phpunit.php
<?php include __DIR__.'/vendor/autoload.php';
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/src/Decimal.php
src/Decimal.php
<?php declare(strict_types=1); namespace Litipk\BigNumbers; use Litipk\BigNumbers\DecimalConstants as DecimalConstants; use Litipk\BigNumbers\Errors\InfiniteInputError; use Litipk\BigNumbers\Errors\NaNInputError; use Litipk\BigNumbers\Errors\NotImplementedError; /** * Immutable object that represents a rational number * * @author Andreu Correa Casablanca <castarco@litipk.com> */ class Decimal { const DEFAULT_SCALE = 16; const CLASSIC_DECIMAL_NUMBER_REGEXP = '/^([+\-]?)0*(([1-9][0-9]*|[0-9])(\.[0-9]+)?)$/'; const EXP_NOTATION_NUMBER_REGEXP = '/^ (?P<sign> [+\-]?) 0*(?P<mantissa> [0-9](?P<decimals> \.[0-9]+)?) [eE] (?P<expSign> [+\-]?)(?P<exp> \d+)$/x'; const EXP_NUM_GROUPS_NUMBER_REGEXP = '/^ (?P<int> \d*) (?: \. (?P<dec> \d+) ) E (?P<sign>[\+\-]) (?P<exp>\d+) $/x'; /** * Internal numeric value * @var string */ protected $value; /** * Number of digits behind the point * @var integer */ private $scale; private function __construct(string $value, int $scale) { $this->value = $value; $this->scale = $scale; } private function __clone() { } /** * Decimal "constructor". * * @param mixed $value * @param int $scale * @return Decimal */ public static function create($value, int $scale = null): Decimal { if (\is_int($value)) { return self::fromInteger($value); } elseif (\is_float($value)) { return self::fromFloat($value, $scale); } elseif (\is_string($value)) { return self::fromString($value, $scale); } elseif ($value instanceof Decimal) { return self::fromDecimal($value, $scale); } else { throw new \TypeError( 'Expected (int, float, string, Decimal), but received ' . (\is_object($value) ? \get_class($value) : \gettype($value)) ); } } public static function fromInteger(int $intValue): Decimal { self::paramsValidation($intValue, null); return new static((string)$intValue, 0); } /** * @param float $fltValue * @param int $scale * @return Decimal */ public static function fromFloat(float $fltValue, int $scale = null): Decimal { self::paramsValidation($fltValue, $scale); if (\is_infinite($fltValue)) { throw new InfiniteInputError('fltValue must be a finite number'); } elseif (\is_nan($fltValue)) { throw new NaNInputError("fltValue can't be NaN"); } $strValue = (string) $fltValue; $hasPoint = (false !== \strpos($strValue, '.')); if (\preg_match(self::EXP_NUM_GROUPS_NUMBER_REGEXP, $strValue, $capture)) { if (null === $scale) { $scale = ('-' === $capture['sign']) ? $capture['exp'] + \strlen($capture['dec']) : self::DEFAULT_SCALE; } $strValue = \number_format($fltValue, $scale, '.', ''); } else { $naturalScale = ( \strlen((string)\fmod($fltValue, 1.0)) - 2 - (($fltValue < 0) ? 1 : 0) + (!$hasPoint ? 1 : 0) ); if (null === $scale) { $scale = $naturalScale; } else { $strValue .= ($hasPoint ? '' : '.') . \str_pad('', $scale - $naturalScale, '0'); } } return new static($strValue, $scale); } /** * @param string $strValue * @param integer $scale * @return Decimal */ public static function fromString(string $strValue, int $scale = null): Decimal { self::paramsValidation($strValue, $scale); if (\preg_match(self::CLASSIC_DECIMAL_NUMBER_REGEXP, $strValue, $captures) === 1) { // Now it's time to strip leading zeros in order to normalize inner values $value = self::normalizeSign($captures[1]) . $captures[2]; $min_scale = isset($captures[4]) ? \max(0, \strlen($captures[4]) - 1) : 0; } elseif (\preg_match(self::EXP_NOTATION_NUMBER_REGEXP, $strValue, $captures) === 1) { list($min_scale, $value) = self::fromExpNotationString( $scale, $captures['sign'], $captures['mantissa'], \strlen($captures['mantissa']) - 1, $captures['expSign'], (int)$captures['exp'] ); } else { throw new NaNInputError('strValue must be a number'); } $scale = $scale ?? $min_scale; if ($scale < $min_scale) { $value = self::innerRound($value, $scale); } elseif ($min_scale < $scale) { $hasPoint = (false !== \strpos($value, '.')); $value .= ($hasPoint ? '' : '.') . \str_pad('', $scale - $min_scale, '0'); } return new static($value, $scale); } /** * Constructs a new Decimal object based on a previous one, * but changing it's $scale property. * * @param Decimal $decValue * @param null|int $scale * @return Decimal */ public static function fromDecimal(Decimal $decValue, int $scale = null): Decimal { self::paramsValidation($decValue, $scale); // This block protect us from unnecessary additional instances if ($scale === null || $scale >= $decValue->scale) { return $decValue; } return new static( self::innerRound($decValue->value, $scale), $scale ); } /** * Adds two Decimal objects * @param Decimal $b * @param null|int $scale * @return Decimal */ public function add(Decimal $b, int $scale = null): Decimal { self::paramsValidation($b, $scale); return self::fromString( \bcadd($this->value, $b->value, \max($this->scale, $b->scale)), $scale ); } /** * Subtracts two BigNumber objects * @param Decimal $b * @param integer $scale * @return Decimal */ public function sub(Decimal $b, int $scale = null): Decimal { self::paramsValidation($b, $scale); return self::fromString( \bcsub($this->value, $b->value, \max($this->scale, $b->scale)), $scale ); } /** * Multiplies two BigNumber objects * @param Decimal $b * @param integer $scale * @return Decimal */ public function mul(Decimal $b, int $scale = null): Decimal { self::paramsValidation($b, $scale); if ($b->isZero()) { return DecimalConstants::Zero(); } return self::fromString( \bcmul($this->value, $b->value, $this->scale + $b->scale), $scale ); } /** * Divides the object by $b . * Warning: div with $scale == 0 is not the same as * integer division because it rounds the * last digit in order to minimize the error. * * @param Decimal $b * @param integer $scale * @return Decimal */ public function div(Decimal $b, int $scale = null): Decimal { self::paramsValidation($b, $scale); if ($b->isZero()) { throw new \DomainException("Division by zero is not allowed."); } elseif ($this->isZero()) { return DecimalConstants::Zero(); } else { if (null !== $scale) { $divscale = $scale; } else { // $divscale is calculated in order to maintain a reasonable precision $this_abs = $this->abs(); $b_abs = $b->abs(); $log10_result = self::innerLog10($this_abs->value, $this_abs->scale, 1) - self::innerLog10($b_abs->value, $b_abs->scale, 1); $divscale = (int)\max( $this->scale + $b->scale, \max( self::countSignificativeDigits($this, $this_abs), self::countSignificativeDigits($b, $b_abs) ) - \max(\ceil($log10_result), 0), \ceil(-$log10_result) + 1 ); } return self::fromString( \bcdiv($this->value, $b->value, $divscale+1), $divscale ); } } /** * Returns the square root of this object * @param integer $scale * @return Decimal */ public function sqrt(int $scale = null): Decimal { if ($this->isNegative()) { throw new \DomainException( "Decimal can't handle square roots of negative numbers (it's only for real numbers)." ); } elseif ($this->isZero()) { return DecimalConstants::Zero(); } $sqrt_scale = ($scale !== null ? $scale : $this->scale); return self::fromString( \bcsqrt($this->value, $sqrt_scale+1), $sqrt_scale ); } /** * Powers this value to $b * * @param Decimal $b exponent * @param integer $scale * @return Decimal */ public function pow(Decimal $b, int $scale = null): Decimal { if ($this->isZero()) { if ($b->isPositive()) { return Decimal::fromDecimal($this, $scale); } else { throw new \DomainException("zero can't be powered to zero or negative numbers."); } } elseif ($b->isZero()) { return DecimalConstants::One(); } else if ($b->isNegative()) { return DecimalConstants::One()->div( $this->pow($b->additiveInverse(), max($scale, self::DEFAULT_SCALE)), max($scale, self::DEFAULT_SCALE) ); } elseif (0 === $b->scale) { $pow_scale = \max($this->scale, $b->scale, $scale ?? 0); return self::fromString( \bcpow($this->value, $b->value, $pow_scale+1), $pow_scale ); } else { if ($this->isPositive()) { $pow_scale = \max($this->scale, $b->scale, $scale ?? 0); $truncated_b = \bcadd($b->value, '0', 0); $remaining_b = \bcsub($b->value, $truncated_b, $b->scale); $first_pow_approx = \bcpow($this->value, $truncated_b, $pow_scale+1); $intermediate_root = self::innerPowWithLittleExponent( $this->value, $remaining_b, $b->scale, $pow_scale+1 ); return Decimal::fromString( \bcmul($first_pow_approx, $intermediate_root, $pow_scale+1), $pow_scale ); } else { // elseif ($this->isNegative()) if (!$b->isInteger()) { throw new NotImplementedError( "Usually negative numbers can't be powered to non integer numbers. " . "The cases where is possible are not implemented." ); } return (\preg_match('/^[+\-]?[0-9]*[02468](\.0+)?$/', $b->value, $captures) === 1) ? $this->additiveInverse()->pow($b, $scale) // $b is an even number : $this->additiveInverse()->pow($b, $scale)->additiveInverse(); // $b is an odd number } } } /** * Returns the object's logarithm in base 10 * @param integer $scale * @return Decimal */ public function log10(int $scale = null): Decimal { if ($this->isNegative()) { throw new \DomainException( "Decimal can't handle logarithms of negative numbers (it's only for real numbers)." ); } elseif ($this->isZero()) { throw new \DomainException( "Decimal can't represent infinite numbers." ); } return self::fromString( self::innerLog10($this->value, $this->scale, $scale !== null ? $scale+1 : $this->scale+1), $scale ); } public function isZero(int $scale = null): bool { $cmp_scale = $scale !== null ? $scale : $this->scale; return (\bccomp(self::innerRound($this->value, $cmp_scale), '0', $cmp_scale) === 0); } public function isPositive(): bool { return ($this->value[0] !== '-' && !$this->isZero()); } public function isNegative(): bool { return ($this->value[0] === '-'); } public function isInteger(): bool { return (\preg_match('/^[+\-]?[0-9]+(\.0+)?$/', $this->value, $captures) === 1); } /** * Equality comparison between this object and $b * @param Decimal $b * @param integer $scale * @return boolean */ public function equals(Decimal $b, int $scale = null): bool { self::paramsValidation($b, $scale); if ($this === $b) { return true; } else { $cmp_scale = $scale !== null ? $scale : \max($this->scale, $b->scale); return ( \bccomp( self::innerRound($this->value, $cmp_scale), self::innerRound($b->value, $cmp_scale), $cmp_scale ) === 0 ); } } /** * $this > $b : returns 1 , $this < $b : returns -1 , $this == $b : returns 0 * * @param Decimal $b * @param integer $scale * @return integer */ public function comp(Decimal $b, int $scale = null): int { self::paramsValidation($b, $scale); if ($this === $b) { return 0; } $cmp_scale = $scale !== null ? $scale : \max($this->scale, $b->scale); return \bccomp( self::innerRound($this->value, $cmp_scale), self::innerRound($b->value, $cmp_scale), $cmp_scale ); } /** * Returns true if $this > $b, otherwise false * * @param Decimal $b * @param integer $scale * @return bool */ public function isGreaterThan(Decimal $b, int $scale = null): bool { return $this->comp($b, $scale) === 1; } /** * Returns true if $this >= $b * * @param Decimal $b * @param integer $scale * @return bool */ public function isGreaterOrEqualTo(Decimal $b, int $scale = null): bool { $comparisonResult = $this->comp($b, $scale); return $comparisonResult === 1 || $comparisonResult === 0; } /** * Returns true if $this < $b, otherwise false * * @param Decimal $b * @param integer $scale * @return bool */ public function isLessThan(Decimal $b, int $scale = null): bool { return $this->comp($b, $scale) === -1; } /** * Returns true if $this <= $b, otherwise false * * @param Decimal $b * @param integer $scale * @return bool */ public function isLessOrEqualTo(Decimal $b, int $scale = null): bool { $comparisonResult = $this->comp($b, $scale); return $comparisonResult === -1 || $comparisonResult === 0; } /** * Returns the element's additive inverse. * @return Decimal */ public function additiveInverse(): Decimal { if ($this->isZero()) { return $this; } elseif ($this->isNegative()) { $value = \substr($this->value, 1); } else { // if ($this->isPositive()) { $value = '-' . $this->value; } return new static($value, $this->scale); } /** * "Rounds" the Decimal to have at most $scale digits after the point * @param integer $scale * @return Decimal */ public function round(int $scale = 0): Decimal { if ($scale >= $this->scale) { return $this; } return self::fromString(self::innerRound($this->value, $scale)); } /** * "Ceils" the Decimal to have at most $scale digits after the point * @param integer $scale * @return Decimal */ public function ceil($scale = 0): Decimal { if ($scale >= $this->scale) { return $this; } if ($this->isNegative()) { return self::fromString(\bcadd($this->value, '0', $scale)); } return $this->innerTruncate($scale); } private function innerTruncate(int $scale = 0, bool $ceil = true): Decimal { $rounded = \bcadd($this->value, '0', $scale); $rlen = \strlen($rounded); $tlen = \strlen($this->value); $mustTruncate = false; for ($i=$tlen-1; $i >= $rlen; $i--) { if ((int)$this->value[$i] > 0) { $mustTruncate = true; break; } } if ($mustTruncate) { $rounded = $ceil ? \bcadd($rounded, \bcpow('10', (string)-$scale, $scale), $scale) : \bcsub($rounded, \bcpow('10', (string)-$scale, $scale), $scale); } return self::fromString($rounded, $scale); } /** * "Floors" the Decimal to have at most $scale digits after the point * @param integer $scale * @return Decimal */ public function floor(int $scale = 0): Decimal { if ($scale >= $this->scale) { return $this; } if ($this->isNegative()) { return $this->innerTruncate($scale, false); } return self::fromString(\bcadd($this->value, '0', $scale)); } /** * Returns the absolute value (always a positive number) * @return Decimal */ public function abs(): Decimal { return ($this->isZero() || $this->isPositive()) ? $this : $this->additiveInverse(); } /** * Calculate modulo with a decimal * @param Decimal $d * @param integer $scale * @return $this % $d */ public function mod(Decimal $d, int $scale = null): Decimal { $div = $this->div($d, 1)->floor(); return $this->sub($div->mul($d), $scale); } /** * Calculates the sine of this method with the highest possible accuracy * Note that accuracy is limited by the accuracy of predefined PI; * * @param integer $scale * @return Decimal sin($this) */ public function sin(int $scale = null): Decimal { // First normalise the number in the [0, 2PI] domain $x = $this->mod(DecimalConstants::PI()->mul(Decimal::fromString("2"))); // PI has only 32 significant numbers $scale = (null === $scale) ? 32 : $scale; return self::factorialSerie( $x, DecimalConstants::zero(), function ($i) { return ($i % 2 === 1) ? ( ($i % 4 === 1) ? DecimalConstants::one() : DecimalConstants::negativeOne() ) : DecimalConstants::zero(); }, $scale ); } /** * Calculates the cosecant of this with the highest possible accuracy * Note that accuracy is limited by the accuracy of predefined PI; * * @param integer $scale * @return Decimal */ public function cosec(int $scale = null): Decimal { $sin = $this->sin($scale + 2); if ($sin->isZero()) { throw new \DomainException( "The cosecant of this 'angle' is undefined." ); } return DecimalConstants::one()->div($sin)->round($scale); } /** * Calculates the cosine of this method with the highest possible accuracy * Note that accuracy is limited by the accuracy of predefined PI; * * @param integer $scale * @return Decimal cos($this) */ public function cos(int $scale = null): Decimal { // First normalise the number in the [0, 2PI] domain $x = $this->mod(DecimalConstants::PI()->mul(Decimal::fromString("2"))); // PI has only 32 significant numbers $scale = ($scale === null) ? 32 : $scale; return self::factorialSerie( $x, DecimalConstants::one(), function ($i) { return ($i % 2 === 0) ? ( ($i % 4 === 0) ? DecimalConstants::one() : DecimalConstants::negativeOne() ) : DecimalConstants::zero(); }, $scale ); } /** * Calculates the secant of this with the highest possible accuracy * Note that accuracy is limited by the accuracy of predefined PI; * * @param integer $scale * @return Decimal */ public function sec(int $scale = null): Decimal { $cos = $this->cos($scale + 2); if ($cos->isZero()) { throw new \DomainException( "The secant of this 'angle' is undefined." ); } return DecimalConstants::one()->div($cos)->round($scale); } /** * Calculates the arcsine of this with the highest possible accuracy * * @param integer $scale * @return Decimal */ public function arcsin(int $scale = null): Decimal { if($this->comp(DecimalConstants::one(), $scale + 2) === 1 || $this->comp(DecimalConstants::negativeOne(), $scale + 2) === -1) { throw new \DomainException( "The arcsin of this number is undefined." ); } if ($this->round($scale)->isZero()) { return DecimalConstants::zero(); } if ($this->round($scale)->equals(DecimalConstants::one())) { return DecimalConstants::pi()->div(Decimal::fromInteger(2))->round($scale); } if ($this->round($scale)->equals(DecimalConstants::negativeOne())) { return DecimalConstants::pi()->div(Decimal::fromInteger(-2))->round($scale); } $scale = ($scale === null) ? 32 : $scale; return self::powerSerie( $this, DecimalConstants::zero(), $scale ); } /** * Calculates the arccosine of this with the highest possible accuracy * * @param integer $scale * @return Decimal */ public function arccos(int $scale = null): Decimal { if($this->comp(DecimalConstants::one(), $scale + 2) === 1 || $this->comp(DecimalConstants::negativeOne(), $scale + 2) === -1) { throw new \DomainException( "The arccos of this number is undefined." ); } $piOverTwo = DecimalConstants::pi()->div(Decimal::fromInteger(2), $scale + 2)->round($scale); if ($this->round($scale)->isZero()) { return $piOverTwo; } if ($this->round($scale)->equals(DecimalConstants::one())) { return DecimalConstants::zero(); } if ($this->round($scale)->equals(DecimalConstants::negativeOne())) { return DecimalConstants::pi()->round($scale); } $scale = ($scale === null) ? 32 : $scale; return $piOverTwo->sub( self::powerSerie( $this, DecimalConstants::zero(), $scale ) )->round($scale); } /** * Calculates the arctangente of this with the highest possible accuracy * * @param integer $scale * @return Decimal */ public function arctan(int $scale = null): Decimal { $piOverFour = DecimalConstants::pi()->div(Decimal::fromInteger(4), $scale + 2)->round($scale); if ($this->round($scale)->isZero()) { return DecimalConstants::zero(); } if ($this->round($scale)->equals(DecimalConstants::one())) { return $piOverFour; } if ($this->round($scale)->equals(DecimalConstants::negativeOne())) { return DecimalConstants::negativeOne()->mul($piOverFour); } $scale = ($scale === null) ? 32 : $scale; return self::simplePowerSerie( $this, DecimalConstants::zero(), $scale + 2 )->round($scale); } /** * Calculates the arccotangente of this with the highest possible accuracy * * @param integer $scale * @return Decimal */ public function arccot(int $scale = null): Decimal { $scale = ($scale === null) ? 32 : $scale; $piOverTwo = DecimalConstants::pi()->div(Decimal::fromInteger(2), $scale + 2); if ($this->round($scale)->isZero()) { return $piOverTwo->round($scale); } $piOverFour = DecimalConstants::pi()->div(Decimal::fromInteger(4), $scale + 2); if ($this->round($scale)->equals(DecimalConstants::one())) { return $piOverFour->round($scale); } if ($this->round($scale)->equals(DecimalConstants::negativeOne())) { return DecimalConstants::negativeOne()->mul($piOverFour, $scale + 2)->round($scale); } return $piOverTwo->sub( self::simplePowerSerie( $this, DecimalConstants::zero(), $scale + 2 ) )->round($scale); } /** * Calculates the arcsecant of this with the highest possible accuracy * * @param integer $scale * @return Decimal */ public function arcsec(int $scale = null): Decimal { if($this->comp(DecimalConstants::one(), $scale + 2) === -1 && $this->comp(DecimalConstants::negativeOne(), $scale + 2) === 1) { throw new \DomainException( "The arcsecant of this number is undefined." ); } $piOverTwo = DecimalConstants::pi()->div(Decimal::fromInteger(2), $scale + 2)->round($scale); if ($this->round($scale)->equals(DecimalConstants::one())) { return DecimalConstants::zero(); } if ($this->round($scale)->equals(DecimalConstants::negativeOne())) { return DecimalConstants::pi()->round($scale); } $scale = ($scale === null) ? 32 : $scale; return $piOverTwo->sub( self::powerSerie( DecimalConstants::one()->div($this, $scale + 2), DecimalConstants::zero(), $scale + 2 ) )->round($scale); } /** * Calculates the arccosecant of this with the highest possible accuracy * * @param integer $scale * @return Decimal */ public function arccsc(int $scale = null): Decimal { if($this->comp(DecimalConstants::one(), $scale + 2) === -1 && $this->comp(DecimalConstants::negativeOne(), $scale + 2) === 1) { throw new \DomainException( "The arccosecant of this number is undefined." ); } $scale = ($scale === null) ? 32 : $scale; if ($this->round($scale)->equals(DecimalConstants::one())) { return DecimalConstants::pi()->div(Decimal::fromInteger(2), $scale + 2)->round($scale); } if ($this->round($scale)->equals(DecimalConstants::negativeOne())) { return DecimalConstants::pi()->div(Decimal::fromInteger(-2), $scale + 2)->round($scale); } return self::powerSerie( DecimalConstants::one()->div($this, $scale + 2), DecimalConstants::zero(), $scale + 2 )->round($scale); } /** * Returns exp($this), said in other words: e^$this . * * @param integer $scale * @return Decimal */ public function exp(int $scale = null): Decimal { if ($this->isZero()) { return DecimalConstants::one(); } $scale = $scale ?? \max( $this->scale, (int)($this->isNegative() ? self::innerLog10($this->value, $this->scale, 0) : self::DEFAULT_SCALE) ); return self::factorialSerie( $this, DecimalConstants::one(), function ($i) { return DecimalConstants::one(); }, $scale ); } /** * Internal method used to compute sin, cos and exp * * @param Decimal $x * @param Decimal $firstTerm * @param callable $generalTerm * @param $scale * @return Decimal */ private static function factorialSerie (Decimal $x, Decimal $firstTerm, callable $generalTerm, int $scale): Decimal { $approx = $firstTerm; $change = DecimalConstants::One(); $faculty = DecimalConstants::One(); // Calculates the faculty under the sign $xPowerN = DecimalConstants::One(); // Calculates x^n for ($i = 1; !$change->floor($scale+1)->isZero(); $i++) { // update x^n and n! for this walkthrough $xPowerN = $xPowerN->mul($x); $faculty = $faculty->mul(Decimal::fromInteger($i)); /** @var Decimal $multiplier */ $multiplier = $generalTerm($i); if (!$multiplier->isZero()) { $change = $multiplier->mul($xPowerN, $scale + 2)->div($faculty, $scale + 2); $approx = $approx->add($change, $scale + 2); } } return $approx->round($scale); } /** * Internal method used to compute arcsine and arcosine * * @param Decimal $x * @param Decimal $firstTerm * @param $scale * @return Decimal */ private static function powerSerie (Decimal $x, Decimal $firstTerm, int $scale): Decimal { $approx = $firstTerm; $change = DecimalConstants::One(); $xPowerN = DecimalConstants::One(); // Calculates x^n $factorN = DecimalConstants::One(); // Calculates a_n $numerator = DecimalConstants::one(); $denominator = DecimalConstants::one(); for ($i = 1; !$change->floor($scale + 2)->isZero(); $i++) { $xPowerN = $xPowerN->mul($x); if ($i % 2 === 0) { $factorN = DecimalConstants::zero(); } elseif ($i === 1) { $factorN = DecimalConstants::one(); } else { $incrementNum = Decimal::fromInteger($i - 2); $numerator = $numerator->mul($incrementNum, $scale +2); $incrementDen = Decimal::fromInteger($i - 1); $increment = Decimal::fromInteger($i); $denominator = $denominator ->div($incrementNum, $scale +2) ->mul($incrementDen, $scale +2) ->mul($increment, $scale +2); $factorN = $numerator->div($denominator, $scale + 2); } if (!$factorN->isZero()) { $change = $factorN->mul($xPowerN, $scale + 2); $approx = $approx->add($change, $scale + 2); } } return $approx->round($scale); } /** * Internal method used to compute arctan and arccotan * * @param Decimal $x * @param Decimal $firstTerm * @param $scale * @return Decimal */ private static function simplePowerSerie (Decimal $x, Decimal $firstTerm, int $scale): Decimal { $approx = $firstTerm; $change = DecimalConstants::One(); $xPowerN = DecimalConstants::One(); // Calculates x^n $sign = DecimalConstants::One(); // Calculates a_n for ($i = 1; !$change->floor($scale + 2)->isZero(); $i++) { $xPowerN = $xPowerN->mul($x); if ($i % 2 === 0) { $factorN = DecimalConstants::zero(); } else { if ($i % 4 === 1) { $factorN = DecimalConstants::one()->div(Decimal::fromInteger($i), $scale + 2); } else { $factorN = DecimalConstants::negativeOne()->div(Decimal::fromInteger($i), $scale + 2); } } if (!$factorN->isZero()) { $change = $factorN->mul($xPowerN, $scale + 2); $approx = $approx->add($change, $scale + 2); } } return $approx->round($scale); } /** * Calculates the tangent of this method with the highest possible accuracy * Note that accuracy is limited by the accuracy of predefined PI; * * @param integer $scale * @return Decimal tan($this) */ public function tan(int $scale = null): Decimal { $cos = $this->cos($scale + 2); if ($cos->isZero()) {
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
true
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/src/DecimalConstants.php
src/DecimalConstants.php
<?php declare(strict_types=1); namespace Litipk\BigNumbers; use Litipk\BigNumbers\Decimal as Decimal; /** * Class that holds many important numeric constants * * @author Andreu Correa Casablanca <castarco@litipk.com> */ final class DecimalConstants { /** @var Decimal */ private static $ZERO = null; /** @var Decimal */ private static $ONE = null; /** @var Decimal */ private static $NEGATIVE_ONE = null; /** @var Decimal */ private static $PI = null; /** @var Decimal */ private static $EulerMascheroni = null; /** @var Decimal */ private static $GoldenRatio = null; /** @var Decimal */ private static $SilverRatio = null; /** @var Decimal */ private static $LightSpeed = null; private function __construct() { } private function __clone() { } public static function zero(): Decimal { if (null === self::$ZERO) { self::$ZERO = Decimal::fromInteger(0); } return self::$ZERO; } public static function one(): Decimal { if (null === self::$ONE) { self::$ONE = Decimal::fromInteger(1); } return self::$ONE; } public static function negativeOne(): Decimal { if (null === self::$NEGATIVE_ONE) { self::$NEGATIVE_ONE = Decimal::fromInteger(-1); } return self::$NEGATIVE_ONE; } /** * Returns the Pi number. * @return Decimal */ public static function pi(): Decimal { if (null === self::$PI) { self::$PI = Decimal::fromString( "3.14159265358979323846264338327950" ); } return self::$PI; } /** * Returns the Euler's E number. * @param integer $scale * @return Decimal */ public static function e(int $scale = 32): Decimal { if ($scale < 0) { throw new \InvalidArgumentException("\$scale must be positive."); } return static::one()->exp($scale); } /** * Returns the Euler-Mascheroni constant. * @return Decimal */ public static function eulerMascheroni(): Decimal { if (null === self::$EulerMascheroni) { self::$EulerMascheroni = Decimal::fromString( "0.57721566490153286060651209008240" ); } return self::$EulerMascheroni; } /** * Returns the Golden Ration, also named Phi. * @return Decimal */ public static function goldenRatio(): Decimal { if (null === self::$GoldenRatio) { self::$GoldenRatio = Decimal::fromString( "1.61803398874989484820458683436564" ); } return self::$GoldenRatio; } /** * Returns the Silver Ratio. * @return Decimal */ public static function silverRatio(): Decimal { if (null === self::$SilverRatio) { self::$SilverRatio = Decimal::fromString( "2.41421356237309504880168872420970" ); } return self::$SilverRatio; } /** * Returns the Light of Speed measured in meters / second. * @return Decimal */ public static function lightSpeed(): Decimal { if (null === self::$LightSpeed) { self::$LightSpeed = Decimal::fromInteger(299792458); } return self::$LightSpeed; } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/src/Errors/BigNumbersError.php
src/Errors/BigNumbersError.php
<?php namespace Litipk\BigNumbers\Errors; use Throwable; interface BigNumbersError extends Throwable { }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/src/Errors/NaNInputError.php
src/Errors/NaNInputError.php
<?php namespace Litipk\BigNumbers\Errors; use DomainException; class NaNInputError extends DomainException implements BigNumbersError { public function __construct(string $message = 'NaN values are not supported') { parent::__construct($message, 0, null); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/src/Errors/NotImplementedError.php
src/Errors/NotImplementedError.php
<?php namespace Litipk\BigNumbers\Errors; use LogicException; class NotImplementedError extends LogicException implements BigNumbersError { public function __construct(string $message = 'Not Implemented feature') { parent::__construct($message, 0, null); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/src/Errors/InfiniteInputError.php
src/Errors/InfiniteInputError.php
<?php namespace Litipk\BigNumbers\Errors; use DomainException; class InfiniteInputError extends DomainException implements BigNumbersError { public function __construct(string $message = 'Infinite values are not supported') { parent::__construct($message, 0, null); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/DecimalConstantsTest.php
tests/DecimalConstantsTest.php
<?php use Litipk\BigNumbers\DecimalConstants as DecimalConstants; use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalConstantsTest extends TestCase { public function testFiniteAbs() { $this->assertTrue(DecimalConstants::pi()->equals( Decimal::fromString("3.14159265358979323846264338327950") )); $this->assertTrue(DecimalConstants::eulerMascheroni()->equals( Decimal::fromString("0.57721566490153286060651209008240") )); $this->assertTrue(DecimalConstants::goldenRatio()->equals( Decimal::fromString("1.61803398874989484820458683436564") )); $this->assertTrue(DecimalConstants::silverRatio()->equals( Decimal::fromString("2.41421356237309504880168872420970") )); $this->assertTrue(DecimalConstants::lightSpeed()->equals( Decimal::fromInteger(299792458) )); } public function testE() { $this->assertTrue(DecimalConstants::e()->equals( Decimal::fromString("2.71828182845904523536028747135266") )); $this->assertTrue(DecimalConstants::e(32)->equals( Decimal::fromString("2.71828182845904523536028747135266") )); $this->assertTrue(DecimalConstants::e(16)->equals( Decimal::fromString("2.7182818284590452") )); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage $scale must be positive. */ public function testNegativeParamsOnE() { DecimalConstants::e(-3); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/regression/issue55Test.php
tests/regression/issue55Test.php
<?php declare(strict_types=1); use Litipk\BigNumbers\Decimal; use PHPUnit\Framework\TestCase; class issue55Test extends TestCase { public function test_that_forcing_concrete_precision_on_creation_does_not_corrupt_the_passed_value() { $this->assertEquals(4.0, Decimal::create(4.0, 8)->asFloat()); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/regression/issue58Test.php
tests/regression/issue58Test.php
<?php declare(strict_types=1); use Litipk\BigNumbers\Decimal; use PHPUnit\Framework\TestCase; class issue58Test extends TestCase { public function test_that_fromString_preserves_the_correct_inner_scale_to_avoid_divisions_by_zero() { $value = Decimal::create('12.99', 4); $divisor = Decimal::create(2, 4); $this->assertEquals(6.495, $value->div($divisor)->asFloat()); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/regression/issue60Test.php
tests/regression/issue60Test.php
<?php declare(strict_types=1); use Litipk\BigNumbers\Decimal; use PHPUnit\Framework\TestCase; class issue60Test extends TestCase { public function test_that_fromFloat_division_does_not_calculate_invalid_log10_avoiding_div_zero() { $value = Decimal::fromFloat(1.001); $divisor = Decimal::fromFloat(20); $this->assertEquals(0.05005, $value->div($divisor)->asFloat()); $this->assertEquals(0.000434077479319, $value->log10()->asFloat()); } public function test_that_fromFloat_less_than_1_still_correct() { $value = Decimal::fromFloat(0.175); $divisor = Decimal::fromFloat(20); $this->assertEquals(0.009, $value->div($divisor)->asFloat()); $this->assertEquals(-0.7569, $value->log10()->asFloat()); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/regression/issue53Test.php
tests/regression/issue53Test.php
<?php declare(strict_types=1); use Litipk\BigNumbers\Decimal; use PHPUnit\Framework\TestCase; class issue53Test extends TestCase { public function test_that_no_division_by_zero_is_performed_without_explicit_scale() { $d1 = Decimal::create(192078120.5); $d2 = Decimal::create(31449600); $d1->div($d2); // We are asserting that no exception is thrown $this->assertTrue(true); } public function test_that_no_division_by_zero_is_performed_with_explicit_scale() { $d1 = Decimal::create(192078120.5, 28); $d2 = Decimal::create(31449600, 28); $d1->div($d2); // We are asserting that no exception is thrown $this->assertTrue(true); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalRoundTest.php
tests/Decimal/DecimalRoundTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalRoundTest extends TestCase { public function testIntegerRound() { $this->assertTrue(Decimal::fromFloat(0.4)->round()->isZero()); $this->assertTrue(Decimal::fromFloat(0.4)->round()->equals(Decimal::fromInteger(0))); $this->assertFalse(Decimal::fromFloat(0.5)->round()->isZero()); $this->assertTrue(Decimal::fromFloat(0.5)->round()->equals(Decimal::fromInteger(1))); } public function testRoundWithDecimals() { $this->assertTrue(Decimal::fromString('3.45')->round(1)->equals(Decimal::fromString('3.5'))); $this->assertTrue(Decimal::fromString('3.44')->round(1)->equals(Decimal::fromString('3.4'))); } public function testNegativeRoundWithDecimals() { $this->assertTrue(Decimal::fromString('-5.59059956723478932512')->round(3)->equals(Decimal::fromString('-5.591'))); $this->assertTrue(Decimal::fromString('-5.59059956723478932512')->round(4)->equals(Decimal::fromString('-5.5906'))); $this->assertTrue(Decimal::fromString('-5.59059956723478932512')->round(5)->equals(Decimal::fromString('-5.59060'))); $this->assertTrue(Decimal::fromString('-5.59059956723478932512')->round(6)->equals(Decimal::fromString('-5.590600'))); } public function testNoUsefulRound() { $this->assertTrue(Decimal::fromString('3.45')->round(2)->equals(Decimal::fromString('3.45'))); $this->assertTrue(Decimal::fromString('3.45')->round(3)->equals(Decimal::fromString('3.45'))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalAsNativeTest.php
tests/Decimal/DecimalAsNativeTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalAsFloatTest extends TestCase { public function testAsInteger() { $this->assertEquals(1, Decimal::fromString('1.0')->asInteger()); $this->assertTrue(is_int(Decimal::fromString('1.0')->asInteger())); $this->assertEquals(1, Decimal::fromInteger(1)->asInteger()); $this->assertTrue(is_int(Decimal::fromInteger(1)->asInteger())); $this->assertEquals(1, Decimal::fromFloat(1.0)->asInteger()); $this->assertEquals(1, Decimal::fromString('1.123123123')->asInteger()); $this->assertTrue(is_int(Decimal::fromFloat(1.0)->asInteger())); $this->assertTrue(is_int(Decimal::fromString('1.123123123')->asInteger())); } public function testAsFloat() { $this->assertEquals(1.0, Decimal::fromString('1.0')->asFloat()); $this->assertTrue(is_float(Decimal::fromString('1.0')->asFloat())); $this->assertEquals(1.0, Decimal::fromInteger(1)->asFloat()); $this->assertTrue(is_float(Decimal::fromInteger(1)->asFloat())); $this->assertEquals(1.0, Decimal::fromFloat(1.0)->asFloat()); $this->assertEquals(1.123123123, Decimal::fromString('1.123123123')->asFloat()); $this->assertTrue(is_float(Decimal::fromFloat(1.0)->asFloat())); $this->assertTrue(is_float(Decimal::fromString('1.123123123')->asFloat())); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalIsIntegerTest.php
tests/Decimal/DecimalIsIntegerTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalIsIntegerTest extends TestCase { public function testIntegers() { $this->assertTrue(Decimal::fromInteger(-200)->isInteger()); $this->assertTrue(Decimal::fromInteger(-2)->isInteger()); $this->assertTrue(Decimal::fromInteger(-1)->isInteger()); $this->assertTrue(Decimal::fromInteger(0)->isInteger()); $this->assertTrue(Decimal::fromInteger(1)->isInteger()); $this->assertTrue(Decimal::fromInteger(2)->isInteger()); $this->assertTrue(Decimal::fromInteger(200)->isInteger()); $this->assertTrue(Decimal::fromString("-200")->isInteger()); $this->assertTrue(Decimal::fromString("-2")->isInteger()); $this->assertTrue(Decimal::fromString("-1")->isInteger()); $this->assertTrue(Decimal::fromString("0")->isInteger()); $this->assertTrue(Decimal::fromString("1")->isInteger()); $this->assertTrue(Decimal::fromString("2")->isInteger()); $this->assertTrue(Decimal::fromString("200")->isInteger()); $this->assertTrue(Decimal::fromString("-200.000")->isInteger()); $this->assertTrue(Decimal::fromString("-2.000")->isInteger()); $this->assertTrue(Decimal::fromString("-1.000")->isInteger()); $this->assertTrue(Decimal::fromString("0.000")->isInteger()); $this->assertTrue(Decimal::fromString("1.000")->isInteger()); $this->assertTrue(Decimal::fromString("2.000")->isInteger()); $this->assertTrue(Decimal::fromString("200.000")->isInteger()); $this->assertTrue(Decimal::fromFloat(-200.0)->isInteger()); $this->assertTrue(Decimal::fromFloat(-2.0)->isInteger()); $this->assertTrue(Decimal::fromFloat(-1.0)->isInteger()); $this->assertTrue(Decimal::fromFloat(0.0)->isInteger()); $this->assertTrue(Decimal::fromFloat(1.0)->isInteger()); $this->assertTrue(Decimal::fromFloat(2.0)->isInteger()); $this->assertTrue(Decimal::fromFloat(200.0)->isInteger()); } public function testNotIntegers() { $this->assertFalse(Decimal::fromString("-200.001")->isInteger()); $this->assertFalse(Decimal::fromString("-2.001")->isInteger()); $this->assertFalse(Decimal::fromString("-1.001")->isInteger()); $this->assertFalse(Decimal::fromString("0.001")->isInteger()); $this->assertFalse(Decimal::fromString("1.001")->isInteger()); $this->assertFalse(Decimal::fromString("2.001")->isInteger()); $this->assertFalse(Decimal::fromString("200.001")->isInteger()); $this->assertFalse(Decimal::fromFloat(-200.001)->isInteger()); $this->assertFalse(Decimal::fromFloat(-2.001)->isInteger()); $this->assertFalse(Decimal::fromFloat(-1.001)->isInteger()); $this->assertFalse(Decimal::fromFloat(0.001)->isInteger()); $this->assertFalse(Decimal::fromFloat(1.001)->isInteger()); $this->assertFalse(Decimal::fromFloat(2.001)->isInteger()); $this->assertFalse(Decimal::fromFloat(200.001)->isInteger()); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalIsZeroTest.php
tests/Decimal/DecimalIsZeroTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalIsZeroTest extends TestCase { public function testZeros() { $this->assertTrue(Decimal::fromInteger(0)->isZero()); $this->assertTrue(Decimal::fromFloat(0.0)->isZero()); $this->assertTrue(Decimal::fromString('0')->isZero()); } public function testPositiveNumbers() { $this->assertFalse(Decimal::fromInteger(1)->isZero()); $this->assertFalse(Decimal::fromFloat(1.0)->isZero()); $this->assertFalse(Decimal::fromFloat(0.1)->isZero()); $this->assertFalse(Decimal::fromString('1')->isZero()); } public function testNegativeNumbers() { $this->assertFalse(Decimal::fromInteger(-1)->isZero()); $this->assertFalse(Decimal::fromFloat(-1.0)->isZero()); $this->assertFalse(Decimal::fromFloat(-0.1)->isZero()); $this->assertFalse(Decimal::fromString('-1')->isZero()); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalArcsinTest.php
tests/Decimal/DecimalArcsinTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; /** * @group arcsin */ class DecimalArcsinTest extends TestCase { public function arcsinProvider() { // Some values provided by wolframalpha return [ ['0.154', '0.15461530016096', 14], ['1', '1.57079632679489662', 17], ['-1', '-1.57079632679489662', 17], ]; } /** * @dataProvider arcsinProvider */ public function testSimple($nr, $answer, $digits) { $x = Decimal::fromString($nr); $arcsinX = $x->arcsin($digits); $this->assertTrue( Decimal::fromString($answer)->equals($arcsinX), "The answer must be " . $answer . ", but was " . $arcsinX ); } /** * @expectedException \DomainException * @expectedExceptionMessage The arcsin of this number is undefined. */ public function testArcsinGreaterThanOne() { Decimal::fromString('25.546')->arcsin(); } /** * @expectedException \DomainException * @expectedExceptionMessage The arcsin of this number is undefined. */ public function testArcsinFewerThanNegativeOne() { Decimal::fromString('-304.75')->arcsin(); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalArctanTest.php
tests/Decimal/DecimalArctanTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; /** * @group arctan */ class DecimalArctanTest extends TestCase { public function arctanProvider() { // Some values provided by wolframalpha return [ ['0.154', '0.15279961393666', 14], ['0', '0', 17], ['-1', '-0.78539816339744831', 17], ]; } /** * @dataProvider arctanProvider */ public function testSimple($nr, $answer, $digits) { $x = Decimal::fromString($nr); $arctanX = $x->arctan($digits); $this->assertTrue( Decimal::fromString($answer)->equals($arctanX), "The answer must be " . $answer . ", but was " . $arctanX ); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalFromFloatTest.php
tests/Decimal/DecimalFromFloatTest.php
<?php declare(strict_types=1); use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; class DecimalFromFloatTest extends TestCase { /** * @expectedException \DomainException * @expectedExceptionMessage fltValue can't be NaN */ public function testNaN() { Decimal::fromFloat(INF - INF); } public function floatProvider() { $tests = [ [1.1, "1.1"], [1234567890.0, "1234567890"], [1.1234567890, "1.123456789"], [-1.1234567890, "-1.123456789"], [0.000001, "0.0000010"], [0.000001, "0.00", 2], [90.05, "90.05"], ]; if (PHP_INT_SIZE >= 8) { // These tests probably won't work if you're not testing on x86-64. // It might also be better to mark the tests skipped. It is certainly // useful to cover this functionality off though as it hits the exponent // parsing in Decimal::fromFloat() $tests[] = [ 1230123074129038740129734907810923874017283094.1, "1230123074129038665578332283019326242900934656.0000000000000000" ]; $tests[] = [ 1230123074129038740129734907810923874017283094.1, "1230123074129038665578332283019326242900934656", 0 ]; $tests[] = [ 0.0000000000000000000000000000000000000000000000123412351234, "0.0000000000000000000000000000000000000000000000123412351234", ]; $tests[] = [ 0.0000000000000000000000000000000000000000000000123412351234, "0.00", 2 ]; } return $tests; } /** * @dataProvider floatProvider */ public function testFromFloat(float $in, string $str, int $scale = null) { $v = Decimal::fromFloat($in, $scale); $this->assertSame($str, $v->innerValue()); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalCompTest.php
tests/Decimal/DecimalCompTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalCompTest extends TestCase { public function testSelfComp() { $ten = Decimal::fromInteger(10); $this->assertTrue($ten->comp($ten) === 0); } public function testBasicCases() { $one = Decimal::fromInteger(1); $ten = Decimal::fromInteger(10); $this->assertTrue($one->comp($ten) === -1); $this->assertTrue($ten->comp($one) === 1); } public function testUnscaledComp() { // Transitivity $this->assertEquals(-1, Decimal::fromFloat(1.001)->comp(Decimal::fromFloat(1.01))); $this->assertEquals(1, Decimal::fromFloat(1.01)->comp(Decimal::fromFloat(1.004))); $this->assertEquals(-1, Decimal::fromFloat(1.001)->comp(Decimal::fromFloat(1.004))); // Reflexivity $this->assertEquals(0, Decimal::fromFloat(1.00525)->comp(Decimal::fromFloat(1.00525))); // Symmetry $this->assertEquals(1, Decimal::fromFloat(1.01)->comp(Decimal::fromFloat(1.001))); $this->assertEquals(-1, Decimal::fromFloat(1.004)->comp(Decimal::fromFloat(1.01))); $this->assertEquals(1, Decimal::fromFloat(1.004)->comp(Decimal::fromFloat(1.001))); $this->assertEquals(1, Decimal::fromFloat(1.004)->comp(Decimal::fromFloat(1.000))); // Warning, float to Decimal conversion can have unexpected behaviors, like converting // 1.005 to Decimal("1.0049999999999999") $this->assertEquals(-1, Decimal::fromFloat(1.0050000000001)->comp(Decimal::fromFloat(1.010))); $this->assertEquals(-1, Decimal::fromString("1.005")->comp(Decimal::fromString("1.010"))); # Proper rounding $this->assertEquals(-1, Decimal::fromFloat(1.004)->comp(Decimal::fromFloat(1.0050000000001))); } public function testScaledComp() { // Transitivity $this->assertEquals(0, Decimal::fromFloat(1.001)->comp(Decimal::fromFloat(1.01), 1)); $this->assertEquals(0, Decimal::fromFloat(1.01)->comp(Decimal::fromFloat(1.004), 1)); $this->assertEquals(0, Decimal::fromFloat(1.001)->comp(Decimal::fromFloat(1.004), 1)); // Reflexivity $this->assertEquals(0, Decimal::fromFloat(1.00525)->comp(Decimal::fromFloat(1.00525), 2)); // Symmetry $this->assertEquals(0, Decimal::fromFloat(1.01)->comp(Decimal::fromFloat(1.001), 1)); $this->assertEquals(0, Decimal::fromFloat(1.004)->comp(Decimal::fromFloat(1.01), 1)); $this->assertEquals(0, Decimal::fromFloat(1.004)->comp(Decimal::fromFloat(1.001), 1)); // Proper rounding $this->assertEquals(0, Decimal::fromFloat(1.004)->comp(Decimal::fromFloat(1.000), 2)); // Warning, float to Decimal conversion can have unexpected behaviors, like converting // 1.005 to Decimal("1.0049999999999999") $this->assertEquals(0, Decimal::fromFloat(1.0050000000001)->comp(Decimal::fromFloat(1.010), 2)); $this->assertEquals(0, Decimal::fromString("1.005")->comp(Decimal::fromString("1.010"), 2)); # Proper rounding $this->assertEquals(-1, Decimal::fromFloat(1.004)->comp(Decimal::fromFloat(1.0050000000001), 2)); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalSqrtTest.php
tests/Decimal/DecimalSqrtTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalSqrtTest extends TestCase { public function testIntegerSqrt() { $this->assertTrue(Decimal::fromInteger(0)->sqrt()->equals(Decimal::fromInteger(0))); $this->assertTrue(Decimal::fromInteger(1)->sqrt()->equals(Decimal::fromInteger(1))); $this->assertTrue(Decimal::fromInteger(4)->sqrt()->equals(Decimal::fromInteger(2))); $this->assertTrue(Decimal::fromInteger(9)->sqrt()->equals(Decimal::fromInteger(3))); $this->assertTrue(Decimal::fromInteger(16)->sqrt()->equals(Decimal::fromInteger(4))); $this->assertTrue(Decimal::fromInteger(25)->sqrt()->equals(Decimal::fromInteger(5))); } public function testNearZeroSqrt() { $this->assertTrue(Decimal::fromString('0.01')->sqrt()->equals(Decimal::fromString('0.1'))); $this->assertTrue(Decimal::fromString('0.0001')->sqrt()->equals(Decimal::fromString('0.01'))); } /** * @expectedException \DomainException * @expectedExceptionMessage Decimal can't handle square roots of negative numbers (it's only for real numbers). */ public function testFiniteNegativeSqrt() { Decimal::fromInteger(-1)->sqrt(); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalSubTest.php
tests/Decimal/DecimalSubTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalSubTest extends TestCase { public function testZeroSub() { $one = Decimal::fromInteger(1); $zero = Decimal::fromInteger(0); $this->assertTrue($one->sub($zero)->equals($one)); $this->assertTrue($zero->sub($one)->equals($one->additiveInverse())); $this->assertTrue($zero->sub($one)->equals(Decimal::fromInteger(-1))); $this->assertTrue($zero->sub($one)->isNegative()); } public function testBasicCase() { $one = Decimal::fromInteger(1); $two = Decimal::fromInteger(2); $this->assertTrue($one->sub($two)->equals(Decimal::fromInteger(-1))); $this->assertTrue($two->sub($one)->equals($one)); $this->assertTrue($one->sub($one)->isZero()); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalIsLessThanTest.php
tests/Decimal/DecimalIsLessThanTest.php
<?php declare(strict_types = 1); use Litipk\BigNumbers\Decimal; use PHPUnit\Framework\TestCase; class DecimalIsLessThanTest extends TestCase { public function testGreater() { $this->assertFalse(Decimal::fromFloat(1.01)->isLessThan(Decimal::fromFloat(1.001))); } public function testEqual() { $this->assertFalse(Decimal::fromFloat(1.001)->isLessThan(Decimal::fromFloat(1.001))); } public function testLess() { $this->assertTrue(Decimal::fromFloat(1.001)->isLessThan(Decimal::fromFloat(1.01))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalArccotTest.php
tests/Decimal/DecimalArccotTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; /** * @group arccot */ class DecimalArccotTest extends TestCase { public function arccotProvider() { // Some values provided by wolframalpha return [ ['0.154', '1.41799671285823', 14], ['0', '1.57079632679489662', 17], ['-1', '-0.78540', 5], ]; } /** * @dataProvider arccotProvider */ public function testSimple($nr, $answer, $digits) { $x = Decimal::fromString($nr); $arccotX = $x->arccot($digits); $this->assertTrue( Decimal::fromString($answer)->equals($arccotX), "The answer must be " . $answer . ", but was " . $arccotX ); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalFromIntegerTest.php
tests/Decimal/DecimalFromIntegerTest.php
<?php declare(strict_types=1); use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; \date_default_timezone_set('UTC'); class DecimalFromIntegerTest extends TestCase { /** * @expectedException \TypeError */ public function testNoInteger() { Decimal::fromInteger(5.1); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalFromStringTest.php
tests/Decimal/DecimalFromStringTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalFromStringTest extends TestCase { public function testNegativeSimpleString() { $n1 = Decimal::fromString('-1'); $n2 = Decimal::fromString('-1.0'); $this->assertTrue($n1->isNegative()); $this->assertTrue($n2->isNegative()); $this->assertFalse($n1->isPositive()); $this->assertFalse($n2->isPositive()); $this->assertEquals($n1->__toString(), '-1'); $this->assertEquals($n2->__toString(), '-1.0'); } public function testExponentialNotationString_With_PositiveExponent_And_Positive() { $this->assertTrue( Decimal::fromString('1e3')->equals(Decimal::fromInteger(1000)) ); $this->assertTrue( Decimal::fromString('1.5e3')->equals(Decimal::fromInteger(1500)) ); } public function testExponentialNotationString_With_PositiveExponent_And_NegativeSign() { $this->assertTrue( Decimal::fromString('-1e3')->equals(Decimal::fromInteger(-1000)) ); $this->assertTrue( Decimal::fromString('-1.5e3')->equals(Decimal::fromInteger(-1500)) ); } public function testExponentialNotationString_With_NegativeExponent_And_Positive() { $this->assertTrue( Decimal::fromString('1e-3')->equals(Decimal::fromString('0.001')) ); $this->assertTrue( Decimal::fromString('1.5e-3')->equals(Decimal::fromString('0.0015')) ); } public function testExponentialNotationString_With_NegativeExponent_And_NegativeSign() { $this->assertTrue( Decimal::fromString('-1e-3')->equals(Decimal::fromString('-0.001')) ); $this->assertTrue( Decimal::fromString('-1.5e-3')->equals(Decimal::fromString('-0.0015')) ); } public function testSimpleNotation_With_PositiveSign() { $this->assertTrue( Decimal::fromString('+34')->equals(Decimal::fromString('34')) ); $this->assertTrue( Decimal::fromString('+00034')->equals(Decimal::fromString('34')) ); } public function testExponentialNotation_With_PositiveSign() { $this->assertTrue( Decimal::fromString('+1e3')->equals(Decimal::fromString('1e3')) ); $this->assertTrue( Decimal::fromString('+0001e3')->equals(Decimal::fromString('1e3')) ); } public function testExponentialNotation_With_LeadingZero_in_ExponentPart() { $this->assertTrue( Decimal::fromString('1.048576E+06')->equals(Decimal::fromString('1.048576e6')) ); } public function testExponentialNotation_With_ZeroExponent() { $this->assertTrue( Decimal::fromString('3.14E+00')->equals(Decimal::fromString('3.14')) ); } /** * @expectedException \Litipk\BigNumbers\Errors\NaNInputError * @expectedExceptionMessage strValue must be a number */ public function testBadString() { Decimal::fromString('hello world'); } public function testWithScale() { $this->assertTrue(Decimal::fromString('7.426', 2)->equals(Decimal::fromString('7.43'))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalExpTest.php
tests/Decimal/DecimalExpTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; /** * @group cos */ class DecimalExpTest extends TestCase { public function expProvider() { // Some values provided by Mathematica return [ ['0', '1', 0], ['0', '1', 1], ['0', '1', 2], ['1', '3', 0], ['1', '2.7', 1], ['1', '2.72', 2], ['1', '2.718', 3], ['-1', '0', 0], ['-1', '0.4', 1], ['-1', '0.37', 2] ]; } /** * @dataProvider expProvider */ public function testSimple($nr, $answer, $digits) { $x = Decimal::fromString($nr); $expX = $x->exp((int)$digits); $this->assertTrue( Decimal::fromString($answer)->equals($expX), "The answer must be " . $answer . ", but was " . $expX ); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalCosTest.php
tests/Decimal/DecimalCosTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; /** * @group cos */ class DecimalCosTest extends TestCase { public function cosProvider() { // Some values provided by Mathematica return [ ['1', '0.54030230586814', 14], ['123.123', '-0.82483472946164834', 17], ['15000000000', '-0.72218064388924347683', 20] ]; } /** * @dataProvider cosProvider */ public function testSimple($nr, $answer, $digits) { $x = Decimal::fromString($nr); $cosX = $x->cos((int)$digits); $this->assertTrue( Decimal::fromString($answer)->equals($cosX), "The answer must be " . $answer . ", but was " . $cosX ); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalCeilTest.php
tests/Decimal/DecimalCeilTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalCeilTest extends TestCase { public function testIntegerCeil() { $this->assertTrue(Decimal::fromFloat(0.00)->ceil()->isZero()); $this->assertTrue(Decimal::fromFloat(0.00)->ceil()->equals(Decimal::fromInteger(0))); $this->assertFalse(Decimal::fromFloat(0.01)->ceil()->isZero()); $this->assertFalse(Decimal::fromFloat(0.40)->ceil()->isZero()); $this->assertFalse(Decimal::fromFloat(0.50)->ceil()->isZero()); $this->assertTrue(Decimal::fromFloat(0.01)->ceil()->equals(Decimal::fromInteger(1))); $this->assertTrue(Decimal::fromFloat(0.40)->ceil()->equals(Decimal::fromInteger(1))); $this->assertTrue(Decimal::fromFloat(0.50)->ceil()->equals(Decimal::fromInteger(1))); } public function testCeilWithDecimals() { $this->assertTrue(Decimal::fromString('3.45')->ceil(1)->equals(Decimal::fromString('3.5'))); $this->assertTrue(Decimal::fromString('3.44')->ceil(1)->equals(Decimal::fromString('3.5'))); } public function testNoUsefulCeil() { $this->assertTrue(Decimal::fromString('3.45')->ceil(2)->equals(Decimal::fromString('3.45'))); $this->assertTrue(Decimal::fromString('3.45')->ceil(3)->equals(Decimal::fromString('3.45'))); } public function testNegativeCeil() { $this->assertTrue(Decimal::fromFloat(-3.4)->ceil()->equals(Decimal::fromFloat(-3.0))); $this->assertTrue(Decimal::fromFloat(-3.6)->ceil()->equals(Decimal::fromFloat(-3.0))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalInternalValidationTest.php
tests/Decimal/DecimalInternalValidationTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalInternalValidationTest extends TestCase { /** * @expectedException \TypeError */ public function testConstructorNullValueValidation() { Decimal::fromInteger(null); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage $scale must be a positive integer */ public function testConstructorNegativeScaleValidation() { Decimal::fromString("25", -15); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage $scale must be a positive integer */ public function testOperatorNegativeScaleValidation() { $one = Decimal::fromInteger(1); $one->mul($one, -1); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalCreateTest.php
tests/Decimal/DecimalCreateTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use Litipk\Exceptions\InvalidArgumentTypeException; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class A {} // Empty class used for testing class DecimalCreateTest extends TestCase { public function testCreateWithInvalidType() { $thrown = false; try { Decimal::create([25, 67]); } catch (\TypeError $e) { $thrown = true; } $this->assertTrue($thrown); $thrown = false; try { Decimal::create(new A()); } catch (\TypeError $e) { $thrown = true; } $this->assertTrue($thrown); } public function testCreateFromInteger() { $this->assertTrue(Decimal::create(-35)->equals(Decimal::fromInteger(-35))); $this->assertTrue(Decimal::create(0)->equals(Decimal::fromInteger(0))); $this->assertTrue(Decimal::create(35)->equals(Decimal::fromInteger(35))); } public function testCreateFromFloat() { $this->assertTrue(Decimal::create(-35.125)->equals(Decimal::fromFloat(-35.125))); $this->assertTrue(Decimal::create(0.0)->equals(Decimal::fromFloat(0.0))); $this->assertTrue(Decimal::create(35.125)->equals(Decimal::fromFloat(35.125))); } public function testCreateFromString() { $this->assertTrue(Decimal::create('-35.125')->equals(Decimal::fromString('-35.125'))); $this->assertTrue(Decimal::create('0.0')->equals(Decimal::fromString('0.0'))); $this->assertTrue(Decimal::create('35.125')->equals(Decimal::fromString('35.125'))); } public function testCreateFromDecimal() { $this->assertTrue(Decimal::create(Decimal::fromString('345.76'), 1)->equals(Decimal::fromString('345.8'))); $this->assertTrue(Decimal::create(Decimal::fromString('345.76'), 2)->equals(Decimal::fromString('345.76'))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalArccosTest.php
tests/Decimal/DecimalArccosTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; /** * @group arccos */ class DecimalArccosTest extends TestCase { public function arccosProvider() { // Some values provided by wolframalpha return [ ['0.154', '1.41618102663394', 14], ['1', '0', 17], ['-1', '3.14159265358979324', 17], ]; } /** * @dataProvider arccosProvider */ public function testSimple($nr, $answer, $digits) { $x = Decimal::fromString($nr); $arccosX = $x->arccos($digits); $this->assertTrue( Decimal::fromString($answer)->equals($arccosX), "The answer must be " . $answer . ", but was " . $arccosX ); } /** * @expectedException \DomainException * @expectedExceptionMessage The arccos of this number is undefined. */ public function testArcosGreaterThanOne() { Decimal::fromString('25.546')->arccos(); } /** * @expectedException \DomainException * @expectedExceptionMessage The arccos of this number is undefined. */ public function testArccosFewerThanNegativeOne() { Decimal::fromString('-304.75')->arccos(); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalEqualsTest.php
tests/Decimal/DecimalEqualsTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalEqualsTest extends TestCase { public function testSimpleEquals() { // Transitivity & inter-types constructors compatibility $this->assertTrue(Decimal::fromInteger(1)->equals(Decimal::fromString("1"))); $this->assertTrue(Decimal::fromString("1")->equals(Decimal::fromFloat(1.0))); $this->assertTrue(Decimal::fromInteger(1)->equals(Decimal::fromFloat(1.0))); // Reflexivity $this->assertTrue(Decimal::fromInteger(1)->equals(Decimal::fromInteger(1))); // Symmetry $this->assertTrue(Decimal::fromString("1")->equals(Decimal::fromInteger(1))); $this->assertTrue(Decimal::fromFloat(1.0)->equals(Decimal::fromString("1"))); $this->assertTrue(Decimal::fromFloat(1.0)->equals(Decimal::fromInteger(1))); } public function testSimpleNotEquals() { // Symmetry $this->assertFalse(Decimal::fromInteger(1)->equals(Decimal::fromInteger(2))); $this->assertFalse(Decimal::fromInteger(2)->equals(Decimal::fromInteger(1))); $this->assertFalse(Decimal::fromFloat(1.01)->equals(Decimal::fromInteger(1))); $this->assertFalse(Decimal::fromInteger(1)->equals(Decimal::fromFloat(1.01))); } public function testScaledEquals() { // Transitivity $this->assertTrue(Decimal::fromFloat(1.001)->equals(Decimal::fromFloat(1.01), 1)); $this->assertTrue(Decimal::fromFloat(1.01)->equals(Decimal::fromFloat(1.004), 1)); $this->assertTrue(Decimal::fromFloat(1.001)->equals(Decimal::fromFloat(1.004), 1)); // Reflexivity $this->assertTrue(Decimal::fromFloat(1.00525)->equals(Decimal::fromFloat(1.00525), 2)); // Symmetry $this->assertTrue(Decimal::fromFloat(1.01)->equals(Decimal::fromFloat(1.001), 1)); $this->assertTrue(Decimal::fromFloat(1.004)->equals(Decimal::fromFloat(1.01), 1)); $this->assertTrue(Decimal::fromFloat(1.004)->equals(Decimal::fromFloat(1.001), 1)); // Proper rounding $this->assertTrue(Decimal::fromFloat(1.004)->equals(Decimal::fromFloat(1.000), 2)); // Warning, float to Decimal conversion can have unexpected behaviors, like converting // 1.005 to Decimal("1.0049999999999999") $this->assertTrue(Decimal::fromFloat(1.0050000000001)->equals(Decimal::fromFloat(1.010), 2)); $this->assertTrue(Decimal::fromString("1.005")->equals(Decimal::fromString("1.010"), 2)); } public function testScaledNotEquals() { # Proper rounding $this->assertFalse(Decimal::fromFloat(1.004)->equals(Decimal::fromFloat(1.0050000000001), 2)); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalFloorTest.php
tests/Decimal/DecimalFloorTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalFloorTest extends TestCase { public function testIntegerFloor() { $this->assertTrue(Decimal::fromFloat(0.00)->floor()->isZero()); $this->assertTrue(Decimal::fromFloat(0.00)->floor()->equals(Decimal::fromInteger(0))); $this->assertTrue(Decimal::fromFloat(0.01)->floor()->isZero()); $this->assertTrue(Decimal::fromFloat(0.40)->floor()->isZero()); $this->assertTrue(Decimal::fromFloat(0.50)->floor()->isZero()); $this->assertTrue(Decimal::fromFloat(0.01)->floor()->equals(Decimal::fromInteger(0))); $this->assertTrue(Decimal::fromFloat(0.40)->floor()->equals(Decimal::fromInteger(0))); $this->assertTrue(Decimal::fromFloat(0.50)->floor()->equals(Decimal::fromInteger(0))); $this->assertTrue(Decimal::fromFloat(1.01)->floor()->equals(Decimal::fromInteger(1))); $this->assertTrue(Decimal::fromFloat(1.40)->floor()->equals(Decimal::fromInteger(1))); $this->assertTrue(Decimal::fromFloat(1.50)->floor()->equals(Decimal::fromInteger(1))); } public function testFloorWithDecimals() { $this->assertTrue(Decimal::fromString('3.45')->floor(1)->equals(Decimal::fromString('3.4'))); $this->assertTrue(Decimal::fromString('3.44')->floor(1)->equals(Decimal::fromString('3.4'))); } public function testNoUsefulFloor() { $this->assertTrue(Decimal::fromString('3.45')->floor(2)->equals(Decimal::fromString('3.45'))); $this->assertTrue(Decimal::fromString('3.45')->floor(3)->equals(Decimal::fromString('3.45'))); } public function testNegativeFloor() { $this->assertTrue(Decimal::fromFloat(-3.4)->floor()->equals(Decimal::fromFloat(-4.0))); $this->assertTrue(Decimal::fromFloat(-3.6)->floor()->equals(Decimal::fromFloat(-4.0))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalSinTest.php
tests/Decimal/DecimalSinTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; /** * @group sin */ class DecimalSinTest extends TestCase { public function sinProvider() { // Some values providede by mathematica return [ ['1', '0.84147098480790', 14], ['123.123', '-0.56537391969733569', 17], ['15000000000', '0.69170450164193502844', 20] ]; } /** * @dataProvider sinProvider */ public function testSimple($nr, $answer, $digits) { $x = Decimal::fromString($nr); $sinX = $x->sin($digits); $this->assertTrue( Decimal::fromString($answer)->equals($sinX), "The answer must be " . $answer . ", but was " . $sinX ); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalSerializationTest.php
tests/Decimal/DecimalSerializationTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalSerializationTest extends TestCase { public function testBaseCase() { $one = Decimal::fromInteger(1); $little = Decimal::fromString('0.0000000000001'); $serialized_one = serialize($one); $unserialized_one = unserialize($serialized_one); $serialized_little = serialize($little); $unserialized_little = unserialize($serialized_little); $this->assertTrue($one->equals($unserialized_one)); $this->assertTrue($little->equals($unserialized_little)); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalAbsTest.php
tests/Decimal/DecimalAbsTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalAbsTest extends TestCase { public function testAbs() { $this->assertTrue(Decimal::fromInteger(0)->abs()->equals(Decimal::fromInteger(0))); $this->assertTrue(Decimal::fromInteger(5)->abs()->equals(Decimal::fromInteger(5))); $this->assertTrue(Decimal::fromInteger(-5)->abs()->equals(Decimal::fromInteger(5))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalAddTest.php
tests/Decimal/DecimalAddTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalAddTest extends TestCase { public function testZeroAdd() { $z = Decimal::fromInteger(0); $n = Decimal::fromInteger(5); $this->assertTrue($z->add($n)->equals($n)); $this->assertTrue($n->add($z)->equals($n)); } public function testPositivePositiveDecimalAdd() { $n1 = Decimal::fromString('3.45'); $n2 = Decimal::fromString('7.67'); $this->assertTrue($n1->add($n2)->equals(Decimal::fromString('11.12'))); $this->assertTrue($n2->add($n1)->equals(Decimal::fromString('11.12'))); } public function testNegativenegativeDecimalAdd() { $n1 = Decimal::fromString('-3.45'); $n2 = Decimal::fromString('-7.67'); $this->assertTrue($n1->add($n2)->equals(Decimal::fromString('-11.12'))); $this->assertTrue($n2->add($n1)->equals(Decimal::fromString('-11.12'))); } public function testPositiveNegativeDecimalAdd() { $n1 = Decimal::fromString('3.45'); $n2 = Decimal::fromString('-7.67'); $this->assertTrue($n1->add($n2)->equals(Decimal::fromString('-4.22'))); $this->assertTrue($n2->add($n1)->equals(Decimal::fromString('-4.22'))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalSecTest.php
tests/Decimal/DecimalSecTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; /** * @group sec */ class DecimalSecTest extends TestCase { public function SecProvider() { // Some values provided by Mathematica return [ ['5', '3.52532008581609', 14], ['456.456', '-1.66172995090378344', 17], ['28000000000', '-1.11551381955633891873', 20], ]; } /** * @dataProvider secProvider */ public function testSimple($nr, $answer, $digits) { $x = Decimal::fromString($nr); $secX = $x->sec((int)$digits); $this->assertTrue( Decimal::fromString($answer)->equals($secX), "The answer must be " . $answer . ", but was " . $secX ); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalMulTest.php
tests/Decimal/DecimalMulTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalMulTest extends TestCase { public function testZeroFiniteMul() { $z = Decimal::fromInteger(0); $n = Decimal::fromInteger(5); $r1 = $z->mul($n); $r2 = $n->mul($z); $this->assertTrue($r1->equals($r2)); $this->assertTrue($r2->equals($r1)); $this->assertTrue($r1->isZero()); $this->assertTrue($r2->isZero()); } public function testSignsMul() { $n1 = Decimal::fromInteger(1); $n2 = Decimal::fromInteger(-1); $n11 = $n1->mul($n1); $n12 = $n1->mul($n2); $n21 = $n2->mul($n1); $this->assertTrue($n1->equals($n11)); $this->assertTrue($n11->equals($n1)); $this->assertTrue($n11->isPositive()); $this->assertFalse($n11->isNegative()); $this->assertTrue($n12->equals($n21)); $this->assertTrue($n21->equals($n12)); $this->assertTrue($n12->isNegative()); $this->assertTrue($n21->isNegative()); $this->assertFalse($n12->isPositive()); $this->assertFalse($n21->isPositive()); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalCotanTest.php
tests/Decimal/DecimalCotanTest.php
<?php use \Litipk\BigNumbers\Decimal as Decimal; use \Litipk\BigNumbers\DecimalConstants as DecimalConstants; use PHPUnit\Framework\TestCase; /** * @group cotan */ class DecimalCotanTest extends TestCase { public function cotanProvider() { // Some values providede by mathematica return [ ['1', '0.64209261593433', 14], ['123.123', '1.45891895739232371', 17], ['15000000000', '-1.04405948230055701685', 20] ]; } /** * @dataProvider cotanProvider */ public function testSimple($nr, $answer, $digits) { $x = Decimal::fromString($nr); $cotanX = $x->cotan($digits); $this->assertTrue( Decimal::fromString($answer)->equals($cotanX), 'cotan('.$nr.') must be equal to '.$answer.', but was '.$cotanX ); } /** * @expectedException \DomainException * @expectedExceptionMessage The cotangent of this 'angle' is undefined. */ public function testCotanPiDiv() { $PI = DecimalConstants::PI(); $PI->cotan(); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalAdditiveInverseTest.php
tests/Decimal/DecimalAdditiveInverseTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalAdditiveInverseTest extends TestCase { public function testZeroAdditiveInverse() { $this->assertTrue(Decimal::fromInteger(0)->additiveInverse()->equals(Decimal::fromInteger(0))); } public function testNegativeAdditiveInverse() { $this->assertTrue(Decimal::fromInteger(-1)->additiveInverse()->equals(Decimal::fromInteger(1))); $this->assertTrue(Decimal::fromString('-1.768')->additiveInverse()->equals(Decimal::fromString('1.768'))); } public function testPositiveAdditiveInverse() { $this->assertTrue(Decimal::fromInteger(1)->additiveInverse()->equals(Decimal::fromInteger(-1))); $this->assertTrue(Decimal::fromString('1.768')->additiveInverse()->equals(Decimal::fromString('-1.768'))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalIsGreaterThanTest.php
tests/Decimal/DecimalIsGreaterThanTest.php
<?php declare(strict_types = 1); use Litipk\BigNumbers\Decimal; use PHPUnit\Framework\TestCase; class DecimalIsGreaterThanTest extends TestCase { public function testGreater() { $this->assertTrue(Decimal::fromFloat(1.01)->isGreaterThan(Decimal::fromFloat(1.001))); } public function testEqual() { $this->assertFalse(Decimal::fromFloat(1.001)->isGreaterThan(Decimal::fromFloat(1.001))); } public function testLess() { $this->assertFalse(Decimal::fromFloat(1.001)->isGreaterThan(Decimal::fromFloat(1.01))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalIsGreaterOrEqualToTest.php
tests/Decimal/DecimalIsGreaterOrEqualToTest.php
<?php declare(strict_types = 1); use Litipk\BigNumbers\Decimal; use PHPUnit\Framework\TestCase; class DecimalIsGreaterOrEqualToTest extends TestCase { public function testGreater() { $this->assertTrue(Decimal::fromFloat(1.01)->isGreaterOrEqualTo(Decimal::fromFloat(1.001))); } public function testEqual() { $this->assertTrue(Decimal::fromFloat(1.001)->isGreaterOrEqualTo(Decimal::fromFloat(1.001))); } public function testLess() { $this->assertFalse(Decimal::fromFloat(1.001)->isGreaterOrEqualTo(Decimal::fromFloat(1.01))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalTanTest.php
tests/Decimal/DecimalTanTest.php
<?php use \Litipk\BigNumbers\Decimal as Decimal; use \Litipk\BigNumbers\DecimalConstants as DecimalConstants; use PHPUnit\Framework\TestCase; /** * @group tan */ class DecimalTanTest extends TestCase { public function tanProvider() { // Some values providede by mathematica return [ ['1', '1.55740772465490', 14], ['123.123', '0.68543903342472368', 17], ['15000000000', '-0.95779983511717825557', 20] ]; } /** * @dataProvider tanProvider */ public function testSimple($nr, $answer, $digits) { $x = Decimal::fromString($nr); $tanX = $x->tan($digits); $this->assertTrue( Decimal::fromString($answer)->equals($tanX), 'tan('.$nr.') must be equal to '.$answer.', but was '.$tanX ); } /** * @expectedException \DomainException * @expectedExceptionMessage The tangent of this 'angle' is undefined. */ public function testTanPiTwoDiv() { $PiDividedByTwo = DecimalConstants::PI()->div(Decimal::fromInteger(2)); $PiDividedByTwo->tan(); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalCosecTest.php
tests/Decimal/DecimalCosecTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; /** * @group cosec */ class DecimalCosecTest extends TestCase { public function cosecProvider() { // Some values provided by Mathematica return [ ['1', '1.18839510577812', 14], ['123.123', '-1.76874094322450309', 17], ['15000000000', '1.44570405082842149818', 20] ]; } /** * @dataProvider cosecProvider */ public function testSimple($nr, $answer, $digits) { $x = Decimal::fromString($nr); $cosecX = $x->cosec((int)$digits); $this->assertTrue( Decimal::fromString($answer)->equals($cosecX), "The answer must be " . $answer . ", but was " . $cosecX ); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalDivTest.php
tests/Decimal/DecimalDivTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalDivTest extends TestCase { public function testZeroFiniteDiv() { $one = Decimal::fromInteger(1); $zero = Decimal::fromInteger(0); $catched = false; try { $one->div($zero); } catch (\DomainException $e) { $catched = true; } $this->assertTrue($catched); $this->assertTrue($zero->div($one)->equals($zero)); } public function testOneDiv() { $one = Decimal::fromInteger(1); $two = Decimal::fromInteger(2); $this->assertTrue($two->div($one)->equals($two)); } public function testBasicDiv() { $one = Decimal::fromInteger(1); $two = Decimal::fromInteger(2); $four = Decimal::fromInteger(4); $eight = Decimal::fromInteger(8); // Integer exact division $this->assertTrue($eight->div($two)->equals($four)); $this->assertTrue($eight->div($four)->equals($two)); // Arbitrary precision division $this->assertTrue($one->div($eight, 0)->equals(Decimal::fromString('0'))); $this->assertTrue($one->div($eight, 1)->equals(Decimal::fromString('0.1'))); $this->assertTrue($one->div($eight, 2)->equals(Decimal::fromString('0.13'))); $this->assertTrue($one->div($eight, 3)->equals(Decimal::fromString('0.125'))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalArcsecTest.php
tests/Decimal/DecimalArcsecTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; /** * @group arcsec */ class DecimalArcsecTest extends TestCase { public function arcsecProvider() { // Some values provided by wolframalpha return [ ['25.546', '1.53164125102163', 14], ['1.5', '0.841068', 6], ['1', '0', 17], ['-1', '3.14159265358979324', 17], ]; } /** * @dataProvider arcsecProvider */ public function testSimple($nr, $answer, $digits) { $x = Decimal::fromString($nr); $arcsecX = $x->arcsec($digits); $this->assertTrue( Decimal::fromString($answer)->equals($arcsecX), "The answer must be " . $answer . ", but was " . $arcsecX ); } /** * @expectedException \DomainException * @expectedExceptionMessage The arcsecant of this number is undefined. */ public function testArcsecBetweenOneAndNegativeOne() { Decimal::fromString('0.546')->arcsec(); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalFromDecimalTest.php
tests/Decimal/DecimalFromDecimalTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalFromDecimalTest extends TestCase { public function testBasicCase() { $n1 = Decimal::fromString('3.45'); $this->assertTrue(Decimal::fromDecimal($n1)->equals($n1)); $this->assertTrue(Decimal::fromDecimal($n1, 2)->equals($n1)); $this->assertTrue(Decimal::fromDecimal($n1, 1)->equals(Decimal::fromString('3.5'))); $this->assertTrue(Decimal::fromDecimal($n1, 0)->equals(Decimal::fromString('3'))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalLog10Test.php
tests/Decimal/DecimalLog10Test.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalLog10Test extends TestCase { /** * @expectedException \DomainException * @expectedExceptionMessage Decimal can't represent infinite numbers. */ public function testZeroLog10() { $zero = Decimal::fromInteger(0); $zero->log10(); } /** * @expectedException \DomainException * @expectedExceptionMessage Decimal can't handle logarithms of negative numbers (it's only for real numbers). */ public function testNegativeLog10() { Decimal::fromInteger(-1)->log10(); } public function testBigNumbersLog10() { $bignumber = Decimal::fromString(bcpow('10', '2417')); $pow = Decimal::fromInteger(2417); $this->assertTrue($bignumber->log10()->equals($pow)); } public function testLittleNumbersLog10() { $littlenumber = Decimal::fromString(bcpow('10', '-2417', 2417)); $pow = Decimal::fromInteger(-2417); $this->assertTrue($littlenumber->log10()->equals($pow)); } public function testMediumNumbersLog10() { $this->assertTrue(Decimal::fromInteger(75)->log10(5)->equals(Decimal::fromString('1.87506'))); $this->assertTrue(Decimal::fromInteger(49)->log10(7)->equals(Decimal::fromString('1.6901961'))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalModTest.php
tests/Decimal/DecimalModTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; /** * @group mod */ class DecimalModTest extends TestCase { public function modProvider() { return [ ['10', '3', '1'], ['34', '3.4', '0'], ['15.1615', '3.156156', '2.536876'], ['15.1615', '3.156156', '2.5369', 4], ['-3.4', '-2', '-1.4'], ['3.4', '-2', '-0.6'], ['-3.4', '2', '0.6'] ]; } /** * @dataProvider modProvider */ public function testFiniteFiniteMod($number, $mod, $answer, $scale = null) { $numberDec = Decimal::fromString($number); $modDec = Decimal::fromString($mod); $decimalAnswer = $numberDec->mod($modDec, $scale); $this->assertTrue( Decimal::fromString($answer)->equals($decimalAnswer), $decimalAnswer . ' % ' . $mod . ' must be equal to ' . $answer . ', but was ' . $decimalAnswer ); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalPowTest.php
tests/Decimal/DecimalPowTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use Litipk\BigNumbers\DecimalConstants as DecimalConstants; use Litipk\BigNumbers\Errors\NotImplementedError; use PHPUnit\Framework\TestCase; date_default_timezone_set('UTC'); class DecimalPowTest extends TestCase { public function testZeroPositive() { $zero = Decimal::fromInteger(0); $two = Decimal::fromInteger(2); $this->assertTrue($zero->pow($two)->isZero()); } /** * TODO : Split tests, change idiom to take exception message into account. */ public function testZeroNoPositive() { $zero = DecimalConstants::Zero(); $nTwo = Decimal::fromInteger(-2); $catched = false; try { $zero->pow($nTwo); } catch (\DomainException $e) { $catched = true; } $this->assertTrue($catched); $catched = false; try { $zero->pow($zero); } catch (\DomainException $e) { $catched = true; } $this->assertTrue($catched); } public function testNoZeroZero() { $zero = DecimalConstants::Zero(); $one = DecimalConstants::One(); $nTwo = Decimal::fromInteger(-2); $pTwo = Decimal::fromInteger(2); $this->assertTrue($nTwo->pow($zero)->equals($one)); $this->assertTrue($pTwo->pow($zero)->equals($one)); } public function testLittleIntegerInteger() { $two = Decimal::fromInteger(2); $three = Decimal::fromInteger(3); $four = Decimal::fromInteger(4); $eight = Decimal::fromInteger(8); $nine = Decimal::fromInteger(9); $twentyseven = Decimal::fromInteger(27); $this->assertTrue($two->pow($two)->equals($four)); $this->assertTrue($two->pow($three)->equals($eight)); $this->assertTrue($three->pow($two)->equals($nine)); $this->assertTrue($three->pow($three)->equals($twentyseven)); } public function testLittlePositiveSquareRoot() { $half = Decimal::fromString('0.5'); $two = Decimal::fromInteger(2); $three = Decimal::fromInteger(3); $four = Decimal::fromInteger(4); $nine = Decimal::fromInteger(9); $this->assertTrue($four->pow($half)->equals($two)); $this->assertTrue($nine->pow($half)->equals($three)); } public function testBigPositiveSquareRoot() { $half = Decimal::fromString('0.5'); $bignum1 = Decimal::fromString('922337203685477580700'); $this->assertTrue($bignum1->pow($half, 6)->equals($bignum1->sqrt(6))); } /** * TODO : Incorrect test! (The exception type should be changed, and the "idiom"!) */ public function testNegativeSquareRoot() { $half = Decimal::fromString('0.5'); $nThree = Decimal::fromInteger(-3); $catched = false; try { $nThree->pow($half); } catch (NotImplementedError $e) { $catched = true; } $this->assertTrue($catched); } public function testPositiveWithNegativeExponent() { $pFive = Decimal::fromInteger(5); $this->assertTrue( $pFive->pow(Decimal::fromInteger(-1))->equals(Decimal::fromString("0.2")), "The answer must be 0.2, but was " . $pFive->pow(Decimal::fromInteger(-1)) ); $this->assertTrue( $pFive->pow(Decimal::fromInteger(-2))->equals(Decimal::fromString("0.04")), "The answer must be 0.04, but was " . $pFive->pow(Decimal::fromInteger(-2)) ); $this->assertTrue( $pFive->pow(Decimal::fromInteger(-3))->equals(Decimal::fromString("0.008")), "The answer must be 0.008, but was " . $pFive->pow(Decimal::fromInteger(-3)) ); $this->assertTrue( $pFive->pow(Decimal::fromInteger(-4))->equals(Decimal::fromString("0.0016")), "The answer must be 0.0016, but was " . $pFive->pow(Decimal::fromInteger(-4)) ); $this->assertTrue( $pFive->pow(Decimal::fromFloat(-4.5))->equals(Decimal::fromString("0.0007155417527999")), "The answer must be 0.0007155417527999, but was " . $pFive->pow(Decimal::fromFloat(-4.5)) ); } public function testNegativeWithPositiveExponent() { $nFive = Decimal::fromInteger(-5); $this->assertTrue($nFive->pow(DecimalConstants::One())->equals($nFive)); $this->assertTrue($nFive->pow(Decimal::fromInteger(2))->equals(Decimal::fromInteger(25))); $this->assertTrue($nFive->pow(Decimal::fromInteger(3))->equals(Decimal::fromInteger(-125))); } public function testNegativeWithNegativeExponent() { $nFive = Decimal::fromInteger(-5); $this->assertTrue( $nFive->pow(Decimal::fromInteger(-1))->equals(Decimal::fromString("-0.2")), "The answer must be -0.2, but was " . $nFive->pow(Decimal::fromInteger(-1)) ); $this->assertTrue($nFive->pow(Decimal::fromInteger(-2))->equals(Decimal::fromString("0.04"))); $this->assertTrue($nFive->pow(Decimal::fromInteger(-3))->equals(Decimal::fromString("-0.008"))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalIsLessOrEqualToTest.php
tests/Decimal/DecimalIsLessOrEqualToTest.php
<?php declare(strict_types = 1); use Litipk\BigNumbers\Decimal; use PHPUnit\Framework\TestCase; class DecimalIsLessOrEqualToTest extends TestCase { public function testGreater() { $this->assertFalse(Decimal::fromFloat(1.01)->isLessOrEqualTo(Decimal::fromFloat(1.001))); } public function testEqual() { $this->assertTrue(Decimal::fromFloat(1.001)->isLessOrEqualTo(Decimal::fromFloat(1.001))); } public function testLess() { $this->assertTrue(Decimal::fromFloat(1.001)->isLessOrEqualTo(Decimal::fromFloat(1.01))); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
Coder-Spirit/php-bignumbers
https://github.com/Coder-Spirit/php-bignumbers/blob/6da5c5ec6ea0c6246cbb5e663e056b7042061482/tests/Decimal/DecimalArccscTest.php
tests/Decimal/DecimalArccscTest.php
<?php use Litipk\BigNumbers\Decimal as Decimal; use PHPUnit\Framework\TestCase; /** * @group arccsc */ class DecimalArccscTest extends TestCase { public function arccscProvider() { // Some values provided by wolframalpha return [ ['25.546', '0.03915507577327', 14], ['1.5', '0.729728', 6], ['1', '1.57079632679489662', 17], ['-1', '-1.57079632679489662', 17], ]; } /** * @dataProvider arccscProvider */ public function testSimple($nr, $answer, $digits) { $x = Decimal::fromString($nr); $arccscX = $x->arccsc($digits); $this->assertTrue( Decimal::fromString($answer)->equals($arccscX), "The answer must be " . $answer . ", but was " . $arccscX ); } /** * @expectedException \DomainException * @expectedExceptionMessage The arccosecant of this number is undefined. */ public function testArccscBetweenOneAndNegativeOne() { Decimal::fromString('0.546')->arccsc(); } }
php
MIT
6da5c5ec6ea0c6246cbb5e663e056b7042061482
2026-01-05T05:23:38.183871Z
false
RikudouSage/GogDownloader
https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/.php-cs-fixer.dist.php
.php-cs-fixer.dist.php
<?php $finder = (new PhpCsFixer\Finder()) ->in(__DIR__ . '/src') ; return (new PhpCsFixer\Config()) ->setRules([ '@PSR2' => true, 'array_syntax' => ['syntax' => 'short'], 'blank_line_after_opening_tag' => true, 'blank_line_before_statement' => [ 'statements' => ['declare', 'return', 'try'], ], 'cast_spaces' => true, 'class_attributes_separation' => true, 'combine_consecutive_unsets' => true, 'compact_nullable_typehint' => true, 'concat_space' => [ 'spacing' => 'one', ], 'explicit_indirect_variable' => true, 'explicit_string_variable' => true, 'final_class' => true, 'fully_qualified_strict_types' => true, 'function_typehint_space' => true, 'include' => true, 'linebreak_after_opening_tag' => true, 'lowercase_cast' => true, 'lowercase_static_reference' => true, 'magic_constant_casing' => true, 'magic_method_casing' => true, 'multiline_comment_opening_closing' => true, 'native_function_casing' => true, 'no_alternative_syntax' => true, 'no_blank_lines_after_class_opening' => true, 'no_blank_lines_after_phpdoc' => true, 'no_empty_comment' => true, 'no_empty_phpdoc' => true, 'no_empty_statement' => true, 'no_extra_blank_lines' => [ 'tokens' => [ 'extra', 'break', 'continue', 'curly_brace_block', 'parenthesis_brace_block', 'return', 'square_brace_block', 'throw', 'use', 'use_trait', 'switch', 'case', 'default', ], ], 'no_leading_import_slash' => true, 'no_leading_namespace_whitespace' => true, 'no_mixed_echo_print' => true, 'no_spaces_around_offset' => true, 'no_trailing_comma_in_singleline_array' => true, 'no_unneeded_final_method' => true, 'no_unused_imports' => true, 'no_whitespace_before_comma_in_array' => true, 'no_whitespace_in_blank_line' => true, 'normalize_index_brace' => true, 'object_operator_without_whitespace' => true, 'ordered_class_elements' => true, 'ordered_imports' => true, 'protected_to_private' => true, 'short_scalar_cast' => true, 'single_blank_line_before_namespace' => true, 'single_line_comment_style' => true, 'single_quote' => true, 'standardize_not_equals' => true, 'ternary_operator_spaces' => true, 'trailing_comma_in_multiline' => true, 'unary_operator_spaces' => true, 'visibility_required' => [ 'elements' => ['property', 'method', 'const'], ], 'whitespace_after_comma_in_array' => true, 'phpdoc_align' => true, 'phpdoc_indent' => true, 'phpdoc_no_package' => true, 'phpdoc_order' => true, 'phpdoc_scalar' => true, 'phpdoc_separation' => true, ]) ->setFinder($finder);
php
MIT
51828fd0d673e8f167e9baaf8636718b27a66950
2026-01-05T05:23:42.986854Z
false
RikudouSage/GogDownloader
https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/AppKernel.php
src/AppKernel.php
<?php namespace App; use App\DependencyInjection\CommandLocatorCompilerPass; use App\DependencyInjection\EventCoordinatorCompilerPass; use Closure; use Symfony\Bundle\FrameworkBundle\FrameworkBundle; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator; use Symfony\Component\DependencyInjection\Loader\PhpFileLoader; use Symfony\Component\HttpKernel\Kernel; final class AppKernel extends Kernel { public function registerBundles(): iterable { yield new FrameworkBundle(); } public function registerContainerConfiguration(LoaderInterface $loader): void { $loader->load(function (ContainerBuilder $container) use ($loader) { $kernelLoader = $loader->getResolver()->resolve(__FILE__); assert($kernelLoader instanceof PhpFileLoader); $kernelLoader->setCurrentDir(__DIR__); /** @noinspection PhpPassByRefInspection */ $instanceof = &Closure::bind(function &() { return $this->instanceof; }, $kernelLoader, $kernelLoader)(); $this->configureContainer(new ContainerConfigurator( $container, $kernelLoader, $instanceof, __FILE__, __FILE__, $this->getEnvironment(), )); }); } public function getCacheDir(): string { return sys_get_temp_dir() . "/{$this->getAppKey()}/cache"; } public function getLogDir(): string { return sys_get_temp_dir() . "/{$this->getAppKey()}/logs"; } protected function configureContainer(ContainerConfigurator $container): void { $container->import('../config/{packages}/*.yaml'); $container->import('../config/{packages}/' . $this->environment . '/*.yaml'); if (is_file(\dirname(__DIR__) . '/config/services.yaml')) { $container->import('../config/services.yaml'); $container->import('../config/{services}_' . $this->environment . '.yaml'); } elseif (is_file($path = \dirname(__DIR__) . '/config/services.php')) { (require $path)($container->withPath($path), $this); } } protected function build(ContainerBuilder $container): void { $container->addCompilerPass(new CommandLocatorCompilerPass()); $container->addCompilerPass(new EventCoordinatorCompilerPass()); } private function getAppKey(): string { return md5(file_get_contents(__FILE__)); } }
php
MIT
51828fd0d673e8f167e9baaf8636718b27a66950
2026-01-05T05:23:42.986854Z
false
RikudouSage/GogDownloader
https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Interfaces/SingleCommandInterface.php
src/Interfaces/SingleCommandInterface.php
<?php namespace App\Interfaces; interface SingleCommandInterface { public static function getCommandName(): string; }
php
MIT
51828fd0d673e8f167e9baaf8636718b27a66950
2026-01-05T05:23:42.986854Z
false