Commit ff6ebc26 authored by Youri van Koppen's avatar Youri van Koppen
Browse files

Issue #3324981 by MegaChriz: BooleanTarget converts non-string values to FALSE

parent 3e27fd4c
Loading
Loading
Loading
Loading
+32 −1
Original line number Diff line number Diff line
@@ -21,7 +21,38 @@ class Boolean extends FieldTargetBase {
   * {@inheritdoc}
   */
  protected function prepareValue($delta, array &$values) {
    $values['value'] = is_string($values['value']) ? (int) (bool) trim($values['value']) : (int) FALSE;
    $values['value'] = $this->convertValue($values['value']);
  }

  /**
   * Converts the given value to a boolean.
   *
   * @param mixed $value
   *   The value to convert.
   *
   * @return bool
   *   The value, converted to a boolean.
   */
  protected function convertValue($value): bool {
    if (is_bool($value)) {
      return $value;
    }
    if (is_string($value)) {
      return (bool) trim($value);
    }
    if (is_scalar($value)) {
      return (bool) $value;
    }
    if (empty($value)) {
      return FALSE;
    }
    if (is_array($value)) {
      $value = current($value);
      return $this->convertValue($value);
    }

    $value = @(string) $value;
    return $this->convertValue($value);
  }

}
+63 −3
Original line number Diff line number Diff line
@@ -25,15 +25,75 @@ class BooleanTest extends FieldTargetTestBase {
  }

  /**
   * Tests preparing a value.
   *
   * @param bool $expected
   *   The expected result.
   * @param mixed $value
   *   The input value.
   *
   * @covers ::prepareValue
   * @dataProvider valueProvider
   */
  public function testPrepareValue() {
  public function testPrepareValue(bool $expected, $value) {
    $target = $this->instantiatePlugin();
    $values = ['value' => 'string'];
    $values = ['value' => $value];

    $method = $this->getProtectedClosure($target, 'prepareValue');
    $method(0, $values);
    $this->assertSame(1, $values['value']);
    $this->assertSame($expected, $values['value']);
  }

  /**
   * Data provider for testPrepareValue().
   */
  public function valueProvider() {
    return [
      [
        'expected' => TRUE,
        'value' => 'string',
      ],
      [
        'expected' => FALSE,
        'value' => '0',
      ],
      [
        'expected' => TRUE,
        'value' => 1,
      ],
      [
        'expected' => FALSE,
        'value' => 0,
      ],
      [
        'expected' => TRUE,
        'value' => TRUE,
      ],
      [
        'expected' => FALSE,
        'value' => FALSE,
      ],
      [
        'expected' => FALSE,
        'value' => [],
      ],
      [
        'expected' => TRUE,
        'value' => [1],
      ],
      [
        'expected' => FALSE,
        'value' => [0],
      ],
      [
        'expected' => TRUE,
        'value' => [[1]],
      ],
      [
        'expected' => FALSE,
        'value' => [[0]],
      ],
    ];
  }

}